summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
author(no author) <(no author)@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2002-03-22 04:48:57 +0000
committer(no author) <(no author)@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2002-03-22 04:48:57 +0000
commit7dc80f4f9c42752a6c870cff8a908f283b37cffa (patch)
tree8d73df58a238e3a123be05e138451e8a6373725d
parent89646912c2310e46b87d1c028d7960e08e80dbad (diff)
This commit was manufactured by cvs2svn to create branch 'SHIGEO'.
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/branches/SHIGEO@2245 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
-rw-r--r--.cvsignore52
-rw-r--r--COPYING56
-rw-r--r--COPYING.ja51
-rw-r--r--ChangeLog14933
-rw-r--r--GPL340
-rw-r--r--LEGAL308
-rw-r--r--LGPL504
-rw-r--r--MANIFEST297
-rw-r--r--Makefile.in284
-rw-r--r--README106
-rw-r--r--README.EXT1026
-rw-r--r--README.EXT.ja1187
-rw-r--r--README.ja153
-rw-r--r--ToDo127
-rw-r--r--array.c1944
-rw-r--r--bignum.c1760
-rw-r--r--class.c859
-rw-r--r--compar.c118
-rw-r--r--config.guess1391
-rw-r--r--config.sub1367
-rw-r--r--configure.in1120
-rw-r--r--cygwin/GNUmakefile.in43
-rw-r--r--defines.h140
-rw-r--r--dir.c1063
-rw-r--r--djgpp/README.djgpp21
-rw-r--r--djgpp/config.hin73
-rw-r--r--djgpp/config.sed80
-rw-r--r--djgpp/config.status77
-rw-r--r--djgpp/configure.bat21
-rw-r--r--djgpp/mkver.sed1
-rw-r--r--dln.c1754
-rw-r--r--dln.h40
-rw-r--r--dmyext.c4
-rw-r--r--doc/NEWS465
-rw-r--r--doc/forwardable.rd84
-rw-r--r--doc/forwardable.rd.ja81
-rw-r--r--doc/irb/irb-tools.rd.ja185
-rw-r--r--doc/irb/irb.rd377
-rw-r--r--doc/irb/irb.rd.ja391
-rw-r--r--doc/net/http.rd.ja433
-rw-r--r--doc/net/pop.rd.ja326
-rw-r--r--doc/net/smtp.rd.ja194
-rw-r--r--doc/shell.rd348
-rw-r--r--doc/shell.rd.ja336
-rw-r--r--enum.c489
-rw-r--r--env.h60
-rw-r--r--error.c1226
-rw-r--r--eval.c9266
-rw-r--r--ext/.cvsignore3
-rw-r--r--ext/Setup20
-rw-r--r--ext/Setup.dj20
-rw-r--r--ext/Setup.emx21
-rw-r--r--ext/Setup.nt24
-rw-r--r--ext/Setup.x6817
-rw-r--r--ext/Win32API/.cvsignore1
-rw-r--r--ext/Win32API/MANIFEST7
-rw-r--r--ext/Win32API/Win32API.c307
-rw-r--r--ext/Win32API/depend1
-rw-r--r--ext/Win32API/extconf.rb7
-rw-r--r--ext/Win32API/getch.rb5
-rw-r--r--ext/Win32API/point.rb18
-rw-r--r--ext/aix_mksym.rb33
-rw-r--r--ext/configsub.rb32
-rw-r--r--ext/curses/.cvsignore2
-rw-r--r--ext/curses/MANIFEST9
-rw-r--r--ext/curses/curses.c1874
-rw-r--r--ext/curses/depend1
-rw-r--r--ext/curses/extconf.rb27
-rw-r--r--ext/curses/hello.rb30
-rw-r--r--ext/curses/mouse.rb53
-rw-r--r--ext/curses/rain.rb76
-rw-r--r--ext/curses/view.rb91
-rw-r--r--ext/curses/view2.rb115
-rw-r--r--ext/dbm/.cvsignore2
-rw-r--r--ext/dbm/MANIFEST4
-rw-r--r--ext/dbm/dbm.c764
-rw-r--r--ext/dbm/depend1
-rw-r--r--ext/dbm/extconf.rb56
-rw-r--r--ext/dbm/testdbm.rb590
-rw-r--r--ext/digest/.cvsignore2
-rw-r--r--ext/digest/MANIFEST39
-rw-r--r--ext/digest/defs.h35
-rw-r--r--ext/digest/depend2
-rw-r--r--ext/digest/digest.c343
-rw-r--r--ext/digest/digest.h32
-rw-r--r--ext/digest/digest.txt113
-rw-r--r--ext/digest/digest.txt.ja111
-rw-r--r--ext/digest/extconf.rb6
-rw-r--r--ext/digest/lib/md5.rb14
-rw-r--r--ext/digest/lib/sha1.rb14
-rw-r--r--ext/digest/md5/.cvsignore2
-rw-r--r--ext/digest/md5/MANIFEST5
-rw-r--r--ext/digest/md5/depend5
-rw-r--r--ext/digest/md5/extconf.rb19
-rw-r--r--ext/digest/md5/md5.c432
-rw-r--r--ext/digest/md5/md5.h83
-rw-r--r--ext/digest/md5/md5init.c34
-rw-r--r--ext/digest/rmd160/.cvsignore2
-rw-r--r--ext/digest/rmd160/MANIFEST6
-rw-r--r--ext/digest/rmd160/depend7
-rw-r--r--ext/digest/rmd160/extconf.rb20
-rw-r--r--ext/digest/rmd160/rmd160.c464
-rw-r--r--ext/digest/rmd160/rmd160.h68
-rw-r--r--ext/digest/rmd160/rmd160hl.c96
-rw-r--r--ext/digest/rmd160/rmd160init.c34
-rw-r--r--ext/digest/sha1/.cvsignore2
-rw-r--r--ext/digest/sha1/MANIFEST6
-rw-r--r--ext/digest/sha1/depend7
-rw-r--r--ext/digest/sha1/extconf.rb20
-rw-r--r--ext/digest/sha1/sha1.c283
-rw-r--r--ext/digest/sha1/sha1.h50
-rw-r--r--ext/digest/sha1/sha1hl.c102
-rw-r--r--ext/digest/sha1/sha1init.c34
-rw-r--r--ext/digest/sha2/.cvsignore2
-rw-r--r--ext/digest/sha2/MANIFEST6
-rw-r--r--ext/digest/sha2/depend7
-rw-r--r--ext/digest/sha2/extconf.rb28
-rw-r--r--ext/digest/sha2/sha2.c937
-rw-r--r--ext/digest/sha2/sha2.h133
-rw-r--r--ext/digest/sha2/sha2hl.c252
-rw-r--r--ext/digest/sha2/sha2init.c47
-rw-r--r--ext/digest/test.rb100
-rw-r--r--ext/digest/test.sh27
-rw-r--r--ext/etc/.cvsignore2
-rw-r--r--ext/etc/MANIFEST6
-rw-r--r--ext/etc/depend1
-rw-r--r--ext/etc/etc.c276
-rw-r--r--ext/etc/etc.txt72
-rw-r--r--ext/etc/etc.txt.ja72
-rw-r--r--ext/etc/extconf.rb22
-rw-r--r--ext/extmk.rb.in780
-rw-r--r--ext/fcntl/.cvsignore2
-rw-r--r--ext/fcntl/MANIFEST3
-rw-r--r--ext/fcntl/depend1
-rw-r--r--ext/fcntl/fcntl.c107
-rw-r--r--ext/gdbm/.cvsignore2
-rw-r--r--ext/gdbm/MANIFEST6
-rw-r--r--ext/gdbm/README1
-rw-r--r--ext/gdbm/depend1
-rw-r--r--ext/gdbm/extconf.rb7
-rw-r--r--ext/gdbm/gdbm.c994
-rw-r--r--ext/gdbm/testgdbm.rb663
-rw-r--r--ext/iconv/MANIFEST4
-rw-r--r--ext/iconv/depend2
-rw-r--r--ext/iconv/extconf.rb8
-rw-r--r--ext/iconv/iconv.c735
-rw-r--r--ext/nkf/.cvsignore2
-rw-r--r--ext/nkf/MANIFEST7
-rw-r--r--ext/nkf/depend1
-rw-r--r--ext/nkf/extconf.rb2
-rw-r--r--ext/nkf/lib/kconv.rb73
-rw-r--r--ext/nkf/nkf.c197
-rw-r--r--ext/nkf/nkf1.7/nkf.c1900
-rw-r--r--ext/nkf/test.rb318
-rw-r--r--ext/pty/.cvsignore2
-rw-r--r--ext/pty/MANIFEST12
-rw-r--r--ext/pty/README93
-rw-r--r--ext/pty/README.expect22
-rw-r--r--ext/pty/README.expect.ja21
-rw-r--r--ext/pty/README.ja89
-rw-r--r--ext/pty/depend1
-rw-r--r--ext/pty/expect_sample.rb56
-rw-r--r--ext/pty/extconf.rb15
-rw-r--r--ext/pty/lib/expect.rb36
-rw-r--r--ext/pty/pty.c488
-rw-r--r--ext/pty/script.rb38
-rw-r--r--ext/pty/shl.rb92
-rw-r--r--ext/readline/.cvsignore2
-rw-r--r--ext/readline/MANIFEST6
-rw-r--r--ext/readline/README62
-rw-r--r--ext/readline/README.ja63
-rw-r--r--ext/readline/depend1
-rw-r--r--ext/readline/extconf.rb27
-rw-r--r--ext/readline/readline.c737
-rw-r--r--ext/sdbm/.cvsignore2
-rw-r--r--ext/sdbm/MANIFEST6
-rw-r--r--ext/sdbm/_sdbm.c973
-rw-r--r--ext/sdbm/depend2
-rw-r--r--ext/sdbm/extconf.rb3
-rw-r--r--ext/sdbm/init.c761
-rw-r--r--ext/sdbm/sdbm.h84
-rw-r--r--ext/sdbm/testsdbm.rb556
-rw-r--r--ext/socket/.cvsignore2
-rw-r--r--ext/socket/MANIFEST8
-rw-r--r--ext/socket/addrinfo.h170
-rw-r--r--ext/socket/depend3
-rw-r--r--ext/socket/extconf.rb386
-rw-r--r--ext/socket/getaddrinfo.c686
-rw-r--r--ext/socket/getnameinfo.c261
-rw-r--r--ext/socket/socket.c2837
-rw-r--r--ext/socket/sockport.h76
-rw-r--r--ext/stringio/MANIFEST4
-rw-r--r--ext/stringio/README19
-rw-r--r--ext/stringio/depend2
-rw-r--r--ext/stringio/stringio.c920
-rw-r--r--ext/syslog/.cvsignore2
-rw-r--r--ext/syslog/MANIFEST6
-rw-r--r--ext/syslog/depend2
-rw-r--r--ext/syslog/extconf.rb10
-rw-r--r--ext/syslog/syslog.c381
-rw-r--r--ext/syslog/syslog.txt121
-rw-r--r--ext/syslog/test.rb161
-rw-r--r--ext/tcltklib/.cvsignore1
-rw-r--r--ext/tcltklib/MANIFEST16
-rw-r--r--ext/tcltklib/MANUAL.euc124
-rw-r--r--ext/tcltklib/README.euc133
-rw-r--r--ext/tcltklib/demo/lines0.tcl42
-rw-r--r--ext/tcltklib/demo/lines1.rb54
-rw-r--r--ext/tcltklib/demo/lines2.rb50
-rw-r--r--ext/tcltklib/depend2
-rw-r--r--ext/tcltklib/extconf.rb72
-rw-r--r--ext/tcltklib/lib/tcltk.rb367
-rw-r--r--ext/tcltklib/sample/batsu.gifbin538 -> 0 bytes
-rw-r--r--ext/tcltklib/sample/maru.gifbin481 -> 0 bytes
-rw-r--r--ext/tcltklib/sample/sample0.rb39
-rw-r--r--ext/tcltklib/sample/sample1.rb634
-rw-r--r--ext/tcltklib/sample/sample2.rb449
-rw-r--r--ext/tcltklib/stubs.c86
-rw-r--r--ext/tcltklib/tcltklib.c561
-rw-r--r--ext/tk/.cvsignore2
-rw-r--r--ext/tk/MANIFEST25
-rw-r--r--ext/tk/depend1
-rw-r--r--ext/tk/extconf.rb2
-rw-r--r--ext/tk/lib/README15
-rw-r--r--ext/tk/lib/tk.rb3592
-rw-r--r--ext/tk/lib/tkafter.rb316
-rw-r--r--ext/tk/lib/tkbgerror.rb17
-rw-r--r--ext/tk/lib/tkcanvas.rb863
-rw-r--r--ext/tk/lib/tkclass.rb38
-rw-r--r--ext/tk/lib/tkdialog.rb141
-rw-r--r--ext/tk/lib/tkentry.rb221
-rw-r--r--ext/tk/lib/tkfont.rb1042
-rw-r--r--ext/tk/lib/tkmenubar.rb137
-rw-r--r--ext/tk/lib/tkmngfocus.rb27
-rw-r--r--ext/tk/lib/tkpalette.rb48
-rw-r--r--ext/tk/lib/tkscrollbox.rb29
-rw-r--r--ext/tk/lib/tktext.rb1000
-rw-r--r--ext/tk/lib/tkvirtevent.rb81
-rw-r--r--ext/tk/sample/tkbiff.rb149
-rw-r--r--ext/tk/sample/tkbrowse.rb79
-rw-r--r--ext/tk/sample/tkdialog.rb62
-rw-r--r--ext/tk/sample/tkfrom.rb132
-rw-r--r--ext/tk/sample/tkhello.rb10
-rw-r--r--ext/tk/sample/tkline.rb45
-rw-r--r--ext/tk/sample/tktimer.rb50
-rw-r--r--ext/tk/tkutil.c45
-rw-r--r--file.c2651
-rw-r--r--gc.c1561
-rw-r--r--hash.c1654
-rw-r--r--inits.c80
-rw-r--r--install-sh0
-rw-r--r--instruby.rb102
-rw-r--r--intern.h446
-rw-r--r--io.c3824
-rw-r--r--keywords42
-rw-r--r--lex.c137
-rw-r--r--lib/English.rb27
-rw-r--r--lib/Env.rb18
-rw-r--r--lib/README72
-rw-r--r--lib/base64.rb29
-rw-r--r--lib/benchmark.rb651
-rw-r--r--lib/cgi-lib.rb270
-rw-r--r--lib/cgi.rb1949
-rw-r--r--lib/cgi/session.rb185
-rw-r--r--lib/complex.rb489
-rw-r--r--lib/date.rb345
-rw-r--r--lib/date2.rb5
-rw-r--r--lib/debug.rb928
-rw-r--r--lib/delegate.rb128
-rw-r--r--lib/e2mmap.rb195
-rw-r--r--lib/eregex.rb37
-rw-r--r--lib/final.rb4
-rw-r--r--lib/finalize.rb201
-rw-r--r--lib/find.rb45
-rw-r--r--lib/forwardable.rb94
-rw-r--r--lib/ftools.rb181
-rw-r--r--lib/ftplib.rb14
-rw-r--r--lib/getoptlong.rb467
-rw-r--r--lib/getopts.rb116
-rw-r--r--lib/importenv.rb31
-rw-r--r--lib/irb.rb314
-rw-r--r--lib/irb/completion.rb177
-rw-r--r--lib/irb/context.rb289
-rw-r--r--lib/irb/extend-command.rb126
-rw-r--r--lib/irb/frame.rb67
-rw-r--r--lib/irb/help.rb33
-rw-r--r--lib/irb/init.rb232
-rw-r--r--lib/irb/input-method.rb118
-rw-r--r--lib/irb/lc/error.rb30
-rw-r--r--lib/irb/lc/help-message34
-rw-r--r--lib/irb/lc/ja/error.rb29
-rw-r--r--lib/irb/lc/ja/help-message35
-rw-r--r--lib/irb/loader.rb118
-rw-r--r--lib/irb/locale.rb186
-rw-r--r--lib/irb/multi-irb.rb232
-rw-r--r--lib/irb/ruby-lex.rb971
-rw-r--r--lib/irb/ruby-token.rb271
-rw-r--r--lib/irb/slex.rb279
-rw-r--r--lib/irb/version.rb16
-rw-r--r--lib/irb/workspace.rb106
-rw-r--r--lib/irb/ws-for-case-2.rb15
-rw-r--r--lib/irb/xmp.rb84
-rw-r--r--lib/jcode.rb216
-rw-r--r--lib/mailread.rb48
-rw-r--r--lib/mathn.rb313
-rw-r--r--lib/matrix.rb1023
-rw-r--r--lib/mkmf.rb612
-rw-r--r--lib/monitor.rb249
-rw-r--r--lib/mutex_m.rb118
-rw-r--r--lib/net/ftp.rb671
-rw-r--r--lib/net/http.rb1473
-rw-r--r--lib/net/imap.rb2878
-rw-r--r--lib/net/pop.rb631
-rw-r--r--lib/net/protocol.rb780
-rw-r--r--lib/net/smtp.rb442
-rw-r--r--lib/net/telnet.rb599
-rw-r--r--lib/observer.rb46
-rw-r--r--lib/open3.rb67
-rw-r--r--lib/ostruct.rb55
-rw-r--r--lib/parsearg.rb83
-rw-r--r--lib/parsedate.rb181
-rw-r--r--lib/ping.rb64
-rw-r--r--lib/pp.rb564
-rw-r--r--lib/prettyprint.rb802
-rw-r--r--lib/profile.rb56
-rw-r--r--lib/pstore.rb159
-rw-r--r--lib/rational.rb390
-rw-r--r--lib/readbytes.rb36
-rw-r--r--lib/resolv-replace.rb41
-rw-r--r--lib/resolv.rb1667
-rw-r--r--lib/shell.rb270
-rw-r--r--lib/shell/builtin-command.rb154
-rw-r--r--lib/shell/command-processor.rb584
-rw-r--r--lib/shell/error.rb26
-rw-r--r--lib/shell/filter.rb111
-rw-r--r--lib/shell/process-controller.rb258
-rw-r--r--lib/shell/system-command.rb168
-rw-r--r--lib/shell/version.rb16
-rw-r--r--lib/shellwords.rb49
-rw-r--r--lib/singleton.rb336
-rw-r--r--lib/sync.rb311
-rw-r--r--lib/telnet.rb9
-rw-r--r--lib/tempfile.rb98
-rw-r--r--lib/thread.rb283
-rw-r--r--lib/thwait.rb133
-rw-r--r--lib/time.rb585
-rw-r--r--lib/timeout.rb56
-rw-r--r--lib/tracer.rb171
-rw-r--r--lib/tsort.rb289
-rw-r--r--lib/uri.rb41
-rw-r--r--lib/uri/common.rb432
-rw-r--r--lib/uri/ftp.rb149
-rw-r--r--lib/uri/generic.rb1099
-rw-r--r--lib/uri/http.rb76
-rw-r--r--lib/uri/https.rb26
-rw-r--r--lib/uri/ldap.rb238
-rw-r--r--lib/uri/mailto.rb260
-rw-r--r--lib/weakref.rb87
-rw-r--r--main.c52
-rw-r--r--marshal.c1171
-rw-r--r--math.c224
-rw-r--r--misc/README5
-rw-r--r--misc/inf-ruby.el332
-rw-r--r--misc/ruby-mode.el904
-rw-r--r--misc/rubydb2x.el104
-rw-r--r--misc/rubydb3x.el115
-rw-r--r--missing/alloca.c194
-rw-r--r--missing/crypt.c276
-rw-r--r--missing/dup2.c61
-rw-r--r--missing/file.h22
-rw-r--r--missing/fileblocks.c1
-rw-r--r--missing/finite.c8
-rw-r--r--missing/flock.c134
-rw-r--r--missing/hypot.c17
-rw-r--r--missing/isinf.c46
-rw-r--r--missing/isnan.c31
-rw-r--r--missing/memcmp.c18
-rw-r--r--missing/memmove.c20
-rw-r--r--missing/mkdir.c104
-rw-r--r--missing/os2.c113
-rw-r--r--missing/strcasecmp.c16
-rw-r--r--missing/strchr.c30
-rw-r--r--missing/strerror.c17
-rw-r--r--missing/strftime.c889
-rw-r--r--missing/strncasecmp.c21
-rw-r--r--missing/strstr.c26
-rw-r--r--missing/strtod.c271
-rw-r--r--missing/strtol.c29
-rw-r--r--missing/strtoul.c184
-rw-r--r--missing/vsnprintf.c1131
-rw-r--r--missing/x68.c40
-rw-r--r--mkconfig.rb120
-rw-r--r--node.h356
-rw-r--r--numeric.c1763
-rw-r--r--object.c1380
-rw-r--r--pack.c1835
-rw-r--r--parse.y5424
-rw-r--r--prec.c81
-rw-r--r--process.c1356
-rw-r--r--random.c181
-rw-r--r--range.c583
-rw-r--r--re.c1489
-rw-r--r--re.h41
-rw-r--r--regex.c4587
-rw-r--r--regex.h227
-rw-r--r--ruby.1291
-rw-r--r--ruby.c1061
-rw-r--r--ruby.h658
-rw-r--r--rubyio.h72
-rw-r--r--rubysig.h90
-rw-r--r--rubytest.rb44
-rw-r--r--sample/README52
-rw-r--r--sample/biorhythm.rb161
-rw-r--r--sample/cal.rb111
-rw-r--r--sample/cbreak.rb36
-rw-r--r--sample/clnt.rb17
-rw-r--r--sample/dbmtest.rb14
-rw-r--r--sample/dir.rb10
-rw-r--r--sample/dualstack-fetch.rb48
-rw-r--r--sample/dualstack-httpd.rb55
-rw-r--r--sample/eval.rb42
-rw-r--r--sample/export.rb40
-rw-r--r--sample/exyacc.rb22
-rw-r--r--sample/fact.rb10
-rw-r--r--sample/fib.awk5
-rw-r--r--sample/fib.pl11
-rw-r--r--sample/fib.py10
-rw-r--r--sample/fib.rb10
-rw-r--r--sample/fib.scm8
-rw-r--r--sample/freq.rb12
-rw-r--r--sample/from.rb98
-rw-r--r--sample/fullpath.rb23
-rw-r--r--sample/getopts.test36
-rw-r--r--sample/goodfriday.rb48
-rw-r--r--sample/irb.rb21
-rw-r--r--sample/less.rb17
-rw-r--r--sample/list.rb80
-rw-r--r--sample/list2.rb16
-rw-r--r--sample/list3.rb18
-rw-r--r--sample/mine.rb175
-rw-r--r--sample/mkproto.rb27
-rw-r--r--sample/mpart.rb44
-rw-r--r--sample/mrshtest.rb13
-rw-r--r--sample/observ.rb32
-rw-r--r--sample/occur.pl9
-rw-r--r--sample/occur.rb12
-rw-r--r--sample/occur2.rb16
-rw-r--r--sample/philos.rb54
-rw-r--r--sample/pi.rb18
-rw-r--r--sample/rcs.awk33
-rw-r--r--sample/rcs.dat17
-rw-r--r--sample/rcs.rb49
-rw-r--r--sample/regx.rb23
-rw-r--r--sample/sieve.rb14
-rw-r--r--sample/svr.rb32
-rw-r--r--sample/test.rb1485
-rw-r--r--sample/time.rb8
-rw-r--r--sample/trojan.rb15
-rw-r--r--sample/tsvr.rb20
-rw-r--r--sample/uumerge.rb43
-rw-r--r--signal.c733
-rw-r--r--sprintf.c655
-rw-r--r--st.c563
-rw-r--r--st.h46
-rw-r--r--string.c3261
-rw-r--r--struct.c592
-rw-r--r--time.c1485
-rw-r--r--util.c650
-rw-r--r--util.h64
-rw-r--r--variable.c1633
-rw-r--r--version.c45
-rw-r--r--version.h4
-rw-r--r--win32/Makefile.sub459
-rw-r--r--win32/README.win32123
-rw-r--r--win32/config.h.in67
-rwxr-xr-xwin32/configure.bat13
-rw-r--r--win32/dir.h20
-rw-r--r--win32/mkexports.rb30
-rw-r--r--win32/resource.rb94
-rw-r--r--win32/setup.mak30
-rw-r--r--win32/win32.c2817
-rw-r--r--win32/win32.h422
-rw-r--r--win32/winmain.c10
-rw-r--r--x68/_dtos18.c250
-rw-r--r--x68/_round.c45
-rw-r--r--x68/fconvert.c81
-rw-r--r--x68/select.c167
487 files changed, 0 insertions, 168269 deletions
diff --git a/.cvsignore b/.cvsignore
deleted file mode 100644
index ac1a9db525..0000000000
--- a/.cvsignore
+++ /dev/null
@@ -1,52 +0,0 @@
-*.bak
-*.orig
-*.rej
-*.sav
-*~
-.ccmalloc
-.ppack
-COPYING.LIB
-ChangeLog.pre-alpha
-ChangeLog.pre1_1
-Makefile
-README.fat-patch
-README.v6
-a.rb
-archive
-automake
-beos
-config.cache
-config.h
-config.h.in
-config.log
-config.status
-configure
-foo.rb
-libruby.so.*
-miniruby
-miniruby.elhash
-miniruby.elhash2
-miniruby.orig2
-miniruby.plhash
-miniruby.plhash2
-modex.rb
-newdate.rb
-newver.rb
-parse.c
-parse.y.try
-pitest.rb
-ppack
-rbconfig.rb
-rename2.h
-repack
-riscos
-rubicon
-ruby
-ruby-man.rd.gz
-rubyunit
-st.c.power
-this that
-tmp
-web
-y.output
-y.tab.c
diff --git a/COPYING b/COPYING
deleted file mode 100644
index 870a5f22d6..0000000000
--- a/COPYING
+++ /dev/null
@@ -1,56 +0,0 @@
-Ruby is copyrighted free software by Yukihiro Matsumoto <matz@netlab.jp>.
-You can redistribute it and/or modify it under either the terms of the GPL
-(see the file GPL), or the conditions below:
-
- 1. You may make and give away verbatim copies of the source form of the
- software without restriction, provided that you duplicate all of the
- original copyright notices and associated disclaimers.
-
- 2. You may modify your copy of the software in any way, provided that
- you do at least ONE of the following:
-
- a) place your modifications in the Public Domain or otherwise
- make them Freely Available, such as by posting said
- modifications to Usenet or an equivalent medium, or by allowing
- the author to include your modifications in the software.
-
- b) use the modified software only within your corporation or
- organization.
-
- c) give non-standard binaries non-standard names, with
- instructions on where to get the original software distribution.
-
- d) make other distribution arrangements with the author.
-
- 3. You may distribute the software in object code or binary form,
- provided that you do at least ONE of the following:
-
- a) distribute the binaries and library files of the software,
- together with instructions (in the manual page or equivalent)
- on where to get the original distribution.
-
- b) accompany the distribution with the machine-readable source of
- the software.
-
- c) give non-standard binaries non-standard names, with
- instructions on where to get the original software distribution.
-
- d) make other distribution arrangements with the author.
-
- 4. You may modify and include the part of the software into any other
- software (possibly commercial). But some files in the distribution
- are not written by the author, so that they are not under these terms.
-
- For the list of those files and their copying conditions, see the
- file LEGAL.
-
- 5. The scripts and library files supplied as input to or produced as
- output from the software do not automatically fall under the
- copyright of the software, but belong to whomever generated them,
- and may be sold commercially, and may be aggregated with this
- software.
-
- 6. THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
- IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- PURPOSE.
diff --git a/COPYING.ja b/COPYING.ja
deleted file mode 100644
index 933cc7cb9a..0000000000
--- a/COPYING.ja
+++ /dev/null
@@ -1,51 +0,0 @@
-$BK\%W%m%0%i%`$O%U%j!<%=%U%H%&%'%"$G$9!%(BGPL(the GNU General
-Public License)$B$^$?$O0J2<$K<($9>r7o$GK\%W%m%0%i%`$r:FG[I[$G(B
-$B$-$^$9!%(BGPL$B$K$D$$$F$O(BGPL$B%U%!%$%k$r;2>H$7$F2<$5$$!%(B
-
- 1. $BJ#@=$O@)8B$J$/<+M3$G$9!%(B
-
- 2. $B0J2<$N>r7o$N$$$:$l$+$rK~$?$9;~$KK\%W%m%0%i%`$N%=!<%9$r(B
- $B<+M3$KJQ99$G$-$^$9!%(B
-
- (a) $B%M%C%H%K%e!<%:$K%]%9%H$7$?$j!$:n<T$KJQ99$rAwIU$9$k(B
- $B$J$I$NJ}K!$G!$JQ99$r8x3+$9$k!%(B
-
- (b) $BJQ99$7$?K\%W%m%0%i%`$r<+J,$N=jB0$9$kAH?%FbIt$@$1$G(B
- $B;H$&!%(B
-
- (c) $BJQ99E@$rL@<($7$?$&$(!$%=%U%H%&%'%"$NL>A0$rJQ99$9$k!%(B
- $B$=$N%=%U%H%&%'%"$rG[I[$9$k;~$K$OJQ99A0$NK\%W%m%0%i(B
- $B%`$bF1;~$KG[I[$9$k!%$^$?$OJQ99A0$NK\%W%m%0%i%`$N%=!<(B
- $B%9$NF~<jK!$rL@<($9$k!%(B
-
- (d) $B$=$NB>$NJQ99>r7o$r:n<T$H9g0U$9$k!%(B
-
- 3. $B0J2<$N>r7o$N$$$:$l$+$rK~$?$9;~$KK\%W%m%0%i%`$r%3%s%Q%$(B
- $B%k$7$?%*%V%8%'%/%H%3!<%I$d<B9T7A<0$G$bG[I[$G$-$^$9!%(B
-
- (a) $B%P%$%J%j$r<u$1<h$C$??M$,%=!<%9$rF~<j$G$-$k$h$&$K!$(B
- $B%=!<%9$NF~<jK!$rL@<($9$k!%(B
-
- (b) $B5!3#2DFI$J%=!<%9%3!<%I$rE:IU$9$k!%(B
-
- (c) $BJQ99$r9T$C$?%P%$%J%j$OL>A0$rJQ99$7$?$&$(!$%*%j%8%J(B
- $B%k$N%=!<%9%3!<%I$NF~<jK!$rL@<($9$k!%(B
-
- (d) $B$=$NB>$NG[I[>r7o$r:n<T$H9g0U$9$k!%(B
-
- 4. $BB>$N%W%m%0%i%`$X$N0zMQ$O$$$+$J$kL\E*$G$"$l<+M3$G$9!%$?(B
- $B$@$7!$K\%W%m%0%i%`$K4^$^$l$kB>$N:n<T$K$h$k%3!<%I$O!$$=(B
- $B$l$>$l$N:n<T$N0U8~$K$h$k@)8B$,2C$($i$l$k>l9g$,$"$j$^$9!%(B
-
- $B$=$l$i%U%!%$%k$N0lMw$H$=$l$>$l$NG[I[>r7o$J$I$KIU$$$F$O(B
- LEGAL$B%U%!%$%k$r;2>H$7$F$/$@$5$$!%(B
-
- 5. $BK\%W%m%0%i%`$X$NF~NO$H$J$k%9%/%j%W%H$*$h$S!$K\%W%m%0%i(B
- $B%`$+$i$N=PNO$N8"Mx$OK\%W%m%0%i%`$N:n<T$G$O$J$/!$$=$l$>(B
- $B$l$NF~=PNO$r@8@.$7$??M$KB0$7$^$9!%$^$?!$K\%W%m%0%i%`$K(B
- $BAH$_9~$^$l$k$?$a$N3HD%%i%$%V%i%j$K$D$$$F$bF1MM$G$9!%(B
-
- 6. $BK\%W%m%0%i%`$OL5J]>Z$G$9!%:n<T$OK\%W%m%0%i%`$r%5%]!<%H(B
- $B$9$k0U;V$O$"$j$^$9$,!$%W%m%0%i%`<+?H$N%P%0$"$k$$$OK\%W(B
- $B%m%0%i%`$N<B9T$J$I$+$iH/@8$9$k$$$+$J$kB;32$KBP$7$F$b@U(B
- $BG$$r;}$A$^$;$s!%(B
diff --git a/ChangeLog b/ChangeLog
deleted file mode 100644
index 1d6f1cd299..0000000000
--- a/ChangeLog
+++ /dev/null
@@ -1,14933 +0,0 @@
-Thu Mar 21 01:11:37 2002 Usaku Nakamura <usa@ruby-lang.org>
-
- * win32/Makefile.sub (config.status): fix install path (prefix).
-
-Thu Mar 21 01:03:05 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * ext/configsub.rb: latest autoconf style support.
-
-Wed Mar 20 22:16:25 2002 Usaku Nakamura <usa@ruby-lang.org>
-
- * mkconfig.rb: close duplicated $stdout before renaming rbconfig.rb.
-
-Wed Mar 20 21:54:17 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * win32/Makefile.sub: made variables configurable.
-
- * win32/Makefile.sub (config.h): updates RUBY_PLATFORM from
- Makefile.
-
- * win32/Makefile.sub (config.status): ditto. and use recent
- autoconf format.
-
- * win32/Makefile.sub (clean): separate ext and local clean up.
-
- * win32/Makefile.sub (distclean): ditto.
-
- * win32/config.status.in: no longer used.
-
-Wed Mar 20 20:12:35 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * variable.c (rb_const_list): a temporary table must be freed.
-
-Wed Mar 20 19:44:09 2002 Tanaka Akira <akr@m17n.org>
-
- * mkconfig.rb: don't touch rbconfig.rb if there is a trouble.
-
-Wed Mar 20 16:05:37 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (is_defined): should check receiver only once.
-
- * eval.c (is_defined): should handle NODE_NEWLINE.
-
-Wed Mar 20 11:29:25 2002 Aristarkh A Zagorodnikov <xm@xml-objects.com>
-
- * file.c (rb_file_s_expand_path): memory leak fixed.
-
-Wed Mar 20 00:36:43 2002 Akinori MUSHA <knu@iDaemons.org>
-
- * util.c (ruby_getcwd): the content of buf is uncertain and must
- not be printed when getcwd(buf, size) has failed.
-
-Mon Mar 18 22:19:52 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * ext/stringio/stringio.c (check_modifiable): wrong declaration.
-
-Mon Mar 18 18:04:05 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * ext/digest: add depend file.
-
- * ext/digest/md5: ditto.
-
- * ext/digest/rmd160: ditto.
-
- * ext/digest/sha1: ditto.
-
- * ext/digest/sha2: ditto.
-
- * ext/iconv/MANIFEST: ditto.
-
- * ext/stringio/MANIFEST: ditto.
-
- * ext/syslog: ditto.
-
-Mon Mar 18 17:18:06 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * eval.c (rb_f_abort): should not bypass cleanup.
-
- * ext/stringio/stringio.c (check_modifiable): void function.
-
-Mon Mar 18 12:52:01 2002 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * ext/iconv/extconf.rb: workaround for GNU libiconv.
-
-Mon Mar 18 10:55:03 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * parse.y (parse_string): part of multi-byte sequence must not
- match to paren.
-
- * parse.y (parse_qstring): ditto.
-
- * parse.y (parse_quotedwords): ditto.
-
- * parse.y (str_extend): handle multi-byte characters.
-
-Mon Mar 18 10:31:20 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * enum.c (enum_find): catch a value before recycle.
-
- * enum.c (enum_all): ditto.
-
- * enum.c (enum_any): ditto.
-
- * enum.c (enum_min): ditto.
-
- * enum.c (enum_max): ditto.
-
-Sun Mar 17 20:08:04 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * ext/iconv/depend: added.
-
- * ext/stringio/depend: added.
-
-Sat Mar 16 22:43:53 2002 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * missing/fileblocks.c: add for autoconf.
-
-Sat Mar 16 15:30:40 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * re.c (rb_reg_search): should clear last_match if pos is out of
- string range.
-
- * string.c (rb_str_index_m): ditto.
-
- * string.c (rb_str_rindex): ditto.
-
-Sat Mar 16 09:04:58 2002 Koji Arai <JCA02266@nifty.ne.jp>
-
- * enum.c (enum_inject): use the first iterated element as the
- initial value when omitted.
-
- * enum.c (inject_i): ditto.
-
- * enum.c (Init_Enumerable): Enumerable#inject now takes variable
- count arguments.
-
-Fri Mar 15 19:47:31 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * win32/win32.c (StartSockets): remove duplicated lines.
-
-Fri Mar 15 17:44:08 2002 Usaku Nakamura <usa@ruby-lang.org>
-
- * bignum.c, intern.h (rb_ull2big, rb_ll2big, rb_ull2inum, rb_ll2inum,
- big2ull, rb_big2ull, rb_big2ll): use LONG_LONG macro instead of
- long long.
-
- * numeric.c, intern.h, ruby.h (rb_num2ll, rb_num2ull): ditto.
-
- * ruby.h: use _I64_MAX and _I64_MIN if they are defined (for VC++).
-
-Fri Mar 15 14:02:43 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * ext/iconv/iconv.c: fixed document, Iconv#new is no longer an
- iterator. thanks to Tanaka Akira <akr@m17n.org>.
-
-Thu Mar 14 22:17:45 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * ext/iconv: imported.
-
-Thu Mar 14 16:42:37 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * class.c (rb_define_class): should handle autoload.
-
- * class.c (rb_define_module): ditto.
-
-Thu Mar 14 16:18:12 2002 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * configure.in: autoconf 2.53 support. use AC_LIBOBJ.
-
-Thu Mar 14 00:29:12 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * re.c (rb_reg_match): should clear $~ if operand is nil.
-
- * re.c (rb_reg_match2): ditto.
-
-Thu Mar 14 12:32:59 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * ext/stringio/stringio.c: fixed frozen string bug. ungetc no
- longer raises on readonly stream unless modifies actually.
-
-Thu Mar 14 08:57:41 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * dir.c (rb_push_glob): avoid SEGV when a block given.
-
-Thu Mar 14 00:16:02 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * string.c (rb_str_subpat_set): must make str independent after
- rb_reg_search() matched.
-
-Wed Mar 13 19:05:15 2002 Akinori MUSHA <knu@iDaemons.org>
-
- * dir.c: FNM_PERIOD is obsoleted and FNM_DOTMATCH is introduced
- instead, which has the opposite meaning of FNM_PERIOD.
-
- * dir.c: Dir::glob now accepts optional FNM_* flags via the second
- argument, whereas Dir::[] doesn't.
-
-Wed Mar 13 18:36:55 2002 Akinori MUSHA <knu@iDaemons.org>
-
- * lib/getopts.rb: single_options can be nil[*], and is not not
- optional. ([*]Pointed out by gotoken)
-
-Wed Mar 13 17:23:46 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * configure: merge Jonathan Baker's large file support patch
- [ruby-talk:35316], with read_all patch in [ruby-talk:35470].
-
-Wed Mar 13 04:06:48 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_f_abort): optional message argument that be printed
- on termination.
-
-Tue Mar 12 17:12:06 2002 Tanaka Akira <akr@m17n.org>
-
- * lib/resolv.rb: don't complete domains for absolute FQNs.
-
-Mon Mar 11 23:08:48 2002 Tanaka Akira <akr@m17n.org>
-
- * lib/tsort.rb: new file.
-
-Mon Mar 11 21:03:37 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * ext/stringio: new.
-
-Mon Mar 11 18:03:37 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * regex.c (re_compile_pattern): '\0111' should be '\011' plus '1',
- since octal literals are formed by three digits at most.
-
-Mon Mar 11 14:44:38 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * marshal.c (w_object): module inclusion using extend() should
- also be detected.
-
- * eval.c (rb_eval_cmd): cbase should not be NULL; it should be
- either ruby_wrapper or Object.
-
-Sun Mar 10 02:18:22 2002 Koji Arai <jca02266@nifty.ne.jp>
-
- * enum.c (enum_each_with_index): should return self.
-
- * process.c (proc_setpgrp): should return value for non-void function.
-
- * process.c (proc_getpgid): should raise exception if getpgid() return -1.
-
- * string.c (rb_str_ljust): should return a duplicated string.
-
- * string.c (rb_str_rjust): ditto.
-
- * string.c (rb_str_center): ditto.
-
-Sat Mar 9 08:45:58 2002 Tanaka Akira <akr@m17n.org>
-
- * ext/socket/extconf.rb (have_struct_member): don't print checked
- result.
-
-Fri Mar 8 12:19:15 2002 Tanaka Akira <akr@m17n.org>
-
- * lib/resolv.rb: use its own thread group for background threads.
-
-Fri Mar 8 02:21:32 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (cvar_cbase): utility function to find innermost non
- singleton cbase.
-
- * eval.c (is_defined): adopt new cvar behavior.
-
- * eval.c (rb_eval): ditto.
-
- * eval.c (assign): ditto.
-
-Thu Mar 7 20:08:25 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * gc.c (rb_source_filename): added. holds unique strings for file
- names with GC space.
-
- * gc.c (rb_gc_mark): mark source file name.
-
- * gc.c (gc_sweep): ditto.
-
- * gc.c (Init_GC): initialize source file name table.
-
- * intern.h (rb_source_filename): added.
-
- * eval.c (rb_eval_string): use rb_source_filename().
-
- * parse.y (yycompile): ditto.
-
- * ruby.c (proc_options): ditto.
-
- * ruby.c (load_file): ditto.
-
- * ruby.c (ruby_script): ditto.
-
- * ruby.c (ruby_prog_init): ditto.
-
-Wed Mar 6 17:58:08 2002 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * dln.c (dln_load): use LoadLibrary instead of LoadLibraryEx.
-
-Wed Mar 6 16:50:37 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * class.c (rb_mod_clone): should not call rb_obj_clone(), since
- Module does not provide "allocate".
-
- * class.c (rb_singleton_class): should create new singleton class
- if obj is a class or module and attached object is different,
- which means metaclass of singleton class is sought.
-
- * time.c (time_s_alloc): now follows allocation framework.
-
-Tue Mar 5 05:56:29 2002 Akinori MUSHA <knu@iDaemons.org>
-
- * lib/getopts.rb: Rewrite to fix some bugs and complete features.
- - Accept options with the colon in the first argument;
- getopts("a:bcd:") is equivalent to getopts("bc", "a:", "d:").
- - Do not discard the argument that caused an error.
- - Do not discard '-', which commonly stands for stdin or stdout.
- - Allow specifying a long option with a value using '='.
- (command --long-option=value)
- - Stop reading options when it meets a non-option argument.
-
-Mon Mar 4 13:19:18 2002 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/extmk.rb.in (dir_config): Sync with mkmf.rb: Fix a bug where
- --with-xx-{include,lib} is ignored when --with-xx-dir is
- specified.
-
-Mon Mar 4 00:09:55 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_eval): should initialize outer class variables from
- methods in singleton class definitions.
-
- * eval.c (assign): ditto.
-
-Fri Mar 1 11:29:10 2002 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * ext/socket/{addinfo.h,getaddrinfo.c} (gai_strerror): add const
- qualifier only for uClibc.
-
-Fri Mar 1 11:22:51 2002 Amos Gouaux <amos+ruby@utdallas.edu>
-
- * lib/net/imap.rb: added document.
-
- * lib/net/imap.rb (getquotaroot): new method.
-
- * lib/net/imap.rb (setacl): remove the rights if the rights
- parameter is nil.
-
- * lib/net/imap.rb (getacl): return an array of MailboxACLItem.
-
-Fri Mar 1 06:25:49 2002 Tanaka Akira <akr@m17n.org>
-
- * ext/socket/extconf.rb (have_struct_member): new method.
- check msg_control and msg_accrights in struct msghdr. check
- sys/uio.h.
-
- * ext/socket/socket.c: include sys/uio.h if available.
- (thread_read_select): new function.
- (unix_send_io): ditto.
- (unix_recv_io): ditto.
- (unix_s_socketpair): ditto.
- (Init_socket): define UNIXSocket#send_io, UNIXSocket#recv_io,
- UNIXSocket.socketpair and UNIXSocket.pair.
-
- * dln.c (dln_load): fix typo.
-
-Wed Feb 27 16:30:50 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_mod_include): load modules in argument order.
-
- * st.c (st_init_table_with_size): num_bins should be prime numbers
- (no decrement).
-
- * st.c (rehash): ditto.
-
-Wed Feb 27 13:18:49 2002 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * io.c (READ_DATA_PENDING): uClibc support.
-
- * random.c (rand_init): ditto.
-
- * ext/socket/{addinfo.h,getaddrinfo.c} (gai_strerror): ditto.
-
-Wed Feb 27 07:05:17 2002 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/digest/sha2/sha2.c: Merge from rough. Fix a couple of
- off-by-one errors in Aaron Gifford's code.
-
- Obtained from: KAME via FreeBSD
- KAME PR: 393
- FreeBSD PR: kern/34242
-
-Wed Feb 27 03:36:47 2002 Koji Arai <jca02266@nifty.ne.jp>
-
- * ext/dbm/dbm.c (fdbm_select): 1.7 behavior.
-
- * ext/gdbm/gdbm.c (fgdbm_select): ditto.
-
- * ext/sdbm/sdbm.c (fsdbm_select): ditto.
-
- * ext/dbm/dbm.c (fdbm_delete): adopt Hash#delete behavior.
-
- * ext/sdbm/sdbm.c (fsdbm_delete): ditto.
-
- * ext/gdbm/gdbm.c: need not to dup key to the block.
-
- * ext/sdbm/sdbm.c : replace RuntimeError with SDBMError.
-
-Tue Feb 26 21:34:07 2002 Usaku Nakamura <usa@ruby-lang.org>
-
- * bignum.c (rb_big_2comp): void function cannot return any value.
-
-Tue Feb 26 16:52:12 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_f_missing): NoMethod error messages for true, false,
- nil must respond visibility like for other objects.
-
-Tue Feb 26 15:41:30 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_eval): call trace_func for if/while conditions.
-
- * marshal.c (r_object): separate r_regist from proc calling.
-
-Tue Feb 26 11:25:50 2002 akira yamada <akira@arika.org>
-
- * lib/uri/generic.rb: merge0 shuld return [oth, oth] if oth is
- absolute URI.
-
- * lib/uri/generic.rb: registry part must not be allowed for any
- schemes for the Internet. (RFC2396, section 3.2.2 and 3.2.1.)
-
-Mon Feb 25 21:22:41 2002 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/syslog/syslog.c: Merge from rough. Use SafeStringValue().
-
-Mon Feb 25 21:12:08 2002 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/syslog/syslog.c: Merge from rough. Turn Syslog into a
- module keeping backward compatibility intact.
-
-Mon Feb 25 19:35:48 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * sample/test.rb (system): test with scripts under the source
- directory.
-
-Mon Feb 25 15:14:01 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (method_inspect): should not dump core for unbound
- singleton methods.
-
- * object.c (rb_mod_to_s): better description.
-
-Mon Feb 25 13:32:13 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * lib/shell.rb (Shell::expand_path): relative to @cwd.
-
-Mon Feb 25 06:30:11 2002 Koji Arai <jca02266@nifty.ne.jp>
-
- * hash.c (env_select): should path the assoc list.
-
-Sun Feb 24 17:20:22 2002 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/digest/*/*.h: Merge from rough.
- - Avoid namespace pollution. (MD5_* -> rb_Digest_MD5_*, etc.)
-
-Sat Feb 23 21:12:13 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * process.c (rb_syswait): thread kludge; should be fixed to
- support native thread.
-
-Fri Feb 22 21:20:53 2002 Minero Aoki <aamine@loveruby.net>
-
- * lib/net/protocol.rb: set read_timeout dynamically.
-
- * lib/net/http.rb: @@newimpl is always true in the main trunk.
-
- * lib/net/http.rb: HTTP.port -> default_port
-
- * lib/net/http.rb: HTTPResponse.read_response_status ->
- read_status_line
-
-Fri Feb 22 19:56:15 2002 Usaku Nakamura <usa@ruby-lang.org>
-
- * win32/config.status.in: set LIBRUBY_SO.
-
-Fri Feb 22 03:34:38 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * bignum.c (get2comp): need to specify to carry or not.
-
- * io.c (rb_io_inspect): embed path info.
-
-Fri Feb 22 11:30:01 2002 Tanaka Akira <akr@m17n.org>
-
- * lib/prettyprint.rb: FillGroup implemented.
-
-Thu Feb 21 21:40:18 2002 Usaku Nakamura <usa@ruby-lang.org>
-
- * ext/extmk.rb.in (create_makefile): remove unnecessary -L option from
- LIBS macro.
-
-Thu Feb 21 02:49:12 2002 Koji Arai <jca02266@nifty.ne.jp>
-
- * pack.c (pack_pack): wrong # comment treatment.
-
- * pack.c (pack_unpack): ditto.
-
-Wed Feb 20 15:15:03 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * intern.h: prototypes; rb_io_addstr(), rb_io_printf(),
- rb_io_print(), rb_io_puts()
-
- * io.c (rb_io_addstr): make extern.
-
- * io.c (rb_io_printf): ditto.
-
- * io.c (rb_io_print): ditto.
-
- * io.c (rb_io_puts): ditto.
-
-Wed Feb 20 13:41:35 2002 Usaku Nakamura <usa@ruby-lang.org>
-
- * io.c (rb_io_close): return Qnil.
-
-Wed Feb 20 12:41:59 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * hash.c (rb_any_cmp): should handle Qundef in keys.
-
- * eval.c (remove_method): should not remove a empty method to
- implement "undef".
-
- * eval.c (rb_eval): should allow singleton class def for
- true/false/nil.
-
-Tue Feb 19 21:43:32 2002 Minero Aoki <aamine@loveruby.net>
-
- * lib/net/protocol.rb: rename Protocol.port to default_port.
-
- * lib/net/smtp.rb: ditto.
-
- * lib/net/pop.rb: ditto.
-
- * lib/net/http.rb: ditto.
-
- * lib/net/protocol.rb: rename BufferedSocket class to
- InternetMessageIO.
-
- * lib/net/smtp.rb: ditto.
-
- * lib/net/pop.rb: ditto.
-
- * lib/net/http.rb: ditto.
-
- * lib/net/protocol.rb: rename InternetMessageIO#write_pendstr to
- write_message.
-
- * lib/net/smtp.rb: ditto.
-
- * lib/net/protocol.rb: new method
- InternetMessageIO#through_message.
-
- * lib/net/smtp.rb: ditto.
-
- * lib/net/protocol.rb: rename InternetMessageIO#read_pendstr to
- read_message_to.
-
- * lib/net/pop.rb: ditto.
-
- * lib/net/protocol.rb: rename InternetMessageIO#read_pendlist to
- each_list_item
-
- * lib/net/pop.rb: ditto.
-
- * lib/net/protocol.rb: Now block size is 1024.
-
- * lib/net/smtp.rb: new methods SMTP#esmtp? and #esmtp=.
-
- * lib/net/http.rb: Using singleton method syntax instead of
- singleton class clause, to avoid behavior change of class
- variables in ruby 1.7.
-
- * lib/net/http.rb: HTTPResponse class does not inherit from
- Net::Response.
-
- * lib/net/http.rb: devide HTTP#connecting into
- {begin,end}_transport.
-
- * lib/net/http.rb: unused class Accumulator removed.
-
- * lib/net/http.rb: Net::HTTP reads response. not HTTPRequest.
-
- * lib/net/http.rb: proxy related class-instance-variables are not
- initialized correctly.
-
-Tue Feb 19 20:20:12 2002 Ed Sinjiashvili <edsin@swes.saren.ru>
-
- * parse.y (str_extend): backslash escape was done wrong.
-
-Tue Feb 19 17:10:25 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * file.c (path_check_1): do not fail on world writable *parent*
- directories too.
-
-Tue Feb 19 15:51:41 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * file.c (path_check_1): do not warn on world writable *parent*
- directories.
-
- * class.c (rb_include_module): should preserve ancestor order in
- the included class/module.
-
-Tue Feb 19 14:45:32 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * file.c (path_check_1): should check directory sticky bits.
-
- * process.c (security): need not to warn twice.
-
- * marshal.c (r_object): complete restoration before calling
- r_regist().
-
-Tue Feb 19 14:24:36 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (yylex): operators in the "op" rule should make
- lex_state EXPR_ARG on EXPR_FNAME and EXPR_DOT.
-
-Tue Feb 19 13:38:10 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_eval_string_wrap): should hide the toplevel local
- variable bindings by PUSH_SCOPE().
-
-Tue Feb 19 13:21:51 2002 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * regex.c: fix prototypes of xmalloc(), xcalloc() and xrealloc().
-
-Tue Feb 19 13:16:08 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * io.c (rb_io_ungetc): don't fail pushed EOF back.
-
-Mon Feb 18 20:48:40 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * pack.c (pack_pack): avoid infinite loop at comment.
-
- * pack.c (pack_unpack): ditto.
-
-Mon Feb 18 14:06:28 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * misc/ruby-mode.el (ruby-block-hanging-re): rescue block was too
- indented.
-
-Mon Feb 18 13:56:44 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (expr_value, arg_value, primary_value): value_expr()
- check in place.
-
- * eval.c (block_pass): "&nil" should clear block given.
-
-Mon Feb 18 02:05:56 2002 Wolfgang Jahrling <wolfgang@pro-linux.de>
-
- * dir.c (push_braces): remove MAXPATHLEN dependency.
-
- * dir.c (dir_s_globd): ditto.
-
- * dln.c (init_funcname): ditto.
-
- * dln.c (load_1): ditto.
-
- * dln.c (dln_load): ditto.
-
- * configure.in: add GNU/Hurd switches.
-
-Fri Feb 15 17:44:26 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * pack.c (pack_pack): allows comment in template strings.
-
- * pack.c (pack_unpack): ditto.
-
-Sun Feb 17 23:41:37 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * mkconfig.rb (Config::expand): expand ${} too.
-
- * ext/extmk.rb.in (try_link0): expand command.
-
- * ext/extmk.rb.in (try_cpp): ditto.
-
- * ext/extmk.rb.in (extmake): default $LIBPATH to $libdir
-
-Sun Feb 17 21:39:24 2002 Tetsuya Watanabe <tetsuya.watanabe@nifty.com>
-
- * ext/digest/md5/md5init.c (Init_md5): rb_cvar_declare() is
- replaced by rb_cvar_set().
-
- * ext/digest/rmd160/rmd160init.c (Init_rmd160): ditto.
-
- * ext/digest/sha1/sha1init.c (Init_sha1): ditto.
-
- * ext/digest/sha2/sha2init.c (Init_sha2): ditto.
-
-Sun Feb 17 18:10:09 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * class.c (rb_define_class): warn unless superclass is specified
- explicitly.
-
- * class.c (rb_define_class_under): ditto.
-
-Thu Feb 16 02:11:08 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * misc/ruby-mode.el (ruby-font-lock-keywords): fontify
- instance/class/global variables start with '_'.
-
-Fri Feb 15 14:40:38 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_eval): replace rb_cvar_declare() by rb_cvar_set().
-
- * eval.c (assign): ditto.
-
- * variable.c (rb_cvar_set): 4th argument (warn) added; define new
- class variable if it's not defined yet.
-
- * variable.c (rb_cvar_declare): removed.
-
-Fri Feb 15 13:36:58 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * bignum.c (rb_big_rshift): should properly convert the nagative
- value to 2's compliment.
-
-Thu Feb 14 17:38:35 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * parse.y: avoid SEGV at OP_ASIGN to pseudo variable.
-
-Thu Feb 14 14:13:16 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * struct.c (Init_Struct): should undefine "allocate" for Struct
- class (it's redefined in the subclasses).
-
-Wed Feb 13 17:58:12 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (stmt): local variable declaration order was changed
- since 1.6
-
- * parse.y (arg): ditto.
-
- * pack.c (pack_pack): add templates 'q' and 'Q'.
-
- * pack.c (pack_unpack): ditto.
-
- * bignum.c (rb_quad_pack): new utility function.
-
- * bignum.c (rb_quad_unpack): ditto.
-
-Tue Feb 12 01:21:34 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (assignable): should emit CVASGN within the method
- body.
-
-Mon Feb 11 06:13:53 2002 Matt Armstrong <matt@lickey.com>
-
- * dir.c (dir_s_glob): should not warn even if no match found.
-
-Mon Feb 11 04:25:54 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_eval): clean up class variable behavior.
-
- * eval.c (assign): ditto.
-
- * eval.c (is_defined): ditto.
-
- * variable.c (rb_mod_class_variables): need not to call rb_cvar_singleton().
-
- * variable.c (rb_cvar_singleton): removed.
-
-Mon Feb 11 00:10:41 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * regex.c (re_compile_fastmap): skip begpos.
-
-Sun Feb 10 16:52:53 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * ruby.c (load_file): avoid SEGV on '#' only input.
-
-Fri Feb 8 23:07:23 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_eval): singleton chech should be moved from yycompile
- to here.
-
- * eval.c (is_defined): check should be added here too.
-
-Fri Feb 8 05:31:48 2002 Minero Aoki <aamine@loveruby.net>
-
- * lib/net/http.rb: HTTP.Proxy should use self for proxy-class's
- super class.
-
- * lib/net/http.rb: initialize HTTP.proxy_port by HTTP.port.
-
-Fri Feb 8 01:27:33 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (yycompile): should inherit "in_single" if eval happened
- in a singleton method.
-
- * eval.c (rb_eval): class variables from singleton methods defined
- within singleton class statement should work like ones defined
- by sington def statements.
-
-Thu Feb 07 13:44:08 2002 akira yamada <akira@arika.org>
-
- * uri/common.rb (URI::join): new method.
-
- * uri/generic.rb (Generic#merge): URI.parse("http://a/")+"b" should
- return "http://a/b" but it returned "http://a//b".
-
- * uri/generic.rb (Generic#check_path): corrected error message,
- @path -> v
-
-Thu Feb 7 00:18:43 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (io_write): flag when buffered write is done.
-
- * io.c (fptr_finalize): do not raise error on EBADF if write
- buffer is empty.
-
-Wed Feb 6 17:18:54 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * configure.in: keep old config.h unless changed.
-
-Wed Feb 6 13:28:53 2002 Amos Gouaux <amos+ruby@utdallas.edu>
-
- * lib/net/imap.rb: OpenSSL support.
-
- * lib/net/imap.rb (setquota): unset quota if the second argument
- is nil.
-
-Wed Feb 6 13:05:11 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (rb_io_readlines): avoid calling GetOpenFile() repeatedly.
-
- * io.c (rb_io_each_line): ditto.
-
- * io.c (argf_getline): ditto.
-
- * process.c: should include <time.h> to get proper CLK_TCK.
-
-Wed Feb 6 02:10:30 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * io.c (fptr_finalize): ignore EBADF when f and f2 use same
- descriptor.
-
-Tue Feb 5 16:17:20 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (fptr_finalize): should raise error when fclose fails.
-
- * eval.c (method_inspect): proper output format to distinguish
- methods and singleton methods.
-
-Mon Feb 4 22:44:58 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * file.c (rb_file_s_expand_path): should terminate.
-
-Mon Feb 4 15:38:29 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * object.c (rb_class_real): should not follow ICLASS link
-
- * variable.c (classname): should follow ICLASS link explicitly.
-
- * eval.c (rb_call): ditto.
-
-Fri Feb 1 19:10:04 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * intern.h: prototypes for new functions; rb_cstr_to_inum(),
- rb_str_to_inum(), rb_cstr_to_dbl(), rb_str_to_dbl()
-
- * bignum.c (rb_cstr_to_inum): changed from rb_cstr2inum(), and
- added argument badcheck to be consistent with parser. [new]
-
- * bignum.c (rb_str_to_inum): ditto.
-
- * bignum.c (rb_cstr2inum): wapper of rb_cstr_to_inum() now.
-
- * bignum.c (rb_str2inum): ditto.
-
- * object.c (rb_cstr_to_dbl): float number parser. [new]
-
- * object.c (rb_str_to_dbl): ditto.
-
- * object.c (rb_Float): use rb_cstr_to_dbl() for strict check.
-
- * object.c (rb_Integer): use rb_str_to_inum() for strict check.
-
- * string.c (rb_str_to_f): use rb_str_to_dbl() with less check.
-
- * string.c (rb_str_to_i): use rb_str_to_inum() with less check.
-
- * string.c (rb_str_hex): ditto.
-
- * string.c (rb_str_oct): ditto.
-
- * sprintf.c (rb_f_sprintf): ditto.
-
- * time.c (obj2long): ditto.
-
- * parse.y (yylex): use rb_cstr_to_inum() for strict check.
-
-Fri Feb 1 17:46:39 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * regex.c (mbc_startpos): become macro.
-
- * regex.c (euc_startpos): added for improvement.
-
- * regex.c (sjis_startpos): ditto.
-
- * regex.c (utf8_startpos): ditto.
-
-Fri Feb 1 00:03:30 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * file.c (rb_stat_inspect): print dev, rdev in hexadecimal.
-
-Thu Jan 31 20:45:33 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * lib/mkmf.rb (dir_config): prior --with flag.
-
- * lib/mkmf.rb (arg_config): avoid special variables for
- font-lock-mode.
-
-Thu Jan 31 13:22:36 2002 Tanaka Akira <akr@m17n.org>
-
- * lib/pp.rb (File::Stat#pretty_print): print rdev_major and rdev_minor.
-
-Wed Jan 30 15:58:04 2002 K.Kosako <kosako@sofnec.co.jp>
-
- * regex.c (re_adjust_startpos): fix for SJIS and UTF-8.
-
- * regex.c (mbc_startpos): ditto.
-
-Wed Jan 30 13:37:05 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * re.c (rb_reg_search): should set regs.allocated.
-
-Wed Jan 30 02:25:38 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * regex.c (re_adjust_startpos): search start of multibyte
- backward.
-
- * regex.c (mbc_startpos): ditto.
-
-Tue Jan 29 17:59:20 2002 Tanaka Akira <akr@m17n.org>
-
- * file.c: `major' and `minor' macro needs sys/mkdev.h on SunOS 5.x.
-
- * configure.in: add check for `sys/mkdev.h'.
-
- * lib/pp.rb: don't print a mode File::Stat as decimal number.
-
-Mon Jan 28 19:16:58 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * array.c (rb_ary_fill): shouldn't yield unless block given.
-
-Mon Jan 28 18:33:18 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * parse.y (yylex): strict check for numbers.
-
-Mon Jan 28 18:01:01 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * file.c (rb_stat_rdev_major): added. [new]
-
- * file.c (rb_stat_rdev_minor): added. [new]
-
- * file.c (rb_stat_inspect): print mode in octal.
-
-Mon Jan 28 13:29:41 2002 K.Kosako <kosako@sofnec.co.jp>
-
- * eval.c (is_defined): defined?(Foo::Baz) should check constants
- only, no methods.
-
- * eval.c (is_defined): should not dump core on defined?(a::b)
- where a is not a class nor a module.
-
-Mon Jan 28 02:50:12 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * object.c (Init_Object): remove dup and clone from TrueClass,
- FalseClass, and NilClass.
-
- * array.c (rb_ary_fill): Array#fill takes block to get the value to
- fill.
-
-Sat Jan 26 20:05:18 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_to_i): to_i(0) auto-detects base radix.
-
- * array.c (rb_ary_initialize): fill by the block evaluation value
- if block is given.
-
-Fri Jan 25 17:48:43 2002 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * configure.in (solaris): add '-shared' only for GNU ld.
-
-Fri Jan 25 17:16:23 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * class.c (rb_include_module): detect cyclic module inclusion.
-
-Fri Jan 25 02:17:56 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_thread_cleanup): need not to free thread stacks at
- process termination.
-
- * array.c (rb_ary_fetch): use the block to get the default value
- if the block is given.
-
- * eval.c (rb_thread_schedule): should check time only if BOTH
- WAIT_SELECT and WAIT_TIME.
-
-Thu Jan 24 11:49:05 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (umethod_bind): should update rklass field.
-
- * hash.c (rb_hash_update): if a block is given, yields [key,
- value1, value2] to the block to resolve conflict.
-
-Thu Jan 24 05:42:01 2002 Koji Arai <jca02266@nifty.ne.jp>
-
- * string.c (rb_str_split_m): no need to consider KANJI
- characters, if the length of separator is 1 (byte).
-
-Wed Jan 23 16:07:31 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * array.c (Init_Array): remove Array#filter.
-
-Wed Jan 23 13:27:44 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * eval.c (rb_yield_0): restore source file/line after yield.
-
-Wed Jan 23 02:00:14 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * object.c (rb_mod_initialize): should accept zero argument.
-
- * object.c (rb_mod_cmp): should raise ArgumentError if
- inheritance/inclusion relation between two classes/modules is
- not defined. [new]
-
-Tue Jan 22 17:45:23 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (rb_io_fsync): new method. [new]
-
-Mon Jan 21 22:57:18 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * signal.c (ruby_signal): must define sighandler_t for every
- occasion.
-
-Mon Jan 21 08:25:30 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (ruby_stop): should not trace error handler.
-
- * signal.c (install_sighandler): do not install sighandler unless
- the old value is SIG_DFL.
-
- * io.c (io_write): should not raise exception on O_NONBLOCK io.
-
- * dir.c (dir_set_pos): seek should return dir, pos= should not.
-
-Sat Jan 19 02:31:45 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_eval): need not to clar method cache for NODE_CLASS,
- NODE_SCLASS.
-
- * gc.c (obj_free): need not to clear method cache on class/module
- finalization.
-
-Fri Jan 18 23:38:03 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * array.c (rb_ary_fetch): index out of range raises exception
- unless optional second argument is specified.
-
-Fri Jan 18 17:32:09 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (rb_io_s_new): block check moved from initialize to this
- method.
-
- * io.c (rb_io_s_open): open should call initialize too. IO#for_fd
- also calls initialize. [new]
-
-Fri Jan 18 10:26:33 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * error.c (rb_sys_fail): replace INT2FIX() by INT2NUM() since
- errno value may not fit in Fixnum size on Hurd.
-
- * error.c (set_syserr): ditto.
-
-Fri Jan 18 10:12:00 2002 Usaku Nakamura <usa@ruby-lang.org>
-
- * ext/socket/socket.c (tcp_svr_s_open): fix typo.
-
-Fri Jan 18 02:27:48 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * dir.c (dir_s_glob): returns nil if block given.
-
- * io.c (rb_io_each_byte): should return self.
-
- * io.c (rb_io_close_m): close check added.
-
- * dir.c (dir_seek): should return pos.
-
-Fri Jan 18 01:21:53 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (fixpos): orig may be (NODE*)1, which should not be
- dereferenced.
-
-Thu Jan 17 16:21:42 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (block_pass): allow "retry" from within argument passed
- block. [new]
-
- * eval.c (localjump_error): should preserve exit status in the
- exception object. [new]
-
- * eval.c (proc_invoke): should raise exception for "break" if it's
- yielding, not calling. [new]
-
- * eval.c (block_pass): should NOT raise exception for "break". [new]
-
- * eval.c (block_pass): should allow block argument relay even in
- the tainted mode.
-
-Thu Jan 17 04:51:48 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ext/socket/socket.c: support subclassing by proper "initialize"
- calling convention. [new]
-
-Wed Jan 16 18:25:08 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * st.c: primes should be primes.
-
-Wed Jan 16 12:29:14 2002 Tanaka Akira <akr@m17n.org>
-
- * lib/timeout.rb (timeout): new optional argument to specify an
- exception class.
-
- * lib/resolv.rb: use Resolv::ResolvTimeout for internal timeout to
- avoid problem with timeout of application.
-
-Wed Jan 16 11:12:30 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * object.c (rb_Float): remove underscores between digits.
-
- * bignum.c (rb_cstr2inum): reject prefix followed by spaces only.
-
- * class.c (rb_class_inherited): should use Object when no super
- class.
-
-Tue Jan 15 01:11:44 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (is_defined): method defined? check should honor
- protected too.
-
-Mon Jan 14 13:06:02 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (block_pass): should not pass tainted block, if $SAFE > 0.
-
-Sun Jan 13 09:31:41 2002 Koji Arai <jca02266@nifty.ne.jp>
-
- * variable.c (rb_mod_remove_cvar): should pass the char*.
-
-Fri Jan 11 05:06:25 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * class.c (rb_make_metaclass): [new]
-
- * class.c (rb_define_class_id): use rb_make_metaclass(), don't
- call Class#inherited hook.
-
- * class.c (rb_class_inherited): [new]
-
- * class.c (rb_define_class): call Class#inherited hook here.
-
- * class.c (rb_define_class_under): ditto after class path is set.
-
- * class.c (rb_singleton_class): use rb_make_metaclass().
-
- * eval.c (rb_eval): same as rb_define_class_under().
-
- * intern.h: prototypes of rb_make_metaclass() and
- rb_class_inherited().
-
- * object.c (rb_class_s_new): use rb_make_metaclass() and
- rb_class_inherited().
-
- * object.c (Init_Object): use rb_make_metaclass().
-
- * struct.c (make_struct): use rb_class_inherited().
-
-Thu Jan 10 19:15:15 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * eval.c (rb_add_method): should clear cache by id always.
-
- * eval.c (rb_disable_super): no longer need to clear cache before
- rb_add_method().
-
- * eval.c (rb_export_method): ditto.
-
- * eval.c (rb_attr): ditto.
-
- * eval.c (rb_undef): ditto.
-
- * eval.c (rb_eval): ditto.
-
- * eval.c (rb_mod_modfunc): ditto.
-
- * eval.c (rb_mod_define_method): ditto.
-
-Thu Jan 10 11:42:47 2002 Usaku Nakamura <usa@ruby-lang.org>
-
- * win32/resource.rb: Modify copyright in resource script.
-
-Thu Jan 10 07:15:44 2002 takuma ozawa <metal@mine.ne.jp>
-
- * re.c (match_select): should propagate taintness.
-
-Thu Jan 10 00:54:57 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * hash.c (rb_hash_set_default): Hash#default= should return the
- new value.
-
-Wed Jan 9 20:21:09 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * misc/ruby-mode.el (ruby-calculate-indent): indentation after
- comment at beginning of buffer failed.
-
- * misc/ruby-mode.el (font-lock-defaults): unless XEmacs, set
- font-lock variables in ruby-mode-hook.
-
-Tue Jan 8 15:56:20 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_to_i): accepts optional base argument. [new]
-
- * numeric.c (rb_fix2str): should not handle negative fixnum values
- int32 via calling sprintf() directly.
-
-Tue Jan 8 15:54:02 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * eval.c (rb_add_method): clear replaced method from the cache.
-
-Mon Jan 7 12:38:47 2002 Tanaka Akira <akr@m17n.org>
-
- * lib/time.rb (Time#xmlschema): new optional argument
- fractional_seconds to specify a number of digits of
- fractional part of the time.
-
-Sat Jan 5 13:18:11 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * range.c (range_member): beginning check was
- wrong. [ruby-talk:30252]
-
-Sat Jan 5 03:07:34 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_new2): NULL pointer check added.
-
-Sat Jan 5 00:19:12 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * parse.y (yycompile): strdup()'ed twice.
-
-Fri Jan 4 18:29:10 2002 Michal Rokos <m.rokos@sh.cvut.cz>
-
- * class.c (rb_define_module_under): should locate predefined
- module using rb_const_defined_at().
-
-Fri Jan 4 17:23:49 2002 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * misc/ruby-mode.el (ruby-forward-string): forward a string. [new]
-
- * misc/ruby-mode.el (ruby-parse-region): handle nested parentheses
- in a string and terminators in #{}.
-
- * misc/ruby-mode.el (ruby-calculate-indent): ditto.
-
-Wed Jan 2 23:34:25 2002 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * lib/mkmf.rb (create_makefile): add -I. to CPPFLAGS.
-
- * lib/mkmf.rb (create_makefile): srcdir support(.def and depend file).
-
-Wed Jan 2 11:51:56 2002 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * process.c (rb_f_system): abandon vfork.
-
- * io.c (pipe_open): ditto.
-
-Tue Jan 1 02:16:48 2002 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * ext/curses/extconf.rb: add dir_config.
-
- * Makefile.in (fake.rb): set RUBY_VERSION.
-
-Mon Dec 31 14:20:46 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * parse.y (yycompile): always store copy of filename.
-
- * parse.y (rb_compile_file): no longer need to strdup() here.
-
-Mon Dec 31 05:26:40 2001 Ferris McCormick <fmccor@inforead.com>
-
- * defines.h: sparc linux needs different FLUSH_REGISTER_WINDOWS
-
-Mon Dec 31 04:27:28 2001 Minero Aoki <aamine@mx.edit.ne.jp>
-
- * lib/net/protocol.rb: Protocol#start returns the return value of
- block.
-
- * lib/net/protocol.rb: set timeout limit by default.
-
- * lib/net/protocol.rb: new methods WriteAdapter#write, puts,
- print, printf.
-
- * lib/net/http.rb: rename HTTP#get2 to request_get, post2 to
- request_post ...
-
- * lib/net/smtp.rb: should not resolve HELO domain automatically.
-
-Sun Dec 30 00:59:16 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * ext/extmk.rb.in, lib/mkmf.rb (have_library): accept -lm
- unconditionally on mswin32/mingw32.
-
-Sat Dec 29 01:55:42 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * regex.c (re_search): abandon stclass optimization.
-
-Fri Dec 28 14:39:05 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * array.c (rb_cmpint): fixed typo.
-
-Thu Dec 27 18:43:04 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * bignum.c (rb_cstr2inum): deny "0_".
-
-Thu Dec 27 01:54:02 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * bignum.c (rb_cstr2inum): allow "0\n" and so on.
-
-Wed Dec 26 19:24:21 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * error.c (rb_invalid_str): utility function to show inspect()'ed
- string.
-
- * bignum.c (rb_cstr2inum): prints invalid strings in inspect()'ed
- format.
-
- * object.c (rb_Float): ditto.
-
-Wed Dec 26 02:41:29 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * object.c (rb_convert_type): no longer use rb_rescue().
-
-Tue Dec 25 18:32:16 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * re.c (rb_reg_search): initialize taint status of match object.
-
-Tue Dec 25 02:37:49 2001 Tanaka Akira <akr@m17n.org>
-
- * lib/pp.rb, lib/prettyprint.rb: new files.
-
-Tue Dec 25 02:11:17 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * object.c (rb_convert_type): check method responce check before
- invoking rb_rescue().
-
- * object.c (rb_check_convert_type): ditto.
-
-Mon Dec 24 02:37:40 2001 Le Wang <lewang@bigfoot.com>
-
- * misc/ruby-mode.el (ruby-font-lock-syntactic-keywords):
- fix font-lock problem [ruby-talk:29296].
-
-Sat Dec 22 22:52:14 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * time.c (time_timeval): wrong cast to time_t.
-
- * time.c (time_plus): ditto.
-
-Fri Dec 21 20:33:34 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * parse.y (str_extend): make up "#$;" handling.
-
-Fri Dec 21 16:18:17 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * dln.h, ruby.h, util.h: enable prototypes in C++.
-
-Fri Dec 21 15:12:41 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * time.c (time_plus): result should not be negative unless
- NEGATIVE_TIME_T is defined.
-
- * time.c (time_new_internal): should check tv_sec overflow too.
-
- * time.c (time_timeval): should check time_t range when time is
- initialized from float.
-
- * time.c (time_plus): uses modf(3).
-
-Fri Dec 21 03:15:52 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * eval.c (rb_mod_define_method): must not convert Method to Proc.
-
-Fri Dec 21 01:17:57 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * lib/mkmf.rb (with_destdir): new.
-
- * lib/mkmf.rb: prefix target directories with $(DESTDIR) all.
-
- * lib/mkmf.rb: no need to mkdir $(libdir)
-
-Thu Dec 20 14:08:20 2001 Minero Aoki <aamine@loveruby.net>
-
- * lib/net/protocol.rb: rename Net::Socket to Net::BufferedSocket
-
-Thu Dec 20 13:51:52 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * variable.c (rb_cvar_set): add frozen class/module check.
-
- * variable.c (rb_cvar_declare): add frozen class/module check.
-
-Thu Dec 20 01:01:50 2001 takuma ozawa <metal@mine.ne.jp>
-
- * re.c (match_to_a): should propagate taint.
-
- * re.c (rb_reg_s_quote): ditto.
-
-Wed Dec 19 16:58:29 2001 Shugo Maeda <shugo@ruby-lang.org>
-
- * ext/readline/readline.c: new methods
- Readline::basic_word_break_characters,
- Readline::basic_word_break_characters=,
- Readline::completer_word_break_characters,
- Readline::completer_word_break_characters=,
- Readline::basic_quote_characters,
- Readline::basic_quote_characters=,
- Readline::completer_quote_characters,
- Readline::completer_quote_characters=,
- Readline::filename_quote_characters,
- Readline::filename_quote_characters=.
-
-Wed Dec 19 14:05:00 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_mod_define_method): define_method should follow
- default method visibility.
-
- * eval.c (rb_attr): should warn if the default method visibility
- is "module_function" (can be error).
-
- * eval.c (rb_mod_define_method): should define class/module method
- also if the visibility is "module_function".
-
- * eval.c (rb_mod_define_method): should call hook method
- "method_added", and "singleton_method_added".
-
-Wed Dec 19 11:42:13 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * string.c: use RESIZE_CAPA for capacity change.
-
-Wed Dec 19 03:08:40 2001 Tanaka Akira <akr@m17n.org>
-
- * lib/time.rb: date.rb is not required anymore.
-
- * lib/resolv.rb: fix document. refine IPv6 regex.
-
-Tue Dec 18 23:24:53 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ext/socket/socket.c (Init_socket): add listen method to
- TCPServer and UNIXServer.
-
-Tue Dec 18 17:54:53 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * sample/test.rb: Hash#indexes -> Hash#select.
-
-Tue Dec 18 01:02:13 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_thread_schedule): should not select a thread which is
- not yet initialized.
-
-Mon Dec 17 18:53:49 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * string.c (rb_str_replace): swap arguments of OBJ_INFECT.
-
-Mon Dec 17 16:52:20 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * intern.h: add prototypes.
- rb_gc_enable(), rb_gc_disable(), rb_gc_start(), rb_str_new5()
- rb_str_buf_append(), rb_str_buf_cat(), rb_str_buf_cat2(),
- rb_str_dup_frozen()
-
- * ruby.h: added declaration.
- rb_defout, rb_stdin, rb_stdout, rb_stderr, ruby_errinfo
-
- * rubyio.h: changed double include guard macro to RUBYIO_H.
-
- * array.c (inspect_call): make static.
-
- * eval.c (dvar_asgn): ditto.
-
- * io.c (rb_io_close_read): ditto.
-
- * lex.c (rb_reserved_word): ditto.
-
- * ruby.c: (req_list_head, req_list_last): ditto.
-
- * ruby.c (require_libraries): ditto.
-
-Mon Dec 17 15:41:24 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * time.c (time_plus): wrong boundary check.
-
- * time.c (time_minus): ditto.
-
-Mon Dec 17 15:19:32 2001 Tanaka Akira <akr@m17n.org>
-
- * time.c: new method `gmtoff', `gmt_offset' and `utc_offset'.
- (time_utc_offset): new function.
- (Init_Time): bind above methods to `time_utc_offset'.
-
- * time.c: 64bit time_t support.
- (time_s_at): use NUM2LONG instead of NUM2INT for tv_sec.
- (time_arg): initialize tm_isdst correctly.
- use long to initialize tm_year.
- (search_time_t): renamed from `make_time_t'.
- (make_time_t): call `timegm' and `mktime' instead of `search_time_t'
- if available.
- (time_to_i): use LONG2NUM instead of INT2NUM.
- (time_localtime): check localtime failure.
- (time_gmtime): check gmtime failure.
- (time_year): use LONG2NUM instead of INT2FIX.
- (time_to_a): use long for tm_year.
- (time_dump): check tm_year which is not representable with 17bit.
- (time_load): initialize tm_isdst.
-
- * configure.in: check existence of `mktime' and `timegm'.
- check existence of tm_gmtoff field of struct tm.
- fix negative time_t for 64bit time_t.
-
- * missing/strftime.c: fix overflow by tm_year + 1900.
-
- * lib/time.rb: use Time#utc_offset.
-
-Mon Dec 17 00:02:04 2001 Guy Decoux <ts@moulon.inra.fr>
-
- * variable.c (find_class_path): should initialize iv_tbl if it's
- NULL.
-
-Fri Dec 14 04:23:36 2001 Minero Aoki <aamine@loveruby.net>
-
- * lib/net/pop.rb: new method Net::POP3.APOP
-
- * lib/net/http.rb: set default Content-Type to
- x-www-form-urlencoded (causes warning)
-
- * lib/net/protocol.rb: remove Net::NetPrivate module.
-
- * lib/net/smtp.rb: ditto.
-
- * lib/net/pop.rb: ditto.
-
- * lib/net/http.rb: ditto.
-
-Fri Dec 14 00:16:06 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * class.c (rb_define_class): should return the existing class if
- the class is already defined and its superclass is ideintical to
- the specified superclass.
-
- * class.c (rb_define_class_under): ditto.
-
- * class.c (rb_define_module): should return the existing module if
- the module is already defined.
-
-Thu Dec 13 09:52:59 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * time.c (time_new_internal): avoid loop to calculate negative
- div, mod.
-
- * time.c (time_cmp): should handle Bignums.
-
-Tue Dec 11 17:39:16 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * array.c (rb_ary_pop): should ELTS_SHARED flag check before
- REALLOC.
-
-Tue Dec 11 12:45:28 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_match_m): should convert an argument into
- regexp if it's a string.
-
-Tue Dec 11 03:40:23 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * array.c (rb_ary_select): Array#select(n,m,...) now works like
- Array#indexes(n,m,..). [new, experimental]
-
- * hash.c (rb_hash_select): ditto.
-
- * hash.c (env_select): ditto.
-
- * re.c (match_select): ditto.
-
- * struct.c (rb_struct_select): ditto.
-
-Tue Dec 11 03:17:19 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * object.c (rb_class_real): follow included modules.
-
-Mon Dec 10 23:37:51 2001 Usaku Nakamura <usa@ruby-lang.org>
-
- * util.h: change prototype of ruby_qsort() to accord with its
- definition.
-
-Mon Dec 10 20:30:01 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * gc.c (STR_ASSOC): use FL_USER3 instead of FL_USER2.
-
-Mon Dec 10 17:40:02 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * parse.y (str_extend): make up pushback call.
-
-Mon Dec 10 02:09:28 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * array.c (rb_ary_modify): should copy the internal buffer if the
- modifying buffer is shared.
-
- * array.c (ary_make_shared): make an internal buffer of an array
- to be shared.
-
- * array.c (rb_ary_shift): avoid sliding an internal buffer by
- using shared buffer.
-
- * array.c (rb_ary_subseq): avoid copying the buffer.
-
-Mon Dec 10 01:06:56 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (gettable): should freeze __FILE__ string.
-
-Sun Dec 9 18:06:26 2001 Minero Aoki <aamine@loveruby.net>
-
- * lib/net/protocol.rb: calls on_connect before conn_command
-
-Sat Dec 8 23:27:44 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (rb_io_puts): old behavoir restored. rationale: a) if you
- want to call to_s for arrays, you can just call print a, "\n".
- b) to_s wastes memory if array (and sum of its contents) is
- huge. c) now any object that has to_ary is treated as an array,
- using rb_check_convert_type().
-
-Sat Dec 8 22:40:38 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * hash.c (rb_hash_initialize): now accepts a block to calculate
- the default value. [new]
-
- * hash.c (rb_hash_aref): call "default" method to get the value
- corrensponding to the non existing key.
-
- * hash.c (rb_hash_default): get the default value based on the
- block given to 'new'. Now it takes an optinal "key" argument.
- "default" became the method to get the value for non existing
- key. Users may override "default" method to change the hash
- behavior.
-
- * hash.c (rb_hash_set_default): clear the flag if a block is given
- to 'new'
-
-Sat Dec 8 02:29:54 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * object.c (Init_Object): undef Data.allocate, left Data.new.
-
-Fri Dec 7 19:12:14 2001 Minero Aoki <aamine@loveruby.net>
-
- * lib/net/smtp.rb: SMTP.new requires at least one arg.
-
- * lib/net/pop.rb: POP.new requires at least one arg.
-
- * lib/net/pop.rb: uses "raise *Error.new" instead of simple raise.
-
- * lib/net/http.rb: HTTP.new requires at least one arg.
-
- * lib/net/http.rb: changes implicit start algolithm.
-
-Fri Dec 7 15:49:39 2001 Usaku Nakamura <usa@ruby-lang.org>
-
- * ext/extmk.rb.in: ignore adding -Wl,-R to DLDFLAGS when the directory
- is $topdir.
-
-Fri Dec 7 13:58:58 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ext/curses/curses.c (window_scrollok): use RTEST().
-
- * ext/curses/curses.c (window_idlok): ditto.
-
- * ext/curses/curses.c (window_keypad): ditto.
-
- * ext/curses/curses.c (window_idlok): idlok() may return void on
- some platforms; so don't use return value.
-
- * ext/curses/curses.c (window_scrollok): ditto for consistency.
-
- * ext/curses/curses.c: replace FIX2INT() by typechecking NUM2INT().
-
-Fri Dec 7 09:51:00 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (str_extend): should not process immature #$x and
- #@x interpolation, e.g #@#@ etc.
-
-Fri Dec 7 03:21:18 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * enum.c (enum_sort_by): sort_by does not have to be stable always.
-
- * enum.c (enum_sort_by): call qsort directly to gain performance.
-
-Thu Dec 6 18:52:28 2001 Usaku Nakamura <usa@ruby-lang.org>
-
- * ext/extmk.rb.in: add -Wl,-R flags to DLDFLAGS on netbsdelf.
-
- * lib/mkmf.rb: ditto.
-
-Thu Dec 6 09:15:14 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * util.c (ruby_qsort): ruby_qsort(qs6) is now native thread safe.
-
- * error.c (rb_sys_fail): it must be a bug if it's called when
- errno == 0.
-
-Wed Dec 5 23:36:56 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * regex.c (WC2MBC1ST): should not pass through > 0x80 number in UTF-8.
-
-Wed Dec 5 20:05:18 2001 Florian Frank <flori@ping.de>
-
- * ext/socket/socket.c (bsock_send): should raise EWOULDBLOCK
- exception.
-
- * ext/socket/socket.c (s_recvfrom): ditto.
-
- * ext/socket/socket.c (s_accept): ditto.
-
- * ext/socket/socket.c (udp_send): ditto.
-
-Tue Dec 4 17:43:10 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ruby.h (DUPSETUP): new SETUP macro for duplication.
-
- * time.c (time_dup): implement in Time class using DUPSETUP.
-
- * time.c (time_getlocaltime): new method; probably requires
- better name than getlocaltime. [new,experimental]
-
- * time.c (time_getgmtime): ditto.
-
- * array.c (rb_ary_dup): uses DUPSETUP.
-
- * string.c (rb_str_dup): uses DUPSETUP. now properly copies
- instance variables too.
-
-Tue Dec 4 03:49:06 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (io_fread): EAGAIN/EWOULDBLOCK should not terminate and
- throw away the input.
-
- * time.c (time_new_internal): underflow adjustment must not use
- negative div/mod.
-
- * time.c (time_cmp): should consider tv_usec on non Fixnum number
- comparison.
-Sun Dec 9 23:00:54 2001 Keiju Ishitsuka <keiju@ishitsuka.com>
- * matrix.rb: Vector#* bug. reported from Massimiliano Mirra
- <info@chromatic-harp.com>.
-
-Sun Dec 9 22:15:59 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * enum.c (enum_sort_by): should replace with last elements.
-
-Mon Dec 3 16:06:57 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * ext/socket/extconf.rb: remove -L/usr/local/lib.
-
- * configure.in: add -Wl,-export-dynamic on NetBSD.
-
-Mon Dec 3 16:04:16 2001 Usaku Nakamura <usa@ruby-lang.org>
-
- * configure.in: not use X11BASE, since it's not always set.
-
-Mon Dec 3 13:53:49 2001 Tanaka Akira <akr@m17n.org>
-
- * time.c (rb_strftime): buffer length condition was wrong.
-
- * time.c (time_strftime): should backup buf to the original
- buffer.
-
-Mon Dec 3 09:59:08 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * time.c (time_plus): must detect result overflow.
-
- * time.c (time_minus): ditto.
-
- * time.c (time_new_internal): round usec overflow and underflow
- here.
-
- * time.c (time_plus): move operand overflow/underflow check to
- time_new_internal().
-
- * time.c (time_minus): ditto.
-
- * time.c (time_cmp): should consider tv_usec too.
-
-Mon Dec 3 03:32:22 2001 Usaku Nakamura <usa@ruby-lang.org>
-
- * configure.in: apply patch from NetBSD's pkgsrc (patch-aa).
-
-Sun Dec 2 22:01:52 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * configure.in: use GCC, not without_gcc. remove without_gcc.
-
- * ext/curses/extconf.rb: check for curses.h.
-
- * ext/dbm/extconf.rb: check if $CFLAGS includes DBM_HDR.
-
-Sat Dec 1 12:13:20 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * time.c (time_gmtime): time_modify() should be called even if tm
- struct is not calculated yet.
-
-Fri Nov 30 17:02:55 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * configure.in: set target_cpu to i386 on cygwin and mingw32.
-
- * configure.in: default --enable-shared to yes on cygwin and mingw32.
-
-Fri Nov 30 00:25:28 2001 Usaku Nakamura <usa@ruby-lang.org>
-
- * README.EXT: Appendix B is duplicated.
-
- * README.EXT.ja: ditto.
-
-Thu Nov 29 00:28:07 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_equal): object with to_str must be treated as a
- string.
-
-Wed Nov 28 18:46:28 2001 Ville Mattila <mulperi@iki.fi>
-
- * eval.c (rb_thread_select): should subtract timeofday() from
- limit, not reverse.
-
-Wed Nov 28 16:03:28 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * util.c (scan_hex): x is not a hexadecimal digit.
-
-Wed Nov 28 13:38:04 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_thread_schedule): should treat the case that
- select(2) returns 0, if a thread is under both WAIT_SELECT and
- WAIT_TIME. Jakub Travnik <J.Travnik@sh.cvut.cz> actually fixed
- this bug.
-
-Tue Nov 27 02:15:25 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * marshal.c (w_float): must distinguish -0.0 from 0.0.
-
-Mon Nov 26 20:57:24 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/Setup*, ext/syslog/*: import the "syslog" module from the
- rough ruby project.
-
-Mon Nov 26 16:14:42 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * gc.c (gc_mark_all): tweak mark order for little bit better scan.
-
- * gc.c (rb_gc_mark): ditto.
-
- * gc.c (rb_gc): ditto.
-
-Mon Nov 26 16:54:59 2001 Usaku Nakamura <usa@ruby-lang.org>
-
- * win32/win32.c (mypopen): fixed that mypclose() didn't really close
- pipe.
-
- * win32/win32.c (CreateChild): set STARTF_USESTDHANDLES flag only
- when some handles are passed.
-
-Mon Nov 26 16:31:28 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * enum.c (sort_by_i): slight performance boost.
-
-Sun Nov 25 21:02:18 2001 Usaku Nakamura <usa@ruby-lang.org>
-
- * parse.y (str_extend): change types of second and third arguments
- from char to int.
-
-Thu Nov 22 20:15:28 2001 TAMURA Takashi <sheepman@tcn.zaq.ne.jp>
-
- * gc.c (gc_mark_rest): should call gc_mark_children(), not gc_mark().
-
- * gc.c (rb_gc_mark): may cause infinite looop.
-
-Thu Nov 22 00:28:13 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (str_extend): should check nesting parentheses in #{}.
-
-Wed Nov 21 12:22:52 2001 Shugo Maeda <shugo@ruby-lang.org>
-
- * lib/cgi.rb: CGI#header: do not set Apache.request.status for
- Location: if Apache.request.status is already set.
-
-Wed Nov 21 02:24:18 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * process.c (pst_wstopsig): returns nil unless WIFSTOPPED() is
- non-zero.
-
- * process.c (pst_wtermsig): returns nil unless WIFSIGNALED() is
- non-zero.
-
- * process.c (pst_wexitstatus): returns nil unless WIFEXITED() is
- non-zero.
-
-Wed Nov 21 00:17:54 2001 Ville Mattila <mulperi@iki.fi>
-
- * eval.c (rb_thread_select): tv_sec and tv_usec should not be
- negative.
-
- * signal.c (posix_signal): do not set SA_RESTART for SIGVTALRM.
-
-Tue Nov 20 21:09:22 2001 Guy Decoux <ts@moulon.inra.fr>
-
- * parse.y (call_args2): block_arg may follow the first argument in
- call_args2.
-
-Tue Nov 20 02:01:15 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (stack_check): should avoid stack length check during
- raising SystemStackError exception.
-
-Tue Nov 20 01:07:13 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (str_extend): should not terminate string interpolation
- with newlines in here-docs and newline terminated strings.
-
-Mon Nov 19 17:58:49 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_mod_modfunc): should follow NODE_ZSUPER link; based
- on Guy Decoux's patch in [ruby-talk:25478].
-
-Mon Nov 19 16:09:33 2001 Tanaka Akira <akr@m17n.org>
-
- * string.c (rb_str_succ): there was buffer overrun.
-
-Mon Nov 19 14:14:58 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (str_extend): term can be any character.
-
-Mon Nov 19 04:58:42 2001 Wakou Aoyama <wakou@fsinet.or.jp>
-
- * lib/cgi.rb (header): support for Apache. thanks to
- Shugo Maeda <shugo@ruby-lang.org>.
-
-Sun Nov 18 19:37:55 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * parse.y: needless conditionals.
-
- * parse.y (parse_regx): parse error at unterminated regex /#{.
- (ruby-bugs-ja:PR#142)
-
-Sat Nov 17 12:37:39 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * pack.c (pack_unpack): should give length to utf8_to_uv().
-
- * pack.c (utf8_to_uv): add length check.
-
-Sat Nov 17 01:41:52 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * massages: replace "wrong #" by "wrong number".
-
- * marshal.c (w_float): output Infinity and NaN explicitly.
-
- * marshal.c (r_object): support new explicit float format.
-
- * eval.c (rb_thread_wait_for): select may cause ERESTART on
- Solaris.
-
- * eval.c (rb_thread_select): ditto.
-
-Thu Nov 15 15:29:39 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * array.c (rb_ary_join): non-nil separator must be converted to
- String. and separators' total length was wrong.
-
-Thu Nov 15 03:37:17 2001 Usaku Nakamura <usa@ruby-lang.org>
-
- * hash.c (ruby_setenv): remove USE_WIN32_RTL_ENV block since it's
- obsoleted.
-
- * win32/win32.c, win32/win32.h: sort out #if 0 - #endif or others.
-
-Thu Nov 15 00:07:12 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * array.c (rb_ary_to_s): if rb_output_fs is nil, insert newlines
- between array elements (use rb_default_rs as newline litral)
- [experimental].
-
-Wed Nov 14 15:16:23 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * gc.c (init_mark_stack): no need to clear mark_stack.
-
- * gc.c (gc_mark_all): need to handle finalizer mark.
-
- * gc.c (gc_mark_rest): use MEMCPY instead of memcpy.
-
- * gc.c (rb_gc_mark): earlier const check to avoid pusing special
- constants into mark stack.
-
-Wed Nov 14 01:12:07 2001 Usaku Nakamura <usa@ruby-lang.org>
-
- * win32/win32.c (waitpid): fix wait count.
-
- * win32/win32.c (poll_child_status): rename from wait_child().
-
-Wed Nov 14 01:33:49 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * numeric.c (fix_to_s): 'to_s' now takes optional argument to
- specify radix. [new]
-
- * bignum.c (rb_big_to_s): ditto. [new]
-
-Tue Nov 13 19:50:30 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * configure.in: do not override CC if set.
-
-Tue Nov 13 16:49:16 2001 Usaku Nakamura <usa@ruby-lang.org>
-
- * win32/win32.c (mypopen): return error status instead of calling
- rb_sys_fail().
-
- * win32/win32.c (do_spawn): ditto.
-
-Tue Nov 13 14:39:11 2001 WATANABE Tetsuya <tetsu@jpn.hp.com>
-
- * signal.c (sighandle): should not re-register sighandler if
- POSIX_SIGNAL is defined.
-
-Tue Nov 13 12:55:59 2001 Usaku Nakamura <usa@ruby-lang.org>
-
- * win32/win32.c (do_spawn): use CreateChild() instead of calling
- CreateProcess() directly. Original patches comes from Patrick Cheng.
-
- * win32/win32.c (mypopen): ditto.
-
- * win32/win32.c (mypclose): use rb_syswait() instead of waiting in this
- function.
-
- * win32/win32.c (waitpid): use wait_child() instead of _cwait().
-
- * win32/win32.c (CreateChild): added. [new]
-
- * win32/win32.c (wait_child): added. [new]
-
- * win32/win32.c (FindFirstChildSlot): added. [new]
-
- * win32/win32.c (FindChildSlot): added. [new]
-
- * win32/win32.c (FindPipedChildSlot): added. [new]
-
- * win32/win32.c (CloseChildHandle): added. [new]
-
- * win32/win32.c (FindFreeChildSlot): added. [new]
-
-Tue Nov 13 12:38:12 2001 Usaku Nakamura <usa@ruby-lang.org>
-
- * hash.c (envix): use GET_ENVIRON and FREE_ENVIRON to get environment
- variables list.
-
- * hash.c (env_keys): ditto.
-
- * hash.c (env_each_key): ditto.
-
- * hash.c (env_values): ditto.
-
- * hash.c (env_keys): ditto.
-
- * hash.c (env_each_value): ditto.
-
- * hash.c (env_each): ditto.
-
- * hash.c (env_inspect): ditto.
-
- * hash.c (env_to_a): ditto.
-
- * hash.c (env_size): ditto.
-
- * hash.c (env_empty_p): ditto.
-
- * hash.c (env_has_value): ditto.
-
- * hash.c (env_index): ditto.
-
- * hash.c (env_to_hash): ditto.
-
- * win32/win32.c (win32_getenv): use static buffer.
-
- * win32/win32.c, win32/win32.h (win32_get_environ): get environment
- variables list. [new]
-
- * win32/win32.c, win32/win32.h (win32_free_environ): free environment
- variables list. [new]
-
-Mon Nov 12 16:48:48 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (error_print): errat array may be empty.
-
-Mon Nov 12 01:30:37 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_eval_cmd): should not upgrade safe level unless
- explicitly specified by argument newly added.
-
- * signal.c (sig_trap): should not allow tainted trap closure.
-
- * variable.c (rb_f_trace_var): should not allow trace_var on safe
- level higher than 3.
-
- * variable.c (rb_f_trace_var): should not allow tainted trace
- closure.
-
-Sun Nov 11 00:12:23 2001 TAMURA Takashi <sheepman@tcn.zaq.ne.jp>
-
- * gc.c: do not use static stack until system stack overflows.
-
-Sat Nov 10 03:57:09 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (eval): should call Exception#exception instead of
- calling rb_exc_new3() directly.
-
- * error.c (exc_exception): set "mesg" directly to the clone. it
- might be better to set mesg via some method for flexibility.
-
-Sat Nov 10 00:14:24 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * variable.c (cvar_override_check): should print original module
- name, if 'a' is T_ICLASS.
-
- * parse.y (yylex): float '1_.0' should not be allowed.
-
- * variable.c (var_getter): should care about var as Qfalse
- (ruby-bugs#PR199).
-
-Fri Nov 9 13:50:06 2001 Usaku Nakamura <usa@ruby-lang.org>
-
- * win32/config.status.in: make CFLAGS same as Makefile's one.
-
-Thu Nov 8 20:20:37 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * eval.c (rb_trap_eval): avoid annoying warning with signal.
- [ruby-talk:23225]
-
- * eval.c (rb_call0): adjust caller source file/line while
- evaluating optional arguments.
-
-Thu Nov 8 18:41:58 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * array.c (cmpint): <=> or block for {min,max} may return bignum.
-
- * array.c (sort_1): use rb_compint.
-
- * array.c (sort_2): ditto.
-
- * enum.c (min_ii): ditto.
-
- * enum.c (min_ii): ditto.
-
- * enum.c (max_i): ditto.
-
- * enum.c (max_ii): ditto.
-
-Thu Nov 8 18:21:02 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * file.c (path_check_1): forgot to initialize 'p'.
-
-Thu Nov 8 14:52:15 2001 Tanaka Akira <akr@m17n.org>
-
- * mkconfig.rb: use String#dump to generate Ruby string literal.
-
-Thu Nov 8 15:46:54 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * range.c (range_eql): should override 'eql?'
-
- * array.c (rb_ary_hash): should override 'hash' too.
-
-Tue Nov 6 14:38:48 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * process.c (security): always give warning for insecure PATH.
-
- * dir.c (my_getcwd): do not rely on MAXPATHLEN.
-
- * file.c (rb_file_s_readlink): ditto.
-
- * file.c (path_check_1): ditto.
-
-Tue Nov 6 14:17:14 2001 Amos Gouaux <amos+ruby@utdallas.edu>
-
- * lib/net/imap.rb (getquota_response): use astring for mailbox
- names.
-
- * lib/net/imap.rb (getacl_response): ditto.
-
-Mon Nov 5 17:09:55 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_yield_0): should not call rb_f_block_given_p().
-
-Sat Nov 3 23:33:18 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_chomp_bang): should terminate string by NUL.
-
-Sat Nov 3 22:28:51 2001 Keiju Ishitsuka <keiju@ishitsuka.com>
-
- * matrix.rb (Matrix#column_vectors, Matrix#row_vectors): ditto bug.
- this bug report and fix by tsutomu@nucba.ac.jp.
-
- * forwardable.rb: change raise to Kernel::raise
-
-Sat Nov 3 10:11:57 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_yield_0): better error message.
-
-Thu Nov 1 14:08:42 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * bignum.c (rb_big_aref): idx may be a Bignum.
-
- * numeric.c (fix_aref): negative index must return zero.
-
-Thu Nov 1 13:23:50 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * gc.c (gc_mark_children): should NOT treat last element of
- structs and arrays specially.
-
-Wed Oct 31 16:59:25 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (exec_under): should initialize ruby_frame->self;
-
-Wed Oct 31 15:09:28 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (POP_VARS): should not set DVAR_DONT_RECYCLE if _old
- ruby_vars is already force_recycled.
-
-Wed Oct 31 10:28:49 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * gc.c (rb_gc): handles mark stack overflow.
-
- * gc.c (PUSH_MARK): use static mark stack, no more recursion.
-
-Wed Oct 31 02:44:06 2001 Wakou Aoyama <wakou@fsinet.or.jp>
-
- * lib/cgi.rb: CGI::Cookie::parse(): Ignore duplicate keys caused by
- Netscape bug.
-
-Tue Oct 30 18:21:51 2001 Usaku Nakamura <usa@ruby-lang.org>
-
- * win32/mkexports.rb: follow the change of rb_io_puts().
-
-Tue Oct 30 14:04:04 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_chomp_bang): do smart chomp if $/ == '\n'. [new]
-
- * io.c (rb_io_puts): don't treat Array specially.
-
- * bignum.c (rb_big_cmp): should convert bignum to float.
-
- * eval.c (rb_f_eval): can't modify untainted binding.
-
-Mon Oct 29 16:08:30 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * regex.c (re_compile_pattern): should preserve p0 value.
-
-Mon Oct 29 14:56:44 2001 Usaku Nakamura <usa@ruby-lang.org>
-
- * intern.h (rb_protect_inspect): follow the change of array.c.
-
- * eval.c (rb_exec_end_proc): follow the change of rb_protect().
-
- * eval.c (method_proc, umethod_proc, rb_catch): cast the first
- parameter of rb_iterate() to avoid VC++ warning.
-
- * range.c (range_step): ditto.
-
- * ext/sdbm/init.c (fsdbm_update, fsdbm_replace): ditto.
-
-Mon Oct 29 07:57:31 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (str_extend): should allow interpolation of $-x.
-
- * variable.c (rb_cvar_set): empty iv_tbl may cause infinite loop.
-
- * variable.c (rb_cvar_get): ditto.
-
- * variable.c (cvar_override_check): ditto.
-
-Sat Oct 27 23:01:19 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * bignum.c (rb_big_eq): convert Bignum to Float, instead of
- reverse.
-
-Fri Oct 26 06:19:29 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * time.c (time_localtime): getting tm should not be prohibited for
- frozen time objects.
-
- * time.c (time_gmtime): ditto.
-
- * version.c (Init_version): freeze RUBY_VERSION,
- RUBY_RELEASE_DATE, and RUBY_PLATFORM.
-
- * file.c (Init_File): freeze File::SEPARATOR, ALT_SEPARATOR and
- PATH_SEPARATOR.
-
- * file.c (rb_stat_cmp): should check operand type before calling
- get_stat().
-
-Thu Oct 25 10:28:15 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_eval_cmd): should not invoke "call" with a block on
- any occasion.
-
-Wed Oct 24 03:25:31 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * numeric.c (fix_aref): idx may be a Bignum.
-
-Tue Oct 23 01:21:19 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * eval.c (proc_invoke): fix self switching in Proc#call
- (ruby-bugs-ja#PR108) and GC failure. use Qundef instead of 0
- to direct not switching self.
-
- * eval.c (call_trace_func): ditto.
-
- * eval.c (call_end_proc): ditto.
-
- * eval.c (proc_call): ditto.
-
- * eval.c (proc_yield): ditto.
-
-Tue Oct 23 01:15:43 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * variable.c (rb_global_entry): reconstruct global variable
- aliasing (sharing global_entry->var with other global_entry).
-
- * variable.c (undef_getter): ditto.
-
- * variable.c (undef_setter): ditto.
-
- * variable.c (val_setter): ditto.
-
- * variable.c (mark_global_entry): ditto.
-
- * variable.c (rb_define_hooked_variable): ditto.
-
- * variable.c (rb_f_trace_var): ditto.
-
- * variable.c (remove_trace): ditto.
-
- * variable.c (rb_f_untrace_var): ditto.
-
- * variable.c (rb_gvar_get): ditto.
-
- * variable.c (trace_en): ditto.
-
- * variable.c (rb_gvar_set): ditto.
-
- * variable.c (rb_gvar_defined): ditto.
-
- * variable.c (rb_alias_variable): ditto.
-
-Mon Oct 22 18:53:55 2001 Masahiro Tanaka <masa@stars.gsfc.nasa.gov>
-
- * numeric.c (num_remainder): a bug in Numeric#remainder.
-
-Mon Oct 22 15:21:55 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_exec_end_proc): END might be called within END
- block.
-
- * class.c (rb_mod_clone): should not copy class name, since clone
- should remain anonymous.
-
-Fri Oct 19 23:40:37 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * variable.c (remove_trace): should not access already freed area.
-
- * variable.c (rb_f_untrace_var): fix memory leak.
-
-Fri Oct 19 17:55:14 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * marshal.c (w_uclass): cloned class is not user
- class. (ruby-bugs-ja#PR103)
-
- * marshal.c (r_object): Struct subclass couldn't
- load. (ruby-bugs-ja#PR104)
-
-Wed Oct 17 14:12:50 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * variable.c (alias_fixup): added. ad hoc support for ordinary
- global variable aliasing. when original entry is set, make the
- alias to refer directly as possible.
-
- * variable.c (alias_getter, alias_setter): ditto.
-
- * variable.c (rb_alias_variable): ditto. and no need to mark alias
- variables.
-
- * variable.c (rb_gvar_defined): refer the original entry of an alias.
-
-Tue Oct 16 23:29:26 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_call0): self in a block given to define_method now be
- switched to the receiver of the method.
-
- * eval.c (proc_invoke): added new parameter to allow self
- switching.
-
-Tue Oct 16 21:38:15 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * eval.c (rb_f_missing): check stack level with rb_stack_check().
-
- * eval.c (rb_call0): ditto.
-
- * eval.c, intern.h (rb_stack_check): added. [new]
-
-Tue Oct 16 13:18:47 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * object.c (rb_mod_initialize): optional block with
- Module.new. [new] (from 2001-10-10)
-
-Tue Oct 16 00:07:06 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * parse.y (yylex): disallow alpha-numeric and mbchar for
- terminator of %string.
-
-Mon Oct 15 18:00:05 2001 Pit Capitain <pit@capitain.de>
-
- * string.c (rb_str_index): wrong increment for non alphanumeric
- string.
-
-Mon Oct 15 05:23:02 2001 Koji Arai <JCA02266@nifty.ne.jp>
-
- * sprintf.c (rb_f_sprintf): support "%B".
-
-Wed Oct 10 03:11:47 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * file.c (rb_stat_clone): should copy internal data too.
-
- * numeric.c (num_clone): Numeric should not be copied by clone.
-
- * object.c (rb_obj_clone): should check immediate values.
-
- * parse.y (command): `yield' should take command_args.
-
- * parse.y (parse_quotedwords): %w(...) is not a string.
-
-Tue Oct 9 18:40:35 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * process.c (Init_process): activate the case NT.
-
-Tue Oct 9 17:08:00 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * eval.c (thread_status_name): separated from
- rb_thread_inspect(). return string expression for thread status.
-
- * eval.c (rb_thread_status, rb_thread_inspect): use
- thread_status_name().
-
- * eval.c (rb_thread_priority_set): return the priority not but
- self.
-
-Sat Oct 6 23:07:08 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_eval): NODE_MATCH3 was confusing left and right. sigh.
-
-Fri Oct 5 15:19:46 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * marshal.c (w_unique): should not dump anonymous class.
-
-Fri Oct 5 11:59:13 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * eval.c (proc_s_new): revived.
-
- * eval.c (Init_Proc): define Proc.new instead of Proc.allocate to
- inhibit from creating uninitialized Proc.
-
-Thu Oct 4 14:11:03 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * ext/socket/socket.c (ruby_connect): EALREADY is the equivalent
- for EINPROGRESS in ws2_32.lib.
-
-Wed Oct 3 20:11:06 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * re.c (rb_reg_s_alloc): avoid inifinte recursion.
-
-Wed Oct 3 16:49:49 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * ext/gdbm/gdbm.c (rb_gdbm_fetch): str is a VALUE now.
-
-Wed Oct 3 13:32:06 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * marshal.c (r_object): better allocation type check for
- TYPE_UCLASS. usage of allocation framework is disabled for now.
-
- * variable.c (rb_class_path): Module may have subclass.
-
- * string.c (rb_str_update): should maintain original negative
- offset.
-
- * string.c (rb_str_subpat_set): ditto
-
- * string.c (rb_str_aset): ditto.
-
- * re.c (rb_reg_nth_match): should check negative nth.
-
- * re.c (rb_reg_nth_defined): ditto.
-
-Tue Oct 2 19:12:47 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * lib/ftools.rb (catname): allow trailing '/' for the destination.
-
-Tue Oct 2 18:31:20 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_eval): should override existing class.
-
-Tue Oct 2 17:08:49 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * object.c (rb_obj_alloc): general instance allocation framework.
- use of NEWOBJ() is deprecated except within 'allocate' method.
-
-Tue Oct 2 08:04:52 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * marshal.c (r_object): TYPE_UCLASS check should be inversed.
-
-Mon Oct 1 19:18:54 2001 Tanaka Akira <akr@m17n.org>
-
- * ext/socket/socket.c (unix_addr): getsockname(2) may result len = 0.
-
- * ext/socket/socket.c (unix_peeraddr): getpeername(2) may result
- len = 0.
-
-Mon Oct 1 09:59:07 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_subpat_set): support function for new argument
- pattern String#[re,offset] = val. [new]
-
-Sat Sep 29 02:30:06 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (POP_BLOCK): rb_gc_force_recycle() was called too much.
- Should not be called if SCOPE_DONT_RECYCLE is set.
-
-Wed Sep 26 22:21:52 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_aref_m): new argument pattern
- String#[re,offset]. [new]
-
-Wed Sep 26 19:02:39 2001 Guy Decoux <ts@moulon.inra.fr>
-
- * parse.y: allow 'primary[] = arg'
-
-Tue Sep 25 10:46:42 2001 Usaku Nakamura <usa@ruby-lang.org>
-
- * win32/win32.c (isInternalCmd): check return value of NtMakeCmdVector
- (Tietew <tietew@tietew.net>'s patch).
-
-Mon Sep 24 00:55:06 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_substr): should return an instance of
- receiver's class.
-
- * string.c (rb_str_succ): ditto.
-
- * array.c (rb_ary_subseq): ditto.
-
- * array.c (rb_ary_initialize): Array.new([1,2,3]) => [1,2,3]. [new]
-
-Sat Sep 22 22:16:08 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_reverse): should return an instance of
- receiver's class.
-
- * string.c (rb_str_times): ditto.
-
- * array.c (rb_ary_times): ditto
-
- * string.c (str_gsub): ditto.
-
- * string.c (rb_str_ljust): ditto.
-
- * string.c (rb_str_rjust): ditto.
-
- * string.c (rb_str_center): ditto.
-
-Sat Sep 22 12:13:39 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (eval): retrieves file, line information from binding.
-
-Thu Sep 20 21:25:00 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * eval.c (MATCH_DATA): access via rb_svar().
-
-Thu Sep 20 15:20:00 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * eval.c, intern.h (rb_svar): return reference to special variable
- from local variable index. [new]
-
- * eval.c (rb_eval): use rb_svar() for NODE_FLIP{2,3}.
-
- * parse.y (rb_(backref|lastline)_(get|set)): access via rb_svar().
-
- * eval.c (proc_invoke): push dynamic variables.
-
- * eval.c (rb_thread_yield): push special variables as dynamic
- variables($_, $~ and FLIP states).
-
-Thu Sep 20 15:20:00 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * intern.h, parse.y (rb_is_local_id): return true if the ID is
- local symbol. [new]
-
- * parse.y (internal_id): make new ID for internal use. [new]
-
- * parse.y (cond0): allocate internal ID for NODE_FLIP{2,3}.
-
- * eval.c (rb_f_local_variables): use rb_is_local_id() to select
- visible local variables.
-
-Thu Sep 20 15:20:00 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * eval.c (rb_thread_start_0): SCOPE_SHARED is removed.
-
- * eval.c, intern.h (rb_thread_scope_shared_p): removed. special
- variables are no longer shared by threads.
-
- * re.c (rb_reg_search): MATCHDATA is no longer shared by threads.
-
-Tue Sep 18 11:44:26 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_init): String.new() => "" [new]
-
-Tue Sep 11 20:53:56 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * dir.c (dir_path): new method.
-
- * dir.c (dir_initialize): wrap DIR into struct, along with path
- information.
-
-Sat Sep 8 07:13:42 2001 Wakou Aoyama <wakou@fsinet.or.jp>
-
- * lib/net/telnet.rb: waitfor(): improvement. thanks to
- nobu.nakada@nifty.ne.jp
-
-Sat Sep 8 04:34:17 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_thread_restore_context): save current value of
- lastline and lastmatch in the thread struct for later restore.
-
- * eval.c (rb_thread_save_context): restore lastline and lastmatch.
-
-Fri Sep 7 11:27:56 2001 akira yamada <akira@ruby-lang.org>
-
- * numeric.c (flo_to_s): should handle negative float value.
-
-Fri Sep 7 09:44:44 2001 Wakou Aoyama <wakou@fsinet.or.jp>
-
- * lib/net/telnet.rb: waitfor(): bug fix.
-
-Fri Sep 7 07:11:34 2001 Wakou Aoyama <wakou@fsinet.or.jp>
-
- * lib/cgi.rb: CGI#doctype(): bug fix (html4Fr).
-
- * lib/net/telnet.rb, lib/cgi.rb: remove VERSION, RELEASE_DATE,
- VERSION_CODE, RELEASE_CODE. please use REVISION.
-
- * lib/cgi.rb: CGI#header(): bug fix.
-
- * lib/net/telnet.rb, lib/cgi.rb: concat --> +=
-
-Thu Sep 6 17:38:18 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * dir.c (dir_s_chdir): raise if environment variable HOME/LOGDIR
- not set.
-
- * dir.c (glob_helper): avoid infinite loop on a file name with
- wildcard characters. (ruby-bugs#PR177)
-
-Thu Sep 6 14:25:15 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/digest/digest.c (rb_digest_base_s_hexdigest): remove a debug
- print.
-
-Thu Sep 6 13:56:14 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/digest/digest.c (rb_digest_base_s_digest,
- rb_digest_base_s_hexdigest): ensure that a string is given.
-
-Thu Sep 6 13:28:51 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * lib/jcode.rb (_regexp_quote): fix quote handling, again.
-
-Thu Sep 6 07:28:56 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * file.c (rb_find_file_ext): add const qualifiers to ext.
-
- * intern.h (rb_find_file_ext): ditto.
-
-Thu Sep 6 07:16:14 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * ext/socket/socket.c (Init_socket): remove duplicating constants.
-
-Thu Sep 6 03:15:24 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * class.c (rb_include_module): should check whole ancestors to
- avoid duplicate module inclusion.
-
-Wed Sep 5 20:02:27 2001 Shin'ya Adzumi <adzumi@denpa.org>
-
- * string.c (trnext): should check backslash before updating "now"
- position.
-
-Wed Sep 5 17:41:11 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * lib/jcode.rb (_regexp_quote): fix quote handling.
-
-Tue Sep 4 01:03:18 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * re.c (Init_Regexp): to_s to be alias to inspect.
-
-Mon Sep 3 22:46:59 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (yylex): should support 'keyword='.
-
-Mon Sep 3 20:26:08 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * intern.h (rb_find_file_ext): changed from rb_find_file_noext().
-
-Mon Sep 3 15:12:49 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ruby.c (proc_options): should not adjust argc/argv if -e option
- is supplied.
-
-Mon Sep 3 14:11:17 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * error.c: unbreak the build on *BSD with gcc 3.0.1 by removing
- the conflicting declaration of sys_nerr for *BSD.
-
-Sat Sep 1 18:50:07 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ruby.c (proc_options): should not alter origargv[].
-
- * ruby.c (set_arg0): long strings for $0 dumped core.
-
-Sat Sep 1 09:50:54 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * ruby.c (set_arg0): prevent SEGV when val is longer than the
- original arguments.
-
- * ruby.c (ruby_process_options): initialize total length of
- original arguments at first.
-
-Sat Sep 1 14:05:28 2001 Brian F. Feldman <green@FreeBSD.org>
-
- * ruby.c (set_arg0): use setprogtitle() if it's available.
-
-Sat Sep 1 03:49:11 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (rb_io_popen): accept integer flags as mode.
-
-Fri Aug 31 19:46:05 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * file.c (rb_find_file_ext): extension table can be supplied from
- outside. renamed.
-
- * eval.c (rb_f_require): replace rb_find_file_noext by
- rb_find_file_ext.
-
-Fri Aug 31 19:26:55 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * eval.c (rb_provided): should also check feature without
- extension.
-
-Fri Aug 31 13:06:33 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * numeric.c (flo_to_s): do not rely on decimal point to be '.'
-
-Wed Aug 29 02:18:53 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (yylex): ternary ? can be followed by newline.
-
-Tue Aug 28 00:40:48 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_f_require): should check static linked libraries
- before raising exception.
-
-Fri Aug 24 15:17:40 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * array.c (rb_ary_equal): check identiry equality first.
-
- * string.c (rb_str_equal): ditto.
-
- * struct.c (rb_struct_equal): ditto.
-
-Fri Aug 24 14:38:17 2001 Usaku Nakamura <usa@ruby-lang.org>
-
- * dln.c (dln_strerror): fix a bug that sometimes made null message on
- win32 (Tietew <tietew@tietew.net>'s patch).
-
- * win32/win32.c (mystrerror): ditto.
-
-Fri Aug 24 03:15:07 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * numeric.c (Init_Numeric): undef Integer::new.
-
-Fri Aug 24 00:46:44 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_eval): NODE_WHILE should update result for each
- conditional evaluation.
-
- * eval.c (rb_eval): NODE_UNTIL should return last evaluated value
- (or value given to break).
-
-Thu Aug 23 21:59:38 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * enum.c (sort_by_i): fix typo.
-
-Thu Aug 23 10:10:59 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (is_defined): should not dump core for "defined?(())".
-
- * eval.c (umethod_bind): recv can be an instance of descender of
- oklass if oklass is a Module.
-
-Wed Aug 22 23:20:03 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * hash.c (rb_hash_equal): check identiry equality first.
-
-Wed Aug 22 19:58:59 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * eval.c (intersect_fds): counts intersecting fds.
-
- * eval.c (rb_thread_schedule): only fds requested by
- each thread count as select_value.
-
-Tue Aug 21 22:28:09 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * file.c (group_member): should check real gid only.
-
- * file.c (eaccess): do not cache euid, since effective euid may be
- changed via Process.euid=().
-
- * file.c (eaccess): return -1 unless every specified access mode
- is permitted.
-
-Tue Aug 21 16:09:27 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_eval): while/until returns the value which is given
- to break.
-
- * parse.y (value_expr): using while/until/class/def as an
- expression is now gives a warning, not an error.
-
-Tue Aug 21 11:56:02 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * range.c (range_eqq): should compare strings based on magical
- increment (using String#upto), not dictionary order.
-
-Mon Aug 20 19:53:16 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * ext/digest/sha2/extconf.rb: fix support for cross-compiling.
-
- * mkconfig.rb: fix support for autoconf 2.52.
-
-Mon Aug 20 17:24:15 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * enum.c (enum_sort_by): new method for Schewartzian transformed
- stable sort.
-
-Mon Aug 20 16:09:05 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * variable.c (mod_av_set): detect constant overriding for built-in
- classes/modules.
-
-Mon Aug 20 15:14:27 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (tokadd_escape): escaped backslashes too much.
-
-Mon Aug 20 13:24:08 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * range.c (range_step): 'iter' here should be an array.
-
-Mon Aug 20 12:43:08 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * marshal.c (w_object): should retrieve __member__ data from
- non-singleton class.
-
-Sat Aug 18 23:11:14 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * variable.c (rb_cvar_get): class variable override check added.
-
- * variable.c (rb_cvar_set): ditto
-
- * variable.c (rb_cvar_declare): ditto.
-
-Fri Aug 17 12:13:48 2001 Minero Aoki <aamine@loveruby.net>
-
- * lib/net/protocol.rb: Protocol.new requires at least one arg.
-
- * lib/net/smtp.rb: ditto.
-
- * lib/net/pop.rb: ditto.
-
- * lib/net/http.rb: ditto.
-
-Fri Aug 17 00:49:51 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (parse_regx): handle backslash escaping of delimiter here.
-
-Thu Aug 16 23:03:40 2001 Koji Arai <JCA02266@nifty.ne.jp>
-
- * io.c: prevent recursive malloc calls on NEC UX/4800.
-
- * ext/socket/socket.c: ditto.
-
-Thu Aug 16 13:54:04 2001 Usaku Nakamura <usa@ruby-lang.org>
-
- * ext/socket/socket.c (s_recvfrom): fix typo.
-
-Thu Aug 16 09:53:28 2001 Usaku Nakamura <usa@ruby-lang.org>
-
- * ext/socket/socket.c (s_recvfrom): avoid VC++6 warning.
-
-Thu Aug 16 03:50:33 2001 Usaku Nakamura <usa@ruby-lang.org>
-
- * win32/win32.c (NtCmdGlob): avoid VC++ warning.
-
- * lib/mkmf.rb: add -I$(srcdir) to CPPFLAGS.
-
-Wed Aug 15 04:59:15 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/digest/*/extconf.rb: really fix so that they build from any
- directory.
-
-Wed Aug 15 04:04:02 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/digest/sha2/extconf.rb: fix so that they build from any
- directory.
-
-Wed Aug 15 01:59:19 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/digest/defs.h: Define NO_UINT64_T instead of emitting an
- error to fail.
-
- * ext/digest/sha2/extconf.rb: Do not exit on error, and utilize
- NO_UINT64_T to detect if the system has a 64bit integer type.
-
-Tue Aug 14 21:14:07 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/digest/sha2/extconf.rb: do not create Makefile when no 64bit
- integer type is detected.
-
-Tue Aug 14 17:09:12 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * range.c (range_step): new method.
-
-Tue Aug 14 11:49:00 2001 TOYOFUKU Chikanobu <toyofuku@juice.or.jp>
-
- * string.c (rb_str_cmp): remove needless conditional.
-
-Tue Aug 14 03:23:25 2001 Koji Arai <JCA02266@nifty.ne.jp>
-
- * string.c (rb_str_lstrip_bang) `return Qnil' was missing.
-
-Mon Aug 13 14:16:46 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * bignum.c, marshal.c: Detypo: s/SIZEOF_ING/SIZEOF_INT/.
-
-Sun Aug 12 15:01:58 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * string.c (rb_str_cat): fix buffer overflow.
-
- * string.c (rb_str_append): nothing to append actually when `str2'
- is empty.
-
-Sat Aug 11 14:43:47 2001 Tanaka Akira <akr@m17n.org>
-
- * array.c (rb_inspecting_p): initialize inspect_key if it is
- not initialized yet.
-
-Fri Aug 10 22:14:37 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (cond0): operands of logical operators are not treated
- as conditional expresion anymore, but propagate conditional
- status if used in conditionals.
-
-Tue Aug 7 09:10:32 2001 Usaku Nakamura <usa@ruby-lang.org>
-
- * win32/win32.h: fix problems with BC++ (ruby-bugs#PR161).
-
-Mon Aug 6 23:47:46 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * pack.c (pack_pack): associates p/P strings once at last
- (reverted to 1.26).
-
- * string.c (rb_str_associate): associates an Array at once, not
- but a String. realloc's when str_buf.
-
-Mon Aug 6 17:01:33 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_gc_mark_threads): should mark ruby_cref.
-
-Mon Aug 6 14:31:37 2001 Usaku Nakamura <usa@ruby-lang.org>
-
- * numeric.c (num_divmod): fix typo.
-
-Mon Aug 6 03:29:03 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_lstrip_bang): new method.
-
- * string.c (rb_str_rstrip_bang): new method.
-
-Mon Aug 6 00:35:03 2001 Guy Decoux <decoux@moulon.inra.fr>
-
- * struct.c (rb_struct_modify): should check frozen and taint
- status.
-
-Sun Aug 5 19:28:39 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * string.c (rb_str_associate): should consider STR_ASSOC too.
-
-Sun Aug 5 07:46:18 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * eval.c (rb_undefined): do not recurse if method_missing is
- undefined.
-
-Thu Aug 2 21:37:32 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * process.c (proc_waitpid): now all arguments are optional.
-
- * process.c (Init_process): waitpid is now alias to wait.
-
- * process.c (Init_process): waitpid2 is now alias to wait2.
-
- * process.c (rb_waitpid): made public.
-
- * ext/pty/pty.c (pty_getpty): avoid disturbing SIGCHLD using
- thread and rb_waitpid.
-
-Thu Aug 2 11:23:07 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * process.c (proc_getpgrp): now takes no argument on all
- platforms.
-
- * process.c (proc_setpgrp): ditto.
-
-Thu Aug 2 01:29:42 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * file.c (strrdirsep): removed meaningless code.
-
- * file.c (rb_file_s_expand_path): reverted to 1.66.
-
-Wed Aug 1 16:17:47 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ext/socket/socket.c (sock_s_pack_sockaddr_in): added
- Socket::pack_sockaddr_in(). [new]
-
- * ext/socket/socket.c (sock_s_pack_sockaddr_un): added
- Socket::pack_sockaddr_un(). [new]
-
- * ext/socket/socket.c (sock_s_pack_sockaddr_in): added
- Socket::unpack_sockaddr_in(). [new]
-
- * ext/socket/socket.c (sock_s_pack_sockaddr_un): added
- Socket::unpack_sockaddr_un(). [new]
-
-Wed Aug 1 15:42:16 2001 Usaku Nakamura <usa@ruby-lang.org>
-
- * eval.c (ruby_run): avoid VC++ warning.
-
-Tue Jul 31 17:30:53 2001 Usaku Nakamura <usa@ruby-lang.org>
-
- * marshal.c (Init_marshal): fix typos.
-
-Tue Jul 31 15:16:39 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * process.c (last_status_set): nothing returned, should be void.
-
- * ext/socket/socket.c (load_addr_info): ditto.
-
-Tue Jul 31 12:11:42 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * marshal.c (Init_marshal): new constant Marshal::MAJOR_VERSION
- and Marshal::MINOR_VERSION.
-
-Tue Jul 31 07:18:04 2001 Nobuyoshi Nakada <nobu.nokada@softhome.net>
-
- * file.c (rb_file_s_expand_path): scans per path element not per
- byte/character, including fix of [ruby-talk:18152] and
- multi-byte pathname support.
-
-Tue Jul 31 11:52:10 2001 akira yamada <akira@ruby-lang.org>
-
- * marshal.c (marshal_load): ruby_verbose test should be wrapped by
- RTEST().
-
-Mon Jul 30 17:54:23 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * hash.c (rb_hash_index): should return nil (not the default
- value) if value is not in the hash.
-
-Mon Jul 30 12:55:47 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * numeric.c (num_div): new method added. alias to '/' which
- should be preserved even if '/' is redefined (e.g. by
- mathn). [new]
-
-Mon Jul 30 11:12:14 2001 Amos Gouaux <amos+ruby@utdallas.edu>
-
- * lib/net/imap.rb: added new commands for managing folder quotas
- and folder ACLs.
-
-Mon Jul 30 03:19:53 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * bignum.c (rb_cstr2inum): "0 ff".hex should return 0, not 255.
-
-Fri Jul 27 22:29:41 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * file.c (rb_file_s_expand_path): fixed using CharNext().
-
-Fri Jul 27 18:07:27 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_provided): extension should be guessed using
- rb_find_file_noext().
-
- * eval.c (rb_f_require): should call rb_feature_p() after
- extension completion.
-
-Fri Jul 27 16:25:52 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_eval): add CHECK_INTS before next, redo, retry to
- avoid potential uninterruptable infinite loop.
-
-Thu Jul 26 11:27:12 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * file.c (rb_find_file_noext, rb_find_file): fix tilde expansion
- problem.
-
-Wed Jul 25 17:54:20 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * file.c (rb_file_s_expand_path): use CharNext() to expand.
-
-Wed Jul 25 17:16:26 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * intern.h: add some missing function prototypes.
-
-Wed Jul 25 15:50:05 2001 Guy Decoux <decoux@moulon.inra.fr>
-
- * file.c (rb_file_s_expand_path): should not expand "." and ".."
- not following dirsep.
-
-Wed Jul 25 12:15:32 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * file.c (rb_find_file_noext): should update f by expanded path.
-
- * file.c (rb_find_file): ditto.
-
-Tue Jul 24 23:10:47 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * file.c (strrdirsep): multi-byte pathname and DOSish separater
- supprot. originally comes from Patrick Cheng. [new]
-
- * file.c (rb_file_s_basename, rb_file_s_dirname): use
- strrdirsep(). comes from Patrick Cheng.
-
- * file.c (is_absolute_path): restricted in DOSish absolute path
- with drive letter, and UNC support. originally comes from
- Patrick Cheng.
-
- * file.c (getcwd): define macro using getwd() unless provided.
-
-Tue Jul 24 19:23:15 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/extmk.rb.in, lib/mkmf.rb: dig the target subdirectory for
- lib/* files properly in case of create_makefile("dir/name").
-
-Mon Jul 23 00:26:04 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_provide_feature): should not tweak extension used for
- loading.
-
-Sun Jul 22 21:16:43 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/extmk.rb.in, lib/mkmf.rb: introduce a couple of new make
- variables: CLEANFILES and DISTCLEANFILES. They'd typically be
- defined in a file "depend".
-
-Sat Jul 21 09:40:10 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * io.c (io_fread): use fread(3) if PENDING_COUNT is available.
-
-Fri Jul 20 22:55:01 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * gc.c (ruby_xrealloc): fix a dangling bug which led memory
- reallocation to fail even though the second try after a GC
- succeeds.
-
-Fri Jul 20 03:00:46 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * class.c (rb_mod_include_p): Module#include? added. [new]
-
-Fri Jul 20 01:05:50 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * re.c (ignorecase_setter): give warning on modifying $=.
-
- * string.c (rb_str_casecmp): new method. [new]
-
- * string.c (rb_str_eql): separated from rb_str_equal(), make it
- always be case sensitive. [new]
-
- * string.c (rb_str_hash): made it always be case sensitive.
-
-Thu Jul 19 13:03:15 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * eval.c (rb_f_require): should not include path in $" value
-
- * file.c (rb_find_file): should return 0 explicitly on failure.
-
-Tue Jul 17 11:44:40 2001 Usaku Nakamura <usa@osb.att.ne.jp>
-
- * ruby.h: enable volatile directive with VC++.
-
- * regex.c: ditto.
-
-Tue Jul 17 06:01:12 2001 Minero Aoki <aamine@loveruby.net>
-
- * doc/net/smtp.rd.ja, pop.rd.ja, http.rd.ja: new files.
-
- * MANIFEST: add doc/net/{http,pop,smtp}.rd.ja.
-
-Tue Jul 17 11:22:01 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * regex.c (NUM_FAILURE_ITEMS): was confusing NUM_REG_ITEMS and
- NUM_NONREG_ITEMS, which have happened to be same value.
-
-Tue Jul 17 11:08:34 2001 Usaku Nakamura <usa@osb.att.ne.jp>
-
- * ext/extmk.rb.in: modify RM macro because command.com/cmd.exe don't
- recognize single quotation as quote character.
-
- * lib/mkmf.rb: ditto.
-
-Tue Jul 17 01:38:15 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * class.c (rb_class_new): subclass check moved to this function.
-
- * class.c (rb_class_boot): check less version of rb_class_new().
-
-Man Jul 16 13:21:30 2001 Usaku Nakamura <usa@osb.att.ne.jp>
-
- * file.c (file_load_ok): fix typo.
-
-Mon Jul 16 12:58:07 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (proc_invoke): should preserve iter status for embedded
- frame in the block.
-
-Mon Jul 16 00:04:39 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * file.c (rb_file_s_expand_path): may overrun buffer on stack.
-
-Sun Jul 15 01:38:28 2001 Guy Decoux <decoux@moulon.inra.fr>
-
- * string.c (rb_str_insert): forgot to call rb_str_modify().
-
-Sat Jul 14 12:26:30 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * ext/digest/*/extconf.rb: fix so that they build from any
- directory.
-
-Sat Jul 14 06:20:17 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * lib/net/http.rb: HTTP#proxy? did not worked.
-
-Sat Jul 14 02:56:19 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/extmk.rb.in: support multi-level ext/ directories.
- (e.g. you can have ext/foo, ext/foo/bar and ext/foo/baz)
-
-Sat Jul 14 02:55:02 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/.cvsignore: let cvs ignore extinit.c.
-
-Fri Jul 13 23:47:35 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * regex.c (re_search): should consider reverse search.
-
-Fri Jul 13 22:26:09 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * lib/mkmf.rb: use File::split to split a target into a prefix and
- a module name. This also works around a just found bug of
- String#rindex.
-
- * ext/extmk.rb.in: ditto.
-
-Fri Jul 13 02:36:10 2001 Minero Aoki <aamine@loveruby.net>
-
- * dir.c (dir_s_chdir): warn only when invoked from multiple
- threads or block is not given.
-
-Thu Jul 12 15:11:48 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * ext/socket/socket.c (ruby_connect): workaround for the setup of
- Cygwin socket(EALREADY).
-
-Mon Jul 9 16:49:30 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * ext/extmk.rb.in: modify RM macro.
-
- * lib/mkmf.rb: ditto.
-
-Sun Jul 8 20:52:02 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * ruby.h: fix a wrong function name: rb_iglob() -> rb_globi().
-
-Sun Jul 8 16:04:35 2001 Minero Aoki <aamine@loveruby.net>
-
- * lib/net/http.rb: rename HTTP#request_by_name to send_request.
-
- * lib/net/protocol.rb (ProtoSocket#read): modify typo.
-
-Sat Jul 7 17:45:35 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * object.c (rb_convert_type): should use rb_rescue(), not rb_rescue2().
-
- * range.c (range_init): ditto.
-
-Fri Jul 6 18:01:10 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * object.c (rb_obj_dup): copies (actually does not free)
- generic_ivar on dupif original owns them.
-
-Fri Jul 6 02:15:06 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * lib/tempfile.rb: a tempfile must be created with mode 0600.
-
-Thu Jul 5 20:28:53 2001 Tietew <tietew@tietew.net>
-
- * string.c (rb_str_each_line): should propagate taint mark.
-
- * ext/nkf/nkf.c (rb_nkf_kconv): ditto.
-
-Fri Jul 6 14:54:27 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_f_require): revamp for simpler implementation.
-
- * file.c (rb_find_file_noext): use String object, instead of
- passing char* around.
-
- * file.c (rb_find_file): ditto.
-
-Thu Jul 5 22:01:02 2001 Mitsuhiro Kondo <kondo@nik-prt.co.jp>
-
- * dln.c (dln_load): should use NSLINKMODULE_OPTION_BINDNOW.
-
-Thu Jul 5 13:44:03 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ruby.c (load_file): local variables 'c' remain uninitialized on
- xflag.
-
-Thu Jul 5 10:00:59 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * regex.c (re_match): prefetched escaped character too early.
-
-Wed Jul 4 08:58:30 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_call0): add argument check for attr_readers.
-
-Wed Jul 4 04:22:44 2001 Minero Aoki <aamine@loveruby.net>
-
- * lib/net/http.rb (HTTP#request_by_name): arg order changes.
-
-Wed Jul 4 04:07:36 2001 Minero Aoki <aamine@loveruby.net>
-
- * lib/net/http.rb (HTTP#request_by_name): bug fix.
-
- * lib/net/http.rb: does not write Connection: by default.
-
- * lib/net/protocol.rb: "start" for started protocol is an error.
-
- * lib/net/protocol.rb: "finish" for finished protocol is an error.
-
-Wed Jul 4 03:17:31 2001 Minero Aoki <aamine@loveruby.net>
-
- * lib/net/http.rb: new method HTTP#request_by_name (test)
-
- * lib/net/http.rb: new class HTTPGenericRequest
-
-Tue Jul 3 23:58:29 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * lib/mkmf.rb: distclean should remove mkmf.log as well.
-
-Tue Jul 3 18:35:49 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_eval_string_wrap): should push frame (and adjust
- cbase) before wrapped eval.
-
- * eval.c (rb_eval_cmd): ditto.
-
- * eval.c (eval): should update ruby_class always after all.
-
-Tue Jul 3 14:56:27 2001 Shugo Maeda <shugo@ruby-lang.org>
-
- * eval.c (block_pass): do not change wrapper information.
-
- * eval.c (rb_yield_0): preserve wrapper information.
-
-Tue Jul 3 08:59:50 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * error.c (rb_name_error): raise NameError instead of LoadError.
-
-Mon Jul 2 17:22:00 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * error.c (exc_exception): clone the receiver exception instead of
- creating brand new exception object of the receiver.
-
-Mon Jul 2 09:53:12 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_eval_string_wrap): extend new ruby_top_self, not
- original self.
-
- * eval.c (rb_eval_cmd): respect ruby_wrapper if set.
-
- * eval.c (eval): do not update ruby_class unless scope is not
- provided.
-
-Sun Jul 1 10:51:15 2001 Shugo Maeda <shugo@ruby-lang.org>
-
- * eval.c (eval): preserve wrapper information.
-
- * eval.c (proc_invoke): ditto.
-
- * eval.c (block_pass): ditto.
-
-Sat Jun 30 02:55:45 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (void_expr): too much warnings for void context
- (e.g. foo[1] that can be mere Proc call).
-
-Fri Jun 29 17:23:18 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * error.c (rb_name_error): new function to raise NameError with
- name attribute set.
-
- * eval.c (rb_f_missing): set name and args in the exception
- object. [new]
-
- * error.c (name_name): NameError#name - new method.
-
- * error.c (nometh_args): NoMethodError#args - new method.
-
-Fri Jun 29 15:29:31 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lex.c (rb_reserved_word): lex_state after tRESCUE should be
- EXPR_MID.
-
-Thu Jun 28 00:21:28 2001 Keiju Ishitsuka <keiju@ishitsuka.com>
-
- * lib/matrix.rb: resolve 'ruby -w' warnings.
-
- * lib/irb/locale.rb: resolve 'ruby -w' warnings.
-
- * lib/irb/multi-irb.rb: resolve 'ruby -w' warnings.
-
- * lib/irb/ruby-lex.rb: fix problem for "\\M-\\..." and "\\C-\\..."
- and resolve 'ruby -w' warnings.
-
- * lib/irb/ruby-token.rb: fix typo
-
- * lib/shell/command-processor.rb: resolve 'ruby -w' warnings.
-
-Wed Jun 27 08:53:26 2001 Minero Aoki <aamine@loveruby.net>
-
- * lib/net/pop.rb: new methods POP3.auth_only, POP3#auth_only
-
- * lib/net/http.rb: HTTP.Proxy returns self if ADDRESS is nil.
-
- * lib/net/protocol.rb: new method ProtocolError#response
-
- * lib/net/protocol.rb,smtp.rb,pop.rb,http.rb: add document.
-
-Tue Jun 26 18:42:42 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * gc.c (add_heap): allocation size of the heap unit is doubled for
- each allocation.
-
-Mon Jun 25 09:54:48 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * dir.c (isdelim): space, tab, and newline are no longer
- delimiters for glob patterns.
-
-Sat Jun 23 22:28:52 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (svalue_to_avalue): new conversion scheme between single
- value and array values.
-
- * eval.c (avalue_to_svalue): ditto.
-
- * eval.c (rb_eval): REXPAND now uses avalue_to_svalue(), return
- and yield too.
-
- * eval.c (rb_yield_0): use avalue_to_svalue().
-
- * eval.c (proc_invoke): Proc#call gives avaules, whereas
- Proc#yield gives mvalues.
-
- * eval.c (bmcall): convert given value (svalue) to avalue.
-
-Sat Jun 23 18:28:52 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/readline/readline.c (readline_event): a non-void function
- should return a value.
-
-Fri Jun 22 23:17:28 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * ext/socket/socket.c (ruby_connect): workaround for the setup of
- Cygwin socket.
-
-Fri Jun 22 23:11:17 2001 Keiju Ishitsuka <keiju@ishitsuka.com>
-
- * lib/irb/locale.rb: fix for require "kconv" problem
-
-Fri Jun 22 18:08:45 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_yield_0): no mvalue_to_svalue conversion here.
-
- * eval.c (massign): takes svalue, convert it to mvalue inside.
-
- * eval.c (rb_eval): parameters for yield/return are always
- svalues now.
-
- * eval.c (svalue_to_mvalue): more strict conversion.
-
- * eval.c (mvalue_to_svalue): ditto.
-
-Fri Jun 22 17:12:23 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * st.c (new_size): prime hash size enabled.
-
- * ext/socket/socket.c (Init_socket): SO_* constants added.
-
-Tue Jun 19 22:24:07 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * gc.c (rb_setjmp): avoid GCC 3.0 warnings.
-
-Tue Jun 19 18:19:30 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/readline/readline.c: add new methods:
- Readline::completion_append_character and
- Readline::completion_append_character=.
-
-Tue Jun 19 16:29:50 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (svalue_to_mvalue): new function to convert from svalue
- to mvalue. [experimental]
-
- * eval.c (mvalue_to_svalue): new function to convert from mvalue
- to svalue.
-
- * eval.c (rb_eval): use mvalue_to_svalue().
-
- * eval.c (rb_yield_0): use mvalue_to_svalue().
-
- * eval.c (proc_invoke): proper mvalue handling.
-
-Mon Jun 18 17:38:50 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_f_require): searches ".rb" and ".so" at the same
- time. previous behavior (search ".rb", then ".so") has a
- security risk (ruby-bugs#PR140).
-
- * array.c (rb_ary_to_ary): new function to replace internal
- rb_Array(), which never calls to_a, but to_ary (rb_Array() might
- call both). [new]
-
-Mon Jun 18 00:43:20 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * regex.c (PUSH_FAILURE_POINT): push option status again.
-
- * regex.c (re_compile_pattern): avoid pushing unnecessary
- option_set.
-
-Sat Jun 16 10:58:48 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_load): tainted string is OK if wrapped *and*
- $SAFE >= 4.
-
-Thu Jun 14 16:27:07 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_thread_start_0): should not nail down higher blocks
- before preserving original context (i.e. should not alter
- original context).
-
-Wed Jun 13 19:34:59 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * dir.c (Init_Dir): add a new method File::fnmatch? along with
- File::Constants::FNM_*. While I am here, FNM_NOCASE is renamed
- to FNM_CASEFOLD which is commonly used by *BSD and GNU libc.
-
-Wed Jun 13 09:33:45 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (proc_yield): new method equivalent to Proc#call but no
- check for number of arguments. [new]
-
-Tue Jun 12 14:21:28 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * lib/mkmf.rb: target_prefix is only for installation, not for
- build.
-
-Tue Jun 12 00:41:18 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (method_eq): new method Method#==. [new]
-
-Mon Jun 11 14:29:41 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * confgure.in: add RUBY_CANONICAL_BUILD.
-
-Sun Jun 10 17:31:47 2001 Guy Decoux <decoux@moulon.inra.fr>
-
- * gc.c (STR_NO_ORIG): STR_NO_ORIG value was different between
- string.c and gc.c
-
-Sat Jun 9 22:10:04 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_eval): should convert *non-array at the end of
- arguments by using Array().
-
-Sat Jun 9 17:04:30 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * hash.c (ruby_setenv): readline library leaves their environment
- strings uncopied. "free" check revised.
-
-Sat Jun 9 16:31:03 2001 Usaku Nakamura <usa@osb.att.ne.jp>
-
- * ext/extmk.rb.in: Use -F and -T for mswin32 because cl.exe doesn't
- support -o officially and cl.exe considers that *.cc and *.cxx are
- OBJs.
-
- * lib/mkmf.rb: ditto.
-
- * win32/Makefile.sub: Use del instead of rm.
- All these changes are derived from Nobuyoshi Nakada's patch.
- Thanks.
-
-Fri Jun 8 22:37:40 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * gc.c (Init_stack): avoid __builtin_frame_address(2) to retrieve
- stack bottom line.
-
-Fri Jun 8 18:14:12 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * st.c (numhash): should shuffle bits by dividing by prime number.
-
-Fri Jun 8 17:05:21 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_eval): multiple assignment behavior fixed, which
- results "*a = nil" makes "a == []" now.
-
-Fri Jun 8 15:25:09 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_f_require): should set SCOPE_PUBLIC before calling
- dln_load().
-
-Thu Jun 7 17:28:00 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (yylex): exclude kDO_BLOCK too much by false condition.
-
-Wed Jun 6 23:02:36 2001 Keiju Ishitsuka <keiju@ishitsuka.com>
-
- * lib/sync.rb: bug fix if obj.initialize has parameters when
- obj.extend(Sync_m)
-
- * lib/mutex_m.rb: modified bit
-
-Wed Jun 6 16:11:06 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_load): should check if tainted even when wrap is
- specified.
-
-Wed Jun 6 14:34:27 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (mrhs_basic): "*arg" should always be expanded by REXPAND.
-
- * regex.c (re_compile_pattern): too much optimization for the
- cases like /(.|a)b/.
-
-Tue Jun 5 23:58:43 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * variable.c (fc_i): removed vast string allocation.
-
-Tue Jun 5 16:45:48 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * error.c (Init_Exception): NameError went under StandardError,
- and NoMethodError went under NameError.
-
-Tue Jun 5 16:40:06 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (rb_intern): non identifier symbols should be
- categorized as ID_JUNK. [new]
-
-Tue Jun 5 16:15:58 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * variable.c (rb_mod_const_at): use hash table as internal
- data. [new]
-
- * variable.c (rb_mod_const_of): ditto.
-
- * variable.c (rb_const_list): new function to convert internal
- data (hash table) to array of strings.
-
- * eval.c (rb_mod_s_constants): data handling scheme has changed.
-
-Tue Jun 5 15:16:06 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_add_method): should not call rb_secure(), for
- last_func may not be set.
-
- * io.c (rb_io_ctl): ioctl should accept any integer within C long
- range.
-
-Tue Jun 5 13:41:13 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * ext/etc/extconf.rb: use egrep_cpp.
-
-Tue Jun 5 12:44:59 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * marshal.c (r_object): wrong type check for modules.
-
- * marshal.c (w_object): should not dump anonymous classes/modules.
-
-Tue Jun 5 01:19:34 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (rb_open_file): use rb_file_sysopen_internal() if the 3rd
- argument (permission flags) is given. [new, should be backported?]
-
- * io.c (rb_io_mode_binmode): mode string (e.g. "r+") to flags to
- open(2).
-
-Mon Jun 4 23:55:54 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_eval): NODE_REXPAND expand an array of 1 element as
- the element itself. [new, should be backported?]
-
- * parse.y (ret_args): should treat "*[a]" in rhs expression as
- "a", not "[a]".
-
-Mon Jun 4 04:14:53 2001 Wakou Aoyama <wakou@fsinet.or.jp>
-
- * lib/shellwords.rb: don't destroy argument.
-
-Sat Jun 2 23:23:05 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * regex.c (re_compile_pattern): should push option modifier at the
- right place.
-
-Sat Jun 2 23:05:20 2001 Shugo Maeda <shugo@ruby-lang.org>
-
- * lib/cgi/session.rb: don't use module_function for Class.
-
-Sat Jun 2 00:02:22 2001 Keiju Ishitsuka <keiju@ishitsuka.com>
-
- * irb messages: fix typos.
-
-Fri Jun 1 17:26:24 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * hash.c (replace_i): ignore when key == Qundef.
-
-Fri Jun 1 16:50:59 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (call_args2): confusion with list_append() and
- list_concat() was fixed.
-
-Fri Jun 1 15:01:40 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (yylex): fixed 'print CGI::bar() {}, "\n"' syntax
- breakage, adding new lex_state status. sigh. [new]
-
-Fri Jun 1 11:21:04 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * configure.in: use waitpid on mingw32.
-
- * ext/dbm/extconf.rb: include <ndbm.h>, not <gdbm.h>.
-
-Thu May 31 18:34:57 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * file.c (rb_file_s_unlink): should not allow if $SAFE >= 2.
-
-Thu May 31 17:23:25 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * range.c (Init_Range): define "to_ary".
-
-Thu May 31 13:30:25 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * mkconfig.rb, ext/configsub.rb: VERSION -> RUBY_VERSION.
-
-Thu May 31 08:00:58 2001 Usaku Nakamura <usa@osb.att.ne.jp>
-
- * win32/dir.h: re-add.
-
-Thu May 31 01:25:59 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * configure.in: default --with-libc_r to `no' until the problem is
- fixed. (FreeBSD only)
-
-Tue May 29 17:24:23 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * ruby.c (proc_options): unexpected SecurityError happens when -T4.
-
-Tue May 29 18:46:04 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * regex.c (re_compile_pattern): * \1 .. \9 should be
- backreferences always.
-
- * regex.c (re_match): backreferences corresponding to
- unclosed/unmatched parentheses should fail always.
-
-Tue May 29 16:35:49 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_cat): use rb_str_buf_cat() if possible. [new]
-
- * string.c (rb_str_append): ditto.
-
- * string.c (rb_str_buf_cat): remove unnecessary check (type,
- taint, modify) to gain performance.
-
- * string.c (rb_str_buf_append): ditto.
-
- * string.c (rb_str_buf_finish): removed.
-
-Tue May 29 02:05:55 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_buf_new): buffering string function. [new]
-
- * string.c (rb_str_buf_append): ditto.
-
- * string.c (rb_str_buf_cat): ditto.
-
- * string.c (rb_str_buf_finish): ditto.
-
-Mon May 28 23:20:43 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * configure.in: remove unnecessary AC_CANONICAL_BUILD
-
- * defins.h: #define HAVE_SETITIMER on Cygwin(bug fixed).
-
- * ruby.c: use relative path from LIBRUBY_SO.
-
- * ruby.c: don't use -mwin32 option on Cygwin.
-
- * cygwin/GNUmakefile.in: ditto.
-
- * ext/sdbm/_sdbm: ditto.
-
- * ext/tcltklib/extconf.rb: ditto.
-
- * ext/tcltklib/stubs.c: ditto.
-
-Mon May 28 22:12:01 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * ext/extconf.rb.in: make the priority of the make rule of .c
- higher than .C .
-
-Mon May 28 13:22:19 2001 Tanaka Akira <akr@m17n.org>
-
- * time.c (make_time_t): local time adjustment revised.
-
-Mon May 28 02:20:38 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * dir.c (glob_helper): teach has_magic() to handle flags and get
- glob_helper to properly support FNM_NOESCAPE.
-
- * dir.c (fnmatch): fix a bug when FNM_PATHNAME and FNM_PERIOD are
- specified at the same time.
-
-Sat May 26 09:55:26 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y: accomplish extended syntax described in [ruby-talk:14525]
- using tSPC token. [new, experimental]
-
-Sat May 26 07:05:45 2001 Usaku Nakamura <usa@osb.att.ne.jp>
-
- * MANIFEST: add win32/dir.h .
-
-Fri May 25 20:03:51 2001 Pascal Rigaux <pixel@mandrakesoft.com>
-
- * dln.c (dln_find_1): should exclude directories in executable
- file lookup.
-
-Fri May 25 18:00:26 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * class.c (rb_obj_singleton_methods): list methods in extended
- modules if optional argument is true. [new]
-
-Fri May 25 14:19:25 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * string.c (rb_str_replace): add taint status infection
- (OBJ_INFECT()).
-
- * string.c (rb_str_crypt): ditto.
-
- * string.c (rb_str_ljust): ditto.
-
- * string.c (rb_str_rjust): ditto.
-
- * string.c (rb_str_center): ditto.
-
-Fri May 25 05:39:03 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/sha1/sha1-ruby.c (sha1_hexdigest): fix buffer overflow. The
- buffer for a SHA-1 hexdigest needs to be 41 bytes in length.
-
-Fri May 25 01:47:39 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * MANIFEST: update the entries I forgot to add or remove.
-
-Fri May 25 00:57:25 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/sha1/sha1-ruby.c (sha1_new): separate initialize() from
- new().
-
- * ext/md5/md5init.c (md5i_new): ditto.
-
-Fri May 25 00:53:41 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/dbm/extconf.rb: fix support for *BSD and set $CFLAGS
- properly.
-
-Thu May 24 16:10:33 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * range.c (range_member): check based on "<=>" comparison. [new]
-
- * range.c (range_check): add "succ" check if first end is not a
- numeric.
-
- * range.c (range_eqq): comparison should based on "<=>".
-
- * range.c (range_each): ditto.
-
-Thu May 24 16:08:21 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * mkconfig.rb: autoconf 2.50 support.
-
-Thu May 24 14:23:35 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_yield_0): need argument adjustment for C defined
- blocks too.
-
-Thu May 24 01:11:30 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ext/dbm/extconf.rb: header search added. [new]
-
-Wed May 23 02:58:21 2001 Tanaka Akira <akr@m17n.org>
-
- * time.c (make_time_t): fix ad-hoc local time adjustment, using
- binary tree search.
-
-Tue May 22 17:10:35 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * variable.c (rb_alias_variable): should not allow variable
- aliasing if $SAFE >= 4.
-
-Tue May 22 02:37:45 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (expr): "break" and "next" to take optional expression,
- which is used as a value for termination. [new, experimental]
-
- * eval.c (rb_eval): "break" can give value to terminating method.
-
- * eval.c (rb_eval): "break" and "next" to take optional expression.
-
- * eval.c (rb_yield_0): "next" can give value to terminating "yield".
-
- * eval.c (rb_iterate): "break" can give value to terminating method.
-
- * eval.c (proc_call): ditto.
-
-Mon May 21 13:15:25 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * bignum.c (rb_big2str): t should be protected from GC.
-
-Sat May 19 09:29:07 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * process.c (rb_proc_times): need not to check retrun value from
- times(2).
-
-Fri May 18 05:36:08 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/extmk.rb.in (xsystem): backout the previous fix which was
- bogus.
-
-Fri May 18 05:19:55 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * lib/mkmf.rb (xsystem): make a temporary fix to get $(...) macros
- properly expanded on a command execution.
-
- * ext/extmk.rb.in (xsystem): ditto.
-
-Fri May 18 03:45:55 2001 Brian F. Feldman <green@FreeBSD.org>
-
- * lib/mkmf.rb: unbreak "make install". lib/* must be installed
- under $rubylibdir, not under $libdir.
-
-Fri May 18 01:28:07 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (expr): break, next, redo, retry are moved from primary.
-
-Fri May 18 01:11:02 2001 Usaku Nakamura <usa@osb.att.ne.jp>
-
- * ext/sha1/sha1-ruby.c (sha1_new): get rid of an unneeded
- rb_obj_call_init() call.
-
-Fri May 18 01:03:55 2001 Usaku Nakamura <usa@osb.att.ne.jp>
-
- * ext/sha1/sha1.txt, ext/sha1/sha1.txt.jp: fix typos.
-
-Thu May 17 19:17:11 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * lib/shell.rb, lib/shell/process-controller.rb,
- lib/shell/command-processor.rb: translate Japanese comments into
- English.
-
-Thu May 17 19:07:14 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * doc/shell.rd.jp: RD'ify and make some fixes.
-
- * doc/shell.rd: RD'ify, delete Japanese leftovers, make overall
- English fixes, and sync with doc/shell.rd.jp.
-
-Thu May 17 17:35:04 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_call0): address of local_vars might change during eval.
-
-Thu May 17 07:27:09 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/md5/md5.txt.jp, ext/sha1/sha1.txt.jp:
- s/SuperClass/Superclass/.
-
-Thu May 17 07:21:44 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/Setup.dj, ext/Setup.emx, ext/Setup.nt, ext/Setup.x68:
- compile sha1 in as well as md5.
-
- * ext/Setup: put sha1 in a comment.
-
-Thu May 17 07:16:38 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/sha1/sha1.txt.jp: add the Japanese version derived from
- ext/md5/md5.txt.jp.
-
- * ext/sha1/sha1.txt: revise the copyright info and reduce the
- difference from ext/md5/md5.txt.
-
- * ext/md5/md5.txt: reduce the difference from ext/sha1/sha1.txt.
-
-Thu May 17 07:11:35 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/sha1/extconf.rb, ext/sha1/sha1.c: use WORDS_BIGENDIAN to
- detect the platform's endian.
-
-Thu May 17 06:31:30 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/md5/md5.txt: make wording fixes, and mention the newly added
- method: "<<".
-
- * ext/md5/md5.txt.jp: ditto.
-
-Wed May 16 18:05:52 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/md5/md5init.c: add an instance method "<<" as an alias for
- "update". (inspired by Steve Coltrin's ruby-sha1)
-
-Tue May 15 17:46:37 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * array.c (rb_ary_and): should not push frozen key string.
-
- * array.c (rb_ary_or): ditto.
-
-Tue May 15 02:18:23 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * lib/thread.rb: rescue ThreadError in case the thread is dead
- just before calling Thread#run.
-
-Mon May 14 13:50:22 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_thread_schedule): should save context before raising
- deadlock, saved context for current thread might be obsolete.
-
- * time.c (make_time_t): non DST timezone shift supported (hopefully).
-
- * time.c (make_time_t): strict range detection for negative time_t.
-
-Mon May 14 11:54:20 2001 Tanaka Akira <akr@m17n.org>
-
- * signal.c: SIGINFO added.
-
-Mon May 14 08:57:06 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_ensure): should not SEGV when prot_tag is NULL.
-
-Sun May 13 23:51:14 2001 Usaku Nakamura <usa@osb.att.ne.jp>
-
- * win32/resource.rb: Modify copyright in resource script.
-
-Sun May 13 14:03:33 2001 Okada Jun <yun@be-in.org>
-
- * lib/thread.rb: fix Queue#pop and SizedQueue#max= to avoid
- deadlock.
-
-Sat May 12 15:43:55 2001 Usaku Nakamura <usa@osb.att.ne.jp>
-
- * win32/win32.c (kill): add support of signal 9 on mswin32/mingw32.
-
-Fri May 11 15:09:52 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * ruby.h (rb_string_value): add volatile to avoid compiler warning.
-
- * string.c (rb_string_value): ditto.
-
-Fri May 11 03:35:33 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * README.EXT: Document find_library(), with_config() and
- dir_config().
-
-Fri May 11 03:34:20 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * README.EXT.jp: Remove the description of find_header() because
- such a function does not actually exist.
-
- * README.EXT.jp: Update the description of dir_config().
-
-Fri May 11 02:42:05 2001 Kazuhiro NISHIYAMA <zn@mbf.nifty.com>
-
- * README, README.jp: Fix CVS access and mailing lists info.
-
-Fri May 11 02:00:44 2001 Ryo HAYASAKA <ryoh@jaist.ac.jp>
-
- * bignum.c (bigdivrem): access boundary bug.
-
-Thu May 10 02:40:47 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * marshal.c (w_object): prohibit dumping out singleton classes.
-
- * object.c (rb_mod_to_s): distinguish singleton classes.
-
- * variable.c (rb_class2name): it's ok to reveal NilClass,
- TrueClass, FalseClass.
-
-Wed May 9 14:38:33 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * eval.c (rb_yield_0): preserve and restore ruby_cref as well.
-
-Tue May 8 18:28:19 2001 Keiju Ishitsuka <keiju@ishitsuka.com>
-
- * lib/irb.rb lib/irb/multi-irb.rb lib/irb/ruby-lex.rb
- lib/irb/version.rb resolve ctrl-c problem
-
-Tue May 8 17:12:43 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * eval.c (is_defined): core dumped during instance_eval for
- special constants.
-
- * eval.c (rb_eval): ditto.
-
-Tue May 8 08:52:57 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * doc/forwardable.rd, doc/forwardable.rd.jp: Hit `=begin' and
- `=end' in proper places so rd2 can format them without a problem.
-
- * doc/irb/irb-tools.rd.jp, doc/irb/irb.rd, doc/irb/irb.rd.jp:
- ditto.
-
-Tue May 8 08:38:53 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * doc/forwardable.rd, doc/forwardable.rd.jp, lib/forwardable.rb:
- Import forwardable 1.1.
-
-Tue May 8 08:34:33 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * doc/irb/irb-tools.rd.jp, doc/irb/irb.rd.jp: Convert from JIS to
- EUC.
-
-Tue May 8 03:46:39 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * sample/rbc.rb: Obsoleted by IRB.
-
-Mon May 7 15:58:45 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (arg): "||=" should not warn for uninitialized instance
- variables.
-
- * eval.c (rb_eval): ditto.
-
- * eval.c (eval): preserve and restore ruby_cref as well.
-
-Mon May 7 15:45:48 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * lib/ftools.rb (syscopy): chmod destination file only if
- it does not exist.
-
-Mon May 7 14:35:57 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * object.c (rb_obj_is_instance_of): takes only class/module as an
- argument.
-
-Sun May 6 16:27:29 2001 Koji Arai <JCA02266@nifty.ne.jp>
-
- * eval.c (is_defined): rb_reg_nth_defined() may return Qnil.
-
-Thu May 3 03:15:06 2001 SHIROYAMA Takayuki <psi@fortune.nest.or.jp>
-
- * configure.in: get --enable-shared to work on MacOS X.
-
- * Makefile.in: make $(LIBRUBY_SO) depend on miniruby properly.
- Now `make -jN' should work without a problem.
-
-Thu May 3 02:07:45 2001 Usaku Nakamura <usa@osb.att.ne.jp>
-
- * win32/config.h.in: add SIZEOF___INT64 definition.
-
-Wed May 2 20:39:35 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * dir.c (rb_glob, rb_globi): remove unnecessary FNM_PATHNAME.
-
-Wed May 2 11:46:13 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * eval.c (block_pass): should not downgrade safe level.
-
-Wed May 2 03:07:49 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ext/dbm/extconf.rb: allow specifying dbm-type explicitly.
-
- * ext/dbm/extconf.rb: avoid gdbm if possible, because it leaks
- memory, whereas gdbm.so doesn't. potential incompatibility.
-
-Wed May 2 02:02:18 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_insert): new method.
-
-Tue May 1 17:55:58 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (yylex): lex_state after RESCUE_MOD should be EXPR_BEG.
-
-Tue May 1 16:23:03 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * array.c (rb_ary_insert): new method.
-
- * array.c (rb_ary_update): new utility function.
-
-Tue May 1 03:24:05 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * lib/irb/completion.rb, lib/irb/frame.rb, lib/irb/xmp.rb,
- doc/irb/irb-tools.rd.jp: Merge from irb-tools 0.7.1.
-
-Tue May 1 03:07:17 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * sample/irb.rb, lib/irb.rb, lib/irb/*, doc/irb/*: Merge from irb
- 0.7.3.
-
- * instruby.rb: Install help-message's too.
-
- * lib/irb/main.rb: This file is not needed anymore.
-
-Fri Apr 27 09:27:10 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (set_outfile): should check if closed before assignment.
-
-Thu Apr 26 22:36:11 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * configure.in: don't use tzname on Cygwin 1.3.1+.
-
- * configure.in: add -mieee/-ieee to CFLAGS on OSF1/Alpha
- to disable "DIVISION BY ZERO" exception.
-
-Thu Apr 26 22:30:43 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_eval): should preserve value of ruby_errinfo.
-
-Thu Apr 26 10:36:09 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_thread_schedule): infinite sleep should not cause
- dead lock.
-
-Wed Apr 25 16:40:44 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * array.c (rb_ary_flatten_bang): proper recursive detection.
-
-Wed Apr 25 15:36:15 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * eval.c (yield_under): need not to prohibit at safe level 4.
-
-Wed Apr 25 15:22:20 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * pack.c (pack_pack): p/P packs nil into NULL.
-
- * pack.c (pack_unpack): p/P unpacks NULL into nil.
-
-Tue Apr 24 15:35:32 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * pack.c (pack_pack): size check for P template.
-
- * ruby.c (set_arg0): wrong predicate when new $0 value is bigger
- than original space.
-
-Tue Apr 24 15:18:49 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/extmk.rb.in, lib/mkmf.rb: (dir_config) do not add the
- specified include directory if already included in $CPPFLAGS.
-
- * ext/extmk.rb.in, lib/mkmf.rb: (dir_config) return a more useful
- value, [include_dir, lib_dir].
-
-Mon Apr 23 14:43:59 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * gc.c (id2ref): should use NUM2ULONG()
-
- * object.c (rb_mod_const_get): check whether name is a class
- variable name.
-
- * object.c (rb_mod_const_set): ditto.
-
- * object.c (rb_mod_const_defined): ditto.
-
-Sat Apr 21 22:33:26 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * marshal.c (w_float): precision changed to "%.16g"
-
-Sat Apr 21 22:07:58 2001 Guy Decoux <decoux@moulon.inra.fr>
-
- * eval.c (rb_call0): wrong retry behavior.
-
-Fri Apr 20 19:12:20 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * numeric.c (fix_aref): a bug on long>int architecture.
-
-Fri Apr 20 14:57:15 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * eval.c (rb_eval_string_wrap): should restore ruby_wrapper.
-
-Sun Apr 22 17:44:37 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * configure.in: add -mieee to CFLAGS on Linux/Alpha
- to disable "DIVISION BY ZERO" exception.
-
- * configure.in: remove -ansi on OSF/1.
-
-Wed Apr 18 04:37:51 2001 Wakou Aoyama <wakou@fsinet.or.jp>
-
- * lib/cgi.rb: CGI::Cookie: no use PATH_INFO.
-
-Wed Apr 18 00:24:40 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * regex.c (re_compile_pattern): char class at either edge of range
- should be invalid.
-
-Tue Apr 17 17:33:55 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (handle_rescue): use === to compare exception match.
-
- * error.c (syserr_eqq): comparison between SytemCallErrors should
- based on their error numbers.
-
-Tue Apr 17 16:54:39 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * eval.c (safe_getter): should use INT2NUM().
-
-Tue Apr 17 15:12:56 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * bignum.c (rb_big2long): 2**31 cannot fit in 31 bit long.
-
-Sat Apr 14 22:46:43 2001 Guy Decoux <decoux@moulon.inra.fr>
-
- * regex.c (calculate_must_string): wrong length calculation.
-
-Sat Apr 14 13:37:32 2001 Usaku Nakamura <usa@osb.att.ne.jp>
-
- * win32/config.status.in: no longer use missing/alloca.c.
-
- * win32/Makefile.sub: ditto.
-
-Fri Apr 13 12:40:48 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * eval.c (rb_thread_start_0): fixed memory leak.
-
-Fri Apr 13 16:41:18 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (none): should clear cmdarg_stack too.
-
-Fri Apr 13 06:19:29 2001 GOTOU YUUZOU <gotoyuzo@notwork.org>
-
- * io.c (rb_fopen): use setvbuf() to avoid recursive malloc() on
- some platforms.
-
-Wed Apr 11 23:36:26 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * file.c (rb_stat_dev): device functions should honor stat field
- types (except long long such as dev_t).
-
-Wed Apr 11 18:07:53 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * eval.c (rb_mod_nesting): should not push nil for nesting array.
-
- * eval.c (rb_mod_s_constants): should not search array by
- rb_mod_const_at() for nil (happens for singleton class).
-
-Wed Apr 11 13:29:26 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * class.c (rb_singleton_class_attached): should modify iv_tbl by
- itself, no longer use rb_iv_set() to avoid freeze check error.
-
- * variable.c (rb_const_get): error message "uninitialized constant
- Foo at Bar::Baz" instead of "uninitialized constantBar::Baz::Foo".
-
-Tue Apr 10 17:52:10 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_mod_included): new hook called from rb_mod_include().
-
-Tue Apr 10 02:24:40 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * io.c (opt_i_set): should strdup() inplace_edit string.
-
-Mon Apr 9 23:29:54 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (exec_under): need to push cref too.
-
-Mon Apr 9 15:20:21 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_f_missing): raise NameError for "undefined local
- variable or method".
-
- * error.c (Init_Exception): new exception NoMethodError.
- NameError moved under ScriptError again.
-
- * eval.c (rb_f_missing): use NoMethodError instead of NameError.
-
-Mon Apr 9 12:05:44 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * file.c (Init_File): should redifine "new" class method.
-
-Mon Apr 9 11:56:52 2001 Shugo Maeda <shugo@ruby-lang.org>
-
- * lib/net/imap.rb: fix typo.
-
-Fri Apr 6 01:46:35 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (PUSH_CREF): sharing cref node was problematic. maintain
- runtime cref list instead.
-
- * eval.c (rb_eval): copy defn node before registering.
-
- * eval.c (rb_load): clear ruby_cref before loading.
-
-Thu Apr 5 22:40:12 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * variable.c (rb_const_get): no recursion to show full class path
- for modules.
-
- * eval.c (rb_set_safe_level): should set safe level in curr_thread
- as well.
-
- * eval.c (safe_setter): ditto.
-
-Thu Apr 5 13:46:06 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * object.c (rb_obj_is_instance_of): nil belongs to false, not true.
-
-Thu Apr 5 02:19:03 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * time.c (make_time_t): proper (I hope) daylight saving time
- handling for both US and Europe. I HATE DST!
-
- * eval.c (rb_thread_wait_for): non blocked signal interrupt should
- stop the interval.
-
-Wed Apr 4 03:47:03 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (proc_eq): class check aded.
-
- * eval.c (proc_eq): typo fixed ("return" was ommitted).
-
- * error.c (Init_Exception): move NameError under StandardError.
-
- * class.c (rb_mod_clone): should copy method bodies too.
-
- * bignum.c (bigdivrem): should trim trailing zero bdigits of
- remainder, even if dd == 0.
-
- * file.c (check3rdbyte): safe string check moved here.
-
-Tue Apr 3 09:56:20 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * ext/extmk.rb.in (create_makefile): create def file only if
- it does not yet exist.
-
- * lib/mkmf.rb: ditto.
-
-Tue Apr 3 00:05:07 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * time.c (make_time_t): remove HAVE_TM_ZONE code since it
- sometimes reports wrong time.
-
- * time.c (make_time_t): remove unnecessary range check for
- platforms where negative time_t is available.
-
-Mon Apr 2 16:52:48 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * process.c (proc_waitall): should push Process::Status instead of
- Finuxm status.
-
- * process.c (waitall_each): should add all entries in pid_tbl.
- these changes are inspired by Koji Arai. Thanks.
-
- * process.c (proc_wait): should not iterate if pid_tbl is 0.
-
- * process.c (proc_waitall): ditto.
-
-Mon Apr 2 14:25:49 2001 Shugo Maeda <shugo@ruby-lang.org>
-
- * lib/monitor.rb (wait): ensure reentrance.
-
- * lib/monitor.rb (wait): fix timeout support.
-
-Mon Apr 2 12:40:45 2001 Shugo Maeda <shugo@ruby-lang.org>
-
- * lib/net/imap.rb (media_subtype): return subtype.
-
-Mon Apr 2 12:01:15 2001 Shugo Maeda <shugo@ruby-lang.org>
-
- * lib/net/imap.rb (flag_list): capitalize flags.
-
-Mon Apr 2 01:32:38 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * Makefile.in: Introduce MAINLIBS.
-
- * configure.in: Link libc_r against the ruby executable on
- FreeBSD, which is the first attempt to work around a certain
- problem regarding pthread on FreeBSD. It should make ruby/libruby
- happy when it loads an extention to a library compiled and linked
- with -pthread. Note, however, that libruby is _not_ linked with
- libc_r so as not to mess up pthread unfriendly stuff including
- apache+mod_ruby and vim6+ruby_interp.
-
-Mon Apr 2 01:16:24 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * win32/win32.c: use ruby's opendir on mingw32.
-
- * win32/dir.h, dir.c, Makefile: ditto.
-
-Sun Apr 1 23:26:14 2001 TOYOFUKU Chikanobu <toyofuku@juice.or.jp>
-
- * numeric.c (flodivmod): a bug in no fmod case.
-
-Sun Apr 1 18:36:14 2001 Koji Arai <JCA02266@nifty.ne.jp>
-
- * process.c (pst_wifsignaled): should apply WIFSIGNALED for status
- (int), not st (VALUE).
-
-Sat Mar 31 04:47:55 2001 Shugo Maeda <shugo@ruby-lang.org>
-
- * lib/net/imap.rb: add document and example code.
-
-Sat Mar 31 03:24:10 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (Init_IO): value of $/ and $\ are no longer restricted to
- strings. type checks are done on demand.
-
- * class.c (rb_include_module): module inclusion should be check
- taints.
-
- * ruby.h (STR2CSTR): replace to StringType() and StringTypePtr().
-
- * ruby.h (rb_str2cstr): ditto.
-
-Fri Mar 30 23:37:49 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_load): should not copy topleve local variables. It
- cause variable/method ambiguity. Thanks to L. Peter Deutsch.
-
-Fri Mar 30 22:56:56 2001 Shugo Maeda <shugo@ruby-lang.org>
-
- * lib/net/imap.rb: rename ContinueRequest to ContinuationRequest.
-
-Fri Mar 30 12:51:19 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * class.c (rb_include_module): freeze check at first.
-
-Thu Mar 29 17:05:09 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_attr): sprintf() and rb_intern() moved into
- conditional body.
-
-Wed Mar 28 23:43:00 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * ext/extmk.rb.in, lib/mkmf.rb: add C++ rules in addition to C
- rules for the mswin32 platforms.
-
-Wed Mar 28 19:29:21 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/extmk.rb.in, lib/mkmf.rb: move C++ rules to the right place.
-
-Wed Mar 28 17:39:04 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * object.c (rb_str2cstr): warn if string contains \0 and length
- value is ignored.
-
-Wed Mar 28 15:00:31 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * class.c (rb_singleton_class_clone): should copy class constant
- table as well.
-
-Wed Mar 28 14:23:23 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * class.c (rb_include_module): sometimes cache was mistakenly left
- uncleared - based on the patch by K.Kosako.
-
- * ruby.h: all Check_SafeStr()'s are replaced by SafeStr() to
- ensure 'to_str' be always effective.
-
-Wed Mar 28 09:52:33 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * win32/Makefile.sub: disable global optimization.
-
-Tue Mar 27 15:00:54 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * eval.c (rb_mod_define_method): should have clear method cache.
-
- * eval.c (rb_mod_define_method): should have raised exception for
- type error.
-
-Tue Mar 27 14:48:17 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ruby.h: changed "extern INLINE" to "static inline".
-
-Mon Mar 26 23:19:33 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * time.c (rb_strftime): check whether strftime returns empty string.
-
-Mon Mar 26 21:16:56 2001 Shugo Maeda <shugo@ruby-lang.org>
-
- * lib/net/imap.rb: supports response handlers and multiple commands.
-
-Mon Mar 26 17:21:07 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c: remove TMP_PROTECT_END to prevent C_ALLOCA crash.
-
-Mon Mar 26 14:04:41 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * ext/Win32API/Win32API.c: remove Init_win32api().
-
-Sun Mar 25 16:52:48 2001 Koji Arai <JCA02266@nifty.ne.jp>
-
- * file.c (rb_file_flock): do not trap EINTR.
-
- * missing/flock.c (flock): returns the value from lockf(2)
- directly.
-
-Sat Mar 24 23:44:50 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (ev_const_defined): should ignore toplevel cbase (Object).
-
- * eval.c (ev_const_get): ditto.
-
-Fri Mar 23 17:37:52 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ext/md5/md5.h: replace by independent md5 implementation
- contributed by L. Peter Deutsch (thanks).
-
- * ext/md5/md5init.c: adopted to Deutsch's md5 implementation.
-
-Fri Mar 23 17:26:19 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * pack.c (pack_unpack): string from P/p should be tainted.
-
-Fri Mar 23 12:18:44 2001 SHIROYAMA Takayuki <psi@fortune.nest.or.jp>
-
- * ext/curses/curses.c: curses on Mac OS X public beta does not
- have _maxx etc.
-
-Fri Mar 23 10:50:31 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * marshal.c (w_object): should truncate trailing zero short for
- bignums.
-
-Fri Mar 23 09:49:02 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * object.c (sym_intern): new method.
-
-Thu Mar 22 22:15:45 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * ext/Win32API/extconf.rb: add -fno-omit-frame-pointer.
-
-Thu Mar 22 18:17:36 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_mod_nesting): should not include Object at the
- toplevel.
-
-Thu Mar 22 17:43:44 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ruby.h: better inline function support.
-
- * configure.in (NO_C_INLINE): check if inline is available for the
- C compiler.
-
-Mon Mar 19 11:03:10 2001 Koji Arai <JCA02266@nifty.ne.jp>
-
- * marshal.c (r_object): len calculation patch was wrong for
- machines SIZEOF_BDIGITS == SIZEOF_SHORT.
-
- * gc.c: alloca prototype reorganized for C_ALLOCA machine.
-
-Wed Mar 21 23:07:45 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * win32/win32.c (win32_stat): WinNT/2k "//host/share" support.
-
-Wed Mar 21 08:05:35 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * win32/dir.h: replace missing/dir.h .
-
- * win32/win32.h: ditto.
-
- * win32/win32.c: ditto.
-
-Wed Mar 21 01:26:14 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * gc.c (id2ref): sometimes confused symbol and reference.
-
-Tue Mar 20 23:09:33 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * win32/win32.c (win32_stat): UNC support.
-
- * dir.c (extract_path): fix "./*" problem.
-
-Tue Mar 20 15:10:00 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * dir.c (glob_helper): breaks loop after calling recusive
- glob_helper; all wild cards should be consumed; no need for
- further match.
-
- * dir.c (dir_s_glob): gives warning if no match found.
-
-Tue Mar 20 14:13:45 Koji Arai <JCA02266@nifty.ne.jp>
-
- * object.c (sym_inspect): did allocate extra byte space.
-
-Mon Mar 19 19:14:47 2001 Guy Decoux <decoux@moulon.inra.fr>
-
- * marshal.c (shortlen): shortlen should return number of bytes
- written.
-
-Mon Mar 19 16:52:23 2001 K.Kosako <kosako@sofnec.co.jp>
-
- * eval.c (ev_const_defined): need not to check if cbase->nd_class
- is rb_cObject.
-
- * eval.c (ev_const_get): ditto.
-
-Mon Mar 19 17:11:20 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * time.c (time_zone): return "UTC" for UTC time objects.
-
-Mon Mar 19 16:27:32 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (THREAD_ALLOC): flags should be initialized.
-
- * signal.c (rb_f_kill): should use FIX2INT, not FIX2UINT.
-
-Mon Mar 19 10:55:10 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * dir.c (glob_helper): replace lstat() by stat() to follow symlink
- in the case like 'symlink/*'.
-
- * dir.c (glob_helper): gave warning too much.
-
-Sun Mar 18 08:58:18 2001 Wakou Aoyama <wakou@fsinet.or.jp>
-
- * lib/cgi.rb: // === '' --> //.match('')
-
- * lib/cgi.rb: cgi#header(): improvement for mod_ruby.
-
- * lib/cgi.rb: cgi#rfc1123date(): improvement.
- thanks to TADA Tadashi <sho@spc.gr.jp>.
-
- * lib/cgi.rb: cgi#rfc1123date(): document bug fix.
- thanks to Kazuhiro NISHIYAMA <zn@mbf.nifty.com>.
-
- * lib/cgi.rb: cgi#header(): bug fix.
- thanks to IWATSUKI Hiroyuki <don@na.rim.or.jp>.
-
-Sat Mar 17 11:11:24 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * dir.c (glob_helper): * should follow symlink, whereas ** should
- not follow.
-
-Thu Mar 15 01:28:02 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * dir.c (dir_s_chdir): block form of Dir.chdir. (RCR#U016).
-
-Fri Mar 16 17:14:17 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * configure.in: Set SOLIBS properly for all ELF and
- FreeBSD/NetBSD/OpenBSD a.out platforms so that the shlib
- dependencies are recorded in the libruby shlib.
-
-Wed Mar 14 16:41:45 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_thread_schedule): raise FATAL just once to
- THREAD_TO_KILL.
-
-Wed Mar 14 10:41:34 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_yield_0): 0 (= Qfalse) is a valid value, so that
- default self should be checked by klass == 0.
-
- * bignum.c (rb_cstr2inum): should disallow '++1', '+-1', etc.
-
-Tue Mar 13 17:51:09 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (ev_const_defined): add new parameter self for special
- const fallback.
-
- * eval.c (ev_const_get): ditto.
-
-Tue Mar 13 16:39:45 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * dir.c (rb_glob_helper): fix drive letter handling on DOSISH.
-
-Tue Mar 13 14:54:39 2001 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/http.rb: add HTTPRequest#basic_auth.
-
- * lib/net/smtp.rb: raise if only account or password is given.
-
- * lib/net/protocol.rb: WriteAdapter#<< returns self.
-
-Tue Mar 13 14:41:16 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (argf_seek_m): wrong calling sequence of rb_io_seek().
-
-Tue Mar 13 09:14:19 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (cond0): no special treatment of string literal in
- condition.
-
-Mon Mar 12 18:59:38 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * lib/mkmf.rb (create_makefile): save/restore $libs and $LIBPATH.
-
-Sun Mar 11 18:13:34 2001 Masahiro Tanaka <masa@stars.gsfc.nasa.gov>
-
- * math.c: add acos, asin, atan, conh, sinh, tanh and hypot to Math.
-
- * configure.in: check hypot availablility.
-
- * missing/hypot.c: public domain rewrite of hypot.
-
-Sun Mar 11 13:21:04 2001 Koji Arai <JCA02266@nifty.ne.jp>
-
- * parse.y (warn_unless_e_option): warning condition was wrong.
-
- * parse.y (warning_unless_e_option): ditto.
-
-Sun Mar 11 00:55:31 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * lib/mkmf.rb (install_rb): fix handling of destination path.
-
-Sat Mar 10 22:56:44 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * enum.c (enum_all): new method 'all?', which returns true if
- block returns true for all elements.
-
- * enum.c (enum_any): new method 'any?', which returns true if
- block retruns true for any of elements.
-
-Sat Mar 10 02:34:18 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * math.c (math_log, math_log10): use nan() instead of 0.0/0.0 on Cygwin.
-
-Fri Mar 9 09:56:19 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * marshal.c (marshal_load): do not give warning unless explicitly
- set to verbose.
-
-Fri Mar 9 02:07:53 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_exit): give string value "exit" to SystemExit.
-
- * ruby.c (proc_options): -v should not print version if
- proc_options called via moreswitches().
-
-Thu Mar 8 17:45:19 2001 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb: one write(2) per one line.
-
-Wed Mar 7 14:26:11 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * math.c (math_log, math_log10): should return NaN if x < 0.0
- on Cygwin.
-
-Thu Mar 7 10:31:26 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * parse.y (stmt): while/until modifier must work for empty body.
-
-Tue Mar 6 22:53:58 2001 Kazuhiro Yoshida <moriq.kazuhiro@nifty.ne.jp>
-
- * ruby.c (ruby_set_argv): clear ARGV contents before adding args.
-
-Tue Mar 6 10:50:29 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (primary): rescue and ensure clauses should be allowed
- to appear in singleton method body.
-
-Mon Mar 5 17:25:13 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (proc_eq): compare Procs using blocktag equality.
-
- * eval.c (proc_to_s): stringify according to block tag address.
-
-Mon Mar 5 17:19:56 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * win32/win32.c (gettimeofday): use GetLocalTime() instead of ftime()
- for high-resolution timing.
-
-Sun Mar 4 17:01:09 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * string.c (trnext): support backslash escape in String#tr.
-
-Sat Mar 3 16:15:16 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_eval): push cbase if ruby_cbase != ruby_class, for
- example in the case NODE_DEFN/NODE_DEFS are called within
- module_eval.
-
-Wed Feb 28 11:02:41 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_delete_bang): delete! should take at least 1
- argument.
-
- * ruby.c (load_file): add rb_gc() after loading to avoid
- extraordinary memory growth.
-
-Wed Feb 28 05:01:40 2001 Koji Arai <JCA02266@nifty.ne.jp>
-
- * dir.c (rb_glob_helper): "./foo" should match "foo", not "./foo".
-
-Tue Feb 27 16:38:15 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (ev_const_get): retrieve Object's constant if no current
- class is available (e.g. defining singleton class for Fixnums).
-
- * eval.c (ev_const_defined): check Object's constant if no current
- class is available (e.g. defining singleton class for Fixnums).
-
- * time.c (time_timeval): negative time interval shoule not be
- allowed.
-
- * eval.c (proc_call): ignore block to `call' always, despite of
- being orphan or not.
-
-Wed Feb 27 10:16:32 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * eval.c (rb_yield_0): should check based on rb_block_given_p()
- and rb_f_block_given_p().
-
-Tue Feb 27 04:13:45 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * configure.in (frame-address): --enable-frame-address to allow
- __builtin_frame_address() to be used.
-
- * eval.c (stack_length): use __builtin_frame_address() based on
- the macro USE_BUILTIN_FRAME_ADDRESS.
-
- * gc.c (rb_gc): ditto.
-
- * gc.c (Init_stack): ditto.
-
-Mon Feb 26 16:20:27 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ruby.c (proc_options): call ruby_show_version() just once.
-
- * dir.c (dir_s_open): returns the value from a block (if given).
-
-Mon Feb 26 14:29:04 2001 Akinori MUSHA <knu@iDaemons.org>
-
- * ext/extmk.rb.in, lib/mkmf.rb: add C++ rules in addition to C
- rules.
-
-Mon Feb 26 00:04:52 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (proc_call): should not modify ruby_block->frame.iter
- based on ruby_frame->iter altered by PUSH_ITER().
-
-Mon Feb 26 05:27:52 2001 Wakou Aoyama <wakou@fsinet.or.jp>
-
- * lib/net/telnet.rb: #telnetmode(), #binmode(): bug fix.
- thanks to nobu.nakada@nifty.ne.jp.
-
-Mon Feb 26 04:55:50 2001 Wakou Aoyama <wakou@fsinet.or.jp>
-
- * lib/cgi.rb: CGI#form(): bug fix.
- thanks to MoonWolf <moonwolf@moonwolf.com>.
-
- * lib/cgi.rb: CGI#rfc1123_date(): improvement.
- thanks to Tomoyasu Akita <genzo-@dm4lab.to>.
-
- * lib/cgi.rb: CGI#header(): improvement for mod_ruby.
- thanks to Shugo Maeda <shugo@ruby-lang.org>.
-
-Sun Feb 25 02:45:30 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * file.c (rb_file_s_rename): avoid Cygwin's bug.
-
-Sat Feb 24 23:32:55 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_thread_fd_close): should save current context before
- raising exception.
-
-Sat Feb 24 22:14:00 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * win32/win32.c (myrename): fix error handling.
-
-Sat Feb 24 13:58:48 2001 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/http.rb: always close connection on request without
- body.
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: change copyright.
-
-Sat Feb 24 03:15:49 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (set_stdin): preserve original stdin.
-
- * io.c (set_outfile): preserve original stdout/stderr.
-
-Fri Feb 23 08:28:58 2001 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb: clear read buffer after reopen.
-
- * lib/net/protocol.rb: refactoring.
-
- * lib/net/http.rb: split module HTTPHeader from HTTPResponse.
-
-Tue Feb 20 23:45:35 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * process.c: add W* macro if not available.
-
-Tue Feb 20 16:37:58 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * configure.in: add check for negative time_t for gmtime(3).
-
- * time.c (time_new_internal): no positive check if gmtime(3) can
- handle negative time_t.
-
- * time.c (time_timeval): ditto.
-
- * bignum.c (rb_big2long): should not raise RangeError for Bignum
- LONG_MIN value.
-
-Mon Feb 19 17:46:37 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_substr): "a"[1,2] should return ""; need
- rubicon upgrade.
-
-Mon Feb 19 12:10:36 2001 Triet H. Lai <thlai@mail.usyd.edu.au>
-
- * error.c (rb_sys_warning): new function to give warning with
- strerror() message.
-
- * dir.c (rb_glob_helper): better error handling, along with
- performance tune.
-
-Mon Feb 19 01:55:43 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (secure_visibility): visibility check for untainted modules.
-
-Mon Feb 19 00:29:29 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * signal.c (sigpipe): sighandler which does nothing.
-
- * signal.c (trap): set sigpipe function for SIGPIPE.
-
- * signal.c (Init_signal): default SIGPIPE handler should be
- sigpipe function.
-
-Sun Feb 18 15:42:38 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * ext/curses/extconf.rb: add dir_config.
-
- * missing/flock.c: use fcntl(2) instead of lockf(2).
-
-Sun Feb 18 05:46:03 2001 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/http.rb: Response#range_length was not debugged.
-
-Sun Feb 18 04:02:03 2001 Yasushi Shoji <yashi@yashi.com>
-
- * array.c (rb_ary_subseq): wrong boundary check.
-
-Sun Feb 18 00:09:50 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * win32/win32.c: make file I/O faster on mswin32/mingw32.
-
- * win32/win32.h: ditto.
-
- * rubysig.h: ditto.
-
-Sat Feb 17 23:32:45 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (cond0): integer literal in condition should not be
- compared to lineno ($.).
-
-Fri Feb 16 01:44:56 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (set_outfile): f should be the FILE* from the assigning value.
-
- * ext/socket/socket.c (tcp_s_open): should not give default value
- to local_host.
-
- * time.c (time_s_times): move to Process::times.
-
- * file.c (rb_file_s_lchmod): new method File::lchmod.
-
- * file.c (rb_file_s_lchown): new method File::lchown.
-
-Thu Feb 15 11:33:49 2001 Shugo Maeda <shugo@ruby-lang.org>
-
- * lib/cgi/session.rb (close): fixed reversed condition.
-
-Thu Feb 15 08:34:14 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * process.c (proc_waitall): new method based on a patch from Brian
- Fundakowski Feldman <green@green.dyndns.org>.
-
- * process.c (last_status_set): objectify $? value (Process::Status).
-
-Wed Feb 14 17:28:24 2001 Shugo Maeda <shugo@ruby-lang.org>
-
- * lib/net/imap.rb: supports unknown resp_text_code.
-
-Wed Feb 14 00:44:17 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * dir.c (dir_s_glob): support backslash escape of metacharacters
- and delimiters.
-
- * dir.c (remove_backslases): remove backslashes from path before
- calling stat(2).
-
- * dir.c (dir_s_glob): call rb_yield directly (via push_pattern) if
- block is given to the method.
-
- * dir.c (push_pattern): do not call rb_ary_push; yield directly.
-
- * eval.c (blk_copy_prev): reduced ALLOC_N too much.
-
- * eval.c (frame_dup): ditto.
-
-Tue Feb 13 23:05:38 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * dir.c (lstat): should use rb_sys_stat if lstat(2) is not
- available.
-
-Tue Feb 13 08:43:10 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (rb_io_ctl): do not call ioctl/fcntl for f2, if f and f2
- have same fileno.
-
-Tue Feb 13 01:13:43 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_load): raise LocaJumpError if unexpected local jumps
- appear during load.
-
- * ext/socket/socket.c (bsock_close_read): don't call rb_thread_fd_close();
- it's supposed to be called by io_io_close().
-
- * ext/socket/socket.c (bsock_close_read): do not modify f and f2.
-
- * ext/socket/socket.c (bsock_close_write): ditto.
-
- * ext/socket/socket.c (sock_new): avoid dup(2) on sockets.
-
- * parse.y (primary): preserve and clear in_single and in_def using
- stack to prevent nested method errors in singleton class bodies.
-
-Sun Feb 11 16:00:30 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * eval.c (stack_length): use __builtin_frame_address() only if
- GCC and i386 CPU.
-
- * gc.c (rb_gc, Init_stack): ditto.
-
- * configure.in: add ac_cv_func_getpgrp_void=yes on DJGPP.
-
-Sat Feb 10 23:43:49 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * hash.c (rb_any_hash): dumped core on machines sizeof(int) != sizeof(long).
-
-Sat Feb 10 23:07:15 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (rb_io_s_for_fd): IO::for_fd(fd) - new method.
-
- * regex.c (PREV_IS_A_LETTER): should not treat c>0x7f as a word
- character if -Kn.
-
-Sat Feb 10 00:00:30 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * win32/win32.c (win32_stat): replace stat to enable when pathname
- ends with '/' or '\' for mswin32 on Win9X / Win2k.
-
- * win32/win32.h: ditto.
-
- * ruby.h: ditto.
-
- * dir.c (rb_glob_helper): ditto.
-
- * file.c (rb_stat, rb_file_s_stat, eaccess, check3rdbyte): ditto.
-
-Fri Feb 9 22:54:57 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * ruby.c (ruby_init_loadpath): convert '\\' to '/'
- before finding executable file path.
-
-Fri Feb 9 17:41:53 2001 Triet H. Lai <thlai@mail.usyd.edu.au>
-
- * dir.c (rb_glob_helper): do not follow symbolic links.
-
-Thu Feb 8 21:27:24 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * lib/mkmf.rb (install_rb): fix handling of relative path.
-
- * lib/mkmf.rb (create_makefile): add srcdir.
-
-Thu Feb 8 02:22:09 2001 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/http.rb: join HTTPReadResponse into HTTPResponse again.
-
- * lib/net/http.rb: move http_version() from HTTPRequest to
- HTTPResponse.
-
- * lib/net/protocol.rb: refactoring.
-
-Wed Feb 7 16:27:27 2001 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/http.rb: split HTTPResponse into HTTPReadResponse
- module.
-
- * lib/net/protocol.rb: add Net::net_private.
-
- * lib/net/protocol.rb: Socket#reopen takes arg, open_timeout.
-
-Wed Feb 7 16:05:22 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * parse.y (parse_quotedwords): %w should allow parenthesis escape.
-
-Wed Feb 7 00:57:42 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (parse_qstring): %q should allow terminator escape.
-
- * re.c (rb_reg_options): new method to give an option values.
-
- * parse.y (cond0): disable special treating of integer literal in
- conditional unless option -e is supplied. changes current
- behavior. experimental.
-
- * parse.y (cond0): give warning for string/integer literals and
- dot operators in conditionals unless option -e is supplied.
-
- * re.c (rb_reg_equal): all option flags should be same to be equal.
-
-Tue Feb 6 21:30:44 2001 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/http.rb: call on_connect() on re-opening socket.
-
- * lib/net/pop.rb: also POP3 can use APOP auth.
-
-Tue Feb 6 20:19:10 2001 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/http.rb: add HTTP#request.
-
- * lib/net/http.rb: take HTTP 1.0 server into account (incomplete).
-
- * lib/net/protocol.rb: timeout for open/read.
-
- * lib/net/protocol.rb: add Protocol#on_connect,on_disconnect.
-
-Mon Feb 5 23:15:46 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * error.c (Init_Exception): make Interrupt a subclass of
- SignalException.
-
-Mon Feb 5 00:39:06 2001 KANEKO Naoshi <wbs01621@mail.wbs.ne.jp>
-
- * dir.c: use ISXXX() instead of isxxx().
-
- * dln.c (aix_loaderror): ditto.
-
- * file.c (rb_file_s_expand_path): ditto.
-
- * string.c (rb_str_upcase_bang): ditto.
-
- * win32/win32.c (do_spawn): ditto.
-
- * win32/win32.c (NtMakeCmdVector): ditto.
-
- * win32/win32.c (opendir): ditto.
-
-Sat Feb 3 14:44:53 2001 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * configure.in (AC_C_INLINE): check inline attribute.
-
- * gc.c (is_pointer_to_heap): use inline rather than __inline__.
-
- * pack.c (hex2num): ditto.
-
- * ruby.h (rb_class_of, rb_type, rb_special_const_p): ditto.
-
- * util.c (rb_class_of, rb_type, rb_special_const_p): defined in
- ruby.h.
-
-Fri Feb 2 16:14:51 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * array.c (rb_ary_sort_bang): returns self, even if its length is
- less than 2.
-
- * eval.c (POP_VARS): propagate DVAR_DONT_RECYCLE, if
- SCOPE_DONT_RECYCLE of ruby_scope is set.
-
-Wed Jan 31 22:27:29 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * configure.in: gcc-2.95.2-7(Cygwin) support.
- add -mwin32 if available.
-
- * cygwin/GNUmakefile: ditto.
-
-Tue Jan 30 17:56:48 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * array.c (rb_ary_fetch): new method.
-
-Mon Jan 29 17:36:19 2001 TOYOFUKU Chikanobu <toyofuku@juice.or.jp>
-
- * eval.c (rb_eval): nd_iter evaluation should be wrapped by
- BEGIN_CALLARGS and END_CALLARGS.
-
-Mon Jan 29 14:25:39 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (block_pass): return from block jumps directory to
- block invoker.
-
-Mon Jan 29 01:40:27 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (str_independent): should not clear str->orig here.
- it's too early.
-
-Fri Jan 26 01:42:40 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y: clarify do ambiguity, bit more complex but natural
- from my point of view.
-
-Wed Jan 24 14:58:08 2001 Akinori MUSHA <knu@ruby-lang.org>
-
- * lib/cgi.rb: fix the problem that when running under mod_ruby
- header() outputs only one Set-Cookie line.
-
-Wed Jan 24 01:45:49 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (POP_BLOCK_TAG): call rb_gc_force_recycle() if block has
- not been objectified.
-
- * eval.c (rb_callcc): should nail down block->tag history to avoid
- rb_gc_force_recycle().
-
-Tue Jan 23 18:51:57 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * gc.c (rb_gc_call_finalizer_at_exit): should finalize objects in
- deferred_final_list too.
-
-Tue Jan 23 16:10:12 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * gc.c (os_live_obj): do not list terminated object.
-
- * gc.c (os_obj_of): ditto.
-
- * gc.c (rb_gc_mark): support new T_BLKTAG tag.
-
- * gc.c (obj_free): ditto.
-
- * eval.c (new_blktag): creation of new block tag, which holds
- destination of global jump and orphan status.
-
- * eval.c (block_pass): break from orphan Proc object will raise a
- LocalJumpError exception.
-
-Mon Jan 22 16:33:16 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * mkconfig.rb: autoconf 2.49 support.
-
-Mon Jan 22 00:32:44 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (block_pass): behavior consistency with proc_call(). do
- not propagate `break'.
-
-Sat Jan 20 03:54:00 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (yylex): fixed serious syntax misbehavior. do's
- preceding was too high. a block in `foo bar do .. end' should
- be passed to `foo', not `bar'.
-
- * parse.y (block_call): syntax restructure.
-
-Thu Jan 18 04:28:14 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (rb_io_s_read): new method to call IO#read from
- pathname. In addition, it accepts third optional argument to
- specify starting point.
-
-Wed Jan 17 13:28:26 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * configure.in: remove DEFS definition.
-
- * mkconfig.rb: ditto.
-
- * win32/config.status.in: ditto.
-
-Tue Jan 16 17:00:50 2001 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb: ignore EOFError for read.
-
- * lib/net/http.rb: user specified header was not used.
-
-Mon Jan 15 16:00:07 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * pack.c (pack_unpack): should check associated pointer packed by
- pack("P"). Thus pointers can be retrieved only from pointer
- packed strings. restriction added.
-
-Sun Jan 14 21:49:28 2001 Koji Arai <JCA02266@nifty.ne.jp>
-
- * sprintf.c (rb_f_sprintf): simple typo. binary base should be 2,
- not '2'.
-
- * re.c (rb_reg_s_last_match): should explicitly return nth match.
-
-Sun Jan 14 18:21:30 2001 Usaku Nakamura <usa@osb.att.ne.jp>
-
- * win32/config.status.in: add some field.
-
- * win32/win32.c (isInternalCmd): ignore case for shell's internal
- command.
-
- * win32/win32.c (do_spawn): recognize quoted command line.
-
-Sun Jan 14 04:10:27 2001 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb (adding): too few "yield" in case of arg is
- not String/File.
-
- * lib/net/http.rb: add http request object.
-
-Sat Jan 13 19:39:30 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * re.c (rb_reg_desc): separate RE_OPTION_MULTILINE
-
- * re.c (rb_reg_options): add RE_OPTION_{POSIXLINE,RE_OPTION_MULTILINE,
- RE_OPTION_EXTENDED}
-
-Thu Jan 11 10:45:04 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * win32/win32.h, win32/config.h.in: move NORETURN from win32.h
- to config.h.in.
-
- * win32/config.h.in (inline): renamed from INLINE.
-
- * djgpp/config.hin (INLINE): removed.
-
-Thu Jan 11 06:45:55 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * object.c (rb_mod_dup): should propagate FL_SINGLETON.
-
- * object.c (inspect_obj): handles the case of no instance variable.
-
-Wed Jan 10 16:15:08 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * ruby.h: NORETURN macro is changed for VC++ 6.0.
-
- * eval.c, intern.h: ditto.
-
- * djgpp/config.hin, win32/win32.h: ditto.
-
- * configure.in: ditto.
-
-Wed Jan 10 13:54:53 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * process.c (proc_setuid): use setresuid() if available.
-
- * process.c (proc_setgid): use setresgid() if available.
-
- * configure.in: ditto.
-
-Wed Jan 10 01:50:45 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * configure.in (AC_C_INLINE): check inline attribute.
-
- * string.c (rb_str_reverse_bang): forgot to call rb_str_modify().
-
-Tue Jan 9 17:41:40 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * object.c (rb_obj_taint): check frozen status before modifying
- taint status.
-
- * object.c (rb_obj_untaint): ditto.
-
-Tue Jan 9 16:22:14 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * enum.c (enum_inject): new method.
-
-Tue Jan 9 02:16:42 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * gc.c (rb_gc_call_finalizer_at_exit): clear klass member of
- terminating object.
-
- * eval.c (rb_call): raise exception for terminated object.
-
-Mon Jan 8 21:24:37 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * bignum.c (bigdivrem): t2 might be too big for signed long; do
- not use rb_int2big(), but rb_uint2big().
-
-Mon Jan 8 21:35:10 2001 Guy Decoux <decoux@moulon.inra.fr>
-
- * file.c (path_check_1): should restore modified path.
-
-Mon Jan 8 03:09:58 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * error.c (rb_load_fail): new func to report LoadError.
-
- * ruby.c (load_file): use rb_load_fail.
-
-Sat Jan 6 00:17:18 2001 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * pack.c (pack_pack): avoid infinite loop(pack 'm2').
-
-Fri Jan 5 01:02:17 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (ruby_finalize): should enclosed by PUSH_TAG/POP_TAG.
-
- * gc.c (rb_gc_mark): link 2 of NODE_IFUNC should not be explicitly
- marked. it may contain non object pointer.
-
-Tue Jan 2 00:20:06 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * re.c (reg_s_last_match): Regexp::last_match(nth) returns nth
- substring of the match (alternative for $& and $<digit>).
-
-Sun Dec 31 01:39:16 2000 Guy Decoux <decoux@moulon.inra.fr>
-
- * eval.c (rb_mod_define_method): wrong comparison for blocks.
-
-Sat Dec 30 19:28:50 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * gc.c (id2ref): should handle Symbol too.
-
- * gc.c (id2ref): should print original ptr value
-
-Sat Dec 30 03:14:22 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_iterate): NODE_CFUNC does not protect its data
- (nd_tval), so create new node NODE_IFUNC for iteration C
- function.
-
- * eval.c (rb_yield_0): use NODE_IFUNC.
-
- * gc.c (rb_gc_mark): support NODE_IFUNC.
-
-Fri Dec 29 11:41:55 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * gc.c (mem_error): prohibit recursive mem_error().
- (ruby-bugs-ja:PR#36)
-
-Fri Dec 29 11:05:41 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_thread_fd_writable): should not switch context if
- rb_thread_critical is set.
-
- * eval.c (rb_thread_wait_fd): ditto.
-
- * eval.c (rb_thread_wait_for): ditto.
-
- * eval.c (rb_thread_select): ditto.
-
- * eval.c (rb_thread_join): join during critical section causes
- deadlock.
-
-Fri Dec 29 00:38:46 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * m17n.c: new file - core functions of M17N.
-
-Tue Dec 26 18:46:41 2000 NAKAMURA Hiroshi <nakahiro@sarion.co.jp>
-
- * lib/debug.rb: Avoid thread deadlock in debugging stopped thread.
-
- * lib/debug.rb: Uncleared 'finish' state.
-
-Tue Dec 26 16:53:55 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_yield_0): remove dvar node by rb_gc_force_recycle()
- more eagerly.
-
- * eval.c (rb_f_binding): recycling should be stopped for outer
- scope too.
-
- * eval.c (proc_new): ditto.
-
-Tue Dec 26 15:45:35 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_inspect): should treat multibyte chracters
- properly.
-
-Mon Dec 25 17:49:08 2000 K.Kosako <kosako@sofnec.co.jp>
-
- * string.c (rb_str_replace_m): unexpected string share happens if
- replace is done for associated (STR_NO_ORIG) string.
-
-Tue Dec 26 15:01:53 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (rb_f_p): should not call rb_io_flush() if rb_defout is not
- a IO (T_FILE).
-
-Mon Dec 25 15:52:39 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * stable version 1.6.2 released.
-
-Mon Dec 25 05:11:04 2000 Wakou Aoyama <wakou@fsinet.or.jp>
-
- * lib/cgi.rb: version 2.1.2 (some bug fixes).
-
- * lib/cgi.rb: Regexp::last_match[1] --> $1
-
- * lib/net/telnet.rb: ditto.
-
-Mon Dec 25 04:43:02 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/http.rb: does not send HEAD on closing socket.
-
-Mon Dec 25 00:44:48 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * hash.c (rb_any_cmp): should use rb_str_cmp() if TYPE == T_STRING
- and CLASS_OF == rb_cString.
-
- * string.c (rb_str_new4): should copy class of original too.
-
-Mon Dec 25 00:04:54 2000 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * eval.c (rb_thread_schedule): initial value of `max' changed to -1.
-
-Mon Dec 25 00:16:14 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_replace_m): copy-on-write replace.
-
- * parse.y (yylex): should handle => after identifier as well as ==
- and =~.
-
-Sat Dec 23 23:55:57 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * bignum.c (rb_cstr2inum): Integer("") should not return 0.
-
-Sat Dec 23 11:55:57 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * array.c (rb_ary_and): Array#& should preverve original order.
-
-Sat Dec 23 03:44:16 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb: set @closed false in Socket#reopen.
-
- * lib/net/pop.rb: add POP3.foreach, delete_all.
-
- * lib/net/pop.rb: add POP3#delete_all.
-
- * lib/net/http.rb: add HTTP.version_1_1, version_1_2
-
- * lib/net/http.rb: refactoring.
-
-Fri Dec 22 23:11:12 2000 Ueno Katsuhiro <unnie@blue.sky.or.jp>
-
- * eval.c (rb_feature_p): ext might be null.
-
-Fri Dec 22 17:04:12 2000 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * win32/win32.c (myselect): avoid busy loop by adjusting fd_count.
-
-Fri Dec 22 15:07:55 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * bignum.c (rb_cstr2inum): prefix like '0x' had removed too much.
-
-Thu Dec 21 13:01:46 2000 Tanaka Akira <akr@m17n.org>
-
- * lib/net/ftp.rb (makeport): don't use TCPsocket.getaddress.
-
-Wed Dec 20 12:00:15 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * bignum.c (rb_big_lshift): should cast up to BDIGIT_DBL.
-
- * parse.y (yylex): disallow trailing '_' for numeric litrals.
-
- * bignum.c (rb_cstr2inum): allow `_' within converting string.
-
- * eval.c (specific_eval): should take no argument if block is
- supplied.
-
-Tue Dec 19 13:44:50 2000 K.Kosako <kosako@sofnec.co.jp>
-
- * io.c (rb_f_p): should flush rb_defout, not stdout.
-
-Tue Dec 19 00:57:10 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * time.c (time_minus): usec might overflow. (ruby-bugs-ja:PR#35)
-
- * eval.c (rb_obj_extend): Object#extend should take at least one
- argument.
-
- * parse.y (mrhs_basic): should check value_expr($3), not $1.
-
-Mon Dec 18 23:18:39 2000 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * util.c (mblen, __crt0_glob_function): add for multibyte
- on DJGPP 2.03.
-
-Mon Dec 18 18:10:30 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * time.c (time_plus): usec might underflow (ruby-bugs-ja:#PR33).
-
-Mon Dec 18 08:11:20 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * hash.c (rb_hash_set_default): should call rb_hash_modify().
-
-Sat Dec 16 02:58:26 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * eval.c (rb_eval): should clear ruby_errinfo on retry.
-
- * eval.c (rb_rescue2): ditto.
-
-Thu Dec 14 13:06:18 2000 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * class.c (rb_include_module): prohibit fronzen class/module.
-
- * eval.c (rb_frozen_class_p): make external.
-
- * intern.h (rb_frozen_class_p): prototyped.
-
- * intern.h (rb_undef): prototyped not but rb_undef_method()
- which is also in ruby.h.
-
-Thu Dec 14 09:20:26 2000 Wakou Aoyama <wakou@fsinet.or.jp>
-
- * lib/cgi.rb: support -T1 on ruby 1.6.2
-
- * lib/cgi.rb: $1 --> Regexp::last_match[1]
-
- * lib/net/telnet.rb: ditto.
-
-Wed Dec 13 23:27:06 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_eval): handles case statement without expr, which
- looks for any TRUE (non nil, non false) when expression.
-
- * parse.y (primary): case expression should not be compstmt, but
- mere expr.
-
- * parse.y (primary): case without following expression is now
- separated rule.
-
-Wed Dec 13 12:41:27 2000 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * ruby.c (proc_options): accept "--^M" for DOS line endings.
-
-Tue Dec 12 15:45:42 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (newline_node): cancel newline unification.
-
-Mon Dec 11 23:01:57 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (yylex): supports cases `?' precedes EOF and newline.
-
-Mon Dec 11 12:11:25 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (call_end_proc): some frame members were left
- uninitialized.
-
-Mon Dec 11 01:14:58 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (rb_io_fptr_finalize): do not fclose stdin, stdout and
- stderr at exit.
-
-Sat Dec 9 17:34:48 2000 Tachino Nobuhiro <tachino@open.nm.fujitsu.co.jp>
-
- * time.c (time_cmp): should check with kind_of?, not instance_of?
-
- * time.c (time_eql): ditto.
-
- * time.c (time_minus): ditto.
-
-Fri Dec 8 17:23:25 2000 Tachino Nobuhiro <tachino@open.nm.fujitsu.co.jp>
-
- * sprintf.c (rb_f_sprintf): proper string precision treat.
-
-Fri Dec 8 10:44:05 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * variable.c (rb_mod_remove_cvar): Module#remove_class_variable
- added.
-
-Thu Dec 7 17:35:51 2000 Shugo Maeda <shugo@ruby-lang.org>
-
- * eval.c (stack_length): don't use __builtin_frame_address() on alpha.
-
-Wed Dec 6 18:07:13 2000 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * djgpp/config.sed, win32/Makefile.sub: typo.
-
- * eval.c (rb_mod_define_method): avoid VC4.0 warnings.
-
-Wed Dec 6 13:38:08 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * array.c (rb_ary_and): tuning, make hash from shorter operand.
-
-Wed Dec 6 01:28:50 2000 SHIROYAMA Takayuki <psi@fortune.nest.or.jp>
-
- * gc.c (rb_gc): __builtin_frame_address() should not be used on
- MacOS X.
-
- * gc.c (Init_stack): ditto.
-
-Mon Dec 4 13:44:01 2000 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * lib/jcode.rb: consider multibyte. not /n.
-
-Mon Dec 4 09:49:36 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_inspect): output whole string contents. no more `...'
-
- * string.c (rb_str_dump): should propagate taintness.
-
- * hash.c (env_inspect): hash like human readable output.
-
- * variable.c (rb_ivar_get): prohibiting instance variable access
- is too much restriction.
-
- * class.c (method_list): retrieving information should not be
- restricted where $SAFE=4.
-
- * class.c (rb_obj_singleton_methods): ditto.
-
- * eval.c (rb_thread_priority): ditto.
-
- * eval.c (rb_thread_local_aref): ditto.
-
- * variable.c (rb_obj_instance_variables): ditto.
-
- * variable.c (rb_mod_const_at): ditto.
-
- * variable.c (rb_mod_class_variables): ditto.
-
- * eval.c (rb_exec_end_proc): end_proc should be preserved.
-
-Sat Dec 2 22:32:43 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_yield_0): || should accept exactly zero argument.
-
- * parse.y (stmt): multiple right hand side for single assignment
- (e.g. a = 1,2) is allowed.
-
-Wed Nov 29 07:55:29 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * marshal.c (w_long): dumping long should be smaller than 32bit max.
-
- * marshal.c (w_long): shorter long format for small integers(-123..122).
-
- * marshal.c (r_long): ditto.
-
-Tue Nov 28 18:10:51 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_mod_define_method): quick hack to implement
- on-the-fly method definition. experimental.
-
-Mon Nov 27 17:00:35 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_eval): should not redefine builtin classes/modules
- from within wrapped load.
-
-Mon Nov 27 08:57:33 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (call_end_proc): should be isolated from outer block.
-
-Mon Nov 27 00:10:08 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (rb_io_ctl): call ioctl/fcntl for fptr->f2 too.
-
- * process.c (rb_f_fork): call rb_thread_atfork() after creating
- child process.
-
- * eval.c (rb_thread_atfork): kill all other threads immediately,
- then turn the current thread into the main thread.
-
-Sat Nov 25 23:12:22 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (ruby_run): move calling point of rb_trap_exit after
- cleaning up threads.
-
- * eval.c (ruby_finalize): new function to call EXIT trap, END
- procs and GC finalizers.
-
- * eval.c (rb_exec_end_proc): prevent recursion.
-
- * gc.c (rb_gc_call_finalizer_at_exit): ditto.
-
- * signal.c (rb_trap_exit): ditto. made static.
-
- * process.c (rb_f_fork): should swallow all exceptions from block
- execution.
-
- * process.c (fork_rescue): should call ruby_finalize().
-
- * parse.y (yycompile): rb_gc() removed. I don't remember why I put
- this here. test code?
-
-Fri Nov 24 22:03:48 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * range.c (EXCL): exclusive infomation is now stored in an
- instance variable. this enables proper marshal dump.
-
- * process.c (proc_waitpid): should clear rb_last_status ($?) if
- no pid was given by waitpid(2).
-
-Thu Nov 23 01:35:38 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * process.c (proc_waitpid2): returns nil if no pid found.
-
-Wed Nov 22 23:45:15 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * range.c (range_eq): new method. Compares start and end of range
- respectively.
-
-Wed Nov 22 11:01:32 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * variable.c (rb_mod_class_variables): should honor singleton
- class variable rule defined yesterday.
-
-Tue Nov 21 23:24:14 2000 Mitsuteru S Nakao <nakao@kuicr.kyoto-u.ac.jp>
-
- * numeric.c (flodivmod): missing second operand (typo).
-
-Tue Nov 21 03:39:41 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * marshal.c (marshal_load): marshal format compatibility check
- revised. greater minor revision is UPWARD compatibile;
- downward compatibility is not assured.
-
- * eval.c (is_defined): clarify class variable behavior for
- singleton classes. class variables within singleton class
- should be treated like within singleton method.
-
-Mon Nov 20 13:45:21 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_eval): set ruby_sourceline before evaluating
- exceptions.
-
- * gc.c (gc_sweep): defer finalization in GC during compilation or
- interrupt prohibit section.
-
- * gc.c (gc_sweep): mark all nodes before sweeping if GC happened
- during compilation.
-
- * eval.c (rb_eval): should treat class variables specially in a
- method defined in the singleton class.
-
-Mon Nov 20 10:20:21 2000 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * dir.c, win32/win32.c, ruby.h: add rb_iglob().
-
-Mon Nov 20 00:18:16 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * array.c (rb_ary_subseq): should return nil for outbound start
- index.
-
- * marshal.c (marshal_load): show format versions explicitly when
- format version mismatch happens.
-
-Sun Nov 19 06:13:24 2000 Kazuhiro NISHIYAMA <zn@mbf.nifty.com>
-
- * marshal.c: use long for string/array length.
-
- * pack.c (swaps): use bit-or(|) instead of plus(+).
-
- * pack.c (swapl): ditto.
-
-Sat Nov 18 15:18:16 2000 Kazuhiro NISHIYAMA <zn@mbf.nifty.com>
-
- * array.c (rb_ary_replace): array size should be in long.
-
- * array.c (rb_ary_concat): ditto.
-
- * array.c (rb_ary_hash): ditto.
-
-Sat Nov 18 14:07:20 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/http.rb: Socket#readline() reads until "\n", not "\r\n"
-
-Fri Nov 17 14:55:18 2000 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * string.c (rb_str_succ): output should be NUL terminated.
-
-Fri Nov 17 02:54:15 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (rb_io_close): need not to flush before closing.
-
- * eval.c (rb_thread_join): should preserve last thread status when
- THREAD_TO_KILL.
-
- * eval.c (rb_thread_stop): ditto.
-
- * io.c (io_fflush): wrap fflush by TRAP_BEG, TRAP_END.
-
- * eval.c (rb_eval): method defined within singleton class
- definition should behave like singleton method about class
- variables.
-
- * eval.c (is_defined): ditto.
-
-Thu Nov 16 23:06:07 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/http.rb: can call {old,new}_implementation any times.
-
- * lib/net/http.rb: HTTP#connecting, receive ->
- common_oper, connecting.
-
- * lib/net/http.rb: output warning if u_header includes
- duplicated header.
-
- * lib/net/http.rb: not check Connection:/Proxy-Connection;
- always read until eof.
-
- * lib/net/protocol.rb: detects and catches "break" from block.
-
-Thu Nov 16 16:32:45 2000 Masahiro Tanaka <masa@stars.gsfc.nasa.gov>
-
- * bignum.c (bigdivrem): should have incremented ny first.
-
-Thu Nov 16 14:58:00 2000 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * ext/socket/socket.c (sock_new): duplicates file descriptor
- with myfddup() on mswin32/mingw32.
-
- * win32/win32.h: uses system original fdopen().
-
- * win32/win32.c (myfddup): newly added instead of myfdopen().
-
- * win32/win32.c (mybind, myconnect, mygetsockname, mygetsockopt,
- mylisten, mysetsockopt): now accept file descriptor only, not
- SOCKET.
-
- * win32/win32.c (myaccept, mysocket): return file descriptor,
- instead of SOCKET.
-
-Thu Nov 16 10:23:24 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (massign): too strict check for nameless rest argument.
-
- * eval.c (method_arity): mere * should return -1.
-
- * eval.c (intersect_fds): should check all FDs in the fd_set.
-
-Wed Nov 15 19:33:20 2000 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * eval.c (rb_attr): should clear method cache before calling hook.
-
- * eval.c (rb_eval): ditto.
-
- * eval.c (rb_mod_modfunc): ditto.
-
-Mon Nov 13 22:44:52 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * error.c (rb_bug): print version to stderr.
-
-Mon Nov 13 19:02:08 2000 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * win32/win32.c, io.c, process.c: the exit status of program must be
- multiplied 256 on mswin32 and msdosdjgpp(system(), ``).
-
-Sat Nov 11 22:57:38 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (arg): uniformed treatment of -a**b, where a is a
- number literal; hacky but behavior appears more consistent.
-
- * parse.y (newline_node): reduce newline node (one per line).
-
- * random.c (rb_f_srand): should be prohibited in safe level
- greater than 4.
-
-Sat Nov 11 22:37:36 2000 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * rubysig.h: do not use rb_trap_immediate on win32.
-
- * rubysig.h: new macros, ATOMIC_TEST, ATOMIC_SET, ATOMIC_INC,
- ATOMIC_DEC, RUBY_CRITICAL and new definition of TRAP_BEG,
- TRAP_END.
-
- * gc.c (ruby_xmalloc): should wrap malloc() by RUBY_CRITICAL.
-
- * signal.c (sighandle): better win32 sig handling.
-
- * win32/win32.c (flock): better implementation.
-
- * win32/win32.c (myselect): ditto.
-
- * win32/win32.c (myaccept): ditto.
-
- * win32/win32.c (waitpid): ditto.
-
- * win32/win32.c (myrename): ditto.
-
- * win32/win32.c (wait_events): support function for win32 signal
- handling.
-
-Sat Nov 11 08:34:18 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: 1.1.31.
-
- * lib/net/http.rb: initializes header in HTTP, not HTTPCommand.
-
- * lib/net/protocol.rb, http.rb: rewrites proxy code.
-
-Fri Nov 10 16:15:53 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * numeric.c (rb_num2long): use to_int, not to_i.
-
- * error.c: T_SYMBOL was misplaced by T_UNDEF.
-
- * parse.y (yylex): eval("^") caused infinite loop.
-
-Thu Nov 9 14:22:13 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (rb_io_taint_check): should check IO taintness; no
- operation for untainted IO should be allowed in the sandbox.
-
- * rubyio.h (GetOpenFile): check IO taintness inside using
- rb_io_taint_check().
-
-Wed Nov 8 03:08:53 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (io_fflush): ensure fflush(3) would not block by calling
- rb_thread_fd_writable().
-
-Tue Nov 7 20:29:56 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: 1.1.30.
-
- * lib/net/protocol.rb, smtp.rb: Command#critical_ok -> error_ok
-
- * lib/net/http.rb: reads header when also "100 Continue".
-
-Tue Nov 7 04:32:19 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * bignum.c (bigdivrem): use bit shift to make y's MSB set.
-
-Mon Nov 6 1:22:49 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * error.c (warn_print): do not use err_append(), to ensure output
- to stderr.
-
- * error.c (rb_warn): use warn_print() instead of err_print().
-
- * error.c (rb_warning): ditto.
-
- * error.c (rb_bug): ditto.
-
- * eval.c (rb_load): re-raise exceptions during load.
-
- * time.c (make_time_t): remove useless adjust
-
-Thu Nov 2 18:01:16 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * random.c (rb_f_rand): half-baked float support fixed. This fix
- was originally proposed by K.Kosako <kosako@sofnec.co.jp>.
-
-Tue Oct 31 17:27:17 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * bignum.c: change digit size to `long|int' if long long is
- available.
-
- * marshal.c (w_object): support `long|int' digits.
-
- * marshal.c (r_object): ditto.
-
-Sat Oct 28 23:54:22 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (yylex): allow =end at the end of file (without a
- newline at the end).
-
-Fri Oct 27 10:00:27 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * bignum.c (rb_cstr2inum): should ignore trailing white spaces.
-
- * bignum.c (rb_str2inum): string may not have sentinel NUL.
-
-Fri Oct 27 02:37:22 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * bignum.c (rb_cstr2inum): wrongly assigned base to c before
- badcheck check.
-
-Thu Oct 26 02:42:50 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb: Command#critical_ok
-
- * lib/net/smtp.rb: clear critical flag before go to SMTP
-
-Wed Oct 25 12:30:19 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * array.c (rb_ary_concat): replacing array might be the receiver
- itself. do not call rb_ary_push_m.
-
- * array.c (rb_ary_replace): replacing array might be the receiver
- itself. use memmove.
-
-Fri Oct 20 07:56:23 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_eval): ARGSPUSH should not modify args array.
-
-Thu Oct 19 14:58:17 2000 WATANABE Tetsuya <tetsu@jpn.hp.com>
-
- * pack.c (NUM2U32): should use NUM2ULONG().
-
-Tue Oct 17 17:30:34 2000 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * eval.c (error_print): ruby_sourcefile may be NULL.
-
-Tue Oct 17 16:36:28 2000 Wes Nakamura <wknaka@pobox.com>
-
- * pack.c (NATINT_U32): wrong use of sizeof.
-
-Tue Oct 17 12:48:20 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * eval.c (rb_abort): nil check against ruby_errinfo.
-
- * eval.c (rb_thread_schedule): use FOREACH_THREAD_FROM instead of
- FOREACH_THREAD, since curr_thread may be removed from thread ring.
-
- * eval.c (THREAD_ALLOC): errinfo should be Qnil.
-
- * eval.c (rb_callcc): th->prev,th->next are now already
- initialized in THREAD_ALLOC.
-
-Mon Oct 16 15:37:33 2000 Kazuhiro NISHIYAMA <zn@mbf.nifty.com>
-
- * eval.c (rb_thread_inspect): tag size was shorter than required.
-
- * object.c (rb_obj_inspect): ditto.
-
-Mon Oct 16 14:25:18 2000 Shugo Maeda <shugo@ruby-lang.org>
-
- * object.c (sym_inspect): used `name' before initialization.
-
-Mon Oct 16 14:06:00 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * pack.c (pack_pack): use NATINT_U32 for 'l', 'L', and 'N'.
-
- * pack.c (I32,U32): 32 bit sized integer.
-
- * pack.c (OFF16,OFF32B): big endian offset for network byteorder.
-
-Mon Oct 16 06:39:32 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/http.rb: hex-alpha is not [a-h] but [a-f].
-
-Mon Oct 16 01:02:02 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_thread_start_0): should not abort on exception if
- $SAFE >= 4.
-
- * parse.y (sym): symbols for class variable names.
-
-Sun Oct 15 01:49:18 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * file.c (rb_file_flock): should accept interrupt.
-
- * process.c (rb_waitpid): ditto.
-
- * process.c (rb_waitpid): ditto.
-
- * process.c (proc_wait): ditto.
-
- * process.c (proc_waitpid2): wrong recursion.
-
-Sat Oct 14 03:32:13 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_thread_alloc): should not link a new thread in the
- live thread ring before initialization.
-
-Fri Oct 13 17:08:09 2000 Shugo Maeda <shugo@ruby-lang.org>
-
- * lib/net/imap.rb: new file.
-
-Thu Oct 12 18:56:28 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/pop.rb: POP3#reset
-
- * lib/net/http.rb: a code for "Switch Protocol" was wrongly 100.
-
-Thu Oct 12 01:23:38 2000 Wakou Aoyama <wakou@fsinet.or.jp>
-
- * lib/cgi.rb: bug fix: CGI::html(): PRETTY option didn't work.
-
-Thu Oct 12 00:03:02 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * object.c (sym_inspect): should adjust string length.
-
- * struct.c (rb_struct_to_s): ditto.
-
- * struct.c (rb_struct_inspect): ditto.
-
-Wed Oct 11 22:15:47 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * eval.c (rb_thread_inspect): should adjust string length.
-
- * object.c (rb_any_to_s): ditto.
-
- * object.c (rb_obj_inspect): ditto.
-
-Wed Oct 11 18:13:50 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_thread_start_0): should check insecure exit.
-
-Wed Oct 11 14:29:51 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb: 2nd arg for ProtocolError#initialize is
- optional.
-
- * lib/net/http.rb: code refining.
-
-Wed Oct 11 11:13:03 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (primary): setter method (e.g. foo=) should always be
- public.
-
- * eval.c (rb_thread_raise): should not raise SecurityError if
- exception raised by the interpreter.
-
- * eval.c (rb_thread_cleanup): skip all THREAD_KILLED threads
- before FOREACH_THREAD.
-
-Tue Oct 10 16:11:54 2000 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * dln.c (dln_load): remove unused code for Cygwin.
-
-Tue Oct 10 09:49:23 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * file.c (Init_File): FileTest.size should return 0 (not nil) for
- empty files.
-
-Sun Oct 8 13:20:26 2000 Guy Decoux <decoux@moulon.inra.fr>
-
- * eval.c (POP_SCOPE): not just set SCOPE_DONT_RECYCLE, but do
- scope_dup().
-
-Sat Oct 7 15:10:50 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_reverse_bang): unnecessary ALLOCA_N() was
- removed.
-
-Fri Oct 6 14:50:24 2000 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * ext/extmk.rb.in, lib/mkmf.rb: remove "DESTDIR =".
-
- * Makefile.in, win32/Makefile.sub, ruby.1: renamed -X to -C.
-
-Fri Oct 6 12:50:52 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * array.c (rb_ary_plus): use to_ary(), not Check_Type().
-
- * array.c (rb_ary_concat): ditto.
-
- * gc.c (rb_gc): use __builtin_frame_address() for gcc.
-
- * eval.c (stack_length): ditto.
-
- * parse.y (assign_in_cond): stop warning till some better warning
- condition will be found.
-
-Thu Oct 5 18:02:39 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * object.c (rb_obj_dup): should have propagated taint flag.
- (ruby-bugs:#PR64,65)
-
-Wed Oct 4 00:26:11 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (proc_arity): proc{|a|}'s arity should be -1.
-
-Mon Oct 2 05:28:58 2000 akira yamada <akira@ruby-lang.org>
-
- * string.c (trnext): minus at the end of pattern.
-
-Sun Oct 1 00:43:34 2000 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * configure.in: exp-name was wrong on cygwin and mingw32.
-
-Thu Sep 28 14:57:09 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * regex.c (re_compile_pattern): should try must_string calculation
- every time.
-
-Tue Sep 19 23:47:44 2000 SHIROYAMA Takayuki <psi@fortune.nest.or.jp>
-
- * configure.in, config.guess, config.sub: MacOS X support.
-
-Wed Sep 27 18:40:05 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * stable version 1.6.1 released.
-
-Wed Sep 27 16:13:05 2000 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * mkconfig.rb: variables should be expanded only if /\$\{?\w+\}?/.
-
-Tue Sep 26 18:09:51 2000 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * string.c: include <math.h>
-
-Tue Sep 26 15:59:50 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * object.c (rb_mod_dup): metaclasses of class/module should not be
- cleared by rb_obj_dup.
-
-Tue Sep 26 02:44:54 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * gc.c (GC_MALLOC_LIMIT): size extended.
-
- * regex.c (DOUBLE_STACK): use machine's stack region for regex
- stack if its size is small enough.
-
-Mon Sep 25 18:13:07 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * regex.c: include <defines.h>.
-
- * eval.c (rb_add_method): cache mismatch by method
- definition. need to clear_cache_by_id every time.
-
-Mon Sep 25 13:31:45 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * win32/win32.c (NtCmdGlob): substitute '\\' with '/'.
-
-Mon Sep 25 00:35:01 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * defines.h: #undef HAVE_SETITIMER on cygwin.
-
-Sun Sep 24 03:01:53 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb, http.rb: typo.
-
-Sat Sep 23 07:33:20 2000 Aleksi Niemela <aleksi.niemela@cinnober.com>
-
- * regex.c (re_compile_pattern): nicer regexp error messages for
- invalid patterns.
-
-Sat Sep 23 03:06:25 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * variable.c (rb_autoload_load): should not require already
- provided features.
-
-Fri Sep 22 15:46:21 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/http.rb: too early parameter expansion in string.
-
-Fri Sep 22 13:58:51 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * ext/extmk.rb.in: don't use default $:
-
-Fri Sep 22 13:42:50 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * regex.c (PUSH_FAILURE_COUNT): avoid casting warning on alpha.
-
- * regex.c (PUSH_FAILURE_POINT): ditto.
-
-Fri Sep 22 10:16:21 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * win32/config.h.in: add HAVE_TELLDIR, HAVE_SEEKDIR
-
-Thu Sep 21 19:04:34 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * ext/extmk.rb, lib/mkmf.rb (install_rb): check whether libdir is
- directory or not.
-
-Thu Sep 21 17:23:05 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * file.c (rb_file_s_symlink): use HAVE_SYMLINK.
-
- * file.c (rb_file_s_readlink): use HAVE_READLINK.
-
- * dir.c (dir_tell): use HAVE_TELLDIR.
-
- * dir.c (dir_seek): use HAVE_SEEKDIR.
-
- * configure.in (AC_CHECK_FUNCS): lstat, symlink, readlink,
- telldir, seekdir checks added.
-
- * file.c (lstat): should use stat(2) if lstat(2) is not
- available.
-
-Thu Sep 21 15:59:23 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: 1.1.29.
-
- * lib/net/http.rb: HTTPReadAdapter -> HTTPResponseReceiver
-
- * lib/net/http.rb (connecting): response is got in receive()
-
-Thu Sep 21 15:49:07 2000 Wayne Scott <wscott@ichips.intel.com>
-
- * lib/find.rb (find): should not follow symbolic links;
- tuned performance too.
-
-Wed Sep 20 23:21:38 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ruby.c (load_file): two Ctrl-D was required to stop ruby at the
- beginning of stdin script read.
-
-Wed Sep 20 14:01:45 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_provided): detect infinite load loop.
-
- * eval.c (rb_provided): too weak filename comparison.
-
- * eval.c (rb_thread_alloc): avoid recycling still referenced
- dvar structures.
-
- * eval.c (rb_callcc): ditto.
-
- * eval.c (THREAD_ALLOC): fiil dyna_vars field by ruby_dyna_vars.
-
-Tue Sep 19 17:47:03 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * stable version 1.6.0 released.
-
-Tue Sep 19 16:24:52 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * marshal.c (Init_marshal): provide marshal.so no more.
-
-Tue Sep 19 14:01:01 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * configure.in, win32/setup.mak: include version number
- in RUBY_SO_NAME.
-
-Tue Sep 19 13:07:47 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (yylex): was confusing $~ and $_.
-
-Tue Sep 19 13:06:53 2000 GOTOU YUUZOU <gotoyuzo@notwork.org>
-
- * signal.c (rb_f_kill): signum may be a negative number, should be
- treated by signed number.
-
-Tue Sep 19 01:14:56 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_provide): better feature handling.
-
- * eval.c (rb_f_require): loading ruby library may be partial
- state. checks in rb_thread_loading is integrated.
-
- * eval.c (rb_provided): better thread awareness.
-
- * lib/irb/frame.rb: 6 (not 5) parameters for trace_func proc.
-
- * eval.c (error_print): should print error position even if
- get_backtrace() failed.
-
-Sat Sep 16 03:29:59 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_f_require): rb_provided() was called too early; does
- not work well with threads.
-
- * parse.y (ensure): should distinguish empty ensure and non
- existing ensure.
-
- * file.c (Init_File): extending File by class of FileTest was
- serious mistake.
-
-Thu Sep 14 02:46:54 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_thread_yield): array strip should be done in this
- function.
-
-Wed Sep 13 17:01:03 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * bignum.c (rb_big_eq): incomplete value comparison of bignums.
-
-Wed Sep 13 06:39:54 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * variable.c (rb_mod_class_variables): Module#class_variables added.
-
-Wed Sep 13 06:09:26 2000 Wakou Aoyama <wakou@fsinet.or.jp>
-
- * lib/cgi.rb: bug fix: CGI::header(): output status header.
-
-Wed Sep 13 01:09:12 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (yylex): allow global variables like '$__a'.
-
-Tue Sep 12 22:28:43 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * ext/socket/extconf.rb: avoid using terrible <netinet/tcp.h>
- on cygwin 1.1.5.
-
-Tue Sep 12 16:01:58 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * array.c (rb_ary_unshift_m): typo.
-
-Tue Sep 12 15:37:55 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_yield_0): stripped array too much, should remove just
- for proc_call().
-
-Tue Sep 12 07:05:24 2000 Wakou Aoyama <wakou@fsinet.or.jp>
-
- * lib/cgi.rb: version 2.0.0: require ruby1.5.4 or later.
-
- * lib/net/telnet.rb: version 1.6.0
-
-Tue Sep 12 03:26:07 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (massign): use to_ary to get an array if available.
-
- * object.c (rb_Array): ditto.
-
-Mon Sep 11 14:24:47 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * hash.c (ruby_setenv): should not free the element of
- origenvironment.
-
- * parse.y (command_call): kYIELD moved to this rule to allow
- 'a = yield b'. (ruby-bugs-ja:#PR15)
-
-Mon Sep 11 01:27:54 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_yield_0): proc#call([]) should pass single value to
- the block.
-
- * eval.c (callargs): reduce array allocation.
-
- * eval.c (massign): precise check for argument number.
-
-Fri Sep 8 10:05:17 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * gc.c (STR_NO_ORIG): should be FL_USER2.
-
-Thu Sep 7 14:17:51 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_cat): should work even for concatenating same
- string.
-
-Wed Sep 6 17:06:38 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * variable.c (rb_cvar_declare): should check superclass's class
- variable first.
-
-Wed Sep 6 10:42:02 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * misc/ruby-mode.el (ruby-calculate-indent): shift continuing line
- if previous line ends with modifier keyword.
-
- * misc/ruby-mode.el (ruby-parse-region): should not give up if
- modifiers are at the end of line.
-
- * misc/ruby-mode.el (ruby-expr-beg): indented wrongly if modified
- statement was size 1.
-
-Wed Sep 6 10:41:19 2000 Kenichi Komiya <kom@mail1.accsnet.ne.jp>
-
- * misc/ruby-mode.el (ruby-parse-region): modifier was not handled
- well on emacs19.
-
-Tue Sep 5 17:10:12 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * time.c (time_to_s): fixed zone string UTC for utc time object.
-
-Tue Sep 5 00:26:06 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * regex.c (re_search): range worked wrongly on bm_search().
-
-Mon Sep 4 13:40:40 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * configure.in: renamed libruby.a to libruby.{cygwin,mingw32}.a
- on cygwin and mingw32.
-
-Sun Sep 3 23:44:04 2000 Noriaki Harada <tenmei@maoh.office.ne.jp>
-
- * io.c (NO_SAFE_RENAME): for BeOS too.
-
-Sun Sep 3 11:31:53 2000 Takaaki Tateishi <ttate@jaist.ac.jp>
-
- * parse.y (rescue): no assignment was done if rescue body was
- empty.
-
-Sat Sep 2 10:52:21 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (call_args,aref_args): block_call can be the last
- argument.
-
- * parse.y (COND_PUSH,COND_POP): maintain condition stack to allow
- kDO2 in parentheses in while/until/for conditions.
-
- * parse.y (yylex): generate kDO2 for EXPR_ARG outside of
- while/until/for condition.
-
-Fri Sep 1 10:36:29 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (aref_args,opt_call_args): add block_call to allow a
- method without parentheses and with block as a last argument.
-
- * hash.c (rb_hash_sort): should not return nil.
-
- * re.c (match_aref): should use rb_reg_nth_match().
-
- * eval.c (POP_SCOPE): recycled scopes too much
-
- * eval.c (Init_eval): extend room for stack allowance.
-
- * eval.c (POP_SCOPE): frees scope too much.
-
-Thu Aug 31 14:28:39 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * gc.c (rb_gc_mark): T_SCOPE condition must be more precise.
-
- * eval.c (scope_dup): should not make all duped scope orphan.
-
-Thu Aug 31 10:11:47 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (stmt): allow stmt_rhs to be right hand side of multiple
- assignment.
-
- * time.c (rb_time_timeval): type error should not mention the word
- 'interval'.
-
-Wed Aug 30 23:21:20 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * numeric.c (rb_num2long): use rb_Integer() instead of independent
- convert routine.
-
- * eval.c (rb_rescue2): now takes arbitrary number of exception types.
-
- * object.c (rb_convert_type): use rb_rescue2 now to handle NameError.
-
- * object.c (rb_convert_type): better error message.
-
-Wed Aug 30 17:09:14 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * ext/Win32API/Win32API.c (Win32API_initialize): AlphaNT support.
-
-Wed Aug 30 14:19:07 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (node_assign): should support NODE_CVASGN2 too.
-
-Wed Aug 30 11:31:47 2000 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * ext/Win32API/Win32API.c (Win32API_initialize): add the
- arguments checking.
-
- * ext/Win32API/Win32API.c (Win32API_initialize): add taint
- checking. allow String object in the third argument.
-
-Wed Aug 30 10:29:40 2000 Masahiro Tomita <tommy@tmtm.org>
-
- * io.c (rb_f_p): flush output buffer.
-
-Tue Aug 29 16:29:15 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (assignable): remove NODE_CVASGN3.
-
- * parse.y (gettable): remove NODE_CVAR3.
-
-Tue Aug 29 02:02:14 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/mkmf.rb (create_makefile): handles create_makefile("a/b").
-
- * ext/extmk.rb.in (create_makefile): ditto
-
-Mon Aug 28 18:43:54 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (is_defined): now handles class variables.
-
- * eval.c (rb_eval): class variable behavior revisited.
-
- * parse.y (assignable): ditto.
-
- * parse.y (gettable): ditto.
-
- * regex.c (PUSH_FAILURE_COUNT): push/pop interval count on failure
- stack. this fix is inspired by the Emacs21 patch from Stefan
- Monnier <monnier@cs.yale.edu>.
-
-Fri Aug 25 15:24:39 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * variable.c (rb_cvar_get): should not follow __attached__.
-
- * variable.c (rb_cvar_set): ditto.
-
- * variable.c (rb_cvar_declare): ditto.
-
- * variable.c (mod_av_set): second class variable assignment at the
- toplevel should not give warning.
-
-Fri Aug 25 01:18:36 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (next_argv): prepare path for open file.
-
- * string.c (rb_str_setter): moved from io.c.
-
- * io.c (next_argv): filename should be "-" for refreshed ARGF.
-
-Thu Aug 24 15:27:39 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * ext/socket/socketport.h: use `extern int h_errno' if needed.
-
-Sat Aug 19 01:34:02 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * ext/sdbm/_sdbm.c (sdbm_prep): flags should be or-ed by O_BINARY on
- Win32 too.
-
- * ext/sdbm/_sdbm.c (makroom): fill hole with 0 on Win32 too.
-
-Fri Aug 18 13:23:59 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_eval): should preserve and clear $! value before
- compilation.
-
- * eval.c (eval): ditto.
-
-Fri Aug 18 11:06:19 2000 Shugo Maeda <shugo@ruby-lang.org>
-
- * ext/socket/socket.c (s_accept): start GC on EMFILE/ENFILE.
-
-Thu Aug 17 16:04:48 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (is_defined): should clear ruby_errinfo.
-
-Thu Aug 17 04:26:31 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: 1.1.27.
-
- * lib/net/protocol.rb: writing methods returns written byte size.
-
- * lib/net/smtp.rb: send_mail accepts many destinations.
-
-Wed Aug 16 00:43:47 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * time.c (time_s_times): use CLK_TCK for HZ if it's defined.
-
-Tue Aug 15 17:30:59 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (frame_dup): should set flag FRAME_MALLOC after
- argv allocation.
-
- * eval.c (blk_free): should not free argv if GC was called before
- frame_dup.
-
-Tue Aug 15 16:08:40 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * configure.in: add ac_cv_func_times=yes for mingw32.
-
- * win32/win32.c (mytimes): typo.
-
-Tue Aug 15 01:45:28 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (argf_eof): should return true at the end of ARGF without
- checking stdout if arguments are given.
-
-Mon Aug 14 10:34:32 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_thread_status): status should return false for normal
- termination, nil for termination by exception.
-
-Fri Aug 11 15:43:46 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_undef): give warning for undefining __id__, __send__.
-
-Thu Aug 10 08:05:03 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_callcc): returned current thread instead of
- continuation wrongly.
-
-Thu Aug 10 05:40:28 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * ext/extmk.rb.in: $CPPFLAGS should be initialized.
-
- * ext/tcltklib/depend: add stubs.o.
-
- * ext/tcltklib/extconf.rb: use $CPPFLAGS instead of $CFLAGS.
-
-Wed Aug 9 16:31:48 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_callcc): thread status for continuations must be
- THREAD_KILLED, otherwise thread_free() breaks other threads.
-
-Wed Aug 9 13:24:25 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * win32/win32.[ch]: emulate rename(2).
-
-Tue Aug 8 14:01:46 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * ext/tcltklib/tcltklib.c: support --enable-tcltk_stubs
-
- * ext/tcltklib/extconf.rb: ditto.
-
- * ext/tcltklib/stubs.c: created. examine candidate shared libraries.
-
-Mon Aug 7 13:59:12 2000 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ruby.h (CLONESETUP): should copy flags before any potential
- object allocation.
-
- * regex.c (re_match): check for stack depth was needed.
-
-Sat Aug 5 16:43:43 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * djgpp/*: convert DOS line endings to UNIX style.
-
- * djgpp/config.status: rename to config.sed for SFN.
-
- * lib/ftools.rb (compare, safe_unlink, chmod): avoid warnings.
-
- * lib/ftools.rb (move): typo. not `tpath', but `to'.
-
-Fri Aug 4 23:26:48 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (proc_call): gives warning if a block is supplied.
-
- * eval.c (rb_eval): no warning for discarding if an alias for the
- method is already made.
-
-Fri Aug 4 16:32:29 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * array.c (rb_ary_reject_bang): returns nil if no element removed.
-
- * hash.c (rb_hash_reject_bang): returns nil if no element removed.
-
-Thu Aug 3 19:44:26 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_thread_fd_writable): should return integer value.
-
- * array.c (rb_ary_assoc): search array element whose length is
- longer than 0 (not 1).
-
-Wed Aug 2 18:27:47 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_thread_wait_fd): prohibit thread context switch
- during compilation.
-
- * eval.c (rb_cont_call): prohibit Continuation#call across threads.
-
-Wed Aug 2 08:22:04 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * gc.c (rb_gc): clear malloc_memories to zero, to avoid potential
- super frequent GC invocation. (ruby-bugs:#PR48)
-
- * gc.c (rb_gc): only add_heap() if GC trigger condition is
- satisfied.
-
-Tue Aug 1 16:41:58 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ruby.c (proc_options): global load path setting moved from
- ruby_prog_init().
-
- * ruby.c (incpush): renamed. push path entry at the END of the
- load path array. This makes -I directories sorted in order in
- the arguments.
-
-Sat Jul 29 23:42:04 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * dir.c (dir_each): should check whether dir is closed during the
- block execution. (ruby-bugs:#PR47)
-
-Sat Jul 29 21:57:30 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * ruby.c (rubylib_mangle): provide another buffer for the result.
-
-Wed Jul 26 10:09:01 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * configure.in: set SOLIBS to LIBS on Cygwin.
-
- * configure.in: LIBRUBY_SO='$(RUBY_INSTALL_NAME)'.$target_os.dll
- on cygwin and mingw32. ruby-cygwin.dll is bad. why?
-
-Wed Jul 26 10:04:03 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * gc.c (gc_sweep): avoid full scan during compilation.
-
- * gc.c (rb_gc): add heap during no gc period (including
- compilation).
-
-Tue Jul 25 19:03:04 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * cygwin/GNUmakefile: use puts instead of print, because
- Cygwin DLL's behavior is changed(or bug?).
-
- * configure.in: LIBRUBY_SO='$(RUBY_INSTALL_NAME)'-$target_os.dll
- on cygwin and mingw32.
-
- * cygwin/GNUmakefile: ditto.
-
- * Makefile.in: $(SOLIBS) should be put after dmyext.@OBJEXT@.
-
- * instruby.rb: install $(LIBRUBY) to libdir
- if $(LIBRUBY) != $(LIBRUBY_A_).
-
-Tue Jul 25 15:16:00 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (rb_p): redirect to $defout.
-
-Mon Jul 24 18:52:55 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * win32/win32.c (win32_getenv): should remove `static'.
-
- * ruby.c (rubylib_mangle): support "/hoge;/foo"
-
-Mon Jul 24 10:28:55 2000 GOTO Kentaro <gotoken@math.sci.hokudai.ac.jp>
-
- * string.c (rb_str_count): raise exception if no argument is
- given.
-
-Sun Jul 23 12:55:04 2000 Dave Thomas <Dave@Thomases.com>
-
- * string.c (rb_str_rindex): Support negative end position.
-
-Fri Jul 21 17:35:01 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (aref_args): command_call now be permitted as
- aref_args.
-
- * process.c (proc_getpriority): getpriority(2) may return valid
- negative number. use errno to detect error.
-
- * marshal.c (dump_ensure): dumped string should be tainted if
- any among target objects is tainted.
-
- * marshal.c (r_regist): restored object should be tainted if and
- only if the source is a file or a tainted string.
-
-Wed Jul 19 15:14:04 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * bignum.c (bigdivrem): should use rb_int2big(), not rb_uint2big().
-
-Tue Jul 18 14:58:30 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (ruby_options): should treat SystemExit etc. properly.
-
- * parse.y (yycompile): should check compile_for_eval, not
- ruby_in_eval.
-
-Mon Jul 17 04:29:50 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/mkmf.rb: converts extension of $objs into $OBJEXT.
-
-Sun Jul 16 03:02:34 2000 Dave Thomas <dave@thomases.com>
-
- * lib/weakref.rb: Change to use new ObjectSpace calls.
-
-Sat Jul 15 21:59:58 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_eval): should not redefine __id__ nor __send__.
-
- * gc.c (define_final): integrate final.rb features into the
- interpreter. define_finalizer and undefine_finalizer was
- added to ObjectSpace. plus, add_finalizer, remove_finalizer,
- and call_finalizer are deprecated now.
-
-Sat Jul 15 01:32:34 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_mod_method): implements unbound method.
-
- * eval.c (Init_eval): should prohibit `module_function' for class
- Class.
-
-Fri Jul 14 17:19:59 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * cygwin/GNUmakefile.in: use miniruby instead of sed.
-
-Fri Jul 14 12:49:50 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (argf_eof): need to check stdin, when next_p == -1.
-
- * io.c (read_all): use io_fread() instead of fread(3).
-
- * io.c (io_reopen): should clearerr FILE if fd < 3.
-
- * re.c (rb_reg_match_m): the result is exported, so it should be
- declared as busy.
-
- * eval.c (rb_eval): should preserve errinfo even if return, break,
- etc. is called in rescue clause.
-
- * instruby.rb: install irb too.
-
-Wed Jul 12 15:32:57 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * variable.c (rb_const_get): constants for builtin classes must
- have higher priority than constants from included modules at
- Object class.
-
- * bignum.c (bigdivrem): small embarrassing typo.
-
-Wed Jul 12 15:06:28 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_eval): use rb_const_get_at().
-
- * variable.c (top_const_get): retrieve toplevel constants only,
- not ones of Object (and its included modules) in general.
-
-Wed Jul 12 15:04:11 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: 1.1.26.
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb:
- add module Net::NetPrivate and its inner classes
- {Read,Write}Adapter, Command, Socket,
- SMTPCommand, POP3Command, APOPCommand, HTTPCommand
-
-Wed Jul 12 13:10:30 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * bignum.c (bigdivrem): defer bignorm().
-
- * bignum.c (bignorm): accepts accidental fixnums.
-
-Tue Jul 11 16:54:17 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (yylex): `@<digit>' is no longer a valid instance
- variable name.
-
-Tue Jul 11 01:51:50 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * bignum.c (rb_big_divmod): should not use Integer(float) for
- the right operand.
-
- * bignum.c (rb_big_remainder): ditto.
-
- * bignum.c (rb_big_modulo): ditto.
-
-Mon Jul 10 15:27:16 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * io.c (pipe_finalize): should set rb_last_status when pclose().
-
-Mon Jul 10 09:07:54 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * error.c (rb_bug): print version number and such too.
-
-Sat Jul 8 23:08:40 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_thread_start_0): should copy previous scopes to
- prevent rb_gc_force_recycle().
-
-Fri Jul 7 23:36:36 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * ext/socket/addrinfo.h: move IN_EXPERIMENTAL and IN_LOOPBACKNET
- definitions to ext/socket/sockport.h.
-
- * ext/socket/extconf.rb: add getservbyport() and arpa/inet.h check.
-
- * ext/socket/getaddrinfo.c (getaddrinfo): SOCK_RAW may not be
- defined (ex. BeOS, Palm OS 2.x or before).
-
- * ext/socket/getnameinfo.c (getnameinfo): getservbyport() may not
- exist (ex. BeOS, Palm OS).
-
- * ext/socket/sockport.h: add IN_EXPERIMENTAL, IN_CLASSA_NSHIFT,
- IN_LOOPBACKNET, AF_UNSPEC, PF_UNSPEC and PF_INET.
-
-Fri Jul 7 03:30:00 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (aref_args): should allow Hash[:a=>2] etc.
-
- * numeric.c (fix_aref): convert index by NUM2INT, not FIX2INT.
- (ruby-bugs:#PR37)
-
- * time.c (time_localtime): should prohibit for frozen time.
-
- * time.c (time_gmtime): ditto.
-
-Thu Jul 6 19:12:12 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (rb_file_s_open): should not terminate fptr; just clear it.
-
- * ruby.c (proc_options): should not call require_libraries()
- twice.
-
- * ruby.c (require_libraries): clear req_list_head.next after
- execution.
-
-Thu Jul 6 13:51:57 2000 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * object.c (rb_to_id): name may not be symbol nor fixnum.
-
- * struct.c (rb_struct_s_def): name may be nil.
-
-Thu Jul 6 02:09:06 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * bignum.c (bigdivrem): new function to return remainder.
-
- * numeric.c (fixdivmod): now returns modulo, not remainder.
-
- * numeric.c (flodivmod): ditto.
-
- * bignum.c (bigdivmod): ditto.
-
- * numeric.c (num_modulo): new method; alias to '%'.
-
-Thu Jul 6 00:51:43 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * win32/win32.c (NtCmdGlob): patterns should be separated and
- NUL terminated.
-
-Wed Jul 5 22:27:56 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * cygwin/GNUmakefile: use ruby.def to make rubycw.dll.
-
- * ext/extmk.rb.in: create target.def.
-
- * lib/mkmf.rb: ditto.
-
-Wed Jul 5 09:47:14 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * time.c (time_arg): Time::local, Time::gm now take 7th optional
- argument for usec.
-
- * numeric.c (num_ceil, etc): default ceil, floor, round, truncate
- implementation for Numeric, using `to_f'.
-
- * io.c (rb_io_reopen): clear fptr->path after free() to prevent
- potential GC crash.
-
- * io.c (rb_file_s_open): terminate fptr unless null.
-
- * io.c (rb_file_initialize): ditto.
-
- * lib/tempfile.rb: specify FILE::CREAT|File::EXCL to open for
- better security.
-
- * numeric.c (flo_truncate): new method.
-
-Wed Jul 5 01:02:53 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * ext/extmk.rb.in: join ' ' -> join(' ').
-
- * lib/mkmf.rb: ditto.
-
-Tue Jul 4 13:51:29 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/dbm/dbm.c: add methods added to Hash in 1.5.x.
-
- * ext/gdbm/gdbm.c: ditto.
-
- * ext/sdbm/init.c: ditto.
-
- * eval.c (proc_call): args may be Qundef (means no argument), do
- not call TYPE() for args.
-
-Tue Jul 4 13:20:56 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * ext/extmk.rb.in: make command line must be single-quoted.
- $(RUBY_INSTALL_NAME) is command substitution in the POSIX sh.
-
-Tue Jul 4 13:16:02 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * util.c (rb_type): should add T_UNDEF.
-
-Tue Jul 4 09:30:35 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (here_document): supports EOF right after terminator.
-
- * random.c (rb_f_rand): argument is now optional (rand(max=0)).
-
-Tue Jul 4 01:50:49 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * win32/ruby.def: remove ruby_mktemp.
-
-Tue Jul 4 01:27:13 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_rescue2): new function to rescue arbitrary exception.
-
- * numeric.c (do_coerce): should catch NameError explicitly.
-
-Tue Jul 4 00:15:23 2000 Dave Thomas <Dave@thomases.com>
-
- * numeric.c (Init_Numeric): forgot to register Numeric#remainder.
-
-Mon Jul 3 23:46:56 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * win32/win32.c (myselect, myaccept): disable interrupt while
- executing accept() or select() to avoid Ctrl-C causes
- "unknown software exception (0xc0000029)".
-
-Mon Jul 3 18:35:41 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * lib/mkmf.rb: use null device if it exists for cross-compiling.
-
-Mon Jul 3 18:19:51 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: 1.1.26.
-
- * lib/net/protocol.rb (finish): do nothing unless active.
-
- * lib/net/http.rb: HTTP#{get,post}2 again (for new impl).
-
-Mon Jul 3 16:47:22 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * cygwin/GNUmakefile: librubys.a -> lib$(RUBY_INSTALL_NAME)s.a
-
- * configure.in: use AC_CANONICAL_{HOST,TARGET,BUILD}.
-
-Mon Jul 3 13:15:02 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * numeric.c (fix_divmod): x * d + m = y where d, m = x.divmod(y).
-
- * bignum.c (rb_big_divmod): ditto.
-
- * numeric.c (fixdivmod): does not depend C's undefined %
- behavior. adopt to fmod(3m) behavior.
-
- * numeric.c (flo_mod): modulo now reserves fmod(3m) behavior.
-
- * numeric.c (num_remainder): 'deprecated' warning.
-
-Mon Jul 3 10:27:28 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * configure.in: use AC_CANONICAL_SYSTEM.
-
-Sun Jul 2 21:17:37 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * configure.in: support without --enable-shared for cygwin/mingw32.
-
- * cygwin/GNUmakefile: ditto.
-
- * ext/extmk.rb.in: use null device if it exists for cross-compiling.
-
- * lib/mkmf.rb: ditto.
-
- * util.c (ruby_mktemp): remove unused ruby_mktemp().
-
-Sun Jul 2 14:18:04 2000 Koji Arai <JCA02266@nifty.ne.jp>
-
- * eval.c (TMP_PROTECT_END): tmp__protect_tmp may be NULL.
-
-Sun Jul 2 03:37:50 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: 1.1.25.
-
- * lib/net/protocol.rb (each_crlf_line): beg = 0 is needed in adding{}
-
- * lib/net/smtp.rb: allow String for to_addr of SMTP#sendmail
-
-Sat Jul 1 15:22:35 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * numeric.c (fix_rshift): should handle shift value more than
- sizeof(long).
-
-Sat Jul 1 15:22:35 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_eval): the value from RTEST() is not valid Ruby
- object. result should be either true or false.
-
-Sat Jul 1 09:30:06 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * re.c (rb_reg_initialize): was freeing invalid pointer.
-
-Sat Jul 1 03:25:56 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (call_args): command_call can be the last argument of
- call_args. It had to be the only argument.
-
- * re.c (rb_reg_s_quote): should not dump core even for unsane mbc
- string.
-
-Fri Jun 30 01:36:20 2000 Aleksi Niemela <aleksi.niemela@cinnober.com>
-
- * parse.y (f_norm_arg): better, nicer error message.
-
-Thu Jun 29 07:45:33 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/socket/socket.c (udp_send): destination may be packed
- struct sockaddr.
-
- * object.c (rb_Integer): Integer(nil) should be invalid, on the
- other hand, nil.to_i is OK.
-
-Wed Jun 28 17:26:06 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/socket/socket.c (ip_recvfrom): udp_recvfrom and tcp_recvfrom
- is merged and moved to IPSocket#recvfrom.
-
- * ext/socket/socket.c (sock_s_getaddrinfo): family can be a
- strings such as "AF_INET" etc.
-
- * ruby.c (require_libraries): . and RUBYLIB added to $load_path
- just before -r procedure.
-
- * ruby.c (proc_options): -e, - did not exec -r.
-
-Wed Jun 28 14:52:28 2000 Koga Youichirou <y-koga@mms.mt.nec.co.jp>
-
- * config.sub: NetBSD/hpcmips support.
-
-Wed Jun 28 10:11:06 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * gc.c: gc trigger threshold changed; GC_NEWOBJ_LIMIT removed,
- FREE_MIN is increased to 4096.
-
-Tue Jun 27 22:39:28 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: 1.1.24.
-
- * lib/net/protocol.rb: modified each_crlf_line again.
-
- * lib/net/protocol.rb: do_write_beg,do_write_end -> writing{}
- do_write_do -> do_write
-
- * lib/net/http.rb: can make proxy connection by passing
- addresses to HTTP.new, start.
-
- * lib/net/http.rb: HTTP.new_implementation, old_implementation:
- can use 1.2 implementation of head, get, post, put.
- (see document)
-
-Tue Jun 27 12:05:10 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * win32.c (myfdclr): new function.
-
- * win32.h: add FD_CLR.
-
-Mon Jun 26 23:41:41 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * ruby.h: add cast for ANSI style.
-
- * gc.c (rb_data_object_alloc): use RUBY_DATA_FUNC.
-
-Mon Jun 26 22:20:03 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * win32/win32.c (is_socket, extract_file_fd): New function.
-
- * win32/win32.c (myfdopen): use is_socket().
-
- * win32/win32.c (myselect): return non socket files immediately
- if file and socket handles are mixed.
-
-Mon Jun 26 16:21:30 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_thread_schedule): wait_for cleared too early.
-
-Mon Jun 26 09:15:31 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * pack.c: remove obsolete 'F', 'D' specifiers.
-
-Sun Jun 25 00:55:03 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * ext/socket/socket.c (sock_s_getnameinfo): `res' would not
- be assigned if TYPE(sa) == T_STRING.
-
-Sat Jun 24 14:36:29 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * config*.dj, configure.bat, top.sed: move to djgpp/.
-
-Sat Jun 24 02:34:17 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ruby.c (load_file): call require_libraries() here to let
- debug.rb work properly.
-
-Fri Jun 23 22:34:51 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * bignum.c (rb_big_lshift): reorder xds assignment to avoid
- reusing `x' as `len' by VC++ 6.0 SP3 compiler with -Ox switch.
-
-Fri Jun 23 01:11:27 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (rb_str_substr): should return empty string (""),
- if beg == str.size and len == zero, mostly for convenience and
- backward compatibility.
-
- * parse.y (new_super): should tweak block_pass node for super too.
-
- * string.c (rb_str_split_m): last split element should not be nil,
- but "" when limit is specified.
-
-Thu Jun 22 17:27:46 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (rb_str_substr): str[n,m] now returns nil when n equals
- to str.size.
-
-Thu Jun 22 13:49:02 2000 Uechi Yasumasa <uechi@ryucom.ne.jp>
-
- * lib/net/ftp.rb: support resuming.
-
-Thu Jun 22 13:37:19 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * eval.c (rb_thread_sleep_forever): merge pause() macro.
-
-Wed Jun 21 08:49:04 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_eval): should not raise exception just by defining
- singleton class.
-
-Wed Jun 21 01:18:03 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ruby.h: two macros RUBY_DATA_FUNC and RUBY_METHOD_FUNC are added
- to make writing C++ extensions easier.
-
- * array.c (rb_ary_dup): internal classes should not be shared by dup.
-
- * hash.c (rb_hash_dup): ditto.
-
- * object.c (rb_obj_dup): ditto.
-
- * string.c (rb_str_dup): ditto.
-
- * error.c (Init_Exception): renamed NotImplementError to
- NotImplementedError.
-
-Tue Jun 20 16:22:38 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * time.c (make_time_t): bug in DST boundary.
-
-Tue Jun 20 10:54:19 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * configure.in: add eval sitedir.
-
-Tue Jun 20 06:14:43 2000 Wakou Aoyama <wakou@fsinet.or.jp>
-
- * lib/cgi.rb: change: version syntax. old: x.yz, now: x.y.z
-
- * lib/net/telnet.rb: ditto.
-
-Tue Jun 20 00:37:45 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * re.c (rb_reg_kcode_m): Regexp#kcode returns nil for code unfixed
- regexp object.
-
- * bignum.c (bigdivmod): bignum zero check was wrong.
-
-Mon Jun 19 10:48:28 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * variable.c (rb_cvar_set): forgot to add security check for class
- variable assignment.
-
-Sun Jun 18 22:49:13 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * configure.in: single quoted sitedir.
-
- * mkconfig.rb: add DESTDIR for cross-compiling.
-
- * lib/mkmf.rb: add DESTDIR.
-
- * ruby.c (load_file): force binmode if fname includes ".exe"
- on DOSISH.
-
-Sat Jun 17 23:22:17 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * sprintf.c (rb_f_sprintf): should ignore negative precision given
- by <%.*>.
-
- * sprintf.c (rb_f_sprintf): should allow zero precision.
-
-Sat Jun 17 03:13:29 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * time.c (time_localtime): avoid unnecessary call of localtime.
-
- * time.c (time_gmtime): avoid unnecessary call of gmtime.
-
- * process.c (proc_wait2): new method.
-
- * process.c (proc_waitpid): second argument made optional.
-
- * process.c (proc_waitpid2): new method.
-
-Sat Jun 17 00:05:00 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * re.c (rb_reg_clone): should initialize member fields.
-
-Fri Jun 16 22:49:34 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (rb_io_rewind): set lineno to zero.
-
-Fri Jun 16 22:47:47 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: 1.1.23.
-
- * lib/net/protocol.rb: too many CRLF in last line.
-
-Fri Jun 16 21:23:59 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * configure.in: add pause(2) checking.
-
- * eval.c: define pause() if missing.
-
-Fri Jun 16 18:41:58 2000 Koji Arai <JCA02266@nifty.ne.jp>
-
- * process.c (proc_setsid): BSD-style setpgrp() don't return
- process group ID, but 0 or -1.
-
-Fri Jun 16 16:23:35 2000 Koji Arai <JCA02266@nifty.ne.jp>
-
- * file.c (rb_stat_inspect): gives detailed information;
- compatibility with ruby-1.4.x.
-
-Fri Jun 16 05:18:45 2000 Yasuhiro Fukuma <yasuf@bsdclub.org>
-
- * configure.in: FreeBSD: do not link dummy libxpg4 which was
- merged into libc.
-
-Fri Jun 16 03:17:36 2000 Satoshi Nojo <nojo@t-samukawa.or.jp>
-
- * ext/dbm/dbm.c (fdbm_length): use GetDBM. empty?, [] too.
-
- * ext/gdbm/gdbm.c (fgdbm_length): ditto.
-
- * ext/sdbm/init.c (fsdbm_length): ditto.
-
-Fri Jun 16 01:57:31 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_thread_sleep_forever): pause(2) instead of sleep(3).
-
-Thu Jun 15 10:46:36 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (rb_str_sub_bang): should probagate taintness from
- replacement string.
-
-Wed Jun 14 17:01:41 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * rubytest.rb: add CONFIG['EXEEXT'] to the executable file name.
-
-Wed Jun 14 14:50:00 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (rb_f_sub): assign to $_ only if modification happens.
-
- * string.c (rb_f_gsub): ditto.
-
- * string.c (rb_f_chop): ditto.
-
- * string.c (rb_f_chomp): ditto.
-
- * io.c (io_reopen): preserve file position by ftell/fseek, if io
- is a seekable.
-
- * eval.c (method_arity): wrong arity number for the methods with
- optional arguments.
-
- * time.c (make_time_t): opposite timezone shift (should be negative).
-
-Wed Jun 14 14:07:38 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * io.c: typo(ig/if).
-
- * re.c: typo(re/reg). add rb_reg_check().
-
- * time.c: remove unneeded declare(daylight, timezone).
-
- * configure.in: add include <time.h> when daylight checking.
-
-Wed Jun 14 11:36:52 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * marshal.c (r_object): modified for symbols.
-
- * marshal.c (w_object): ditto.
-
-Wed Jun 14 10:04:58 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * re.c (rb_memcmp): should compare according to ruby_ignorecase.
-
- * string.c (rb_str_cmp): use rb_memcmp.
-
- * string.c (rb_str_index): ditto.
-
- * string.c (rb_str_rindex): ditto.
-
- * string.c (rb_str_each_line): ditto.
-
-Wed Jun 14 04:58:53 2000 Dave Thomas <dave@thomases.com>
-
- * io.c (rb_io_set_lineno): should have returned VALUE, not
- integer.
-
-Wed Jun 14 09:29:42 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (rb_str_dup): dup should always propagate taintness.
-
-Wed Jun 14 00:50:14 2000 Wakou Aoyama <wakou@fsinet.or.jp>
-
- * lib/cgi.rb: read_multipart(): if no content body then raise EOFError.
-
-Tue Jun 13 11:46:17 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * process.c (proc_setsid): try implement it using setpgrp() and
- ioctl(fd, TIOCNOTTY, NULL).
-
- * re.c (rb_reg_prepare_re): magic variable $= should affect regex
- pattern match.
-
- * time.c (make_time_t): use tm.tm_gmtoff if possible.
-
- * time.c (time_zone): use tm.tm_zone if available.
-
-Tue Jun 13 01:50:57 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: 1.1.22.
-
- * lib/net/http.rb: HTTPResponse#body returns body.
-
-Mon Jun 12 23:41:54 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * configure.in (daylight): avoid GCC optimization.
-
-Mon Jun 12 19:02:27 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * configure.in: cygwin has strange timezone.
-
- * time.c (time_zone): use tzname and daylight.
-
-Sat Jun 10 23:10:32 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (rb_io_seek): whence is optional, default is SEEK_SET.
-
-Fri Jun 9 17:00:29 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: 1.1.21.
-
- * lib/net/http.rb: exception is raised with response object.
-
-Fri Jun 9 15:11:35 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * time.c (make_time_t): supports daylight saving time.
-
- * eval.c (rb_thread_safe_level): should retrieve current $SAFE
- value if a thread is the current thread.
-
-Thu Jun 8 14:25:45 2000 Hiroshi Igarashi <iga@ruby-lang.org>
-
- * lib/mkmf.rb: add target `distclean' in Makefile for extlib.
- target `clean' doesn't remove Makefile.
-
-Thu Jun 8 13:34:03 2000 Dave Thomas <dave@thomases.com>
-
- * numeric.c: add nan?, infinite?, and finite? to Float
-
-Thu Jun 8 00:31:04 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * regex.h: export re_mbctab properly on cygwin.
-
- * dln.c: use dlopen instead of LoadLibrary on cygwin.
-
-Thu Jun 8 13:41:34 2000 Tadayoshi Funaba <tadf@kt.rim.or.jp>
-
- * file.c (rb_file_s_basename): might dump core.
-
-Tue Jun 6 03:29:12 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * dir.c (dir_foreach): now returns nil for consistency.
-
- * bignum.c (bigdivmod): modulo by small numbers was wrong.
-
-Mon Jun 5 00:18:08 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * bignum.c: avoid conflict with USHORT on mingw32.
-
-Mon Jun 5 00:13:35 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * eval.c (rb_thread_schedule): =/== typo.
-
-Sun Jun 4 03:17:36 2000 Wakou Aoyama <wakou@fsinet.or.jp>
-
- * lib/cgi.rb: improve: CGI::pretty()
-
-Sun Jun 4 02:01:10 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * lib/mkmf.rb: do not need to add -L$(topdir) in --enable-shared case.
-
-Sat Jun 3 13:50:06 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (rb_id2name): should support constant attrset
- identifiers.
-
- * bignum.c (rb_big_eq): Bignum#== should not raise exception.
-
-Fri Jun 2 11:24:48 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (rb_io_popen): open with a block returns the value from the
- block. old behavior was back.
-
-Fri Jun 2 00:42:31 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
-
- * eval.c (rb_thread_cleanup): should clear priority for thread
- termination.
-
-Thu Jun 01 22:39:41 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: 1.1.20.
-
- * lib/net/http.rb: wrongly closed the socket twice
- when no Content-Length: was given.
-
-Thu Jun 1 00:59:15 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_yield_0): convert Qundef to [].
-
-Wed May 31 20:45:59 2000 Dave Thomas <Dave@Thomases.com>
-
- * string.c (rb_str_slice_bang): wrong argument number.
-
-Wed May 31 12:37:04 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_exec_end_proc): print error message from END procs.
-
-Wed May 31 04:06:41 2000 Wakou Aoyama <wakou@fsinet.or.jp>
-
- * lib/cgi.rb: change: CGI#out() if "HEAD" == REQUEST_METHOD then
- output only HTTP header.
-
-Wed May 31 01:54:21 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_thread_schedule): set main_thread->status to
- THREAD_TO_KILL, before raising deadlock error.
-
- * eval.c (rb_thread_deadlock): if curr_thread == main_thread, do
- not call rb_thread_restore_context()
-
-Tue May 30 23:33:41 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * lib/mkmf.rb (create_makefile): add $(TARGET).ilk and *.pdb
- to cleanup files for mswin32.
-
-Mon May 29 10:41:10 2000 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * file.c (rb_file_s_basename): should propagate taintness.
-
-Sun May 28 21:37:13 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * eval.c: bug fix: DLEXT2.
-
-Sun May 28 19:21:43 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * win32/win32.c: use ruby's glob.
-
- * dir.c: "glob" exported and renamed to "rb_glob".
-
- * ruby.h: ditto.
-
- * main.c: turn off command line mingw32's globbing.
-
-Wed May 25 22:25:13 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * ext/extmk.rb.in: use "ftools" instead of "rm -f".
-
- * lib/mkmf.rb: ditto.
-
-Thu May 25 22:01:32 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * defines.h: mswin32: remove obsolete USHORT definition.
-
- * re.h: mswin32: use EXTERN instead of extern.
-
- * regex.h: mswin32: export re_mbctab properly.
-
- * win32/ruby.def: add ruby_ignorecase and regex.c's exports.
-
-Thu May 25 21:28:44 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * re.c (rb_reg_expr_str): escape un-printable character.
-
-Thu May 25 01:35:15 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (tokadd_escape): forgot to add `\x' to hexadecimal
- escape sequences.
-
- * object.c (rb_obj_dup): dup for normal object (T_OBJECT) copies
- instance variables only.
-
-Wed May 24 23:49:47 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * object.c (rb_mod_initialize): should provide initialize.
-
-Wed May 24 23:17:50 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * win32/Makefile: remove unnecessary mv and rm command call.
-
-Wed May 24 21:01:04 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * ext/pty/pty.c: use "" instead of <> to include ruby.h and rubyio.h
- for BeOS (PowerPC).
-
- * file.c (rb_find_file): should check dln_find_file() result.
-
- * win32/ruby.def: add rb_block_given_p.
-
-Wed May 24 16:32:45 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (rb_io_popen): popen does not take 3rd argument anymore.
-
- * re.c (rb_reg_desc): re may be zero, check before dereferencing.
-
-Wed May 24 16:03:06 2000 Wakou Aoyama <wakou@fsinet.or.jp>
-
- * lib/cgi.rb: bug fix: CGI::escape(), CGI::Cookie::new()
-
- * lib/net/telnet.rb: improve: binmode(), telnetmode() interface
-
-Wed May 24 13:12:31 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * misc/ruby-mode.el (ruby-parse-region): support `while .. do'
- etc. But corresponding keywords must be at the beginning of
- line.
-
-Tue May 23 23:50:12 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * re.c (rb_reg_initialize_m): wrong kcode value.
-
- * re.c (rb_reg_s_new): forgot to initialize re->ptr.
-
-Tue May 23 08:36:24 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_compile_pattern): forgot to restore old option
- status by (?ix-ix).
-
- * regex.c (re_compile_fastmap): anychar may match newline if
- RE_OPTION_MULTILINE or RE_OPTION_POSIXLINE is set.
-
-Mon May 22 22:45:06 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: 1.1.19.
-
- * lib/net/http.rb: do not use Regexp "p" option.
-
-Mon May 22 21:56:43 2000 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * struct.c (rb_struct_getmember): should use ID2SYM, not INT2NUM.
-
-Mon May 22 15:07:37 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * file.c (rb_find_file): should check if the file really exists.
-
-Mon May 22 09:08:12 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (rb_io_popen): _exit(0) after processing block under the
- child process.
-
- * io.c (rb_io_popen): flush stdout/stderr before subprocess
- termination.
-
- * eval.c (rb_check_safe_str): insert rb_secure(4); operation
- requires untainted string should be prohibited in level 4.
-
-Sun May 21 21:17:00 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * configure.in: add Setup.dj for djgpp cross-compiling.
-
- * Setup.dj: add readline.
-
- * instruby.rb: copy win32/win32.h to archlibdir on mingw32.
-
-Sun May 21 20:58:08 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * pack.c: fix OFF16 and OFF32 definitions for Alpha and IRIX64.
-
-Sun May 21 17:31:37 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * instruby.rb: support "make install" for cross-compiling.
-
- * ext/extmk.rb.in: ditto.
-
-Sun May 21 14:22:49 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * Makefile.in: rename prep.rb to fake.rb.
-
- * configure.in: ditto.
-
-Sat May 20 23:29:14 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * dir.c (dir_s_new): does not take block; "open" does.
-
- * io.c (rb_io_s_new): ditto.
-
-Fri May 19 07:44:26 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * dir.c (dir_s_open): Dir#open does not returns closed Dir if a
- block is given to the method.
-
- * re.c (rb_reg_initialize_m): Regexp::new calls initialize now.
-
- * string.c (Init_String): String#delete_at removed.
-
- * string.c (rb_str_aset_m): should have checked argc != 2.
-
- * eval.c (rb_thread_schedule): select(2) was called too many.
-
- * regex.c (re_compile_pattern): a bug in (?m) support. Pointed
- out by Dave Thomas <Dave@thomases.com>.
-
-Thu May 18 23:55:26 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * dln.c (search_undef): st_lookup()'s 3rd parameter should be
- a pointer of the variable which has the same size and alignment
- as `char *'.
-
- * marshal.c (w_symbol, w_object): ditto.
-
- * parse.y (rb_intern): ditto.
-
-Thu May 18 18:00:35 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: 1.1.18.
-
- * lib/net/protocol.rb: Net::Version was removed.
-
- * lib/net/smtp.rb: use Socket.gethostname to get local host name.
-
-Thu May 18 13:34:57 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/socket/socket.c (ruby_connect): should not have replaced
- thread_write_select() by rb_thread_fd_writable().
-
-Thu May 18 09:01:25 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * configure.in, ext/extmk.rb.in, lib/mkmf.rb: remove BeOS R3 support.
- Make a shared library (libruby.so) only if the --enable-shared
- option is specified.
-
- * instruby.rb: no longer use libruby.so.LIB and import.h.
-
- * io.c: fix READ_DATA_PENDING definition for BeOS (PowerPC).
-
-Wed May 17 14:14:23 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * re.c (rb_reg_new_1): use /m instead of /p.
-
-Wed May 17 02:22:03 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_thread_polling): wait 0.06 second to let other
- processes run.
-
- * process.c (rb_waitpid): avoid busy wait using rb_thread_polling.
-
- * file.c (rb_thread_flock): ditto.
-
- * parse.y (expr): avoid calling value_expr() twice.
-
-Wed May 17 00:45:57 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * io.c (rb_io_binmode): should check PLATFORMs, not O_BINARY, sigh...
-
-Wed May 17 00:40:15 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * win32/config.h: add DLEXT2, now DLEXT on mswin32 is "so".
-
- * win32/config.status: ditto.
-
- * win32/ruby.def: add symbol "rb_big_divmod".
-
-Tue May 16 19:45:32 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * intern.h: use EXTERN instead of extern.
-
- * win32/ruby.def: add rb_defout, rb_stdout, ruby_errinfo,
- ruby_sourceline, ruby_sourcefile to work with eruby
- reported by Hiroshi Saito <HiroshiSaito@pob.org>.
- Export both ruby_xmalloc and xmalloc etc.
-
-Tue May 16 17:00:05 2000 Masaki Fukushima <fukusima@goto.info.waseda.ac.jp>
-
- * eval.c (rb_thread_select): should check whether fds are null.
-
-Tue May 16 11:51:31 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (pipe_open): synchronize subprocess stdout/stderr.
-
-Mon May 15 15:38:09 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ruby.h: exported symbols should be for xmalloc etc. are now
- prefixed by 'ruby_', e.g. ruby_xmalloc().
-
- * eval.c (rb_thread_select): remove busy wait for select.
-
- * dir.c (glob): trailing path may be null, e.g. glob("**").
-
-Mon May 15 14:48:41 2000 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * io.c (rb_io_pid): new method; returns nil if no process attached
- to the IO.
-
-Mon May 15 01:18:20 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (rb_io_s_popen): _exit after Proc execution.
-
-Sun May 14 18:05:59 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * Makefile.in: missing/nt.c -> win32/win32.c
-
- * configure.in: bug fix; static linking on mingw32.
-
- * cygwin/GNUmakefile.in: remove VPATH.
-
- * ext/extmk.rb.in: Makefile set binmode with mingw32 on cygwin32.
-
- * lib/mkmf.rb: ditto.
-
- * win32/config.h: undef HAVE_SYS_FILE_H.
-
-Sun May 14 02:02:48 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * lib/irb/ruby-lex.rb: '/' should be escaped in character class.
-
-Sun May 14 00:54:43 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * configure.in, ...: support mingw32.
-
- * defines.h: ditto. undef EXTERN for tcl/tk on cygwin.
-
- * ext/*/extconf.rb: replace PLATFORM with RUBY_PLATFORM.
-
- * ext/socket/sockport.h: define IN_MULTICAST for missing IN_MULTICAST.
-
- * ext/tcltklib/tcltklib.c: remove declaration of rb_argv0.
-
- * file.c: should check S_IXGRP, S_ISGID, not NT.
-
- * io.c (rb_io_binmode): should check _IOBIN, O_BINARY, not PLATFORMs.
-
-Sat May 13 14:21:15 2000 Koji Arai <JCA02266@nifty.ne.jp>
-
- * io.c (rb_io_s_popen): should check whether a block is given.
-
-Fri May 12 17:33:44 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_compile_pattern): charset_not should not exclude
- newline from matching set.
-
-Thu May 11 22:51:05 2000 Ryunosuke Ohshima <ryu@jaist.ac.jp>
-
- * pack.c (pack_pack): Bignum support.
-
- * pack.c (pack_unpack): ditto.
-
-Thu May 11 21:19:29 2000 Hiroshi Igarashi <iga@ruby-lang.org>
-
- * intern.h: add missing declarations of ruby API functions.
-
- * ruby.h: fix function name in declarations.
-
-Thu May 11 22:29:25 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * ext/md5/depend: add $(topdir)/config.h dependency to md5c.o.
-
- * ext/md5/extconf.rb: new file to add -DHAVE_CONFIG_H flag for Alpha.
-
-Thu May 11 10:55:52 2000 Ryunosuke Ohshima <ryu@jaist.ac.jp>
-
- * pack.c (pack_pack): packing BER compressed integer by `w'.
-
- * pack.c (pack_unpack): unpacking BER.
-
-Thu May 11 00:37:55 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (parse_regx): remove in_brack.
-
-Wed May 10 12:51:18 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ruby.c (proc_options): move adding RUBYLIB and "." to the load
- path after #! line parsing.
-
- * parse.y (parse_regx): should parse backslash escape like `\c['
- here to avoid causing `unterminated regexp' error.
-
-Wed May 10 00:19:53 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * MANIFEST, beos/GNUmakefile.in, configure.in: no longer need
- beos/GNUmakefile.in to support BeOS R4.5.2 (Intel) as a result
- of eban's Makefile.in change.
-
- * io.c: NOFILE is already defined on BeOS R4.5 (Intel) or later.
-
- * lib/matrix.rb: remove debug print.
-
- * regex.c: don't use nested comment.
-
-Tue May 9 17:08:43 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (massign): no longer convert nil into empty array.
-
- * io.c (rb_io_s_popen): optional 3rd argument to give proc, which
- will be executed in spawned child process.
-
-Mon May 8 23:47:39 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * eval.c (rb_callcc): prev & next should be initialized to zero.
-
-Mon May 8 23:17:36 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * dln.c (dln_init): remove possible buffer overrun. This is
- suggested by Aleksi Niemela <aleksi.niemela@cinnober.com>.
-
- * dln.c (init_funcname): ditto.
-
-Sat May 6 23:35:47 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (lhs): should allow `obj.Attr = 5' type expression.
-
-Sat May 6 15:46:08 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * ext/socket/extconf.rb: add a new configure option to force use
- of the WIDE Project's getaddrinfo(): --enbale-wide-getaddrinfo.
-
-Fri May 5 21:19:22 2000 MOROHOSHI Akihiko <moro@remus.dti.ne.jp>
-
- * parse.y (yylex): allow '$1foo' and such.
-
-Fri May 5 17:57:24 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: 1.1.17.
-
- * lib/net/http.rb: write also port number in Host: field.
-
- * lib/net/http.rb: see Proxy-Connection: to decide socket connection.
-
-Fri May 5 03:25:15 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_compile_fastmap): charset_not for multibyte
- characters excluded too many characters.
-
-Tue May 2 13:23:43 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_thread_schedule): little bit more impartial context
- switching.
-
-Tue May 2 09:50:03 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * configure.in: add DLDLIBS to set platform specific library
- for extensions.
-
- * ext/extmk.rb.in: use @DLDLIBS@ instead of RUBY_PLATFORM choice.
-
- * lib/mkmf.rb: use CONFIG["DLDLIBS"] instead of RUBY_PLATFORM choice.
-
- * config_s.dj: add @DLDLIBS@.
-
- * win32/config.status: ditto.
-
- * win32/ruby.def: regular maintenance.
-
-Mon May 1 23:42:44 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * configure.in, eval.c: add DLEXT2. now DLEXT on Cygwin is "so".
-
- * defines.h: use dllimport, dllexport for Cygwin 1.1.x.
-
- * ruby.h: ditto.
-
- * cygwin/GNUmakefile.in: ditto.
-
- * ext/Win32API/Win32API.c: directly "call" in asm statement for
- gcc 2.95.x or newer.
-
-Sat Apr 29 04:58:12 2000 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * array.c (rb_ary_unshift_m): performance improvement.
-
-Fri Apr 28 00:19:22 2000 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * array.c (rb_ary_unshift_m): takes items to push.
-
-Wed Apr 26 15:23:02 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (rb_str_succ): insert carrying character just before
- the leftmost alpha numeric character.
-
- * string.c (rb_str_succ): proper behavior for "".succ and "\377".succ.
-
- * string.c (rb_str_succ): use realloc and memmove.
-
-Tue Apr 25 18:28:45 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: 1.1.16.
-
- * lib/net/smtp.rb: add SMTP AUTH
-
-Tue Apr 25 14:30:13 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (rb_io_gets_internal): shortcut when rs == rb_default_rs.
-
-Sat Apr 22 23:14:41 2000 SHIROYAMA Takayuki <psi@fortune.nest.or.jp>
-
- * configure.in: MacOS X support.
-
-Sat Apr 22 16:37:10 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: 1.1.15.
-
- * lib/net/http.rb: closing socket by watching both
- user header and server response
-
-Fri Apr 21 21:44:34 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * io.c (rb_io_s_pipe): should set FMODE_SYNC.
-
-Thu Apr 20 16:59:22 2000 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * eval.c (massign): `*lvalue = false' should assign `[false]' to
- lvalue.
-
-Wed Apr 19 08:35:08 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * class.c (rb_singleton_class): generate singleton class for
- special constants: nil, true, false.
-
-Wed Apr 19 02:09:30 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * class.c (rb_singleton_class): singleton method for nil, true,
- false is possible now.
-
- * eval.c (rb_eval): ditto.
-
-Tue Apr 18 18:54:25 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: 1.1.14.
-
- * lib/net/http.rb: new method HTTP#head2.
-
- * lib/net/http.rb: get2/post2 does not raise exceptions.
-
-Mon Apr 17 15:16:31 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (rb_io_close): to detect some exceptional status, writable
- IO should be flushed before close;
-
-Sat Apr 15 18:29:00 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * array.c (rb_ary_collect_bang): Array#filter renamed.
-
-Fri Apr 14 19:47:11 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: 1.1.13.
-
- * lib/net/pop.rb: accept illegal timestamp
-
- * lib/net/http.rb: when body was chunked, does not set Content-Length:
-
-Tue Apr 11 21:14:42 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * config_s.dj: add @sitedir@.
- * configure.in: add --with-sitedir=DIR option.
- * instruby.rb: use CONFIG["sitedir"].
- * lib/mkmf.rb: support 'make site-install'.
- * win32/config.status: add @sitedir@.
-
-Tue Apr 11 16:25:15 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * bignum.c (rb_big_2comp): unnecessary lvalue cast removed.
-
-Tue Apr 11 02:25:53 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * hash.c (env_fetch): new method.
-
- * marshal.c (marshal_dump): accepts depth = nil for unlimited depth.
-
-Sun Apr 9 20:49:19 2000 Dave Thomas <Dave@Thomases.com>
-
- * parse.y (str_extend): Allow class variables to be expanded.
-
-Fri Apr 7 02:03:54 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * error.c (rb_sys_fail): escape non-printable characters.
-
-Thu Apr 6 20:10:47 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * ext/extmk.rb.in (create_makefile): BeOS --program-suffix support.
- * lib/mkmf.rb (create_makefile): ditto.
-
-Thu Apr 6 09:55:26 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * error.c (rb_sys_fail): need rb_exc_new2() call on BeOS.
-
-Mon Apr 3 17:22:27 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (rb_io_reopen): support tempfile.
-
- * eval.c (catch_i): should supply argument.
-
-Sat Apr 1 22:50:28 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * marshal.c (r_object): wrong symbol restoration.
-
-Sat Apr 1 21:30:53 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * io.c (rb_io_printf, rb_f_printf): should use rb_io_write.
-
-Sat Apr 1 00:16:05 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * gc.c (rb_gc_call_finalizer_at_exit): should be clear flags
- before calling finalizers.
-
- * eval.c (specific_eval): can be called without SecurityError, if
- $SAFE >= 4.
-
- * object.c (sym_inspect): inspect gives ":sym", to_s gives "sym".
-
-Fri Mar 31 22:07:04 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: 1.1.12.
-
- * lib/net/protocol.rb: update Net::Protocol::Proxy#connect
-
- * lib/net/protocol.rb: ReplyCode is not a class
-
- * lib/net/http.rb: header value format was change:
- values do not include header name
-
- * lib/net/http.rb: header is not a Hash, but HTTPResponse
-
-Thu Mar 30 12:19:44 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * enum.c (enum_find): rb_eval_cmd() should be called with array.
-
-Tue Mar 28 13:57:05 2000 Clemens Hintze <c.hintze@gmx.net>
-
- * ext/dbm/dbm.c (fdbm_invert): should return new hash.
-
- * ext/gdbm/gdbm.c (fgdbm_invert): ditto.
-
-Tue Mar 28 00:58:03 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: 1.1.11.
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: does not
- dispatch any commands while dispatching command.
-
- * lib/net/protocol.rb: failed to get error class of
- inherited ReplyCode
-
- * lib/net/http.rb: change feature of "get2", "post2"
-
-Mon Mar 27 01:34:58 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: 1.1.10.
-
- * lib/net/http.rb: return value of 'head' was wrong.
-
-Sun Mar 26 17:47:35 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: 1.1.9.
-
- * lib/net/smtp.rb: SMTP#do_ready wrongly took no arguments
-
-Sat Mar 25 23:21:10 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * marshal.c (w_object): symbols should be converted to ID before
- dumping out.
-
-Fri Mar 24 18:26:51 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * file.c (test_check): should have checked exact number of arguments.
-
-Fri Mar 24 21:02:11 2000 Koji Arai <JCA02266@nifty.ne.jp>
-
- * signal.c (trap): should treat some symbols as the signal.
-
-Fri Mar 24 06:58:03 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: 1.1.8.
-
- * lib/net/http.rb: post, get2, post2, get_body
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: separate
- Command/Socket documentation.
-
-Thu Mar 23 02:26:14 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (rb_io_fptr_finalize): fptr may be null.
-
- * io.c (rb_io_s_new): now calls `initialize'.
-
- * io.c (rb_io_initialize): actual open done in this method.
-
- * io.c (rb_file_initialize): ditto.
-
- * eval.c (rb_eval): class variables in singleton class definition
- is now handled properly (I hope).
-
-Wed Mar 22 21:49:36 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * st.c (st_delete_safe): skip already deleted entry.
-
- * hash.c (rb_hash_delete): modify brace miss.
-
-Wed Mar 22 08:53:58 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (exec_under): do not push cbase if ruby_cbase == under.
-
- * node.h (NEW_CREF0): preserve cbase nesting.
-
-Tue Mar 21 12:57:50 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * object.c (rb_class_s_new): Class::new should call `inherited'.
-
-Sat Mar 18 12:36:09 2000 Nobuyoshi Nakada <nobu.nokada@softhome.net>
-
- * eval.c (rb_backtrace, make_backtrace): removed unused variable
- `lev'.
-
- * eval.c (rb_attr): calls `method_added' at attribute definition.
-
- * eval.c (rb_mod_modfunc): calls `singleton_method_added' while
- `module_function'.
-
- * eval.c (rb_eval): parameter to `method_added' and
- `singleton_method_added' is Symbol.
-
- * eval.c (Init_eval): caches IDs for `method_added' and
- `singleton_method_added'.
-
-Sat Mar 18 11:25:10 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (rescue): allows `rescue Error in foo'. experimental.
- which is better this or preparing alias `exception' for `$!'?
-
-Fri Mar 17 15:02:45 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * variable.c (rb_autoload_id): defining new autoload should be
- prohibited for $SAFE > 4.
-
- * variable.c (rb_autoload_load): autoload should be possible for
- $SAFE > 4.
-
- * eval.c (call_trace_func): should handle T_ICLASS properly.
-
-Fri Mar 17 14:34:30 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (str_gsub): forgot to initialize str->orig.
-
-Fri Mar 17 01:24:59 2000 Dave Thomas <Dave@thomases.com>
-
- * string.c (rb_str_clone): forgot to copy str->orig if STR_NO_ORIG
- is set by Array#pack.
-
-Wed Mar 15 21:25:04 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * array.c (rb_ary_join): 'result' is always duplicated
- before concat string.
-
-Wed Mar 15 17:26:05 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * hash.c (rb_hash_s_create): unexpected recursive call removed.
- this bug was found by Satoshi Nojo <nojo@t-samukawa.or.jp>.
-
-Wed Mar 15 13:12:39 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (Init_Thread): Thread.join removed finally.
-
- * string.c (rb_str_chomp_bang): forgot to call rb_str_modify().
-
-Mon Mar 13 16:12:13 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (block_pass): distinguish real orphan block and still
- on-stack block passed by block argument.
-
-Mon Mar 13 00:20:25 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (f_norm_arg): proper error message when constant comes
- in formal argument list. this message is suggested by Muvaw
- Pnazte <bugathlon@yahoo.com>.
-
- * eval.c (rb_f_raise): proper error message when the first
- argument is not an exception class/object.
-
- * string.c (rb_str_dup): dup now postpone buffer copy as long as
- possible. performance improved by lazy copying.
-
-Sun Mar 12 13:58:52 2000 Koji Arai <JCA02266@nifty.ne.jp>
-
- * signal.c (rb_f_kill): should treat some symbols as the signal.
-
-Sat Mar 11 22:03:03 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (rb_str_gsub): performance tune by avoiding buffer copy.
-
- * eval.c (rb_f_missing): check if argv[0] is ID.
-
-Sat Mar 11 15:49:41 2000 Tadayoshi Funaba <tadf@kt.rim.or.jp>
-
- * struct.c (rb_struct_aref): struct aref by symbol.
-
-Sat Mar 11 05:07:11 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * process.c (proc_setpriority): should return 0, not nil.
-
- * process.c (proc_setpgid): ditto.
-
-Fri Mar 10 18:14:54 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * file.c (path_check_1): confusing buf and path. this bug found
- by <decoux@moulon.inra.fr>.
-
-Fri Mar 10 09:37:49 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * MANIFEST: add beos/GNUmakefile.in.
- * configure.in: support BeOS R4.5.2 (Intel).
- * beos/GNUmakefile.in: new file to support BeOS R4.5.2 (Intel).
-
-Thu Mar 9 11:13:32 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_compile_fastmap): fixed embarrassing brace bug.
-
-Thu Mar 9 01:36:32 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * missing/flock.c: emulate missing flock() with fcntl().
-
-Thu Mar 9 00:29:35 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * object.c (sym_to_s): returns ":sym".
-
- * object.c (sym_id2name): separated from to_s; returns "sym".
-
-Wed Mar 8 19:16:19 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: 1.1.7.
-
- * lib/net/http.rb (connecting): returns header
-
-Wed Mar 8 02:08:43 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y: escape expansion too early.
-
- * string.c (rb_f_scan): Kernel#scan added.
-
- * regex.c (re_compile_pattern): support \cX et al.
-
-Tue Mar 7 01:44:27 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (set_stdin): simplified procedure, allows $stdin = DATA;
- experimental.
-
- * io.c (set_outfile): ditto.
-
- * re.c (Init_Regexp): new method Regexp#last_match added; it's an
- alternative for $~.
-
- * configure.in (DEFAULT_KCODE): KCODE_NONE should be the default.
-
- * dir.c (dir_s_rmdir): should return 0 on success.
-
- * signal.c: remove CWGUSI support.
-
-Mon Mar 6 12:28:37 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * marshal.c (w_symbol): support symbol object.
-
- * util.c: make symbol as separated class.
-
- * error.c (Init_Exception): new exception RangeError.
-
- * ext/socket/socket.c (ip_addrsetup): should check length of hostname.
-
- * ext/socket/socket.c (ip_addrsetup): check newline at the end of
- hostname. These fixes suggested by Muvaw Pnazte <bugathlon@yahoo.com>.
-
-Sun Mar 5 20:35:45 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * ext/Win32API/Win32API.c (Win32API_initialize): should call
- LoadLibrary() everytime and should assign the hdll to Win32API
- object(protect the hdll from GC).
-
-Sun Mar 5 18:49:06 2000 Nakada.Nobuyoshi <nobu.nokada@softhome.net>
-
- * misc/ruby-mode.el (ruby-parse-region): not treat method `begin'
- and `end' as reserved words.
-
- * misc/ruby-mode.el (ruby-font-lock-docs): ignore after `=begin'
- and `=end'.
-
- * misc/ruby-mode.el (ruby-font-lock-keywords, hilit-set-mode-patterns):
- added `yield' to keywords.
-
- * misc/ruby-mode.el (ruby-font-lock-keywords, hilit-set-mode-patterns):
- matches keywords at end of buffer.
-
-Sun Mar 5 18:08:53 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: 1.1.6.
-
- * lib/net/http.rb: allow to omit 'start'
-
-Tue Feb 29 01:08:26 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * range.c (range_initialize): initialization done in `initialize';
- `initialize' should not be called more than once.
-
- * object.c (Init_Object): default `initialize' should take zero
- argument.
-
- * time.c (time_s_new): call `initialize' in Time::new.
-
-Sat Feb 26 22:39:31 2000 EGUCHI Osamu <eguchi@shizuokanet.ne.jp>
-
- * string.c (rb_str_times): fix String#* with huge string.
-
-Sat Feb 26 00:14:59 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * dir.c (dir_s_new): call `initialize' in Dir::new.
-
-Fri Feb 25 23:01:49 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * ruby.h: export ruby_safe_level by EXTERN for mswin32.
- * win32/ruby.def: regular maintenance.
-
-Fri Feb 25 22:12:46 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (rb_io_reopen): IO#reopen should accept path as well.
-
- * string.c (rb_str_s_new): call `initialize' in String::new.
-
- * hash.c (rb_hash_s_new): call `initialize' in Hash::new.
-
- * array.c (rb_ary_s_new): call `initialize' in Array::new.
-
-Fri Feb 25 12:50:20 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_thread_start_timer): interval changed to 10ms from 50ms.
-
-Fri Feb 25 06:42:26 2000 GOTOU YUUZOU <gotoyuzo@notwork.org>
-
- * ext/socket/socket.c (ip_addrsetup): hostp should remain NULL if
- host is nil.
-
-Thu Feb 24 16:53:47 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_thread_schedule): priority check for sleep expired
- threads needed.
-
-Wed Feb 23 14:22:32 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * array.c (rb_ary_join): forgot to initialize a local variable
- `taint'.
-
-Tue Feb 22 07:40:55 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * re.c (Init_Regexp): renamed to MatchData, old name MatchingData
- remain as alias.
-
-Tue Feb 22 00:20:21 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/protocol.rb, smtp.rb, pop.rb, http.rb: 1.1.5.
-
- * lib/net/session.rb: rename to protocol.rb
-
- * lib/net/protocol.rb: ProtocolSocket -> Net::Socket
-
- * lib/net/protocol.rb: Net::Socket#write, write_pendstr
- can take block
-
- * lib/net/smtp.rb: new methods SMTP#ready SMTPCommand#write_mail
-
- * lib/net/pop.rb: POPMail#pop can take block
-
-Sat Feb 19 23:58:51 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_match): pop_loop should not pop at forward jump.
-
-Fri Feb 18 17:15:40 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (method_clone): method objects are now clonable.
-
-Fri Feb 18 00:27:34 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * variable.c (rb_shared_variable_declare): shared variable (aka
- class/module variable) introduced. prefix `@@'. experimental.
-
- * class.c (rb_scan_args): new format char '&'.
-
-Thu Feb 17 19:09:05 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * win32/win32.c (mypopen): don't close handle if it is not assigned.
- * win32/win32.c (my_open_osfhandle): support O_NOINHERIT flag.
- * win32/win32.c (win32_getcwd): rename getcwd to win32_getcwd
- in order to avoid using the C/C++ runtime DLL's getcwd.
- Use CharNext() to process directory name.
- * win32/win32.h: map getcwd to win32_getcwd.
-
-Wed Feb 16 00:32:49 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (method_arity): nd_rest is -1 for no rest argument.
-
- * process.c (proc_waitpid): returns nil when waitpid(2) returns 0.
-
-Tue Feb 15 01:47:00 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * process.c (rb_f_waitpid): pid_t should be signed.
-
-Mon Feb 14 13:59:01 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (yylex): yylex yields wrong tokens for `:foo=~expr'.
-
- * ruby.c (load_file): exit if reading file is empty.
-
-Mon Feb 14 03:34:52 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (yylex): `foo.bar=1' should be <foo><.><bar><=><1>,
- not <foo><.><bar=><1>.
-
- * eval.c (rb_thread_restore_context): process according to
- RESTORE_* is moved after longjmp().
-
- * eval.c (thread_switch): new function to process RESTORE_*.
-
-Sun Feb 13 16:19:49 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * ruby.c (require_libraries): don't access freed memory.
-
- * ruby.c (add_modules): ditto.
-
-Fri Feb 11 12:06:22 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (parse_quotedwords): %w() need to split not only by mere
- spaces, but by all whitespaces.
-
-Thu Feb 10 02:12:04 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (rb_str_index_m): did not support negative offset.
-
-Wed Feb 9 21:54:26 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * ext/socket/getaddrinfo.c: gcc --traditional support.
- Rearrange headers to work AC_C_CONST.
- * ext/socket/getnameinfo.c: ditto.
- * ext/socket/socket.c: mswin32: use double instead of long long.
-
-Wed Feb 9 16:30:41 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * numeric.c (num_coerce): should return [y, x].
-
-Wed Feb 9 11:07:30 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ruby.c (ruby_prog_init): loadpath structure changed.
-
-Tue Feb 8 02:07:33 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_search): optimize for \G at top.
-
- * regex.c (re_compile_pattern): \G introduced.
-
- * regex.c (re_match): ditto.
-
- * string.c (str_sub_bang): old behavior restored: bang method
- returns nil if string not changed.
-
- * regex.c (re_compile_pattern): support independent subexpression
- `(?>pattern)'.
-
- * regex.c (re_match): ditto.
-
-Mon Feb 7 15:51:08 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_match): now understands interrupts under Ruby.
-
-Mon Feb 7 07:51:52 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * array.c (rb_ary_uniq_bang): always return an Array.
-
- * array.c (rb_ary_compact_bang): ditto.
-
- * array.c (rb_ary_flatten_bang): ditto.
-
- * hash.c (rb_hash_reject): returns a Hash, not an Array.
-
- * hash.c (env_reject): ditto.
-
-Fri Feb 4 10:20:25 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (scan_once): scan now leaves information about the last
- successful pattern match in $&.
-
- * io.c (rb_io_close): should not check closed IO.
-
-Fri Feb 4 05:44:01 2000 Kentaro Inagaki <inagaki@tg.rim.or.jp>
-
- * ext/socket/socket.c (s_recv): TRAP_BEG after retry entry.
-
-Wed Feb 2 22:33:45 2000 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * eval.c (rb_thread_start): receives argument from outside, like
- `Thread::start(1,2,3){|a,b,c| ... }'.
-
-Wed Feb 2 22:14:40 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * re.c (rb_reg_regsub): should check regs->num_regs.
-
- * re.c (rb_reg_search): remove matchcache, use static struct
- re_register instead.
-
- * re.c (match_getter): avoid cloning match data.
-
-Wed Feb 2 17:12:15 2000 Dave Thomas <Dave@Thomases.com>
-
- * samples/eval.rb: Rescue new ScriptError exception
-
-Wed Feb 2 02:06:07 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (str_gsub_bang): gsub! now leaves information about the
- last successful pattern match in $&.
-
-Mon Jan 31 15:24:58 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (str_sub_bang): bang method returns string always.
- experimental.
-
-Sun Jan 30 17:58:09 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * eval.c: arrange to use setitimer(2) for BOW, DJGPP
-
- * defines.h: ditto. use random(3) on cygwin b20.1.
-
-Sun Jan 30 17:20:16 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * eval.c: use getrlimit(2) on DJGPP.
-
-Thu Jan 27 01:27:10 2000 GOTO Kentaro <gotoken@math.sci.hokudai.ac.jp>
-
- * dir.c (glob): glob pattern "/*" did not match.
-
-Wed Jan 26 22:30:47 2000 Shigeo Kobayashi <shigeo@tinyforest.gr.jp>
-
- * numeric.c (flo_modulo): wrong result for negative modulo.
-
-Wed Jan 26 02:01:57 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * file.c (test_c): should use S_ISCHR.
-
- * file.c (rb_stat_c): ditto.
-
- * string.c (rb_str_each_line): should propagate tainting.
-
-Tue Jan 25 04:01:34 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * object.c (rb_obj_freeze): all objects made freezable.
-
-Tue Jan 25 00:37:01 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * configure.in: use AC_CHECK_TOOL for cross compiling.
-
-Mon Jan 24 19:01:54 2000 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * array.c (rb_protect_inspect): should be checked by id of
- objects; not by object themselves.
-
-Mon Jan 24 18:48:08 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * eval.c (rb_eval): too many warnings; warned on every method
- overriding. should be on method discarding.
-
-Mon Jan 24 02:56:44 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (yylex): -2.abs should be `(-2).abs' to accomplish the
- principle of less surprise. `+2' too.
-
- * eval.c (rb_eval): when defining class is already there, and
- superclass differ, throw away the old class.
-
- * variable.c (rb_const_set): gives warning again on constant
- redefinition.
-
- * error.c (Init_Exception): SyntaxError, NameError, LoadError and
- NotImplementError are subclasses of ScriptError<Exception, not
- StandardError. experimental.
-
-Sat Jan 22 00:00:41 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (parse_quotedwords): no longer use `String#split'.
- and enable space escape within quoted word list.
- e.g. %w(a\ b\ c abc) => ["a b c", "abc"].
-
- * string.c (rb_str_slice_bang): new method `slice!'.
-
-Fri Jan 21 21:56:08 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/session.rb, smtp.rb, pop.rb, http.rb: 1.1.4.
-
- * lib/net/http.rb: can receive messages which have
- no Content-Length:.
-
-Fri Jan 21 16:15:59 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (thgroup_s_new): new class ThreadGroup.
-
-Tue Jan 18 12:24:28 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * struct.c (Init_Struct): remove Struct's own hash and eql?.
-
-Sat Jan 15 22:21:08 2000 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * eval.c (search_method): argument klass may be 0.
-
-Sat Jan 15 15:03:46 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * enum.c (enum_index): remove this method.
-
- * enum.c: remove use of pointers to local variables. find,
- find_all, min, max, index, member?, each_with_index,
-
- * eval.c (massign): multiple assignment does not use to_a anymore.
- experimental.
-
-Fri Jan 14 12:22:04 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (rb_str_replace): use memmove instead of memcpy for
- overwrapping strings (e.g. a[1] = a).
-
-Thu Jan 13 11:12:40 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (arg_add): use new node, ARGSPUSH.
-
-Mon Jan 10 18:32:28 2000 Koji Arai <JCA02266@nifty.ne.jp>
-
- * marshal.c (w_object): forgot an argument to call w_ivar().
-
-Sun Jan 9 18:13:51 2000 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * random.c: first was not defined unless HAVE_RANDOM.
-
-Sat Jan 8 19:02:49 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (rb_io_sysread): raise IOError for buffered IO.
-
- * ext/socket/socket.c (s_recv): ditto.
-
-Fri Jan 7 00:59:29 2000 Masahiro Tomita <tommy@tmtm.org>
-
- * io.c (io_fread): TRAP_BEG/TRAP_END added around getc().
-
-Thu Jan 6 00:39:54 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * random.c (rb_f_rand): should be initialized unless srand is
- called before.
-
-Wed Jan 5 16:59:34 2000 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/session.rb, smtp.rb, pop.rb, http.rb: 1.1.3.
-
- * lib/net/session.rb: Session -> Protocol, ...
-
- * lib/net/http.rb: HTTPCommand implementation was changed.
-
-Wed Jan 5 02:14:46 2000 EGUCHI Osamu <eguchi@shizuokanet.ne.jp>
-
- * parse.y: Fix SEGV on empty parens with UMINUS or UPLUS.
-
-Tue Jan 4 22:25:54 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (stmt): `() while cond' dumped core.
-
-Tue Jan 4 06:04:14 2000 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * configure.in: modify for cross-compiling.
- use target_* instead of host_*.
- use AC_CANONICAL_TARGET.
-
- * Makefile.in: ditto.
-
- * cygwin/GNUmakefile.in: ditto.
-
-Sat Jan 1 13:26:14 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_yield_0): force_recycle ruby_dyna_vars to gain
- performance.
-
- * array.c (rb_ary_delete_at_m): takes same argument pattern with
- rb_ary_aref.
-
-Sat Jan 1 10:12:26 2000 Nobuyoshi Nakada <nobu.nokada@softhome.net>
-
- * ruby.h,util.c (rb_special_const_p): peep hole optimization.
-
- * ruby.h,util.c (rb_test_false_or_nil): removed.
-
- * ruby.h (RTEST, SPECIAL_CONST_P): peep hole optimization.
-
- * ruby.h (FL_ABLE, FL_SET, FL_UNSET, FL_REVERSE): made expressions
- not statements.
-
- * ruby.h (OBJ_INFECT): newly added macro which copies taint from
- `s' to `x'.
-
-Sat Jan 1 02:04:18 2000 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_thread_safe_level): new method.
-
- * eval.c (rb_yield_0): recycle dyna_var_map to reduce object
- allocation.
-
-Fri Dec 31 00:52:48 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c: thread independent trace_func not needed.
-
-Thu Dec 30 14:47:31 1999 akira yamada <akira@ruby-lang.org>
-
- * configure.in: specifies -soname in LIBRUBY_DLDFLAGS on linux
- platforms.
-
-Thu Dec 30 10:51:27 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * array.c,io.c,hash,c,re.c,string.c: `_m' suffix instead of
- `_method' for wrapper functions to implement method,
- e.g. `rb_str_join_m()'.
-
-Thu Dec 30 02:08:02 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * bignum.c (rb_cstr2inum): non-numeric format check added.
- currently it works only with base == 0 (i.e. Integer()).
-
- * bignum.c (rb_str2inum): now takes VALUE to 1st argument. null
- byte check added.
-
- * array.c (rb_ary_replace): unless replacement is an array,
- replacement shall be converted to array by `[replacement]', not
- by `replacement.to_a'.
-
- * array.c (rb_ary_plus): right operand must be an array.
-
- * array.c (rb_ary_concat): argument must be an array.
-
-Mon Dec 27 12:35:47 1999 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * ext/socket/socket.c (sock_finalize): mswin32: fix socket handle leak.
-
- * win32/win32.c (myfdclose): ditto.
-
-Sun Dec 26 23:15:13 1999 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * win32/win32.c (mypopen): raise catchable error instead of rb_fatal.
- * win32/win32.c (mypclose): fix process handle leak.
-
-Sun Dec 26 16:17:11 1999 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * ext/Win32API/Win32API.c (Win32API_initialize): use UINT2NUM
- instead of INT2NUM to set __dll__ and __proc__.
-
-Sat Dec 25 00:08:59 1999 KANEKO Naoshi <wbs01621@mail.wbs.ne.jp>
-
- * ext/Win32API/Win32API.c (Win32API_Call): remove 'dword ptr'
- from _asm.
-
-Fri Dec 24 10:26:47 1999 Koji Oda <oda@bsd1.qnes.nec.co.jp>
-
- * win32/win32.h: use "C++" linkage.
-
-Fri Dec 24 02:00:57 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (THREAD_ALLOC): should initialize th->trace.
-
-Fri Dec 24 00:43:39 1999 KANEKO Naoshi <wbs01621@mail.wbs.ne.jp>
-
- * io.c (pipe_open): check for `fptr->f == NULL'.
- * win32/win32.c (mypopen): STDERR does not work during ` function.
-
-Wed Dec 22 22:50:40 1999 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/session.rb, smtp.rb, pop.rb, http.rb: 1.1.2.
-
- * lib/net/http.rb: HTTP support is enhanced a little
-
- * lib/net/http.rb: support proxy
-
-Tue Dec 21 17:21:28 1999 Koji Oda <oda@bsd1.qnes.nec.co.jp>
-
- * ext/socket/socket.c (sock_finalize): mswin32: fix FILE* leak.
-
-Tue Dec 21 05:33:56 1999 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/session.rb, smtp.rb, pop.rb, http.rb: 1.1.1.
-
- * lib/net/http.rb: support HTTP chunk
-
-Mon Dec 20 19:08:12 1999 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * file.c (rb_file_s_expand_path): handle dir separator correctly.
-
-Sun Dec 19 22:56:31 1999 KANEKO Naoshi <wbs01621@mail.wbs.ne.jp>
-
- * lib/find.rb: support dosish root directory.
- * win32/Makefile: ditto.
- * win32/config.status: ditto.
- * win32/win32.c (opendir): ditto.
- * win32/win32.c (opendir): use CharPrev() to get last character
- of the directory name.
-
-Sat Dec 18 03:00:01 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * file.c (path_check_1): check should be done by absolute path.
-
- * marshal.c (r_ivar): should restore generic_ivar too.
-
- * marshal.c (w_ivar): should dump generic_ivar too.
-
-Fri Dec 17 22:46:46 1999 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/session.rb, smtp.rb, pop.rb, http.rb: 1.1.0.
-
- * lib/net/http.rb: test release
-
- * lib/net/session.rb: support class swapping
-
- * lib/net/session.rb: Socket#flush_rbuf
-
- * lib/net/session.rb: doquote -> Net.quote
-
-Fri Dec 17 19:27:43 1999 IWAMURO Motonori <iwa@mmp.fujitsu.co.jp>
-
- * eval.c (rb_load): should initialize ruby_frame->last_class.
-
-Wed Dec 15 01:35:29 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ruby.c (proc_options): option to change directory changed to
- `-C' like tar.
-
- * ruby.c (proc_options): argv boundary check for `-X'.
-
-Mon Dec 13 15:15:31 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_adjust_startpos): separate startpos adjustment
- because of major performance drawback.
-
- * class.c (rb_singleton_class): tainted status of the singleton
- class must be synchronized with the object.
-
- * eval.c (rb_thread_schedule): implement thread priority.
-
-Sat Dec 11 03:34:38 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * gc.c (mark_hashentry): key should be VALUE, not ID.
-
- * io.c (argf_eof): should check next_p too.
-
-Thu Dec 9 18:09:13 1999 EGUCHI Osamu <eguchi@shizuokanet.ne.jp>
-
- * error.c (exc_set_backtrace): forgot to declare a VALUE argument.
-
-Thu Dec 9 14:19:31 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * object.c (rb_obj_taint): explicit tainting must be prohibited at
- level 4 to prevent polluting trusted object by untrusted code.
-
- * file.c: file operations (stat, lstat, chmod, chown, umask,
- truncate, flock) are prohibited in level 2 (was level 4).
-
-Wed Dec 8 11:48:23 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_f_require): prohibiting require() in the secure mode
- cause serious autoloading error.
-
- * variable.c (rb_obj_instance_variables): don't need to prohibit
- to get list of instance variable names of untainted objects.
-
- * variable.c (rb_ivar_get): don't need to prohibit to get instance
- variables of untainted objects.
-
- * variable.c (rb_mod_remove_const): should prohibit constant
- removals too.
-
-Wed Dec 8 09:23:01 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_eval): should try autoloading before defining
- class/module at the toplevel.
-
-Tue Dec 7 22:15:30 1999 EGUCHI Osamu <eguchi@shizuokanet.ne.jp>
-
- * configure.in: Modified rb_cv_rshift_sign detect routine and
- more simple/fast RSHIFT() for hpux-10.x.
-
-Tue Dec 7 11:16:30 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (Init_eval): calculate stack limit from rlimit where
- getrlimit(2) is available.
-
-Tue Dec 7 09:57:33 1999 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * file.c (rb_file_ftype): should have removed mode_t.
-
-Mon Dec 6 15:55:30 1999 EGUCHI Osamu <eguchi@shizuokanet.ne.jp>
-
- * numeric.c (fix_rshift): Fix -1 >> 32 returned 0 (should be -1).
-
- * numeric.c (fix_rshift): Fix 1 >> -1 returned 0 (should be 2).
-
-Mon Dec 6 11:47:23 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * sprintf.c (rb_f_sprintf): formatted string must be tainted if
- any of parameters is a tainted string.
-
- * file.c (rb_file_s_expand_path): expanded file path need not to
- be tainted always.
-
-Sun Dec 5 20:25:29 1999 Katsuhiro Ueno <unnie@blue.sky.or.jp>
-
- * eval.c (Init_Proc): simple typo.
-
- * gc.c (add_heap): sizeof(RVALUE*), not sizeof(RVALUE).
-
-Sat Dec 4 01:40:22 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_search): adjust startpos for multibyte match unless
- the first pattern is forced byte match.
-
- * bignum.c (rb_big_rand): should not use rand/random where drand48
- may be available. RANDOM_NUMBER should be provided from outside.
-
-Fri Dec 3 09:54:59 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ruby.c (moreswitches): there may be trailing garbage at #!
- line.
-
- * eval.c (rb_f_require): should check require 'feature.o' too.
-
-Thu Dec 2 11:58:15 1999 Koji Arai <JCA02266@nifty.ne.jp>
-
- * eval.c (rb_thread_loading): should maintain loading_tbl.
-
-Thu Dec 2 10:21:43 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_thread_loading_done): wrong parameter to st_delete().
-
-Wed Dec 1 11:24:06 1999 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * ruby.c (process_sflag): process -s properly (should not force `--').
-
-Wed Dec 1 09:47:33 1999 Kazunori NISHI <kazunori@swlab.csce.kyushu-u.ac.jp>
-
- * string.c (rb_str_split_method): should increment end too.
-
-Tue Nov 30 18:00:45 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * marshal.c: MARSHAL_MINOR incremented; format version is 4.2.
-
- * marshal.c (w_object): distinguish class and module.
-
- * marshal.c (w_object): save hash's default value.
-
- * marshal.c (r_object): restore hash's default value.
-
-Tue Nov 30 01:46:18 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * re.c (rb_reg_source): generated source string must be tainted if
- regex is tainted.
-
- * file.c (rb_file_s_basename): basename should not be tainted
- unless the original path is tainted.
-
- * file.c (rb_file_s_dirname): ditto.
-
-Mon Nov 29 20:42:13 1999 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * file.c (stat_new): Struct::Stat -> File::Stat; Stat is no longer
- a Struct.
-
-Mon Nov 29 15:28:52 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * variable.c (rb_path2class): evaluated value from path should be
- module or class.
-
-Fri Nov 26 18:12:49 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_exec_end_proc): should remove only end_procs defined
- within load wrapper.
-
- * eval.c (rb_load): save and restore ruby_wrapper around loading.
-
- * eval.c (rb_mark_end_proc): mark end procs registered by END{} or
- at_exit{}.
-
- * eval.c (rb_set_end_proc): should not call rb_global_variable()
- on heap address; it crashed mod_ruby.
-
-Mon Nov 22 14:07:24 1999 Koji Arai <JCA02266@nifty.ne.jp>
-
- * ruby.c (proc_options): variable e_script should be visited by
- garbage collector.
-
-Sat Nov 20 10:10:41 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * hash.c (inspect_i): value may be nil, check revised.
-
-Fri Nov 19 18:06:21 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * dir.c (glob): recursive wildcard match by `**' ala zsh.
-
-Fri Nov 19 11:44:26 1999 EGUCHI Osamu <eguchi@shizuokanet.ne.jp>
-
- * variable.c: was returning void value.
-
-Fri Nov 19 03:57:22 1999 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * file.c: add methods Stat struct class to reduce stat(2).
-
-Thu Nov 18 16:18:27 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * lib/pstore.rb: mutual lock by flock(2).
-
-Thu Nov 18 11:44:13 1999 Masahiro Tomita <tommy@tmtm.org>
-
- * io.c (read_all): should check bytes too.
-
-Wed Nov 17 02:40:40 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (Init_IO): $defout (alias of $>) added.
-
-Tue Nov 16 09:47:14 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * lib/pstore.rb: add mutual lock using symlink.
-
-Mon Nov 15 16:50:34 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * enum.c (enum_grep): non matching grep returns an empty array, no
- longer returns nil.
-
- * enum.c (enum_grep): grep with block returns collection of
- evaluated values of block over matched elements.
-
-Mon Nov 15 04:50:33 1999 Koji Arai <JCA02266@nifty.ne.jp>
-
- * re.c (rb_reg_source): should not call rb_reg_expr_str()
- everytime.
-
-Sat Nov 13 07:34:18 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * variable.c (rb_mod_constants): traverse superclasses to collect
- constants.
-
- * eval.c (assign): modified for shared variables.
-
- * eval.c (rb_eval): search nested scope, then superclasses to
- assign shared variables within methods.
-
- * eval.c (rb_eval): remove warnings from constants modification,
- because they are no longer constants.
-
- * parse.y (node_assign): modified for shared variables.
-
- * parse.y (assignable): allow constant assignment in methods;
- constants should be called `shared variable'.
-
-Fri Nov 12 23:52:19 1999 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * process.c (rb_f_system): argument check for NT, __EMX__, DJGPP.
-
-Wed Nov 10 21:54:11 1999 EGUCHI Osamu <eguchi@shizuokanet.ne.jp>
-
- * hash.c (rb_any_cmp): Fixed return without value.
-
-Wed Nov 10 17:57:06 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * sprintf.c: incorporate <yasuf@big.or.jp>'s sprintf patch at
- [ruby-dev:7754].
-
-Wed Nov 10 08:28:53 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_call0): supply class parameter for each invocation.
-
-Tue Nov 9 13:21:04 1999 EGUCHI Osamu <eguchi@shizuokanet.ne.jp>
-
- * configure.in: AC_MINIX move to before AC_EXEEXT and AC_OBJEXT.
-
-Mon Nov 8 19:52:29 1999 EGUCHI Osamu <eguchi@shizuokanet.ne.jp>
-
- * configure.in: Renamed AC_CHAR_UNSIGNED to AC_C_CHAR_UNSIGNED.
-
- * configure.in: Added default to AC_CHECK_SIZEOF().
-
-Mon Nov 8 14:28:18 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (stmt): rescue modifier added to the syntax.
-
- * keywords: kRESCUE_MOD added.
-
- * eval.c (rb_f_eval): fake outer scope when eval() called without
- bindings.
-
- * eval.c (rb_f_binding): should copy last_class in the outer frame too.
-
-Sun Nov 7 18:31:04 1999 Yasuhiro Fukuma <yasuf@big.or.jp>
-
- * eval.c (is_defined): last_class may be 0.
-
-Sat Nov 6 19:26:55 1999 EGUCHI Osamu <eguchi@shizuokanet.ne.jp>
-
- * Makefile.in: Added depend entry make parse.@OBJEXT@ from parse.c
- for UCB make
-
-Thu Nov 4 17:41:18 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_compile_pattern): \< (wordbeg), \> (wordend) disabled.
-
-Wed Nov 3 08:52:57 1999 Masaki Fukushima <fukusima@goto.info.waseda.ac.jp>
-
- * io.c (Init_IO): forgot to use INT2FIX() around SEEK_SET, etc.
-
-Wed Nov 3 00:25:20 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (rb_str_split_method): use mbclen2() to handle kcode
- option of regexp objects.
-
-Mon Nov 1 14:22:15 1999 EGUCHI Osamu <eguchi@shizuokanet.ne.jp>
-
- * eval.c (rb_eval): reduce recursive calls to rb_eval()
- case of ||= and &&= .
-
-Sun Oct 31 13:12:42 1999 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * regex.c (re_compile_pattern): wrong [\W] match.
-
-Fri Oct 29 16:57:30 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/nkf/lib/kconv.rb: new String methods (kconv, tojis, toeuc,
- tosjis).
-
- * time.c (time_s_at): now accepts optional second argument to
- specify micro second.
-
-Thu Oct 28 13:35:40 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (rb_str_split_method): should be mbchar aware with
- single char separators.
-
-Wed Oct 27 12:57:21 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * random.c (rb_f_srand): random seed should be unsigned.
-
-Tue Oct 26 23:58:15 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * array.c (rb_ary_collect): collect for better performance.
-
-Tue Oct 26 19:20:54 1999 Koji Arai <JCA02266@nifty.ne.jp>
-
- * marshal.c (r_object): should register class/module objects.
-
-Sat Oct 23 15:59:39 1999 Takaaki Tateishi <ttate@jaist.ac.jp>
-
- * process.c (rb_f_system): should require at least one argument.
-
-Sat Oct 23 12:42:44 1999 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * enum.c (enum_collect): collect without block will collect
- elements in enumerable.
-
-Thu Oct 21 16:14:19 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ruby.c (moreswitches): function to process string option;
- the name is stolen from perl (not implementation).
-
- * ruby.c (proc_options): use RUBYOPT environment variable to
- retrieve the default options.
-
- * dir.c (fnmatch): use eban's fnmatch; do not depend on system's
- fnmatch (which may have portability problem) anymore.
-
-Wed Oct 20 15:14:24 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * marshal.c (marshal_load): should protect the generated object
- table (arg->data) from GC.
-
-Mon Oct 18 16:15:52 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/nkf/nkf.c (rb_nkf_kconv): output should be NUL terminated.
-
-Mon Oct 18 09:03:01 1999 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/session.rb, smtp.rb, pop.rb: 1.0.3
-
- * lib/net/pop.rb: new methods POP3Command#uidl, POPMail#uidl.
-
-Sun Oct 17 03:35:33 1999 Masaki Fukushima <fukusima@goto.info.waseda.ac.jp>
-
- * array.c (rb_ary_pop): forgot some freeze checks.
-
-Sat Oct 16 12:57:53 1999 EGUCHI Osamu <eguchi@shizuokanet.ne.jp>
-
- * array.c (rb_ary_sort): always returns the copied array.
-
-Fri Oct 15 22:50:41 1999 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * error.c (sys_nerr): on CYGWIN, it is _sys_nerr.
-
-Fri Oct 15 01:32:31 1999 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * io.c (rb_io_ctl) :need to use NUM2ULONG, not NUM2INT.
-
- * ext/Win32API/Win32API.c (Win32API_Call): need to use NUM2ULONG,
- not NUM2INT.
-
-Fri Oct 15 00:22:30 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * re.c (Init_Regexp): super class of the MatchingData, which was
- Data, to be Object.
-
- * eval.c (ruby_run): evaluate required libraries before load &
- compiling the script.
-
- * parse.y (lex_getline): retrieve a line from the stream, saving
- lines in the table in debug mode.
-
- * eval.c (call_trace_func): treat the case ruby_sourcefile is null.
-
-Thu Oct 14 02:00:10 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (string): compile time string concatenation.
-
-Wed Oct 13 07:28:09 1999 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/session.rb, smtp.rb, pop.rb: 1.0.2
-
- * lib/net/session.rb: new method Session#set_pipe.
-
- * lib/net/session.rb, smtp.rb, pop.rb: add RD documentation.
-
-Wed Oct 13 02:17:05 1999 EGUCHI Osamu <eguchi@shizuokanet.ne.jp>
-
- * array.c (rb_ary_plus): remove recursion.
-
- * array.c (rb_ary_sort_bang): detect modify attempt.
-
-Wed Oct 13 02:17:05 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (block_pass): should copy block to prevent modifications.
- tag in the structure should be updated from latest prot_tag.
-
- * eval.c (proc_s_new): tag in struct BLOCK should not point into
- unused stack.
-
- * dir.c (dir_s_glob): iterate over generated matching filenames if
- the block is given to the method.
-
- * array.c (rb_ary_at): new methods; at, first, last.
-
- * hash.c (rb_hash_fetch): raises exception unless the default
- value is supplied.
-
- * hash.c (rb_hash_s_create): need not remove nil from value.
-
- * hash.c (rb_hash_aset): setting value to nil does not remove key
- anymore.
-
-Tue Oct 12 22:29:04 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (io_read): length may be 0 or negative.
-
-Tue Oct 12 13:26:27 1999 Jun-ichiro itojun Hagino <itojun@itojun.org>
-
- * signal.c (posix_signal): RETSIGTYPE may be void.
-
-Tue Oct 12 03:28:03 1999 EGUCHI Osamu <eguchi@shizuokanet.ne.jp>
-
- * array.c (rb_ary_delete_at): allows negative position.
-
-Mon Oct 11 17:42:25 1999 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * parse.y (rb_intern): should generate distinct ID_ATTRSET symbols
- for the name with multiple `='s at the end.
-
- * Makefile.in (CPPFLAGS): separate cpp flags from CFLAGS.
-
-Mon Oct 11 07:27:05 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_eval): should not execute the `else' clause on the
- case the exceptions are handled by the `rescue' clause.
-
- * signal.c (Init_signal): ignore SIGPIPE by default.
-
-Wed Oct 6 17:13:19 1999 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * ruby.c (addpath): rubylib_mangled_path() modified.
-
-Mon Oct 4 12:42:32 1999 Kazuhiko Izawa <izawa@erec.che.tohoku.ac.jp>
-
- * pack.c (pack_unpack): % in printf format should be %%.
-
-Mon Oct 4 10:01:40 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * variable.c (rb_obj_instance_variables): should always return
- array for all object can have instance variables now.
-
-Mon Oct 4 00:08:34 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * pack.c (OFF16): need to adjust pointer address to pack/unpack on
- 64bit machines.
-
-Sun Oct 03 03:05:59 1999 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * time.c (time_arg): mktime y2k problem.
-
-Sun Sep 26 16:54:45 1999 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * parse.y (here_document): `\r' handling for here documents.
-
-Wed Sep 22 09:20:11 1999 Masahiro Tomita <tommy@tmtm.org>
-
- * ext/socket/socket.c: SOCKS5 support.
-
-Wed Sep 22 07:33:23 1999 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/session.rb, smtp.rb, pop.rb: 1.0.1
-
- * lib/net/pop.rb: APOP did not work.
-
- * lib/net/pop.rb: modify the way to make APOP challenge.
-
-Wed Sep 22 00:35:30 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (rb_str_include): should return boolean value.
-
- * regex.c (re_compile_fastmap): wrong comparison with mbc.
-
- * eval.c (specific_eval): default sourcefile name should be
- "(eval)" for module_eval etc.
-
-Wed Sep 22 00:06:07 1999 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * win32/Makefile: update rules.
-
- * io.c (io_fread): should not assign in char, it maybe -1.
-
-Tue Sep 21 23:57:54 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (call_trace_func): should not propagate retval in
- trace_func.
-
-Mon Sep 20 21:35:39 1999 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * win32/win32.c (myselect): assume non socket files are always
- readable/writable.
-
-Mon Sep 20 01:08:02 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (io_fread): should not block other threads.
-
- * io.c (rb_io_synchronized): renamed from rb_io_unbuffered(); do
- not call setbuf(NULL) anymore.
-
-Sat Sep 18 13:45:43 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * stable version 1.4.2 released.
-
-Fri Sep 17 23:24:17 1999 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * eval.c (rb_f_missing): dumped core if no argument given.
-
-Fri Sep 17 23:21:06 1999 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * win32/win32.c (myselect): translate WSAEINTR, WSAENOTSOCK into
- UNIX errno constants.
-
-Fri Sep 17 00:52:27 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (arg): assignable() may return 0.
-
-Thu Sep 16 20:46:23 1999 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * eval.c (rb_eval): was doubly evaluating the return expression.
-
-Thu Sep 16 18:40:08 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * stable version 1.4.1 released.
-
-Thu Sep 16 11:33:22 1999 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * string.c (rb_str_match): should return nil.
-
-Wed Sep 15 22:46:37 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * re.c (rb_reg_s_quote): should quote `-' too.
-
-Tue Sep 14 15:23:22 1999 Nobuyoshi Nakada <nobu.nakada@nifty.ne.jp>
-
- * parse.y (yylex): no need to ignore `\r' here.
-
- * parse.y (nextc): strip `\r' from text.
-
- * parse.y (nextc): support `__END__\r\n' type terminator.
-
-Mon Sep 13 10:49:19 1999 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * eval.c (rb_eval): needless RTEST(ruby_verbose) removed.
-
-Mon Sep 13 09:10:11 1999 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/net/session.rb, smtp.rb, pop.rb: 1.0.0
-
-Wed Sep 8 11:37:38 1999 Tadayoshi Funaba <tadf@kt.rim.or.jp>
-
- * time.c (make_time_t): bit more strict comparison.
-
-Tue Sep 7 00:50:56 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * range.c (range_each): use rb_str_upto() for strings.
-
- * string.c (rb_str_upto): set upper limit by comparing curr <= end.
-
- * range.c (range_each): should check equality to handle magic
- increment.
-
-Mon Sep 6 22:43:33 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_eval): break/next/redo available within -n/-p loop.
-
-Fri Sep 3 11:14:31 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * compar.c (cmp_equal): should not raise exception; protect by
- rb_rescue().
-
-Thu Sep 2 05:23:05 1999 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * file.c (rb_file_s_expand_path): use dirsep, instead of character
- literal '/'.
-
- * file.c (rb_file_s_expand_path): reduce multiple dirsep at the top.
-
-Wed Sep 1 00:28:27 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_call): call rb_undefined() if a method appears not to
- be exist explicitly from cache.
-
- * eval.c (rb_method_boundp): check method cache before calling
- rb_get_method_body().
-
- * eval.c (rb_get_method_body): store method non-existence
- information in the cache.
-
- * random.c (rb_f_srand): use getpid(2) to generate seed.
-
- * regex.c (re_match): do not apply partial mbc match for
- charset_not.
-
- * regex.c (re_compile_pattern): put extended literal prefix (0xff)
- only before numeric literals, not before all >0x80 char.
-
- * regex.c (re_compile_pattern): put numeric literal in extended
- charset region, not normal charset bits.
-
- * regex.c (re_compile_fastmap): calculate fastmap for charset and
- charset_not to treat numeric literal (e.g. \246) specially.
-
-Fri Aug 28 17:32:55 1999 Yasuhiro Fukuma <yasuf@big.or.jp>
-
- * eval.c (rb_eval): should set return value (nil) explicitly if a
- value is omitted for return statement.
-
-Sun Aug 26 20:26:40 2001 Koji Arai <JCA02266@nifty.ne.jp>
-
- * ext/readline/readline.c: restore terminal mode
- even if readline() interrupted.
-
- * ext/readline/readline.c: returned string need to
- be tainted.
-
- * ext/readline/readline.c: fixed memory leak.
-
- * ext/readline/readline.c: allow negative index.
-
- * ext/readline/readline.c: added Readline::HISTORY.size
- same as Readline::HISTORY.length
-
- * ext/readline/readline.c: allow conditional parsing
- of the ~/.inputrc file by `$if Ruby'.
-
- * ext/readline/extconf.rb: check whether the
- libreadline has the variable `rl_completion_append_character'
- (this feature was implemented from GNU readline 2.1).
-
-Thu Aug 26 15:06:11 1999 Masaki Fukushima <fukusima@goto.info.waseda.ac.jp>
-
- * gc.c (rb_gc): local variables may be placed beyond stack_end, so
- use an address from alloca(1) on non C_ALLOCA platforms.
-
-Thu Aug 26 01:24:17 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * sprintf.c (rb_f_sprintf): "%%" is legal, but "%3.14%" is not.
-
-Mon Aug 23 00:00:54 1999 Tsukada Takuya <tsukada@fminn.nagano.nagano.jp>
-
- * regex.c (re_compile_fastmap): wrong macro caused memory leak.
-
-Sat Aug 21 11:30:51 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (ADJ): should not adjust addresses to data on heap.
-
-Fri Aug 20 20:50:58 1999 Kenji Nagasawa <kenn@hma.att.ne.jp>
-
- * defines.h (PATH_SEP): path separator is ";" for OS/2.
-
-Thu Aug 19 10:50:43 1999 WATANABE Tetsuya <tetsu@jpn.hp.com>
-
- * gc.c (rb_gc): add volatile to avoid GCC optimize bug(?).
-
-Wed Aug 18 23:48:10 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * due to disk trouble, some change records were lost. several
- modification made to eval.c, gc.c, io.c, pack.c,
- ext/extmk.rb.in, and lib/mkmf.rb.
-
-Fri Aug 13 15:41:39 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * stable version 1.4.0 released.
-
-Fri Aug 13 03:16:07 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (argf_forward): since $stdout may be non-IO, ARGF.file is
- not guaranteed to be IO. check and forwarding added to every ARGF
- method.
-
- * io.c (set_outfile): $stdout/$stderr may not be IO now.
-
- * io.c (set_stdin): $stdin may not be IO now.
-
- * range.c (rb_range_beg_len): round `end' to length as documented.
-
- * io.c (Init_IO): preserve original stdin/stdout/stderr.
-
-Thu Aug 12 13:44:33 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (Init_load): require receives 1 argument.
-
- * eval.c (frame_dup): should clear tmp to avoid dangling
- references.
-
-Wed Aug 11 13:33:13 1999 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * eval.c (rb_eval): no automatic aggregate initialization.
-
- * eval.c (module_setup): ditto.
-
-Wed Aug 11 18:18:41 1999 WATANABE Tetsuya <tetsu@jpn.hp.com>
-
- * eval.c (yield_under_i): automatic aggregate initialization is an
- ANSI feature.
-
-Wed Aug 11 10:10:02 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (yylex): parse `[].length==0' as `([].length)==0', not
- `([].length=)=0'
-
- * parse.y (yylex): parse `[].length!=0' as `([].length)!=0', not
- `([].length!)=0'
-
- * parse.y (peek): peek-in lexical buffer.
-
-Wed Aug 11 00:34:05 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_match): bug on backward jump adjustment concerning
- stop_paren.
-
-Tue Aug 10 14:54:25 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/nkf/nkf.c (rb_nkf_guess): binary detection was wrong.
-
-Tue Aug 10 00:07:36 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (rb_io_clone): should use CLONESETUP().
-
-Mon Aug 9 23:57:07 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ruby.h (CLONESETUP): should have copied generic instance
- variables too.
-
-Mon Aug 9 10:46:54 1999 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * ext/socket/extconf.rb: add check for <arpa/nameser.h> and
- <resolv.h>.
-
-Sat Aug 7 13:19:06 1999 EGUCHI Osamu <eguchi@shizuokanet.ne.jp>
-
- * numeric.c (flo_cmp): comparing NaN should not return value.
- raises FloatDomainError.
-
-Sat Aug 7 03:09:08 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (blk_free): free copied frames too.
-
- * eval.c (frame_dup): should copy previous frames from stack to
- heap to preserve frame information.
-
-Fri Aug 6 15:01:07 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.3.7 - version 1.4 beta
-
- * ext/socket/socket.c (s_recv): UDPsocket#recvfrom now returns
- IPsocket#addr information.
-
- * array.c (rb_ary_subary): ary[-3,3] should not return nil.
-
-Thu Aug 5 10:58:01 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (thread_mark): protect old ruby_frame from GC during it
- replaced by eval().
-
- * eval.c (eval): do not modify frame.prev; binding should preserve
- information about calling() too.
-
- * eval.c (rb_yield_0): no arity check for mere yield; but only for
- Proc#call.
-
-Tue Aug 3 22:07:13 1999 Kazuhiro HIWADA <hiwada@kuee.kyoto-u.ac.jp>
-
- * object.c (rb_mod_clone): should check if iv_tbl, m_tbl are
- initialized.
-
-Tue Aug 3 19:03:02 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * hash.c (rb_any_cmp): use rb_with_disable_interrupt() to ensure
- clearance of rb_prohibit_interrupt even on failure.
-
- * eval.c (rb_with_disable_interrupt): new function added.
-
-Sat Jul 31 23:23:44 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_thread_create_0): set THREAD_RAISED flag on thread
- termination by exception.
-
- * eval.c (rb_thread_join): `$!' may not be nil for the threads
- created in rescue clause.
-
- * eval.c (rb_thread_status): ditto.
-
- * eval.c (rb_thread_join): should re-raise exception for already
- dead threads too.
-
-Fri Jul 30 17:56:54 1999 GOTO Kentaro <gotoken@math.sci.hokudai.ac.jp>
-
- * object.c (rb_mod_ge): wrong comparison.
-
-Fri Jul 30 12:15:44 1999 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * ext/tcltklib/extconf.rb: win32 support.
-
- * lib/mkmf.rb: use append_library().
-
- * ext/extmk.rb.in: ditto.
-
-Fri Jul 30 02:11:48 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * array.c (rb_ary_delete): should return nil for deleting non
- existing item.
-
- * io.c (rb_io_close): call rb_sys_wait() on explicit close.
-
- * io.c (rb_io_fptr_close): do not call rb_sys_wait() on finalize.
-
- * eval.c (yield_under_i): cbase context should be maintained for
- Module#module_eval(). suggested by <inaba@st.rim.or.jp>.
-
-Wed Jul 28 01:18:28 1999 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * Makefile.in: add -I$(hdrdir)/lib to install using ftools.
-
- * util.c: use HAVE_FCNTL_H, not HAVE_FCNTL
-
-Wed Jul 28 18:24:45 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.3.6 - version 1.4 alpha
-
-Tue Jul 27 09:38:08 1999 EGUCHI Osamu <eguchi@shizuokanet.ne.jp>
-
- * eval.c (rb_eval): reduce recursive rb_eval() calls by
- NODE_BLOCKs.
-
-Tue Jul 27 01:20:40 1999 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * file.c (rb_file_s_expand_path): drive letter patch.
-
-Mon Jul 26 02:36:31 1999 Shugo Maeda <shugo@netlab.co.jp>
-
- * eval.c (rb_load): should clear ruby_nerr.
-
- * eval.c (rb_thread_join): oldbt should not be empty to unshift.
-
-Sun Jul 25 12:09:16 1999 Koji Arai <JCA02266@nifty.ne.jp>
-
- * dir.c (push_braces): should treat nested braces.
-
-Fri Jul 23 02:49:49 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * hash.c (rb_hash_clear): dummy argument added; suggested by
- <eguchi@shizuokanet.ne.jp>. thanks.
-
-Thu Jul 22 19:37:22 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_thread_join): get_backtrace() may return Qnil.
- typecheck added.
-
-Tue Jul 20 14:36:43 1999 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * range.c (range_each): do not treat String specially (for future
- override).
-
-Tue Jul 20 02:28:34 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (rb_gets): $_ should be nil, when get returns nil.
-
- * io.c (rb_f_gets): ditto.
-
-Mon Jul 19 17:13:09 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_compile_fastmap): should continue fastmap compile
- for anychar_repeat, for it's repeat anyway.
-
-Mon Jul 26 13:33:45 1999 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * lib/jcode.rb: replaced by faster code.
-
-Mon Jul 19 01:57:28 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * lib/mkmf.rb: no longer use install program.
-
- * ext/extmk.rb.in: use miniruby to install programs.
-
-Sat Jul 17 00:06:21 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/socket/socket.c (ipaddr): don't do reverse lookup if
- attribute do_not_reverse_lookup is set for socket classes.
- Experimental. Note this is a global attribute.
-
-Fri Jul 16 22:18:29 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (rb_io_eof): use feof() to check EOF already met.
-
- * io.c (read_all): should return nil at EOF.
-
-Fri Jul 16 13:39:42 1999 Wakou Aoyama <wakou@fsinet.or.jp>
-
- * lib/telnet.rb: version 0.231.
-
-Fri Jul 16 10:58:22 1999 WATANABE Tetsuya <tetsu@jpn.hp.com>
-
- * regex.c (re_match): debug print removed.
-
-Fri Jul 16 09:58:15 1999 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * many files: clean up unused variables found by gcc -Wall.
-
- * lib/mkmf.rb: better cygwin support etc.
-
- * ext/extmk.rb.in: ditto.
-
- * instruby.rb: ditto.
-
-Fri Jul 16 01:37:50 1999 Koji Arai <JCA02266@nifty.ne.jp>
-
- * string.c (rb_str_squeeze_bang): the type of local variable `c'
- should be int, not char.
-
- * string.c (rb_str_reverse): should always return copy.
-
-Thu Jul 15 23:25:57 1999 NAKAMURA Hiroshi <nakahiro@sarion.co.jp>
-
- * lib/debug.rb: better display & frame treatment.
-
-Thu Jul 15 21:16:41 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * array.c (rb_ary_each): returns self for normal termination;
- returns nil for break.
-
- * string.c: non bang methods (e.g. String#sub) should always
- return copy of the receiver.
-
-Thu Jul 15 21:09:15 1999 Masaki Fukushima <fukusima@goto.info.waseda.ac.jp>
-
- * eval.c (find_file): do not add empty string to the path.
-
- * configure.in (with-search-path): should not add empty string if
- the option is not supplied.
-
-Thu Jul 15 17:49:08 1999 Ryo HAYASAKA <hayasaka@univ21.u-aizu.ac.jp>
-
- * ext/tcltklib/tcltklib.c: move `#include "ruby.h"' forward.
-
-Thu Jul 15 16:54:16 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.3.5 - version 1.4 alpha
-
-Wed Jul 14 23:45:33 1999 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * eval.c (ruby_init): initialize for the first time only.
-
-Tue Jul 13 00:15:19 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * hash.c (rb_hash_index): re-defined; method to retrieve a key
- from the value.
-
- * hash.c (Init_Hash): member? should be re-defined for Hash.
-
-Tue Jul 12 13:54:51 1999 EGUCHI Osamu <eguchi@shizuokanet.ne.jp>
-
- * io.c (rb_file_sysopen): wrong number of argument.
-
-Mon Jul 12 11:52:35 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_f_missing): class name included in message.
-
- * eval.c (print_undef): better error message.
-
-Sun Jul 11 05:36:17 1999 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>
-
- * lib/debug.rb: patch to show proper position.
-
-Fri Jul 9 23:56:14 1999 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * dln.c (dln_find_1): path conv. moved to conv_to_posix_path.
-
- * dln.c (conv_to_posix_path): path conv. should be done.
-
-Fri Jul 9 10:26:47 1999 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * random.c (RANDOM_NUMBER): should place parentheses.
-
-Fri Jul 8 11:00:51 1999 Shugo Maeda <shugo@netlab.co.jp>
-
- * numeric.c (fix_div): division may be out of fixnum range.
-
- * bignum.c (bigdivmod): proper sign calculation to result.
-
-Wed Jul 7 18:27:41 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * st.c (st_delete_safe): was modifying wrong slot.
-
-Mon Jul 5 13:17:46 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * gc.c (rb_gc_call_finalizer_at_exit): close all files at exit.
-
-Fri Jul 2 18:00:21 1999 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * lib/Mail/README: Mail-0.3.0 added to the distribution.
-
-Fri Jul 2 01:45:32 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_compile_fastmap): avoid allocation of register
- variables for each invocation of re_match(). Suggested by
- Zasukhin Ruslan <ruslan@paradigmasoft.com>. Thanks.
-
-Tue Jun 29 20:39:24 1999 Koji Arai <JCA02266@nifty.ne.jp>
-
- * ext/tk/lib/tk.rb (TkVariable): bug fix; should value type check
- be added?
-
- * string.c (rb_str_each_line): a bug in paragraph mode.
-
- * ruby.c (load_file): shifted too much to skip #!.
-
-Tue Jun 29 06:50:21 1999 Wakou Aoyama <wakou@fsinet.or.jp>
-
- * lib/CGI.rb: 0.30 - cleanup release, incompatible.
-
- * lib/telnet.rb: 0.22 - timeout added.
-
-Tue Jun 29 10:49:25 1999 SHIROYAMA Takayuki <psi@fortune.nest.or.jp>
-
- * configure.in: better Rhapsody support.
-
- * lib/mkmf.rb: Rhapsody/NEXTSTEP support.
-
-Tue Jun 29 01:42:13 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/pty/pty.c (chld_changed): should use POSIX.1 style wait.
-
-Mon Jun 28 21:07:36 1999 KIMURA Koichi <kbk@kt.rim.or.jp>
-
- * ext/extmk.rb.nt: wrong result for have_library().
-
-Mon Jun 28 15:24:05 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * missing/isinf.c: OSF/1 raises SIGFPE on one()/zero().
-
- * regex.c (re_search): should search til EOS, for patterns may
- match beyond the end of range.
-
-Mon Jun 28 12:49:12 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (rb_f_select): should not accept Time objects as an
- argument for it is time interval.
-
- * process.c (rb_f_sleep): ditto.
-
- * file.c (test_s): should return nil for false condition.
-
-Mon Jun 28 12:23:52 1999 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * bignum.c (rb_dbl2big): typo.
-
- * file.c (rb_f_test): ditto.
-
- * string.c (rb_str_crypt): wrong message.
-
-Sun Jun 27 19:50:11 1999 Tadayoshi Funaba <tadf@kt.rim.or.jp>
-
- * eval.c (rb_f_exit): should have treat signed integer status, not
- VALUE.
-
- * process.c (rb_f_exit_bang): should work like exit().
-
-Sun Jun 27 16:21:32 1999 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * string.c (rb_str_rindex): wrong position to search.
-
-Sat Jun 26 04:05:30 1999 Takaaki Tateishi <ttate@jaist.ac.jp>
-
- * configure.in (configure_args): --with-search-path to specify
- additional ruby search path.
-
- * ruby.c (ruby_prog_init): additional search path.
-
-Fri Jun 25 13:09:12 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * pack.c (pack_unpack): needed to initialize natint.
-
- * regex.c (re_compile_pattern): add start_paren to avoid too much
- finalization on maybe_finalize_jump.
-
-Fri Jun 25 13:07:20 1999 Koji Oda <oda@bsd1.qnes.nec.co.jp>
-
- * missing/isinf.c: include "config.h" added.
-
-Fri Jun 25 07:25:05 1999 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * lib/mkmf.rb: initialize $(topdir).
-
- * ext/extmk.rb.in (install_rb): install lib/*.rb properly.
-
- * configure.in (linux): specifies -rpath on --enable-shared.
-
- * configure.in (aix): ruby.imp must reside in $(topdir).
-
-Thu Jun 24 19:11:29 1999 Yoshida Masato <yoshidam@yoshidam.net>
-
- * parse.y (rb_str_extend): multi-byte identifier in expression
- interpolation in strings.
-
- * parse.y (yylex): support multi-byte char identifiers.
-
-Thu Jun 24 15:27:13 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (f_arg): check duplicate argument names.
-
- * gc.c (rb_gc_mark): marking wrong member for NODE_ARGS.
-
- * string.c (rb_str_rindex): POSITION specifies start point, not
- end point.
-
-Thu Jun 24 13:00:17 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (print_mbc): wrong boundary.
-
- * pack.c (uv_to_utf8): raises ArgError for too big value.
-
-Thu Jun 24 11:02:51 1999 Yoshida Masato <yoshidam@yoshidam.net>
-
- * pack.c (uv_to_utf8): mask needed.
-
-Wed Jun 23 21:03:56 1999 Tadayoshi Funaba <tadf@kt.rim.or.jp>
-
- * ruby.h (struct RFile): remove iv_tbl from struct. instance
- variables are handled as generic ivs.
-
-Wed Jun 23 22:06:26 1999 Tadayoshi Funaba <tadf@kt.rim.or.jp>
-
- * pack.c (utf8_to_uv): pack to 7 bytes sequence.
-
- * pack.c (uv_to_utf8): wrong boundary.
-
- * pack.c (pack_unpack): should treat as unsigned long.
-
-Wed Jun 23 15:10:11 1999 Inaba Hiroto <inaba@sdd.tokyo-sc.toshiba.co.jp>
-
- * parse.y (parse_string): failed to parse nested braces.
-
- * parse.y (parse_regx): nested braces within #{} available.
-
-Wed Jun 23 11:18:38 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (slow_search): wrong shift width for mbcs.
-
- * eval.c (rb_thread_save_context): should not clear th->locals.
-
-Wed Jun 23 02:06:14 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (yylex): UMINUS binds too tight with digits. changed so
- that -2**2 => -4.
-
- * parse.y (close_paren): `do' for expr termination now works it
- used to be.
-
-Wed Jun 22 18:26:42 1999 Koji Arai <JCA02266@nifty.ne.jp>
-
- * pack.c (pack_pack): should initialize local variable `j'.
-
-Wed Jun 22 15:24:59 1999 Koji Arai <JCA02266@nifty.ne.jp>
-
- * parse.y (here_document): a bug for multiline heredoc.
-
-Tue Jun 22 15:06:36 1999 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * ext/socket/socket.c (ruby_socket): forgot to return fd
- explicitly.
-
-Tue Jun 22 13:34:12 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * rubyio.h (MakeOpenFile): should initialize member `iv_tbl'.
-
-Wed Jun 22 10:35:51 1999 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * io.c (rb_io_gets_internal): getc(3) may not set errno on
- interrupt.
-
-Mon Jun 21 22:39:28 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (call_required_libraries): ruby_sourceline should be
- cleared before loading libraries.
-
- * io.c (set_stdin): do not use reopen(), so that we don't need to
- dup original stdin before assigning $stdin.
-
-Mon Jun 21 18:04:27 1999 Ryo HAYASAKA <hayasaka@univ21.u-aizu.ac.jp>
-
- * ext/dbm/dbm.c: include <cdefs.h> for solaris 2.6.
-
-Mon Jun 21 15:59:47 1999 Nobuyoshi Nakada <nobu.nokada@softhome.net>
-
- * ext/socket/socket.c (ip_addrsetup): forgot to put `else'.
-
-Mon Jun 21 15:38:37 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (fptr_finalize): remove rb_syswait() invocation to avoid
- wait4(2) within GC. rb_syswait() moved to rb_io_fptr_close().
-
-Mon Jun 21 12:05:59 1999 Tadayoshi Funaba <tadf@kt.rim.or.jp>
-
- * dir.c (dir_s_glob): remove MAXPATHLEN restriction.
-
- * ext/md5/md5init.c (md5_hexdigest): should have used "%02x".
-
-Sun Jun 20 19:50:38 1999 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * string.c (rb_str_each_line): should have checked string
- boundary.
-
-Sat Jun 19 22:24:12 1999 Kenji Nagasawa <kenn@hma.att.ne.jp>
-
- * OS/2 patch improved.
-
-Fri Jun 18 08:30:17 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * marshal.c (r_byte): add data length check.
-
- * ext/tcltklib/tcltklib.c (_timer_for_tcl): was doing busy-wait.
-
-Tue Jun 15 10:01:21 1999 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * configure.in: remove trailing slash from interpreter embedded
- shared library path.
-
- * configure.in (INSTALL_DLLIB): install shared lib with 0555.
-
- * instruby.rb: changed mode for shared library into 0555.
-
-Fri Jun 11 23:27:00 1999 Tadayoshi Funaba <tadf@kt.rim.or.jp>
-
- * ext/etc/etc.c (etc_passwd): should return nil, not exception for
- call after last passwd entry.
-
-Fri Jun 11 15:21:21 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * gc.c (rb_gc_mark_locations): add safety margin 1.
-
- * eval.c (ruby_run): should protect toplevel node tree.
-
- * ext/etc/etc.c (etc_group): dumps core if there's no more group.
-
-Fri Jun 11 01:50:25 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (ruby_run): Init_stack() was called too late; local
- variables happened to be higher (or lower) than stack_start.
-
-Thu Jun 10 16:41:48 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c: do not call `initialize' for IO objects. So with Array,
- Hash, Range, and Time objects.
-
- * ext/curses/curses.c (curses_getch): made thread aware using
- rb_read_check().
-
- * ext/curses/curses.c (window_getch): ditto.
-
- * ext/curses/curses.c (curses_getstr): made (partially) thread
- aware using rb_read_check().
-
- * ext/curses/curses.c (window_getstr): ditto.
-
- * io.c (rb_read_check): new function to help making something
- (like extension libraries) thread aware.
-
- * eval.c (is_defined): `defined? super' should be true even for
- private superclass methods.
-
-Fri Jun 10 13:42:10 1999 Koji Arai <JCA02266@nifty.ne.jp>
-
- * pack.c (pack_pack): template `Z' should be allowed.
-
-Wed Jun 9 13:26:38 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_thread_loading): modified to avoid nested race
- condition of require().
-
- * ext/tcltklib/tcltklib.c (ip_invoke): queue invocation on non
- main threads.
-
- * ext/tcltklib/tcltklib.c (lib_mainloop): flush invocation
- queues periodically.
-
- * version.c (ruby_show_version): now print the message to stdout.
-
- * version.c (ruby_show_copyright): ditto.
-
-Tue Jun 8 00:00:34 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * pack.c (pack_unpack): append sentinel (NUL) to the string.
-
- * ext/md5/md5init.c (md5_hexdigest): new method to obtain
- printable hash string.
-
- * ext/md5/md5init.c (md5_update): should return self.
-
- * pack.c (pack_pack): undocumented template 'U' for UTF8.
-
- * pack.c (pack_unpack): ditto.
-
- * marshal.c (r_byte): should replace getc() with rb_getc().
-
- * io.c (rb_getc): getc() replacement uses READ_DATA_PENDING() and
- rb_thread_wait_fd().
-
-Mon Jun 7 23:23:38 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * object.c (rb_mod_clone): should call CLOSESETUP().
-
- * eval.c (bind_clone): should call CLONESETUP() for new clone.
-
-Sat Jun 5 10:32:40 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (rb_str_oct): binary (e.g. 0b10111) support.
-
- * variable.c (rb_const_set): raise warning, not exception.
-
- * parse.y (yycompile): initialize parser internal variables.
-
- * parse.y (close_paren): set lex_state to EXPR_PAREN after closing
- parenthesis.
-
- * parse.y (yylex): returns kDO for `do' right after method_call.
-
-Thu Jun 3 11:05:30 1999 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * regex.c (read_backslash): should decode \b within class.
-
-Thu Jun 3 01:06:18 1999 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * dln.c (dln_load): AIX improvement (aix_findmain removed).
-
-Wed Jun 2 00:41:31 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * pack.c (pack_unpack): new undocumented template Z which strips
- stuff after first null.
-
- * pack.c (pack_pack): should preserve specified length of the
- resulting string.
-
-Tue Jun 1 15:29:33 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/socket/socket.c (ruby_socket): retry after GC, if socket(2)
- failed on EMFILE or ENFILE.
-
- * ext/socket/socket.c (sock_s_socketpair): ditto.
-
- * eval.c (module_setup): need to add PUSH_VAR/POP_VAR to clear
- dyna vars link list.
-
- * version.h (RUBY_RELEASE_CODE): integer macro constant for source
- version detection.
-
-Sun May 30 22:19:12 1999 Kenji Nagasawa <kenn@tcp-ip.or.jp>
-
- * ext/socket/socket.c: emx/gcc 0.9d now fixes things about
- AF_UNIX.
-
- * process.c: OS/2 EMX kludge.
-
- * Makefile.in (strncasecmp.o): added dependency.
-
-Mon May 31 16:06:28 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.3.4 - preliminary release for 1.4
-
-Mon May 31 15:57:41 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (rb_io_fptr_close): close on IO which main_thread is
- waiting cause serious exception, that vanishes the actual fd
- closing. Invocation of rb_thread_fd_close() is deferred
- a little.
-
-Sat May 29 18:27:13 1999 Koji Arai <JCA02266@nifty.ne.jp>
-
- * regex.c (re_match): stack boundary check needed.
-
-Sat May 29 12:27:00 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/tcltklib/tcltklib.c (ip_invoke): proper ref count management
- to avoid leak. I HATE REF COUNTING!!
-
- * eval.c (ruby_run): moved ruby_require_libraries() to handle `-r'
- from ruby_options() to avoid stack corruption for threads
- created in libraries.
-
-Sat May 29 02:22:12 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_yield_0): when `for' appeared in blocks, it
- introduced new scope for local variables.
-
-Fri May 28 17:16:49 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (rb_str_squeeze_bang): squeeze AND of the arguments.
- UNDOCUMENTED.
-
- * string.c (rb_str_count): new UNDOCUMENTED method.
-
- * string.c (rb_str_delete_bang): delete AND of the arg ranges.
- UNDOCUMENTED FEATURE for 1.3.x.
-
- * ext/socket/socket.c (setipaddr): re-wrote using ip_addrsetup().
-
- * ext/socket/socket.c (ip_addrsetup): decode symbolic address
- <broadcast>.
-
-Thu May 27 12:27:42 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (tr_trans): should handle NUL (\0) within strings.
-
-Tue May 25 16:45:11 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (rb_f_syscall): syscall may return values other than zero
- on success.
-
- * regex.c (re_match): handle empty loop properly (hopefully).
-
- * regex.c (re_match): remove empty group check, because it does
- not help non-grouping parentheses (?:..).
-
- * regex.c (re_compile_fastmap): treating try_next, finalize_push
- wrong way.
-
- * regex.c: remove some obsolete functions such as
- group_match_null_string_p().
-
-Mon May 24 14:47:54 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (read_backslash): read backslash by regex.
-
-Sun May 23 19:44:58 1999 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * ext/pty/pty.c (getDevice): portability patch.
-
-Fri May 21 23:01:26 1999 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * ext/socket/getaddrinfo.c (GET_AI): should set error code.
-
-Thu May 20 03:43:44 1999 Jun-ichiro itojun Hagino <itojun@itojun.org>
-
- * ext/socket/socket.c: you should use sockaddr_storage to handle
- IPv6 addresses.
-
- * ext/socket/getaddrinfo.c (getaddrinfo): prevent retrieving
- AF_INET6 address if hints.ai_flags == AI_PASSIVE.
-
-Wed May 19 12:27:07 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (exec_end_proc): should protect exceptions.
-
- * gc.c (run_final): ditto.
-
- * parse.y (f_rest_arg): allow just * for rest arg.
-
- * parse.y (mlhs_basic): allow * without formal argument.
-
- * regex.c (re_match): the variable `part' should be initialized.
-
-Tue May 18 15:25:45 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_search): a bug in range adjustment.
-
-Tue May 18 11:35:59 1999 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * dln.c (conv_to_posix_path): path_len argument added.
-
-Mon May 17 12:26:31 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * numeric.c (fix_rev): should treat Fixnum as signed long.
-
- * eval.c (massign): add strict number check for yield (and call).
-
- * eval.c (proc_arity): new method to return number of arguments.
-
- * eval.c (method_arity): new method to return number of arguments.
-
- * parse.y (read_escape): char may be unsigned.
-
- * string.c (rb_str_succ): ditto.
-
- * string.c (tr_trans): ditto.
-
- * object.c (Init_Object): methods `&', `|', `^' are added to nil.
-
- * range.c (rb_range_beg_len): it should be OK for [0..-len-1].
-
- * regex.c (re_search): search for byte literal within mbcs.
-
- * regex.c (is_in_list): parsh
-
- * regex.c (re_compile_fastmap): should have not alter the loop
- variable `j' if TRASLATE_P().
-
- * regex.c (re_compile_pattern): escaped characters should be read
- by PATFETCH_RAW(c).
-
-Sat May 15 11:23:51 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_match): endline2 (\Z) should not match at the point
- between a newline and end-of-line, like endline ($).
-
- * class.c (include_class_new): should initialize iv_tbl to share
- between module and iclass.
-
-Fri May 14 08:50:27 1999 Akira Endo <akendo@t3.rim.or.jp>
-
- * regex.c (re_compile_fastmap): it should be k != 0 to skip.
-
-Fri May 14 12:46:56 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * time.c (time_load): a bug in old marshal format support.
-
- * instruby.rb: make site_ruby directory.
-
-Fri May 14 10:18:02 1999 WATANABE Tetsuya <tetsu@jpn.hp.com>
-
- * regex.c (re_match): a bug in inline `.*' etc.
-
-Fri May 14 09:58:46 1999 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-
- * ruby.c (addpath): should have specified string length.
-
-Thu May 13 10:40:44 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_eval_string_wrap): new function.
-
- * regex.c (re_compile_pattern): POSIX line match should alter
- behavior for `^' and `$' to begbuf and endbuf2 respectively.
-
- * ext/pty/pty.c: un-ANSI-fy function arguments.
-
-Wed May 12 14:19:38 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * struct.c (iv_get): in case of inheritance of generated struct
- class, __member__ and __size__ should also be inherited.
- Thanks for Pros Yeboah <yeboah@tu-harburg.de>.
-
- * io.c (rb_f_gets_internal): should check number of arguments
- before checking rb_rs == rb_default_rs. Thanks for Koji Arai
- <JCA02266@nifty.ne.jp>.
-
-Tue May 11 08:29:28 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_compile_pattern): .?, .+ did not work.
-
-Mon May 10 00:59:33 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * lib/jcode.rb: forgot to squeeze on reverse (complement) case.
-
- * string.c (tr_squeeze): should not set modify flag to be honest,
- if the string is not modified.
-
- * signal.c (Init_signal): SIGTERM should not be handled.
-
- * regex.c (re_match): seeking for longest match is now optional,
- which can be set using RE_OPTION_POSIXMATCH. This satisfies
- POSIX longest match as much as Emacs's posix-* functions, which
- are known to be incomplete.
-
-Sun May 9 13:04:01 1999 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * ext/socket/socket.c (sock_s_getaddrinfo): conversion from
- Fixnums to C integers needed.
-
-Sun May 9 11:51:43 1999 Koji Arai <JCA02266@nifty.ne.jp>
-
- * range.c (range_eqq): reverse condition.
-
- * range.c (range_s_new): default should be end inclusive.
-
-Sat May 8 03:27:51 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/socket/socket.c (thread_connect): replace nasty
- rb_thread_fd_writable() with rb_thread_select().
-
-Fri May 7 20:49:00 1999 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * ext/socket/getaddrinfo.c (inet_pton): wrong parameter to
- inet_aton().
-
- * ext/socket/addrinfo.h (__P): silly cut and paste typo.
-
-Fri May 7 17:03:57 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * dir.c (glob): removed GPL'ed glob.c completely.
-
-Fri May 7 08:17:19 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/sdbm/extconf.rb: sdbm extension added to the distribution.
-
-Fri May 7 01:42:20 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/socket/socket.c (tcp_s_gethostbyname): avoid using struct
- sockaddr_storage.
-
-Thu May 6 13:21:41 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * array.c (rb_ary_indexes): should not use rb_ary_concat().
-
-Thu May 4 12:34:18 1999 Koji Arai <JCA02266@nifty.ne.jp>
-
- * parse.y (parse_string): there should be newline escape by
- backslashes in strings.
-
- * parse.y (parse_qstring): ditto.
-
-Mon May 3 04:37:20 1999 Koji Arai <JCA02266@nifty.ne.jp>
-
- * ext/tcltklib/extconf.rb: better search for libX11.
-
- * range.c (range_s_new): embarrassing =/== typo.
-
- * re.c (Init_Regexp): failed to set default kcode.
-
-Mon May 3 02:39:55 1999 WATANABE Tetsuya <tetsu@jpn.hp.com>
-
- * ext/socket/socket.c (open_inet): typo (res and res0).
-
-Tue May 4 02:07:49 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * mkconfig.rb: leave undefined $(VARIABLE) unexpanded in the
- Config::CONFIG hash table.
-
-Mon May 3 09:37:22 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_compile_pattern): expand exactn{n} at compile time.
- handles stop_paren specially.
-
- * regex.c (re_compile_pattern): expand x{n} at compile time.
-
- * regex.c (re_search): posix line match should be checked.
-
- * regex.c (re_search): a bug in anchor condition.
-
-Fri Apr 30 18:57:41 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.3.3
-
- * string.c (rb_str_rindex): position should be END point, not
- START point.
-
- * re.c (rb_reg_search): pos means end point on reverse now.
-
- * array.c (rb_ary_s_create): should clear ary->ptr to avoid
- potential gc crash.
-
-Fri Apr 30 15:24:58 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/socket/addrinfo.h: compatibility hack for ipv4.
-
- * ext/socket/socket.c: itojun's ipv6 patches applied.
-
- * ext/socket/extconf.rb: detect ipv6 features based on itojun's
- ipv6 patches.
-
- * ext/extmk.rb.in (enable_config): can handle --enable-xxx now.
-
- * lib/mkmf.rb (enable_config): ditto.
-
-Fri Apr 30 05:22:23 1999 Shugo Maeda <shugo@netlab.co.jp>
-
- * string.c (rb_str_aset): last index should not append.
-
-Thu Apr 29 18:55:31 1999 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * dln.c (conv_to_posix_path): remove const from args.
-
- * ruby.c (rubylib_mangle): remove Fatal(), the obsolete function.
-
-Tue Apr 27 14:11:45 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (fname): lazy workaround for keywords did not work well.
-
- * ext/extmk.rb.in: `--with-xxx=yyy' argument configuration.
-
- * lib/mkmf.rb: ditto.
-
- * misc/ruby-mode.el: forgot to handle $`.
-
- * ext/extmk.rb.in: better AIX link support proposed by
- <komatsu@sarion.co.jp>.
-
-Mon Apr 26 16:46:59 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/extmk.rb.in: AIX shared library support modified.
-
- * ext/aix_mksym.rb: ditto.
-
- * configure.in: ditto.
-
- * sprintf.c (rb_f_sprintf): should allocate proper sized buffer
- for float numbers.
-
-Sat Apr 24 00:00:16 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (operation): syntax like `a.[]=(1,2)' is allowed.
-
-Fri Apr 23 23:54:09 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (argf_binmode): binmode method added to ARGF.
-
-Fri Apr 23 13:55:22 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (rb_f_chomp): should assign the result to $_. or maybe
- sub/gsub/chop/chomp should NOT assign $_ altogether.
-
-Thu Apr 22 16:50:54 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_callcc): call scope_dup() for all scopes in
- the interpreter stack.
-
-Tue Apr 20 11:24:18 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (rb_str_dump): `#' should be escaped.
-
-Tue Apr 20 02:32:42 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (parse_regx): option /p for posix match added.
-
- * re.c (rb_reg_desc): did not print options properly.
-
- * io.c (rb_file_s_open): initialize was called twice.
-
-Mon Apr 19 18:56:21 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * configure.in (DEFAULT_KCODE): can specify default code for
- $KCODE by --with-default-kcode=(euc|sjis|utf8|none).
-
- * regex.c (IS_A_LETTER): a byte sequence shorter than mbc should
- not match with \w etc.
-
-Mon Apr 19 13:49:11 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (eval): should restore ruby_dyna_vars.
-
-Fri Apr 16 21:40:43 1999 Nobuyoshi Nakada <gea02117@nifty.ne.jp>
-
- * io.c (f_backquote): pipe_open may return nil.
-
- * io.c (f_open): rb_io_open may return nil.
-
- * io.c (io_s_foreach): ditto.
-
- * io.c (io_s_readlines): ditto.
-
- * io.c (io_defset): wrong message.
-
-Fri Apr 16 15:09:20 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * bignum.c (rb_str2inum): strtoul() returns long, not int.
-
- * eval.c (rb_load): size of VALUE and ID may be different.
-
- * util.c (mmprepare): int is too small to cast from pointers.
-
- * config.guess: avoid 'linux-gnu' for alpha-unknown-linux.
-
-Thu Apr 15 23:46:20 1999 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * ruby.c (rubylib_mangle): mangle path by RUBYLIB_PREFIX.
-
-Wed Apr 14 23:52:51 1999 SHIROYAMA Takayuki <psi@fortune.nest.or.jp>
-
- * node.h (NODE_LMASK): should be long to avoid overflow.
-
-Wed Apr 14 13:14:35 1999 Katsuyuki Komatsu <komatsu@sarion.co.jp>
-
- * dln.c: AIX dynamic link.
-
- * ext/aix_ld.rb: ditto.
-
-Wed Apr 14 12:19:09 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * lib/thread.rb: Queue#{enq,deq} added.
-
-Tue Apr 13 17:43:56 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * hash.c (rb_hash_s_create): Hash::[] acts more like casting.
-
-Tue Apr 13 00:33:52 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (rb_io_stdio_set): warning for assignment to the variables
- $std{in,out,err}.
-
-Mon Apr 12 23:12:32 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (rb_io_reopen): check for reopening same IO.
-
-Fri Apr 9 17:45:11 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (rb_compile_string): bug for nested eval().
-
- * regex.c (re_match): should pop non-greedy stack items on
- failure, after best_regs are fixed.
-
-Thu Apr 8 17:30:40 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * pack.c (PACK_LENGTH_ADJUST): need to adjust for `*' length.
-
-Tue Apr 6 23:28:44 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (void_check): add void context checks.
-
-Mon Apr 5 12:23:42 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * time.c (time_s_at): should copy gmt-mode.
-
- * eval.c (eval_node): preserve ruby_eval_tree.
-
-Fri Apr 2 14:00:34 1999 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>
-
- * lib/debug.rb: wrong command interpreting.
-
-Fri Apr 2 11:46:22 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.3.2
-
-Fri Apr 2 10:40:04 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (rb_io_s_pipe): forgot to define IO::pipe.
-
-Thu Apr 1 14:40:46 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (assign): modified for rhs change.
-
- * parse.y (stmt): unparenthesisized method calls can be right hand
- side expression of the assignment.
-
-Sat Mar 27 22:42:47 1999 Koji Arai <JCA02266@nifty.ne.jp>
-
- * ext/nkf/nkf.c (rb_nkf_kconv): check size output_ctr before
- decrement.
-
-Thu Mar 25 09:11:03 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * time.c (time_s_at): preserve gmt-mode for result.
-
- * parse.y (rb_compile_string): do not use cur_mid, use
- compile_for_eval instead.
-
- * st.c (PTR_NOT_EQUAL): wrong logical condition.
-
-Wed Mar 24 13:06:43 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (yycompile): should clear cur_mid after compilation.
-
- * io.c (next_argv): need to check type for ARGV.shift.
-
- * eval.c (blk_copy_prev): need to preserve outer scope as well as
- outer frames.
-
- * parse.y (rb_compile_string): return can appear within eval().
-
-Tue Mar 23 10:15:07 1999 EGUCHI Osamu <eguchi@shizuokanet.ne.jp>
-
- * configure.in: AC_C_CONST check added.
-
-Tue Mar 23 02:07:35 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * time.c (time_plus): preserve gmt-mode for result.
-
-Mon Mar 22 01:32:37 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_eval): adjust line numbers before expression
- interpolation within strings.
-
- * eval.c (rb_eval): defined? returns nil for false condition.
-
- * numeric.c (num_nonzero_p): returns nil for false condition.
-
-Sat Mar 20 13:07:43 1999 Keiju Ishitsuka <keiju@rational.com>
-
- * lib/weakref.rb: avoid leak for two weakrefs for one object.
-
-Fri Mar 19 11:26:45 1999 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * eval.c (ruby_run): needed to eval END{} on exit.
-
- * eval.c (rb_exit): ditto.
-
-Fri Mar 19 02:17:27 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * signal.c (Init_signal): handles terminating signals HUP, TERM,
- QUIT, PIPE, etc.
-
-Thu Mar 18 15:47:18 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * bignum.c (rb_big_and): bug in sign calculation.
-
- * bignum.c (rb_big_or): ditto.
-
- * io.c (rb_f_select): forgot to use to_io to retrieve IO, after
- calling select(2).
-
-Tue Mar 16 19:54:31 1999 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * ext/extmk.rb.in: static linking cause infinite make loop.
-
-Tue Mar 16 18:50:04 1999 Yoshida Masato <yoshidam@yoshidam.net>
-
- * ext/socket/socket.c (tcp_s_gethostbyname): typo, not NUM2INT(),
- but INT2NUM().
-
- * ext/socket/socket.c (mkhostent): ditto.
-
-Tue Mar 16 12:31:44 1999 Ryo HAYASAKA <hayasaka@cheer.u-aizu.ac.jp>
-
- * file.c (utime_internal): suppress warning by const.
-
- * time.c (time_gmtime): ditto.
-
-Tue Mar 16 10:23:05 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * time.c (time_clone): Time object can be cloned.
-
-Tue Mar 16 03:13:10 1999 Koji Arai <JCA02266@nifty.ne.jp>
-
- * ruby.c (load_file): argv[argc] should be NULL.
-
-Mon Mar 15 22:12:08 1999 Tadayoshi Funaba <tadf@kt.rim.or.jp>
-
- * sprintf.c (rb_f_sprintf): typo in arg_num check at exit.
-
-Mon Mar 15 16:42:22 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * array.c (rb_ary_dup): dup2 should copy class too.
-
-Mon Mar 15 15:12:53 1999 Yasuhiro Fukuma <yasuf@big.or.jp>
-
- * lib/mkmf.rb: install program relative path check.
-
-Mon Mar 15 14:05:25 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * re.c (rb_reg_s_new): 2nd argument is now option.
- Regexp::EXTENDED can be specified.
-
-Fri Mar 12 10:47:49 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (rb_str_index): str.index("") should always match at
- offset point.
-
- * string.c (rb_str_upto): can specify end point exclusion.
-
- * string.c (rb_str_index): negative offset.
-
- * regex.c (re_match): begline should not match at the point
- between a newline and end-of-string. endline neither.
-
- * regex.c (re_compile_pattern): context_indep_anchors .
-
- * parse.y (parse_regx): need not to push backslashes before
- escaped characters.
-
- * eval.c (rb_thread_join): re-raises exception within target.
-
-Fri Mar 12 01:09:36 1999 Koji Arai <JCA02266@nifty.ne.jp>
-
- * ext/readline/readline.c (readline_s_vi_editing_mode): wrong
- number of arguments.
-
-Fri Mar 12 02:12:50 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * pack.c (PACK_ITEM_ADJUST): "a".unpack("C3") => [97, nil, nil]
-
-Thu Mar 11 18:23:50 1999 WATANABE Tetsuya <tetsu@jpn.hp.com>
-
- * ext/socket/socket.c (Init_socket): UDPsocket was omitted.
-
-Thu Mar 11 16:43:30 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * pack.c (PACK_LENGTH_ADJUST): push fixed number of items per
- template to result array.
-
- * pack.c (pack_unpack): I/N/C etc. push nil in the array for "".
-
-Tue Mar 9 00:19:21 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * hash.c (ruby_unsetenv): use ruby_setenv(name, 0).
-
- * hash.c (env_delete): ditto.
-
- * string.c (rb_str_upto): do not check `beg<end' to generate
- strings for the pattern like "a".upto("#a").
-
- * range.c (range_each): treat strings as special case.
-
- * range.c (range_each): no longer use upto for generic cases.
-
-Sun Mar 7 14:21:32 1999 IKARASHI Akira <ikarashi@itlb.te.noda.sut.ac.jp>
-
- * string.c (rb_str_index): wrong end point calculation.
-
-Sat Mar 6 02:19:12 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * re.c (match_index): MatchingData#index(n) added.
-
- * array.c (rb_ary_subseq): ary[n..-1] returns an sub-array unless
- n is too small negative index.
-
- * re.c (rb_reg_match_method): Regexp#match(str) added.
-
- * array.c (rb_ary_indexes): understands ranges as indexes.
-
- * re.c (match_size): MatchingData#size added.
-
-Fri Mar 5 01:04:57 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * array.c (rb_ary_fill): modified for range.
-
- * array.c (rb_ary_aset): a[n..m] revisited.
-
-Thu Mar 4 14:23:29 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (rb_str_subseq): a[n..m] revisited.
-
- * parse.y (method_call): allow Const::method{}.
-
- * array.c (rb_ary_replace_method): should replace original array.
-
-Thu Mar 4 02:30:22 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * configure.in: remove --disable-thread, thread feature is no
- longer optional.
-
-Thu Mar 4 00:32:17 1999 Yasuhiro Fukuma <yasuf@big.or.jp>
-
- * parse.y (read_escape): wrong arguments for scan_oct,scan_hex.
-
-Wed Mar 3 11:51:53 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/socket/socket.c (Init_socket): rename class names as
- TCPsocket -> TCPSocket etc.
-
-Tue Mar 2 19:46:42 1999 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * configure.in (LDSHARED): use gcc -Wl,-G for solaris with gcc.
-
-Tue Mar 2 17:04:19 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (yylex): backslashes do not concatenate comment lines
- anymore.
-
-Mon Mar 1 14:05:12 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_call0): adjust argv for optional arguments. super
- without arguments emit superclass method with the value from
- optional arguments. enabled as experiment.
-
-Sun Feb 28 14:04:07 1999 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * parse.y (nextc): backslash at the eof cause infinite loop
-
-Sun Feb 28 11:01:26 1999 Tadayoshi Funaba <tadf@kt.rim.or.jp>
-
- * time.c (make_time_t): month range check added.
-
-Sat Feb 27 02:36:05 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * re.c (Init_Regexp): add escape as alias of quote.
-
- * re.c (rb_reg_s_quote): char-code can be specified now.
-
-Fri Feb 26 18:45:36 1999 Yasuhiro Fukuma <yasuf@big.or.jp>
-
- * eval.c (error_print): bug for error message with newlines.
-
-Fri Feb 26 12:00:04 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * time.c (make_time_t): future check modified to allow 1969-12-31
- at certain timezone.
-
- * time.c (time_arg): year >= 1000 should be past.
-
- * version.c (Init_version): constant RELEASE_DATE added.
-
-Fri Feb 26 01:08:30 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (rb_str_substr): returns nil for out-of-range access.
-
- * array.c (rb_ary_subseq): returns nil for out-of-range access.
-
- * array.c (rb_ary_store): negative index message has changed.
-
- * string.c (rb_str_aset): reallocation needed.
-
- * string.c (rb_str_aset): allow char append to the string.
-
-Thu Feb 25 23:30:17 1999 Tadayoshi Funaba <tadf@kt.rim.or.jp>
-
- * time.c (time_load): tm_year should be packed in 17 bits, not 18.
-
-Thu Feb 25 12:50:25 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * missing/dup2.c: replaced by public domain version.
-
- * time.c (make_time_t): add `future check' in loops.
-
- * object.c (rb_num2dbl): forbid implicit conversion from nil, or
- strings. thus `Time.now + str' should raise error.
-
- * object.c (rb_Float): convert nil into 0.0.
-
- * object.c (rb_Integer): conversion method improved.
-
-Thu Feb 25 03:27:50 1999 Shugo Maeda <shugo@netlab.co.jp>
-
- * eval.c (rb_call): should handle T_ICLASS properly.
-
-Thu Feb 25 00:04:00 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * error.c (Init_Exception): global function Exception() removed.
-
- * variable.c (rb_class2name): returns "nil"/"true"/"false" for them.
-
- * time.c (time_dump): time marshaling format compressed size from
- 11 bytes to 8 bytes. thanx to tadf@kt.rim.or.jp.
-
- * eval.c (rb_obj_call_init): should specify arguments explicitly.
-
-Wed Feb 24 15:43:28 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (yylex): comment concatenation requires preceding space
- before backslash at the end of line.
-
- * io.c (rb_f_pipe): global pipe is obsolete now.
-
- * object.c (Init_Object): remove true.to_i, false.to_i.
-
-Tue Feb 23 14:21:41 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (yylex): warn if identifier! immediately followed by `='.
-
-Tue Feb 23 12:32:41 1999 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * eval.c (rb_load): tilde expansion moved to find_file.
-
- * eval.c (find_file): tilde expansion added.
-
-Tue Feb 23 10:50:20 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (require_method): require can handle multiple fnames.
-
- * hash.c (rb_hash_foreach_iter): hash key may be nil.
-
-Mon Feb 22 17:44:02 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_match): should not pop failure point on success for
- non-greedy matches.
-
- * io.c (Init_IO): remove global_functions getc, readchar, ungetc,
- seek, tell, rewind.
-
-Sat Feb 20 22:54:26 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * numeric.c (rb_num2long): no implicit conversion from boolean.
-
-Sat Feb 20 09:58:42 1999 EGUCHI Osamu <eguchi@shizuokanet.ne.jp>
-
- * numeric.c (flo_to_s): portable Infinity and NaN support.
-
-Sat Feb 20 07:13:31 1999 WATANABE Tetsuya <tetsu@jpn.hp.com>
-
- * io.c (rb_file_sysopen): forgot to initialize a local variable.
-
-Fri Feb 19 23:05:07 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (rb_str_subseq): range check changed.
-
- * marshal.c: increment MARSHAL_MINOR for Time format change.
-
- * time.c (time_old_load): support old marshal format.
-
- * time.c (time_load): changed for new format Y/M/D/h/m/s/usec.
-
- * time.c (time_dump): marshal dump format has changed.
-
-Fri Feb 19 00:25:57 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * time.c (time_arg): should reject "sep\0" and such.
-
- * time.c (time_plus): Time#+ should not receive Time object
- operand.
-
- * string.c (rb_str_substr): negative length raises exception now.
-
- * array.c (beg_len): if end == -1, it points end of the array.
-
- * array.c (rb_ary_subseq): negative length raises exception now.
-
-Thu Feb 18 20:57:04 1999 Tadayoshi Funaba <tadf@kt.rim.or.jp>
-
- * time.c (rb_strftime): strftime() may return 0 on success too.
-
- * time.c (time_strftime): `\0' within format string should not be
- omitted in the result.
-
- * time.c (rb_strftime): zero length format.
-
- * time.c (time_to_a): yday start with 1 now.
-
- * time.c (time_zone): support for long timezone name.
-
- * time.c (time_yday): yday start with 1 now.
-
- * time.c (time_minus): minus calculation was wrong.
-
- * time.c (time_minus): sec, usec should be at least `long', maybe
- they should be `time_t'.
-
- * time.c (time_plus): addition with float was wrong.
-
- * time.c (time_to_s): support for long timezone name.
-
- * time.c (time_gm_or_local): too far future check moved.
-
- * time.c (time_arg): treat 2 digit year as 69-99 => 1969-1999,
- 00-68 => 2000-2068
-
-Thu Feb 18 03:56:47 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * missing/fnmatch.c: moved to missing directory.
-
-Wed Feb 17 16:22:26 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * struct.c (rb_struct_alloc): actual initialization now be done in
- `initialize'.
-
-Wed Feb 17 09:47:15 1999 okabe katsuyuki <hgc02147@nifty.ne.jp>
-
- * regex.c (re_search): use mbclen() instead of ismbchar().
-
- * re.c (rb_reg_s_quote): should handle mbchars properly.
-
-Wed Feb 17 01:25:26 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (yylex): stop comment concatenation by backslash follows
- after >= 0x80 char. may cause problem with Latin chars.
-
- * eval.c (error_print): exception in rb_obj_as_string() caused
- SEGV. protect it by PUSH_TAG/POP_TAG.
-
- * error.c (exc_exception): `Exception#exception' should return self.
-
-Wed Feb 17 01:12:22 1999 Hirotaka Ichikawa <hirotaka.ichikawa@tosmec.toshiba.co.jp>
-
- * configure.in: BeOS patch.
-
-Tue Feb 16 14:25:00 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_compile_pattern): should reallocate mbc space for
- character class unless current_mbctype is ASCII.
-
-Mon Feb 15 15:48:30 1999 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * configure.in: specify `-Wl,-E' only for GNU ld.
-
-Mon Feb 15 11:43:22 1999 GOTO Kentaro <gotoken@math.sci.hokudai.ac.jp>
-
- * array.c (rb_inspecting_p): should return Qfalse.
-
-Sun Feb 14 22:36:40 1999 EGUCHI Osamu <eguchi@shizuokanet.ne.jp>
-
- * sprintf.c (rb_f_sprintf): `%G' was omitted.
-
-Sun Feb 14 12:47:48 1999 EGUCHI Osamu <eguchi@shizuokanet.ne.jp>
-
- * numeric.c (Init_Numeric): allow divide by zero on FreeBSD.
-
- * numeric.c (Init_Numeric): FloatDomainError added.
-
- * configure.in (AC_REPLACE_FUNCS): add checks for functions
- isinf, isnan, and finite.
-
-Sat Feb 13 01:24:16 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_thread_create_0): should protect th->thread.
-
-Fri Feb 12 16:16:47 1999 Yasuhiro Fukuma <yasuf@big.or.jp>
-
- * string.c (rb_str_inspect): wrong mbc position.
-
-Fri Feb 12 16:21:17 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_thread_fd_close):
-
- * io.c (rb_io_fptr_close): tell scheduler that fd is closed.
-
- * io.c (rb_io_reopen): ditto.
-
- * io.c (READ_CHECK): check if closed after thread context switch.
-
- * ext/socket/socket.c (bsock_close_read): do not check
- the return value from shutdown(2).
-
- * ext/socket/socket.c (bsock_close_write): ditto.
-
- * ext/socket/socket.c (sock_new): need to dup(fd) for close_read
- and close_write.
-
- * parse.y (here_document): handle newlines within #{}.
-
- * regex.h: should replace symbols for ruby.
-
-Fri Feb 12 00:46:28 1999 Shugo Maeda <shugo@netlab.co.jp>
-
- * marshal.c (r_object): should update the method name in message.
-
- * marshal.c (w_object): limit should be converted into Fixnum.
-
-Wed Feb 10 15:20:03 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_match): empty pattern should not cause infinite
- pattern match loop.
-
- * regex.c (re_compile_pattern): RE_OPTIMIZE_ANCHOR for /.*/, not
- for /(.|\n)/.
-
- * numeric.c (fix_pow): `fixnum**nil' should raise TypeError.
-
- * bignum.c (rb_big_pow): need to normalize results.
-
-Wed Feb 10 01:42:41 1999 EGUCHI Osamu <eguchi@shizuokanet.ne.jp>
-
- * numeric.c (fix_pow): `(5**1).type' should be Integer.
-
-Tue Feb 9 01:22:49 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (yylex): do not ignore newlines in mbchars.
-
- * io.c (rb_file_s_open): mode can be specified by flags like
- open(2), e.g. File::open(path, File::CREAT|File::WRONLY).
-
- * io.c (rb_f_open): bit-wise mode flags for pipes
-
- * io.c (Init_IO): bit flags for open.
-
-Sat Feb 6 22:56:21 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (rb_str_sub_bang): should not overwrite match data by
- regexp match within the block.
-
- * string.c (rb_str_gsub_bang): ditto.
-
-Sat Feb 6 03:06:17 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * re.c (match_getter): accessing $~ without matching caused SEGV.
-
-Fri Feb 5 22:11:08 1999 EGUCHI Osamu <eguchi@shizuokanet.ne.jp>
-
- * parse.y (yylex): binary literal support, like 0b01001.
-
- * parse.y (yylex): octal numbers can contain `_'s.
-
- * parse.y (yylex): warns if non-octal number follows immediately
- after octal literal.
-
- * parse.y (yylex): now need at least one digit after prefix such
- as 0x, or 0b.
-
- * bignum.c (rb_str2inum): recognize binary numbers like 0b0101.
-
-Fri Feb 5 03:26:56 1999 Yasuhiro Fukuma <yasuf@big.or.jp>
-
- * ruby.c (proc_options): -e without program prints error.
-
-Fri Feb 5 00:01:50 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (terms): needed to clear heredoc_end.
-
- * numeric.c (flo_div): allow float division by zero.
-
-Thu Feb 4 11:56:24 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * missing/strtod.c: for compatibility.
-
- * configure.in (strtod): add strtod compatible check.
-
- * numeric.c (rb_num2long): missing/vsnprintf.c does not support
- floating points.
-
- * numeric.c (flo_to_s): ditto.
-
-Wed Feb 3 23:02:12 1999 Yoshida Masato <yoshidam@yoshidam.net>
-
- * regex.c (re_compile_pattern): use ismbchar() to get next char.
-
- * regex.c (re_search): wrong mbchar shift.
-
- * re.c (rb_reg_search): needed to reset $KCODE after match.
-
- * regex.c (re_compile_fastmap): mbchars should match with \w.
-
-Wed Feb 3 22:35:12 1999 EGUCHI Osamu <eguchi@shizuokanet.ne.jp>
-
- * parse.y (yylex): too big float raise warning, not error.
-
-Tue Feb 2 23:41:42 1999 Yoshida Masato <yoshidam@yoshidam.net>
-
- * regex.c (re_match): wrong boundary.
-
- * regex.c (IS_A_LETTER): re_mbctab[c] may not be 1 for mbc.
-
- * regex.c (re_search): mbchar support for shifting ranges.
-
- * regex.c (MBC2WC): wrong conversion.
-
-Wed Feb 3 15:03:16 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (parse_regx): need to escape parens if terminators are
- not any kind of parenthesis.
-
- * parse.y (parse_qstring): ditto.
-
- * parse.y (parse_string): ditto.
-
-Tue Feb 2 17:11:26 1999 WATANABE Tetsuya <tetsu@jpn.hp.com>
-
- * string.c (rb_str_gsub_bang): too small realloc condition.
-
-Mon Feb 1 10:01:17 1999 EGUCHI Osamu <eguchi@shizuokanet.ne.jp>
-
- * parse.y (yylex): range check for the float literal.
-
-Sat Jan 30 18:34:16 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ruby.c (usage): -h option to show brief command description.
-
-Sat Jan 30 08:45:16 1999 IKARASHI Akira <ikarashi@itlb.te.noda.sut.ac.jp>
-
- * lib/cgi-lib.rb: cookie support added.
-
-Sat Jan 30 13:38:24 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_compile_pattern): mbchars should match with \w
- within character class. Was matching with \W.
-
- * regex.c (re_match): \w should match with multi byte characters,
- not its first byte.
-
-Sat Jan 30 10:06:41 1999 Yoshida Masato <yoshidam@yoshidam.net>
-
- * re.c (rb_reg_s_new): UTF-8 flag handle (/u, /U).
-
- * re.c (rb_kcode): $KCODE handle for UTF-8.
-
-Sat Jan 30 01:51:16 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * array.c (rb_ary_delete_if): RTEST() missing.
-
- * hash.c (delete_if_i): ditto.
-
- * enum.c (Init_Enumerable): select (=find_all), detect (=find)
- added as aliases.
-
-Fri Jan 29 21:32:19 1999 WATANABE Tetsuya <tetsu@jpn.hp.com>
-
- * hash.c (rb_f_setenv): SEGV caused by small typo.
-
-Fri Jan 29 00:15:58 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * lib/parsedate.rb (parsedate): support date format like
- 23-Feb-93, which is required by HTTP/1.1.
-
- * variable.c (find_class_path): avoid calling rb_iv_set().
-
- * eval.c (backtrace): do not need to modify $SAFE internally.
-
- * variable.c (classname): inline __classid__ access.
-
- * eval.c (THREAD_ALLOC): needed to initialize wrapper.
-
- * lib/ftools.rb (makedirs): allows slash at the end of the path.
-
- * numeric.c (rb_fix_induced_from): ensure result to be Fixnum.
-
-Thu Jan 28 17:31:43 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * numeric.c (flo_to_s): float format changed to "%16.10g".
-
-Thu Jan 28 02:13:11 1999 Yoshinori Toki <toki@freedom.ne.jp>
-
- * array.c (rb_ary_store): expand allocated buffer by 3/2.
-
-Wed Jan 27 17:50:02 1999 Kazuhiro HIWADA <hiwada@kuee.kyoto-u.ac.jp>
-
- * bignum.c (dbl2big): raised error if double is too big to cast
- into long. check added.
-
-Wed Jan 27 03:16:18 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * variable.c (rb_mod_const_at): can't list constants of the
- untainted objects in safe mode.
-
- * class.c (method_list): can't list methods of untainted objects
- in safe mode.
-
-Tue Jan 26 02:40:41 1999 GOTO Kentaro <gotoken@math.sci.hokudai.ac.jp>
-
- * prec.c: Precision support for numbers.
-
-Thu Jan 21 19:08:14 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_f_raise): calls `exception' method, not `new'.
-
- * error.c (exc_exception): renamed from `new'.
-
-Wed Jan 20 03:39:48 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (yycompile): rb_in_compile renamed to ruby_in_compile.
-
- * ruby.c (load_file): define DATA if __END__ appeared in script.
-
-Tue Jan 19 14:57:51 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (here_document): need to protect lex_lastline.
-
- * parse.y (yylex): disable %//, %'', %``.
-
-Tue Jan 19 05:01:16 1999 Koji Arai <JCA02266@nifty.ne.jp>
-
- * array.c (beg_len): round range value too much.
-
-Mon Jan 18 13:02:27 1999 Kuroda Jun <jkuro@dwe.co.jp>
-
- * hash.c (env_keys): strchr() may return NULL.
-
-Mon Jan 18 17:51:47 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * instruby.rb (wdir): install libruby.a in archdir.
-
- * lib/ftools.rb (install): removes file before installing.
-
-Mon Jan 18 16:55:31 1999 MAEDA shugo <shugo@aianet.ne.jp>
-
- * eval.c (rb_callcc): experimental continuation support.
-
-Sun Jan 17 19:45:37 1999 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * pack.c (pack_pack): nil packing caused SEGV.
-
-Sat Jan 16 13:18:03 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (rb_str_concat): character (fixnum) can be append to
- strings
-
- * array.c (rb_ary_unshift): unshift returns array.
-
-Sat Jan 16 01:39:19 1999 Yoshida Masato <yoshidam@tau.bekkoame.ne.jp>
-
- * string.c (rb_str_split_method): UTF-8 support.
-
- * regex.c: UTF-8 support.
-
-Thu Jan 14 00:42:55 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (rb_str_gsub_bang): forget to add offset for null match.
-
- * eval.c (rb_thread_local_aset): can't modify in tainted mode.
-
- * hash.c (env_each_key): avoid generating temporary array.
-
-Wed Jan 13 23:58:50 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * hash.c (rb_f_setenv): name and value can be tainted.
-
-Wed Jan 6 02:42:08 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * bignum.c (Init_Bignum): forgot to define Bignum#===.
-
- * gc.c (gc_sweep): if add_heap() is called during GC, objects on
- allocated heap page(s) are not marked, should not be recycled.
-
- * gc.c (gc_sweep): should refer latest freelist.
-
- * gc.c (id2ref): modified to support performance patch.
-
- * object.c (rb_obj_id): performance patch (no bignum for id).
-
-Tue Jan 5 01:56:18 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * config.guess: merge up-to-date from autoconf 2.12.
-
- * array.c (rb_ary_join): avoid calling rb_protect_inspect() till
- it is really needed.
-
- * object.c (rb_obj_inspect): show detailed information for the
- instance variables (infinite loop can avoid now).
-
- * struct.c (rb_struct_inspect): avoid infinite loop.
-
-Sun Jan 3 01:37:58 1999 Takao KAWAMURA <kawamura@ike.tottori-u.ac.jp>
-
- * misc/ruby-mode.el (ruby-end-of-defun): moved too much.
-
- * misc/ruby-mode.el (ruby-mode-variables): set paragraph-separator
- for the mode.
-
- * misc/ruby-mode.el: proper font-lock for `def' and `nil' etc.
-
-Sat Jan 2 17:09:06 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_jump_tag): new api to invoke JUMP_TAG. tag values
- can obtained from rb_eval_string_protect()/rb_load_protect().
-
- * eval.c (rb_rescue): now catches all exceptions but SystemExit.
-
- * eval.c (rb_eval_string_protect): eval string with protection.
-
- * eval.c (rb_load_protect): load file with protection.
-
- * io.c (rb_io_puts): avoid infinite loop for cyclic arrays.
-
- * eval.c (rb_thread_local_aref): thread local hash tables.
-
- * object.c (rb_equal): check exact equal before calling `=='.
-
-Thu Dec 31 22:28:53 1998 MAEDA shugo <shugo@aianet.ne.jp>
-
- * eval.c (rb_f_require): feature names should be provided with
- DLEXT extension.
-
- * marshal.c (Init_marshal): need to provide `marshal.so'.
-
-Wed Dec 30 02:29:16 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * variable.c (classname): do not call rb_ivar_set().
-
- * eval.c (ruby_run): finalizers were called too early.
-
-Fri Dec 25 12:19:30 1998 Fukuda Masaki <fukuda@wni.co.jp>
-
- * gc.c (rb_gc_mark): should not return on FL_EXIVAR.
-
-Fri Dec 25 11:56:51 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * gc.c (gc_mark): proper scanning for temporary region.
-
- * eval.c (TMP_ALLOC): protection for C_ALLOCA was broken.
-
-Thu Dec 24 18:26:04 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * development version 1.3 released.
-
-Thu Dec 24 00:17:00 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_load): top self should be set properly.
-
- * variable.c (classname): check __classpath__ if it is defined.
-
- * variable.c (classname): invalid warning at -v with static linked
- ruby interpreter.
-
- * eval.c (is_defined): modified for expr::Const support.
-
- * eval.c (rb_eval): invoke method expr::Const if expr is not class
- nor module.
-
- * parse.y (primary): enable expr::identifier as method
- invocation.
-
-Wed Dec 23 03:04:36 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_match): avoid too many loop pops for (?:..).
-
-Tue Dec 22 18:01:08 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental version 1.1d1 released.
-
-Mon Dec 21 01:33:03 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (TMP_PROTECT): add volatile to ensure GC protection.
-
- * string.c (rb_str_gsub_bang): calculate buffer size properly.
-
- * parse.y (lex_get_str): needed to return Qnil at EOS.
-
- * eval.c (find_file): check policy modified, raise exception
- immediately for tainted load_path.
-
- * hash.c (rb_f_setenv): do not depend on setenv() nor putenv().
-
-Thu Dec 17 06:29:23 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/tk/tkutil.c (tk_s_new): use rb_obj_instance_eval(), instead
- of rb_yield_0().
-
- * eval.c (rb_f_require): forgot to call find_file in some cases.
-
- * eval.c (rb_f_require): `require "feature.so"' to load dynamic
- libraries. old `require "feature.o"' is still OK.
-
- * eval.c (rb_eval): yield without value dumped core.
-
-Wed Dec 16 16:28:31 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental version 1.1d0 (pre1.2) released.
-
-Wed Dec 16 10:43:34 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_search): bound check before calling re_match().
-
-Tue Dec 15 13:59:01 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * error.c (exc_to_s): returns class name for unset mesg.
-
- * error.c (exc_initialize): do not initialize @mesg by "".
-
- * parse.y (nextc): __END__ should handle CR+LF newlines.
-
-Wed Dec 9 13:37:12 1998 MAEDA shugo <shugo@aianet.ne.jp>
-
- * pack.c (encodes): use buffering for B-encoding.
-
- * pack.c (pack_pack): Q-encoding by 'M'.
-
-Tue Dec 8 14:10:00 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * variable.c (generic_ivar_get): any object can have instance
- variables now. great improvement.
-
- * variable.c (rb_name_class): do not set __classpath__ by default,
- use __classid__ instead.
-
-Mon Dec 7 22:08:22 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ruby.h (struct RFile): IO objects can have instance variables now.
-
- * parse.y (primary): allows `def obj::foo; .. end'.
-
-Mon Dec 7 18:24:50 1998 WATANABE Tetsuya <tetsu@jpn.hp.com>
-
- * ruby.c (set_arg0): $0 support for HP-UX.
-
-Mon Dec 7 01:30:28 1998 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * dln.c (dln_strerror): better error messages on win32.
-
-Sat Dec 5 23:27:23 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (here_document): indentable here-doc delimiter by
- `<<-'. Proposed by Clemens <c.hintze@gmx.net>. Thanks.
-
-Thu Dec 3 16:50:17 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/extmk.rb.in (realclean): trouble on install.
-
-Sun Nov 29 22:25:39 1998 Takaaki Tateishi <ttate@jaist.ac.jp>
-
- * process.c (f_exec): check number of argument.
-
-Thu Nov 26 17:27:30 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1c9 released.
-
-Wed Nov 25 13:07:12 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (rb_str_dup): do not copy additional data (STR_NO_ORIG).
-
- * parse.y (yycompile): reduce known memory leak (hard to remove).
-
-Wed Nov 25 03:41:21 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * st.c (st_init_table_with_size): round size up to prime number.
-
-Sat Nov 21 23:27:23 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * hash.c (rb_hash_aset): reduce copying key strings.
-
- * gc.c (looks_pointerp): declare as inline function if possible.
-
- * st.c (PTR_NOT_EQUAL): compare hash values first before calling
- comparing function.
-
- * st.c (ADD_DIRECT): save hash value in entries to reduce hash
- calculation.
-
- * string.c (rb_str_gsub_bang): avoid rb_scan_args() to speed-up.
-
- * string.c (rb_str_sub_bang): ditto.
-
-Sat Nov 21 18:44:06 1998 Masaki Fukushima <fukusima@goto.info.waseda.ac.jp>
-
- * time.c (time_s_now): had memory leak.
-
- * ext/md5/md5init.c (md5_new): had memory leak.
-
- * ext/md5/md5init.c (md5_clone): ditto.
-
-Fri Nov 20 23:23:23 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * lib/delegate.rb: do not propagate hash and eql?.
-
-Thu Nov 19 01:40:52 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * sample/ruby-mode.el (ruby-expr-beg): failed to find reserved
- word boundary.
-
- * eval.c (rb_eval): avoid calling `concat' method. calls
- rb_ary_concat() directly for efficiency.
-
- * eval.c (rb_eval): actual rest arguments extended arrays too much.
-
-Wed Nov 18 14:30:24 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * class.c (rb_define_global_function): global functions now be
- module function of the Kernel.
-
-Wed Nov 18 10:48:09 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (read_all): SEGV on large files.
-
-Tue Nov 17 18:11:20 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1c8 released.
-
-Tue Nov 17 16:58:47 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (arg): assignment to attribute name start with capital
- should be allowed.
-
- * eval.c (thread_alloc): needed to mark terminated threads too.
-
-Tue Nov 17 12:33:48 1998 Motoyuki Kasahara <m-kasahr@sra.co.jp>
-
- * ext/extmk.rb.in (create_makefile): Set `libdir' to `@libdir@',
- Set `pkglibdir' to `$libdir/$(RUBY_INSTALL_NAME)'.
-
-Tue Nov 17 10:30:46 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * sprintf.c (f_sprintf): %l%%c -> %%l%c
-
-Tue Nov 17 01:08:50 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (ret_args): distinguish `a' and `*a' for the arguments
- of yield and return.
-
- * eval.c (rb_eval): flip3 should work like sed.
-
- * eval.c (rb_eval): flip{2,3} now have independent state for each
- scope to work fine with thread.
-
-Mon Nov 16 23:26:29 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (primary): exec else clause if no exception raised.
-
-Sun Nov 15 15:44:07 1998 Tadayoshi Funaba <tadf@kt.rim.or.jp>
-
- * ext/extmk.rb.in (install): bug in target.
-
-Sat Nov 14 11:02:05 1998 Motoyuki Kasahara <m-kasahr@sra.co.jp>
-
- * Makefile.in (install): Give the argument `$(DESTDIR)' to
- `instruby.rb'.
-
- * instruby.rb: Recognize ARG[0] as `destdir'.
-
- * instruby.rb: Give the argument `destdir' to `extmk.rb'.
-
- * ext/extmk.rb.in: Recognize ARG[1] as `$destdir'.
-
- * instruby.rb: Create the installation directories (bindir, libdir,
- archdir, pkglibdir, archdir, and mandir) under `destdir', and
- install all files under there.
-
- * ext/extmk.rb.in: Likewise.
-
-Sat Nov 14 10:56:55 1998 Motoyuki Kasahara <m-kasahr@sra.co.jp>
-
- * instruby.rb: Add the variable `pkglibdir'.
-
- * instruby.rb: Set the variable `libdir' to `$(libdir)', not
- `$(libdir)/$(ruby_install_name)'. `libruby.so' and `libruby.so.LIB'
- are installed at `libdir'.
-
- * instruby.rb: Set the variable `archdir' to `$(pkglibdir)/$(arch)'.
-
-Fri Nov 13 19:43:29 1998 KIMURA Koichi <kbk@kt.rim.or.jp>
-
- * missing/nt.c (SafeFree): wrong free offset.
-
-Thu Nov 12 20:11:53 1998 Koji Arai <JCA02266@nifty.ne.jp>
-
- * sample/ruby-mode.el: wrong highlight.
-
- * parse.y (parse_regx): newline in regexp was ignored.
-
-Wed Nov 11 10:54:57 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (here_document): <<'FOO' should not escape anything.
-
- * parse.y (here_document): bare << here-doc available, even though
- it's deprecated.
-
- * file.c (rb_file_s_readlink): return value should be tainted.
-
- * ext/etc/etc.c (setup_passwd): information (eg. GCOS name) should
- be tainted (modified at Perl Conference).
-
-Tue Nov 10 00:22:11 1998 EGUCHI Osamu <eguchi@shizuokanet.ne.jp>
-
- * configure.in: elf support for FreeBSD 3.x
-
-Tue Nov 10 00:05:43 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (yylex): here document available in eval.
-
-Mon Nov 9 17:55:19 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1c7 released.
-
-Fri Nov 6 19:25:27 1998 Takao KAWAMURA <kawamura@ike.tottori-u.ac.jp>
-
- * sample/ruby-mode.el: font-lock patch.
-
-Thu Nov 5 15:42:22 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * sample/README, lib/README: simple description for each file.
-
-Wed Nov 4 18:14:19 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (assign): attribute assignment should be called as public.
-
-Tue Nov 3 23:36:39 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (rb_str_dump): dumps core for negative char value.
-
- * regex.c (re_compile_pattern): out of boundary access for empty
- regexp.
-
-Mon Nov 2 22:54:01 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (rb_str_aset): `str[str]' replaces first match.
-
-Mon Nov 2 18:24:33 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (thread_create): was accessing modified status.
-
-Sun Nov 1 01:18:52 1998 EGUCHI Osamu <eguchi@shizuokanet.ne.jp>
-
- * gc.c (xrealloc): size 0 needs round up to 1.
-
-Sat Oct 31 23:18:34 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (rb_str_split_method): negative LIMIT means number of
- split fields are unlimited, as in perl.
-
- * string.c (rb_str_split_method): if LIMIT is unspecified,
- trailing null fields are stripped.
-
-Sat Oct 31 04:16:14 1998 Inaba Hiroto <inaba@st.rim.or.jp>
-
- * string.c (str_aref): regexp index SEGVed.
-
-Fri Oct 30 14:33:47 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * re.c (reg_match): returns nil for unmatch.
-
- * dir.c (dir_entries): new method.
-
- * eval.c (block_pass): do not push block, substitute it.
-
-Fri Oct 30 01:28:52 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * range.c (range_check): avoid <=> check for Fixnums.
-
- * array.c (rb_ary_aset): accept negative index.
-
-Wed Oct 28 22:00:54 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_match): access out of boundary fixed.
-
-Wed Oct 28 11:37:42 1998 TAMITO <tommy@valley.ne.jp>
-
- * io.c (f_select): fd number comparison bug.
-
-Tue Oct 27 23:07:11 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * sample/ruby-mode.el (ruby-parse-region): forgot to support %w()
- style array literal.
-
- * eval.c (rb_eval): unused block raises warning.
-
-Mon Oct 26 09:37:53 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (dvar_asgn_push): dvar pushed too many times if
- variable-in-block first appear in loops.
-
-Sun Oct 25 22:59:27 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (set_list_bits): was using wrong offset.
-
-Thu Oct 22 00:07:11 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_obj_method): method retrieved from tainted object
- should be tainted too.
-
- * eval.c (method_call): safe_level should be restored during
- Method#call.
-
-Wed Oct 21 14:21:06 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (Init_IO): new constants IO::SEEK_{SET,CUR,END}.
-
- * io.c (rb_f_ungetc): ungetc pushes a char back into STDIN.
-
-Mon Oct 19 11:50:00 1998 Motoyuki Kasahara <m-kasahr@sra.co.jp>
-
- * ext/extmk.rb: Load '@top_srcdir@/lib/find.rb', not
- '../lib/find.rb'.
-
- * ext/extmk.rb: Distinguish between `top_srcdir' and `topdir'.
-
- * Makefile.in (CFLAGS): Add `-I.'.
-
- * Makefile.in (lex.c): Give `@srcdir@/keywords' to gperf, not
- `keywords'.
-
- * instruby.rb: Use `CONFIG["bindir"]', instead of `prefix + "/bin"'.
-
- * instruby.rb: Use `CONFIG["libdir"]', instead of `prefix + "/lib"'.
-
- * instruby.rb Use `CONFIG["mandir"]', instead of `prefix + "/man"'.
-
- * instruby.rb (wdir): Add the variable to preserve the current
- working directory.
-
- * instruby.rb: Chdir to wdir before install `config.h' and
- `rbconfig.rb'.
-
-Mon Oct 19 10:07:01 1998 EGUCHI Osamu <eguchi@shizuokanet.ne.jp>
-
- * eval.c (rb_eval): reduce recursive calls to rb_eval().
-
-Fri Oct 16 15:31:45 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * time.c (time_new_internal): timeval must be positive.
-
-Thu Oct 15 13:54:48 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (arg): local variables can be accessed within right side
- expression in assignment, notably in blocks.
-
-Wed Oct 14 00:18:33 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * array.c (Init_Array): Array#=== is now for equal check, not
- inclusion check.
-
- * parse.y (when_args): `when a, *b' style new syntax for array
- expansion in `case'.
-
-Tue Oct 13 14:30:32 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * object.c (rb_obj_untaint): taint marks can be unset.
-
- * eval.c (rb_eval): taint propagation for embedded strings.
-
-Mon Oct 12 13:27:15 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_call0): check stack depth more frequently.
-
-Mon Oct 12 08:08:30 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (rb_p): can print even in secure mode.
-
-Sun Oct 11 22:50:13 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * variable.c (rb_const_set): taint check for modification.
-
- * variable.c (rb_ivar_set): taint check for modification.
-
- * string.c (rb_str_modify): taint check for modification.
-
- * hash.c (rb_hash_modify): taint check for modification.
-
- * array.c (rb_ary_modify): taint check for modification.
-
- * ruby.h (FL_TAINT): taint for all objects, not only strings.
-
-Fri Oct 9 17:01:14 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (read_all): read() returns "" at immediate EOF.
-
- * io.c (io_read): read(nil) read all until EOF.
-
-Thu Oct 8 13:32:13 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * time.c (time_dump): marshal can dump Time object now.
-
- * marshal.c (Init_marshal): rename marshal methods `_dump_to' to
- `_dump', `_load_from' to `_load'.
-
- * parse.y (rb_intern): "+=".intern generates proper symbol.
-
-Mon Oct 5 18:31:53 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1c6 released.
-
-Fri Oct 2 14:22:33 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_search): `/\s*(--)$/ =~ "- --"' did not match,
- because of wrong optimize condition.
-
-Mon Oct 1 01:55:16 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (rb_intern): should not raise exceptions.
-
- * parse.y (yylex): symbol like `:foo?=' should not be allowed.
-
- * ext/extmk.rb.in: makes *.a for static link modules.
-
-Wed Sep 30 14:13:06 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_thread_start): supports making a subclass of the
- Thread class.
-
-Tue Sep 29 17:46:01 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_thread_join): join is now an instance method.
-
-Fri Sep 25 12:01:19 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (yylex): `@foo!' should be an error.
-
-Thu Sep 24 14:55:06 1998 WATANABE Tetsuya <tetsu@jpn.hp.com>
-
- * ext/etc/etc.c (Init_etc): wrong field definition.
-
-Thu Sep 17 17:09:05 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (io_reopen): was creating FILE* for wrong fd.
-
-Tue Sep 15 05:28:11 1998 Koji Arai <JCA02266@nifty.ne.jp>
-
- * regex.c (re_compile_pattern): forgot to fixup for the pattern
- like (?=(A)|(B)).
-
-Tue Sep 15 01:06:08 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (rb_io_gets_internal): do not set $_ by default, only
- gets/readline set the variable.
-
- * eval.c (rb_f_load): load toplevel class is set to anonymous
- module if safe_level >= 5, to encapsulate modification.
-
- * eval.c (rb_f_load): set frame properly.
-
- * string.c (rb_str_each_line): do not set $_.
-
-Mon Sep 14 14:42:27 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_match): beginning and end of the string, do not
- automatically match `\b'.
-
- * string.c (scan_once): consume at least on character.
-
- * regex.c (re_search): wrong behavior for negative range.
-
-Sat Sep 12 21:21:26 1998 Koji Arai <JCA02266@nifty.ne.jp>
-
- * regex.c (re_search): range value should be maintained.
-
-Thu Sep 10 10:55:00 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (backref_error): yyerror does not understand formats.
-
-Tue Sep 8 18:05:33 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1c5 released.
-
-Tue Sep 8 10:03:39 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (str_each_line): wrong line splitting with newline at
- top of the string.
-
- * string.c: non bang methods return copied string.
-
- * eval.c (f_END): needed to initialize frame->argc;
-
-Fri Sep 4 11:27:40 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * bignum.c (bigadd): proper sign combination.
-
- * regex.c (re_search): wrong return value for \A.
-
-Thu Sep 3 14:08:14 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1c4 released.
-
-Tue Sep 1 10:47:16 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (slow_search): do not compare llen and blen. llen may
- be longer than blen, if little contains 0xff.
-
- * regex.c (mbctab_euc): set 0x8e as multibyte character.
-
- * string.c (str_inspect): mask character for octal output.
-
-Mon Aug 31 15:32:41 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_search): use calculated offset if exactn is the
- first opcode in the compiled regexp.
-
- * regex.c (bm_search): use Boyer-Moore search for simple search.
-
- * regex.c (must_instr): wrong length check if pattern includes
- byte escape by 0xff.
-
- * regex.c (re_compile_pattern): need not to check current_mbctype.
-
-Sat Aug 29 16:31:40 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_check_safe_str): avoid calling rb_id2name() in normal
- cases to speed-up.
-
- * eval.c (thread_raise): do not save context of terminated thread.
-
- * regex.c (re_compile_pattern): mask \nnn over 256.
-
-Sat Aug 29 02:09:46 1998 Koji Arai <JCA02266@nifty.ne.jp>
-
- * sprintf.c (f_sprintf): wrong buffer size check.
-
-Fri Aug 28 01:57:04 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_compile_pattern): accepts (?ix-ix) and (?ix-ix:...).
-
-Fri Aug 28 12:25:33 1998 Hiroshi Igarashi <igarashi@ueda.info.waseda.ac.jp>
-
- * ruby.c (ruby_require_modules): load modules in appearing order.
-
-Fri Aug 28 01:57:04 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_compile_pattern): accepts (?ix-ix) and (?ix-ix:...).
-
-Thu Aug 27 12:54:28 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1c3 released.
-
-Wed Aug 26 14:40:56 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_eval): check whether ruby_class is properly set,
- before accessing it.
-
- * eval.c (rb_obj_instance_eval): ruby_class should be Qnil for
- special objects like Fixnums.
-
- * ext/tkutil/tkutil.c (Init_tkutil): removes calls to
- rb_yield_0(). used instance_eval() instead in the tk.rb.
-
-Wed Aug 26 11:47:00 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_match): pop non-greedy stack elements on success.
-
-Wed Aug 26 09:25:35 1998 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * ruby.h: add #define environ for cygwin32.
-
-Tue Aug 25 08:57:41 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * array.c (rb_ary_sort_bang): temporarily freeze sorting array.
-
-Mon Aug 24 18:46:44 1998 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * dln.c (dln_find_1): path check was too strict.
-
-Mon Aug 24 15:28:11 1998 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * parse.y (f_arglist): opt_nl added after f_args.
-
-Fri Aug 21 01:06:01 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/socket/socket.c: grand renaming on socket.c.
-
- * ext/socket/socket.c (inet_aton): supply inet_aton for those
- systems that do not have it.
-
- * ext/socket/socket.c (setipaddr): use inet_aton instead of
- inet_addr.
-
- * ext/socket/socket.c (tcp_s_gethostbyname): new method: works
- like Socket.gethostbyname but returning array contains ip-addrs
- as octet decimal string format like "127.0.0.1".
-
- * ext/socket/socket.c (mkhostent): return format changed to
- [host, aliases, type, ipaddr..] as documented.
-
-Wed Aug 19 00:31:09 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (io_ctl): forgot to place TRAP_END at right position.
-
-Fri Aug 14 11:01:47 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (call_trace_func): save __FILE__, __LINE__ before
- executing trace_func, since trace function should not corrupt
- line number information.
-
-Thu Aug 13 15:09:02 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * array.c (ary_s_new): was marking unallocated region on GC.
-
-Tue Aug 11 11:57:35 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1c2 released.
-
-Mon Aug 10 14:05:30 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * process.c (f_system): removed fflush(stdin).
-
-Fri Aug 7 17:44:44 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * error.c (err_snprintf): replace sprintf for fixed sized buffer,
- with snprintf to avoid buffer over-run. For systems which does
- dot provide snprintf, missing/snprintf.c added.
-
-Wed Aug 5 00:47:35 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * re.c (rb_reg_search): recycle match object.
-
-Mon Aug 3 09:17:55 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (rb_str_gsub_bang): do not allocate temporary string.
-
- * string.c (rb_str_sub_bang): use inline replace.
-
-Wed Jul 29 00:36:08 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * hash.c (hash_s_new): the default value can be specified.
-
- * hash.c (hash_default): method to set the default value.
-
- * hash.c (hash_aref): now returns the default value.
-
-Tue Jul 28 13:03:25 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * array.c (ary_s_new): argument to specify initial value is added.
-
- * array.c (ary_s_new): specifies size, not capacity.
-
-Mon Jul 27 12:39:34 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (str_replace): zero fill for expansion gap.
-
- * regex.c (mbctab_euc): set flags on for 0xA1-0xFE. suggested by
- <inaba@st.rim.or.jp>.
-
- * string.c (str_inspect): consider current_mbctype.
-
-Sun Jul 26 15:37:11 1998 Tadayoshi Funaba <tadf@kt.rim.or.jp>
-
- * array.c (ary_s_new): Array.new(1<<30) dumps core.
-
-Fri Jul 24 13:40:19 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1c1 released.
-
-Fri Jul 24 02:10:22 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * marshal.c (r_bytes2): allocated buffer size was too short.
-
- * marshal.c (w_object): saves all options, not only casefold flag.
-
- * re.c (reg_clone): now copies options properly.
-
- * re.c (reg_get_kcode): code number was wrong.
-
-Thu Jul 23 13:11:32 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_attr): argument should be symbol or string.
-
-Wed Jul 22 11:59:34 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (calculate_must_string): wrong offset added.
-
-Wed Jul 22 11:59:59 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * st.c (rehash): still had a GC problem. fixed.
-
-Tue Jul 21 13:19:30 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (gc_mark_threads): crashed on GC before thread allocation.
-
- * st.c (rehash): GC during rehash caused SEGV.
-
-Tue Jul 21 01:25:10 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * sprintf.c (f_sprintf): integer formatter totally re-written.
-
- * sprintf.c (remove_sign_bits): support uppercase hexadecimal.
-
-Sat Jul 18 00:14:13 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * sprintf.c (f_sprintf): proper sign position for %X and %O.
-
-Fri Jul 17 14:10:20 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1c0 released.
-
-Fri Jul 17 08:01:49 1998 Tadayoshi Funaba <tadf@kt.rim.or.jp>
-
- * process.c (f_exec): Check_SafeStr() added.
-
- * process.c (f_system): Check_SafeStr() moved before fork().
-
-Thu Jul 16 22:58:48 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (scan_once): substrings to the block should not be
- tainted. use reg_nth_match(), not str_substr().
-
- * string.c (str_substr): needed to transfer taint.
-
-Thu Jul 16 16:15:57 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * gc.c (xmalloc): object allocation count added to GC trigger.
-
- * eval.c (thread_save_context): avoid marking uninitialized stack
- in thread_mark. GC may be triggered by REALLOC_N().
-
-Wed Jul 15 15:11:57 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_31.
-
-Wed Jul 15 15:05:27 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (thread_create): exit() and abort() in threads now
- forwarded to main_thread.
-
-Tue Jul 14 14:03:47 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * variable.c (obj_instance_variables): list names that is not
- instance variables.
-
- * gc.c (GC_MALLOC_LIMIT): choose smaller limit value.
-
-Mon Jul 13 12:39:38 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * object.c (str2cstr): should not return NULL.
-
-Fri Jul 10 11:51:46 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (gettable): needed to add dyna_in_block() check.
-
-Thu Jul 9 17:38:23 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_30.
-
-Thu Jul 9 16:01:48 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * sprintf.c (fmt_setup): format specifier for long needed.
-
- * sprintf.c (f_sprintf): ditto.
-
- * numeric.c (fix2str): ditto.
-
- * eval.c (thread_create): no more ITIMER_REAL.
-
- * eval.c (thread_create): thread finalization needed before
- aborting thread if thread_abort is set.
-
-Wed Jul 8 18:17:33 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * bignum.c (big_pow): abandon power by bignum (too big).
-
-Tue Jul 7 13:58:43 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_catch): add C level catch/throw feature.
-
-Mon Jul 6 15:18:09 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (arg): proper return values for `||=' and `&&='.
-
-Fri Jul 3 16:05:11 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_29.
-
-Fri Jul 3 11:20:46 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * marshal.c (r_byte): byte should not extend sign bit.
-
- * numeric.c (fix_mul): use FIX2LONG() instead of FIX2INT() for
- 64bit architectures.
-
- * marshal.c (r_bytes): remove weird casting between pointer and int.
-
- * process.c (proc_setsid): new method Process#setsid().
-
-Thu Jul 2 12:49:21 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * marshal.c (w_object): remove `write_bignum' label for 64bit
- architectures.
-
- * marshal.c (r_bytes): needs int, not long.
-
-Wed Jul 1 14:21:06 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * numeric.c (flo_plus): should not allow addition with strings.
-
-Wed Jul 1 13:09:01 1998 Keiju ISHITSUKA <keiju@rational.com>
-
- * numeric.c (num_uminus): wrong coerce direction.
-
-Tue Jun 30 10:13:44 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (f_p): accepts arbitrary number of arguments.
-
- * eval.c (rb_yield_0): there's some case that iterator_p() returns
- true even if the_block was not set. check added.
-
-Tue Jun 30 01:05:20 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (BEGIN_CALLARGS): adjust the_block before evaluating the
- receiver's value and the arguments.
-
-Fri Jun 26 18:02:50 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_28.
-
-Fri Jun 26 11:01:26 1998 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * string.c (str_aset_method): needed to convert to string.
-
-Thu Jun 25 02:05:50 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_search): optimize for `.*' at beginning of the
- pattern.
-
- * regex.c (re_search): optimize for character class repeat at
- beginning of the pattern.
-
- * regex.c (re_compile_pattern): detect optimization potential for
- the compiled patterns.
-
-Thu Jun 25 00:02:26 1998 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * re.c (reg_s_new): flag value was wrong.
-
-Wed Jun 24 23:45:06 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_search): wrong anchor handling for reverse search.
-
-Wed Jun 24 02:18:57 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (mlhs): `((a,b)),c = [[1,2]],3' assigns a=1,b=2,c=3.
-
-Tue Jun 23 11:46:16 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (yylex): `&&=' and `||=' added.
-
-Sat Jun 20 02:53:50 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (assignable): nesting local variables should have higher
- priority than normal local variables for assignment too.
-
-Fri Jun 19 18:28:19 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_27.
-
-Fri Jun 19 14:34:49 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (assign): support hack for nested multiple assignment.
-
- * parse.y (mlhs): nested multiple assignment.
-
- * eval.c (rb_eval): in-block variables now honors static scope.
-
- * configure.in: RSHIFT check moved to configure.
-
-Thu Jun 18 16:46:04 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_26.
-
-Thu Jun 18 13:37:19 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * file.c (file_s_ftype): uses lstat(2) instead of stat(2).
-
- * dir.c (dir_s_glob): there can be buffer overrun, check added.
-
- * eval.c (f_binding): handles in-block variables declared after
- binding's generation.
-
- * numeric.c (flo_floor): floor, ceil, round added to Float.
-
-Wed Jun 17 11:20:00 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (gettable): nesting local variables should have higher
- priority than normal local variables.
-
-Tue Jun 16 12:30:46 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * bignum.c (str2inum): handles `+ddd'.
-
- * struct.c (make_struct): name parameter can be nil for unnamed
- structures.
-
-Mon Jun 15 16:30:10 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * object.c (class_s_inherited): prohibiting to make subclass of
- class Class.
-
- * object.c (module_s_new): support for making subclass of Module.
-
- * parse.y (yycompile): clear eval_tree before compiling.
-
-Fri Jun 12 17:58:18 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (eval): write back the_dyna_var into the block.
-
-Thu Jun 11 18:19:18 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_25.
-
- * eval.c (dvar_add_compiling): register dyna_var at compile time.
-
- * regex.c (re_compile_pattern): RE_DUP_MAX iteration is too big.
-
-Wed Jun 10 15:12:04 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (io_eof): do not block other threads.
-
- * signal.c (trap): reserve SIGALRM for thread.
-
- * eval.c (thread_create): use ITIMER_REAL also to avoid system
- call blocking.
-
- * io.c (f_syscall): add TRAP_BEG, TRAP_END around system calls.
-
- * io.c (io_ctl): add TRAP_BEG, TRAP_END around system calls.
-
- * enum.c (enum_collect): did not collect false values.
-
- * array.c (ary_new2): forgot to initialize capa field.
-
-Tue Jun 9 18:36:15 1998 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * string.c (str_split_method): split dumped core for "\xff".
-
-Tue Jun 9 16:22:12 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_24.
-
-Tue Jun 9 16:04:07 1998 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * ext/kconv/kconv.c (kconv_guess): more precise decision for EUC,
- using jless algorithm (3 sequential EUC hiragana characters).
-
-Tue Jun 9 15:12:44 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/kconv/kconv.c (kconv_guess): wrong guess for EUC as SJIS in
- some cases (0xe0 - 0xef).
-
- * gc.c (xmalloc): insert size check for big (negative in signed)
- allocation size.
-
-Tue Jun 9 02:54:51 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * lib/parsedate.rb: wday moved to the last in the return values.
-
-Mon Jun 8 10:40:16 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (str_split_method): split dumped core for "\0".
-
-Sat Jun 6 22:50:52 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (calculate_must_string): wrong condition for
- {start,stop}_nowidth.
-
- * regex.c (re_match): various features imported from GNU regex.c
- 0.12, such as nested grouping, avoiding infinite loop with empty
- match, etc.
-
- * regex.c (register_info_type): now use union.
-
- * regex.c (re_search): more precise anchor(^) check.
-
-Wed Jun 3 18:07:54 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * re.c (reg_raise): check rb_in_compile, not rb_in_eval.
-
-Mon Jun 1 05:26:06 1998 WATANABE Tetsuya <tetsu@jpn.hp.com>
-
- * string.c (trnext): casting to signed char* needed.
-
-Tue Jun 2 16:00:12 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/socket/socket.c (udp_addrsetup): error check enhanced.
-
- * ext/socket/socket.c (sock_s_getservbyaname): use strtoul(), if
- possible.
-
-Sat May 30 07:10:02 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * re.c (reg_prepare_re): no more needless regular expression
- recompile on casefold conditions.
-
-Thu May 28 18:02:55 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * object.c (nil_plus): no more `+' method for nil.
-
-Wed May 27 17:33:46 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * hash.c (hash_fetch): new method.
-
- * regex.c (re_search): check whether translate table is set.
-
-Tue May 26 11:39:50 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_23.
-
- * parse.y (yylex): no UPLUS/UMINUS for 1st argument if
- parenthesises are omitted.
-
-Tue May 26 01:09:55 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_compile_pattern): (?XI) for turns off the
- corresponding option.
-
-Mon May 25 12:38:56 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_compile_pattern): inline i option (?i).
-
- * regex.c (re_compile_pattern): inline x option (?x).
-
- * regex.c (re_compile_pattern): x option for regexp.
-
- * dir.c (dir_s_open): returns block's evaluated value.
-
- * io.c (f_open): returns block's evaluated value.
-
- * ext/curses/curses.c (curses_addstr): nil argument caused SEGV.
-
-Fri May 22 11:52:45 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_compile_pattern): push mark on (?:), so that
- laststart check for {a,b} can be done.
-
-Thu May 21 17:31:16 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_match): wrong match (too non-greedy) for `{a,b}?'.
-
- * io.c (io_lineno): new method IO#lineno, IO#lineno=.
-
-Wed May 20 06:04:43 1998 MAEDA shugo <shugo@aianet.ne.jp>
-
- * BeOS patch.
-
-Wed May 20 16:32:19 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * bignum.c (BIGDN): use RSHIFT(), instead of mere `>>'.
-
-Tue May 19 16:36:26 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_22.
-
-Tue May 19 16:31:57 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (assignable): specification changed for in-block
- variable definition.
-
- * eval.c (dyna_var_asgn): error in in-block variables' compile
- time definition.
-
- * parse.y (str_extend): wrong nesting detection.
-
-Tue May 19 09:47:55 1998 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * numeric.c (num2int): re-defined (extensions may use this).
-
-Mon May 18 16:40:50 1998 MAEDA shugo <shugo@aianet.ne.jp>
-
- * error.c (get_syserr): BeOS support.
-
- * configure.in: modified for BeOS.
-
- * string.c (str_dump): do not call isascii().
-
- * sprintf.c (remove_sign_bits): forgot to initialize end pointer.
-
- * glob.c: #include <alloca.h> added.
-
-Mon May 18 14:52:21 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_21.
-
-Mon May 18 03:27:57 1998 MAEDA shugo <shugo@aianet.ne.jp>
-
- * file.c (file_s_expand_path): optional second argument
- `default_directory' added.
-
-Sat May 16 22:06:52 1998 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * error.c (RAISE_ERROR): wrong error message
-
-Fri May 15 14:43:25 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_20.
-
-Thu May 14 14:44:21 1998 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * sun4 cc patches for intern.h and regex.h.
-
-Thu May 14 14:03:16 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * random.c (RANDOM_MAX): guessing proper maximum value for random
- numbers.
-
- * random.c (f_rand): use drand48 if possible.
-
-Wed May 13 19:05:20 1998 MAEDA shugo <shugo@aianet.ne.jp>
-
- * BeOS patches for io.c, error.c and config.guess.
-
-Wed May 13 14:56:23 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_19.
-
- * most of the Mac and BeOS patches merged, except path separators.
-
- * error.c (err_append): generated SyntaxError was String.
-
- * ruby.h: xxx2INT, xxx2UINT checks values as int, not long.
-
- * ruby.h: remove typedef's. INT, UINT, UCHAR, USHORT.
-
-Tue May 12 17:38:00 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_18.
-
-Tue May 12 11:38:08 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * error.c (syserr_errno): returns errno of the SystemCallError.
-
- * error.c (rb_sys_fail): saves errno in the Exception.
-
- * error.c (set_syserr): no need to protect syserr_list.
-
- * error.c (rb_sys_fail): no more bufsize limit.
-
- * error.c (set_syserr): integer value of errno can be accessed by
- Errno::EXXX::Errno.
-
-Sun May 10 03:10:33 1998 WATANABE Tetsuya <tetsu@jpn.hp.com>
-
- * io.c (io_tell etc.): moved from File class to IO class.
-
-Fri May 8 12:26:37 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * pack.c (pack_unpack): should be unsigned int (was signed int).
-
-Thu May 7 16:34:10 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * pack.c (pack_pack): `V', `N' uses newly created NUM2UINT().
-
- * ruby.h (NUM2UINT): new macro.
-
- * bignum.c (big2uint): try to convert bignum into UINT.
-
- * re.c (reg_match): needed to return false for match with nil.
-
- * gc.c (obj_free): wrong condition to free string.
-
-Wed May 6 21:08:08 1998 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * ruby.c (ruby_process_options): modified for DJGPP.
-
-Wed May 6 15:48:03 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_17.
-
-Wed May 6 01:37:39 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c: remove global variable `errat'.
-
- * eval.c (rb_longjmp): embed error position information in the
- exception object.
-
-Sat May 2 12:20:02 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * re.c (reg_search): supports reverse search.
-
- * string.c (str_index_method): does update $~ etc.
-
- * eval.c (f_load): needed to clear the_dyna_vars.
-
- * eval.c (dyna_var_asgn): do not push dyna_var, which is id == 0.
-
- * error.c (Init_Exception): NotImplementError is no longer
- StandardError, which is not handled by default rescue.
-
-Fri May 1 00:35:51 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ruby.c (proc_options): `-d' turns on verbose flag too.
-
- * error.c (exception): last argument may be the superclass of the
- defining exception(s).
-
- * io.c (Init_IO): EOFError is now subclass of the IOError.
-
- * io.c (Init_IO): forgot to define IOError.
-
- * error.c (Init_Exception): old Exception class renamed to
- StandardError. Exception now replaces old GlobalExit.
-
- * error.c (Init_Exception): Exception is now the root of the
- Global Exits. There's no longer GlobalExit class.
-
- * util.c (ruby_mktemp): check TMP, TMPDIR first.
-
-Thu Apr 30 01:08:35 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * lib/tk.rb: call 'unknown', if proc not defined.
-
- * eval.c (handle_rescue): default rescue handles `Exceptional' not
- only the instance of the `Exception's.
-
- * eval.c (f_raise): exception can be any object.
-
- * time.c (time_gm_or_local): call time_gmtime or time_localtime.
-
- * eval.c (f_raise): raises TypeError if the class which is not a
- subclass of String is specified (checked in exc_new()).
-
- * error.c (exc_new): need to check whether invalid class (not a
- subclass of String) is specified.
-
-Wed Apr 29 21:05:44 1998 WATANABE Hirofumi <eban@os.rim.or.jp>
-
- * ruby.c (proc_options): option '-e' via tempfile.
-
-Tue Apr 28 15:27:58 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_16.
-
-Tue Apr 28 00:07:38 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (obj_is_proc): type check predicate.
-
- * eval.c (obj_is_block): ditto.
-
-Mon Apr 27 16:59:17 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/gtk/gtk.c (Init_gtk): use timeout, not idle to avoid
- consuming CPU too much.
-
- * lib/tk.rb: use tcltklib#_invoke instead of `_eval'.
-
-Mon Apr 27 16:59:17 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * array.c (ary_sort): use dup, not clone.
-
-Mon Apr 27 13:46:27 1998 Tadahiro Maebashi <maebashi@iij.ad.jp>
-
- * ext/tcltklib/tcltklib.c (ip_invoke): invoke tcl command
- directly. need not worry about escaping tcl characters.
-
-Mon Apr 27 12:04:43 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * random.c (f_rand): do not call srand() implicitly.
-
-Fri Apr 24 14:35:45 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_15.
-
- * parse.y (assignable): dyna_var_asgn actually defines nested
- local variables in outer context.
-
- * random.c (f_rand): call srand(), if it has not called yet.
-
- * random.c (f_srand): use tv_usec as the default seed.
-
- * eval.c (rb_eval): values of nested local variables should be
- independent.
-
- * eval.c (rb_yield_0): local variables wrong nested conditions.
-
-Wed Apr 22 23:27:17 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (select_get_io): get IO object by `to_io'.
-
- * io.c (io_to_io): method to retrieve IO object, from delegating
- object for example.
-
-Wed Apr 22 16:52:37 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_14.
-
- * string.c (str_modify): check for embedded pointer reference.
-
- * gc.c (obj_free): ditto.
-
- * pack.c (pack_pack): p/P template to embed pointers.
-
-Wed Apr 22 00:07:10 1998 Tadayoshi Funaba <tadf@kt.rim.or.jp>
-
- * array.c (ary_rindex): embarrassing typo.
-
-Tue Apr 21 12:31:48 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_13.
-
- * configure.in (RUBY_LIB): supports --program-{prefix,suffix}.
-
- * array.c (ary_rindex): new method.
-
- * io.c (io_binmode): should return self.
-
-Tue Apr 21 08:23:04 1998 Tadayoshi Funaba <tadf@kt.rim.or.jp>
-
- * parse.y (here_document): calling parse_string with wrong
- arguments.
-
- * struct.c (struct_aset): problem member assignment with name.
-
-Mon Apr 20 14:47:49 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_12.
-
- * time.c (time_arg): args may be string (support for reduced
- implicit type conversion).
-
- * lib/base64.rb: changed to use pack/unpack with `m' template.
-
-Mon Apr 20 06:23:20 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * variable.c (mod_remove_const): new method.
-
-Sat Apr 18 03:53:27 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * hash.c (hash_each_with_index): removed. use Enumerable's
- each_with_index instead.
-
- * class.c (rb_include_module): check for super modules, since
- module's included modules may be changed.
-
-Fri Apr 17 21:50:47 1998 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * marshal.c (r_long): r_byte() may return signed byte.
-
-Fri Apr 17 11:58:30 1998 NAGAI Hidetoshi <nagai@dumbo.ai.kyutech.ac.jp>
-
- * ext/tcltklib/tcltklib.c (lib_mainloop): thread and interrupt check.
-
-Fri Apr 17 11:06:30 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (find_file): try to fopen() to check whether file exists.
-
- * ruby.c (load_file): ditto.
-
- * struct.c (struct_aset): struct member can be set by member name.
-
-Fri Apr 17 00:47:19 1998 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * ext/extmk.rb.in: added m68k-human support
-
- * file.c (LOCK_SH): defines moved.
-
- * array.c (ary_flatten_bang): simplified loop.
-
-Thu Apr 16 16:52:01 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_11.
-
- * lib/tk.rb: thread support (experimental - maybe slow).
-
- * eval.c (rb_longjmp): trace event on exception in raising
- context, just before raising exception.
-
- * struct.c (struct_s_members): forgot to check singletons.
-
- * struct.c (struct_aref): members can be accessed by names too.
-
- * array.c (ary_flatten): new method.
-
- * eval.c (rb_longjmp): prints exception information with `-d'.
-
- * object.c (any_to_s): remove class name restriction.
-
-Thu Apr 16 01:38:02 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * file.c (thread_flock): do not block other threads.
-
- * eval.c (thread_trap_eval): signals are now delivered to the
- current thread again. In case that the current thread is dead,
- signals are forwarded to the main thread.
-
- * string.c (str_new4): need not to duplicate frozen strings.
-
-Wed Apr 15 08:33:47 1998 Tadayoshi Funaba <tadf@kt.rim.or.jp>
-
- * struct.c (struct_inspect): remove restriction for struct names.
-
-Wed Apr 15 02:55:02 1998 Kazuya 'Sharl' Masuda <sharl@www.ufo.co.jp>
-
- * x68 patches to config.sub, ext/extmk.rb.in
-
-Wed Apr 15 01:22:56 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (str_dup_frozen): do not duplicate frozen strings.
-
- * parse.y (yylex): allow nested parenthesises.
-
- * io.c (obj_displayln): prints newline after `display'ing the
- receiver.
-
- * io.c (io_puts): avoid generating "\n" each time. use RS_default
- instead.
-
- * io.c (f_p): ditto.
-
-Tue Apr 14 22:18:17 1998 Tadayoshi Funaba <tadf@kt.rim.or.jp>
-
- * struct.c (struct_aref): should not subtract negative index.
-
-Tue Apr 14 11:34:50 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_10.
-
- * parse.y: token names prefixed by `t'.
-
- * struct.c (struct_s_def): supports subclassing of Struct.
-
- * io.c (io_s_new): supports subclassing of IO.
-
-Mon Apr 13 11:07:39 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (f_binding): need to restore method name.
-
- * eval.c (rb_call0): raises SystemStackError, not Fatal.
-
- * io.c (obj_display): same as `print self'.
-
- * io.c (f_p): can now be called in the method form.
-
- * re.c (reg_regsub): needed to be mbchar aware.
-
-Mon Apr 13 13:18:32 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (thread_trap_eval): all signals delivered to main_thread.
-
-Mon Apr 13 12:47:03 1998 TAKAHASHI Masayoshi <maki@inac.co.jp>
-
- * re.c (kcode_set_option): did not set SJIS on SJIS condition.
-
-Sun Apr 12 22:14:07 1998 Kazunori NISHI <kazunori@swlab.csce.kyushu-u.ac.jp>
-
- * array.c (ary_uniq_bang): should be `==', not `='. embarrassing.
-
-Sat Apr 11 02:13:30 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * array.c (ary_subseq): SEGVed for `[][1,1]'.
-
-Fri Apr 10 21:29:06 1998 Tadayoshi Funaba <tadf@kt.rim.or.jp>
-
- * array.c (ary_subseq): add check for beg larger than array length.
-
-Wed Apr 8 17:24:11 1998 MAEDA shugo <shugo@po.aianet.ne.jp>
-
- * dir.c (dir_s_open): can be called with block (like IO#open).
-
- * dir.c (dir_s_chdir): print directory path on error.
-
- * dir.c (dir_s_chroot): ditto
-
- * dir.c (Init_Dir): needed to override `new'.
-
-Thu Apr 9 18:24:58 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_09.
-
- * string.c (str_cmp): do not depend on sentinel at the end of the
- strings.
-
- * string.c (str_chomp_bang): forgot to set the sentinel.
-
-Wed Apr 8 00:59:13 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * bignum.c (big2int): converted int may be too big to fit in
- signed int.
-
- * parse.y (arg): `foo += 1' should not cause an error.
-
- * variable.c (rb_const_defined): returned false even if the
- constant is defined at the top level.
-
- * eval.c (f_local_variables): dyna_var->id may be null. should
- have checked before calling str_new2().
-
-Tue Apr 7 01:15:15 1998 Kaneko Naoshi <wbs01621@mail.wbs.or.jp>
-
- * re.c (reg_regsub): need to check string boundary.
-
-Tue Apr 7 19:19:12 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (str_cmp): returns either 1, 0, -1.
-
- * array.c (ary_cmp): should check array length, too
-
-Tue Apr 7 18:50:16 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_08.
-
-Tue Apr 7 18:31:27 1998 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * instruby.rb (mandir): dll installation for cygwin32
-
-Tue Apr 7 01:16:45 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * config.sub (maybe_os): TOWNS support?
-
- * config.guess: too strict check for libc versions on linuxes.
-
- * experimental release 1.1b9_07.
-
- * array.c (ary_cmp): compare each element using `<=>'.
-
- * hash.c (hash_each_with_index): yields [value, key] pair.
-
- * class.c (class_protected_instance_methods): list protected
- method names.
-
- * class.c (ins_methods_i): exclude protected methods.
-
- * eval.c (PUSH_BLOCK): dynamic variables can be accessed from
- eval() with bindings.
-
-Mon Apr 6 14:49:06 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (thread_yield): must return evaluated value.
-
-Fri Apr 3 13:07:29 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (thread_schedule): context switch bypassed on wrong
- conditions.
-
- * variable.c (rb_name_class): set classname by id before String
- class is initialized (1.0 behavior restored).
-
-Fri Apr 3 11:25:45 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * numeric.c (num2int): no implicit conversion from string.
-
- * numeric.c (num2int): check whether `to_i' returns an Integer.
-
- * numeric.c (num_zero_p): new method.
-
- * numeric.c (num_nonzero_p): new method. returns the receiver if
- it's not zero.
-
- * eval.c (obj_instance_eval): the_class should be the object's
- singleton class.
-
- * error.c (exc_s_new): message is converted into a string.
-
-Thu Apr 2 18:31:46 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (obj_call_init): every object call `initialize'.
-
-Wed Apr 1 08:51:53 1998 Tadayoshi Funaba <tadf@kt.rim.or.jp>
-
- * parse.y (stmt): UNTIL_MOD should be for stmt, not only for expr.
-
-Wed Apr 1 01:20:31 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * object.c (true_and): boolean operators &, | and ^.
-
-Tue Mar 31 13:23:58 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * array.c (ary_compact_bang): returns nil, if it does not modify
- the array like String's bang methods.
-
- * array.c (ary_uniq_bang): new method to remove duplicate items.
-
- * eval.c (bind_s_new): new method.
-
- * numeric.c (num2int): raise exception if Fixnums too big to
- convert into `int' in case that sizeof(int) < sizeof(INT).
-
- * string.c (str_center): SEGV on negative width.
-
- * eval.c (eval): forgot to set sourcefile.
-
-Mon Mar 30 11:12:29 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * file.c (f_test): raises exception for unknown command.
-
- * eval.c (Init_eval): `class_eval': alias to the module_eval.
-
-Mon Mar 30 18:50:42 1998 Tadayoshi Funaba <tadf@kt.rim.or.jp>
-
- * string.c (str_capitalize_bang): did not check string modification.
-
- * string.c (str_delete_bang): wrong conversion.
-
- * string.c (str_intern): typo in error message.
-
-Mon Mar 30 01:44:13 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (obj_instance_eval): accepts block as evaluation body.
- No compilation needed each time.
-
- * eval.c (mod_module_eval): ditto
-
- * file.c (file_s_umask): umask did not return old values, if no
- argument given.
-
-Sun Mar 29 00:54:23 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (f_throw): nil returned always.
-
-Sat Mar 28 20:40:12 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_06.
-
-Sat Mar 28 16:07:11 1998 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * io.c (io_closed): should not cause exception for closed IO.
-
- * string.c (str_tr): returned nil for success.
-
-Sat Mar 28 00:47:19 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (f_local_variables): new method to return an array of
- local variable names.
-
- * variable.c (obj_instance_variables): now returns an array of
- variable names, as described in the reference.
-
- * eval.c (rb_attr): honors default method visibility of the
- current scope.
-
-Fri Mar 27 13:49:27 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_05.
-
- * ruby.c (ruby_prog_init): `site_ruby' added to load_path.
-
- * ruby.c (ruby_prog_init): load-path order changed. Paths in
- the RUBYLIB environment variable comes first in non-tainted
- mode.
-
-Thu Mar 26 11:51:09 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_call): new feature: `protected' methods.
-
- * string.c (str_dump): new method.
-
- * eval.c (block_pass): block argument can be nil, which means no
- block is supplied for the method.
-
-Wed Mar 25 21:20:13 1998 Tadayoshi Funaba <tadf@kt.rim.or.jp>
-
- * string.c (str_reverse_bang): string copied to wrong place.
-
-Wed Mar 25 08:12:07 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * numeric.c (flo_modulo): caused SEGV if left operand is not a
- float value.
-
- * eval.c (f_eval): optional third and fourth argument to specify
- file-name and line-number.
-
- * eval.c (eval): file-name and line-number set properly.
-
- * parse.y (assign_in_cond): literal assignment is now warning, not
- compile error.
-
- * error.c (Warn): Warn() always print message, OTOH Waring()
- prints when verbose flag is set.
-
-Tue Mar 24 12:50:06 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ruby.c (ruby_prog_init): `.' should come last in the load-path.
-
- * eval.c (Init_eval): `__send__', alias for `send'.
-
-Mon Mar 23 12:44:12 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (str_chomp_bang): now takes `rs' as an argument.
-
- * eval.c (thread_free): main_thread should not be freed.
-
-Fri Mar 20 16:40:34 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (str_chomp_bang): chomp! (and other ! methods) returns
- nil if it does not modify the string.
-
- * string.c (str_sub_iter_s): should check last pattern since it
- may be matched to null.
-
-Thu Mar 19 13:48:55 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_04.
-
- * parse.y (yylex): `10e0.9' should cause syntax error.
-
-Wed Mar 18 17:46:31 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ruby.c (load_file): new file object constant DATA. Only
- available for the script from the file.
-
- * regex.c (re_match): forwarding failure point popped too much.
-
-Tue Mar 17 18:23:06 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * math.c (math_frexp): newly added.
-
- * math.c (math_ldexp): ditto.
-
- * bignum.c (bigdivmod): calculates modulo.
-
- * numeric.c (fix_remainder): returns reminder, formerly introduced
- as modulo.
-
- * numeric.c (fix_modulo): calculates proper `modulo'.
-
- * bignum.c (bigdivmod): wrong sign for reminder.
-
-Mon Mar 16 17:07:28 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_03.
-
-Mon Mar 16 16:33:53 1998 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * io.c (pipe_finalize): needed to add pipe_finalize to pipes on
- cygwin32.
-
-Mon Mar 16 14:11:06 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * class.c (ins_methods_i): needed to consider NOEX_UNDEF.
-
-Mon Mar 16 13:23:53 1998 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * io.c (io_check_closed): check for `fptr->f2 == NULL'.
-
- * io.c (io_fptr_close): ditto.
-
-Mon Mar 16 11:49:25 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (pipe_atexit): free()ing referencing pipe_list.
-
- * range.c (range_length): returns zero, if the first is greater
- than the last.
-
- * signal.c (trap_restore_mask): restore signal mask before raising
- exceptions and throws.
-
-Fri Mar 13 13:49:24 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_02.
-
- * object.c (mod_clone): need to dups constants and instance
- variables.
-
- * eval.c (rb_eval): forgot to initialize body for NODE_DEFS.
-
- * eval.c (rb_eval): retrieve self from calling frame, since self
- changes sometimes.
-
- * env.h (FRAME): need to save self in the calling frame.
-
- * io.c (f_gets_method): rs should be initialized by RS.
-
-Thu Mar 12 15:33:57 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * experimental release 1.1b9_01.
-
- * range.c (range_s_new): check values by `first <= last'.
-
- * parse.y (lastline_set): fixed offset for $_ and $~ in the local
- variable space.
-
-Wed Mar 11 02:14:17 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (io_gets): handle normal case specially for speed.
-
- * eval.c (rb_disable_super): function to disable superclass's
- method explicitly.
-
- * eval.c (rb_eval): inherits previous method definition's
- NOEX_UNDEF-ness, if exists.
-
- * class.c (rb_define_method): disables superclass's overriding
- method by default.
-
-Wed Mar 11 01:40:48 1998 MAEDA shugo <shugo@po.aianet.ne.jp>
-
- * numeric.c (flo_gt,etc.): do not depend on `<=>', to handle NaN.
-
-Tue Mar 10 00:03:24 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ruby.c (load_file): understands multiple options in #! line.
-
- * regex.c (re_compile_pattern): support for [:alpha:] etc.
-
-Mon Mar 9 16:53:51 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.h (GetOpenFile): embed io_check_closed in GetOpenFile.
-
- * sprintf.c (f_sprintf): zero padding failed for negative
- integers.
-
- * sprintf.c (remove_sign_bits): failed to remove some bits.
-
-Sat Mar 7 21:51:46 1998 MAEDA shugo <shugo@po.aianet.ne.jp>
-
- * class.c (ins_methods_i): body may be NULL for some case.
-
-Fri Mar 6 17:23:07 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (mbcinit): table driven mbchar detection.
-
- * object.c (obj_alloc): check for allocating instance for the
- primitive classes (mostly perfect).
-
- * ext/curses/curses.c (curses_finalize): restore original state at
- interpreter termination.
-
- * ext/curses/curses.c (curses_addstr): forgot to check argument
- type (caused SEGV). now uses STR2CSTR() macro.
-
-Thu Mar 5 13:47:39 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (block_pass): accepts method object as block args.
-
- * eval.c (f_missing): use any_to_s() for stringify.
-
-Wed Mar 4 01:39:52 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (block_arg): new syntax - block argument in the
- calling arglist.
-
- * eval.c (rb_call): no module search. simplified a lot.
-
- * eval.c (rb_eval): block arg support.
-
- * parse.y (f_block_arg): new syntax - block argument in the
- formal arglist.
-
-Tue Mar 3 14:20:15 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (obj_method): returns bound method object.
-
- * eval.c (rb_call): argument check for empty methods.
-
- * ruby.h (NUM2CHR): new macro, originally from curses module.
-
-Tue Mar 3 13:03:35 1998 MAEDA shugo <shugo@po.aianet.ne.jp>
-
- * io.c (io_putc): new method.
-
-Tue Mar 3 11:21:28 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (str_inspect): more strict charcode detection.
-
- * eval.c (thread_stop): stopping only thread raises ThreadError
- exception.
-
-Tue Mar 3 08:04:56 1998 Tadayoshi Funaba <tadf@kt.rim.or.jp>
-
- * struct.c (struct_alloc): incomplete struct initialization made
- GC to access unallocated addresses.
-
-Mon Mar 2 16:28:27 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (thread_stop_method): remove Thread#stop.
-
-Fri Feb 27 18:16:26 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1b9 released.
-
-Fri Feb 27 09:36:35 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * hash.c (hash_delete_nil): needed to compare value to nil, since
- nil is the valid key for hashes.
-
- * hash.c (hash_foreach_iter): rehashing causes IndexError.
-
- * hash.c (hash_foreach_iter): rehash check by pointer comparison.
-
-Thu Feb 26 17:22:13 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (fname): convert reswords into symbols.
-
- * parse.y (reswords): reserved words are now embedded in the
- syntax (sigh).
-
- * parse.y: now reserved words can be method names safely.
-
-Wed Feb 25 15:50:07 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (mod_module_eval): clear the_scope's PRIVATE flag before
- calling eval().
-
- * gc.c (gc_call_finalizer_at_exit): run finalizers before any data
- object being freed.
-
- * eval.c (rb_eval): needed to keep prot_tag->retval before
- evaluating the ensure clause.
-
-Tue Feb 24 11:16:32 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (yylex): reserved words can be appear as method names at
- right after 'def' and `.'(dot), like foo.next.
-
- * eval.c (return_check): checks for return out of thread (formerly
- done in return_value).
-
- * eval.c (POP_TAG): copy retval to outer level.
-
- * eval.c (return_value): just set retval, no check, no unwinding.
-
- * parse.y (nextc): line continuation by backslash at end of line.
-
- * regex.c (re_compile_pattern): forgot to clear pending_exact on
- closing parentheses.
-
- * parse.y (assignable): should not assign dyna_var to true, if it
- is already defined.
-
-Mon Feb 23 14:35:03 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * object.c (obj_is_kind_of): no longer accepts true/false/nil.
-
- * object.c ({true,false,nil}_to_i): can be converted into integers.
-
-Mon Feb 23 12:11:51 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * re.c (reg_s_quote): needed to be mbchar aware.
-
- * eval.c (proc_s_new): wrong iter mark.
-
-Sat Feb 21 22:59:30 1998 MAEDA shugo <shugo@po.aianet.ne.jp>
-
- * io.c (f_syscall): no argument check.
-
-Fri Feb 20 10:17:51 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1b8 released.
-
- * ext/kconv/kconv.c (kconv_kconv): default output code now be
- determined according to the value of $KCODE.
-
- * re.c (rb_get_kcode): can retrieve $KCODE from C code.
-
- * parse.y (stmt): if/unless modifiers returns nil, if condition is
- not established.
-
-Thu Feb 19 11:06:47 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/kconv/kconv.c (kconv_kconv): charcode can be specified by
- code name (JIS, SJIS, EUC like value of $KCODE).
-
- * regex.c (re_compile_pattern): forgot to fixup_jump for (?:..).
-
- * regex.c (re_compile_pattern): needed to clear pending_exact on
- non-registering grouping (?:...).
-
-Wed Feb 18 19:54:21 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (here_document): needed to set lex_state to EXPR_END.
-
-Wed Feb 18 18:45:10 1998 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * patches for cygwin32 applied.
-
-Wed Feb 18 00:41:31 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (str_sub_s): needed to be mbchar aware to increment one
- character.
-
- * regex.c (re_match): \Z matches newline just before the end of
- the string.
-
-Tue Feb 17 00:04:32 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * time.c (time_arg): Time.gm and Time.local now understands
- Time#to_a format.
-
- * string.c (str_sub_s): replace happened twice for null pattern.
-
- * regex.c (re_search): null pattern should not match after newline
- at the end of string.
-
- * time.c (time_isdst): now returns boolean value.
-
- * error.c (rb_check_type): treat special constants in messages.
-
- * parse.y (yylex): new form `::Const' to see toplevel constants.
-
- * parse.y (cond): SEGV on `if ()'.
-
- * gc.c (obj_free): some data needed explicit free().
-
-Mon Feb 16 23:55:40 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (blk_free): release duplicated block informations.
-
- * eval.c (blk_copy_prev): duplicate outer block information into
- the heap, when proc/binding created.
-
-Mon Feb 16 14:38:25 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * time.c (time_mon): now 1 for January and so on.
-
- * time.c (time_year): year in 19xx (no + 1900 needed anymore).
-
-Mon Feb 16 13:28:33 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_compile_pattern): need to fetch mbchar's second byte
- without translation.
-
-Mon Feb 16 12:29:27 1998 MAEDA shugo <shugo@po.aianet.ne.jp>
-
- * eval.c (f_pass_block): pass iterator block to other method.
-
-Fri Feb 13 08:16:11 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (parse_regx): handle \s before read_escape().
-
- * parse.y (read_escape): `\s' in strings as space.
-
-Tue Feb 10 17:29:08 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1b7 released.
-
- * string.c (str_aset): string insertion by `str[n] = str2'.
-
- * string.c (str_oct): does recognize `0x'.
-
- * sprintf.c (f_sprintf): use base 10 for conversion from string to
- integer.
-
-Mon Feb 9 14:51:56 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * numeric.c (do_coerce): proper error message.
-
- * string.c (str_sum): bug - masked by wrong value. (sigh..)
-
-Sat Feb 7 15:11:14 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (str_empty): new method
-
-Fri Feb 6 01:42:15 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * time.c (time_asctime): use asctime(3), not strftime(3).
-
-Thu Feb 5 18:58:46 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (io_fptr_close): do not free path on close().
-
- * array.c (ary_filter): new method.
-
- * enum.c (enum_each_with_index): new method.
-
-Thu Feb 5 14:10:35 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (primary): singleton class def can be appeared inside
- method bodies.
-
- * hash.c (hash_replace): replace content.
-
- * string.c (str_replace_method): replace content.
-
- * array.c (ary_replace_method): replace elements.
-
- * string.c (str_succ_bang): String#succ!
-
-Thu Feb 5 18:20:30 1998 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * string.c (str_upcase_bang): multi byte character support.
-
-Wed Feb 4 13:55:26 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * array.c (ary_reverse): SEGV on empty array reverse.
-
-Tue Feb 3 12:24:07 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * re.c (match_to_a): non matching element should be nil.
-
- * ruby.c (ruby_load_script): load script after all initialization.
-
- * bignum.c (str2inum): need to interpret prefix `0' of `0x'.
-
-Tue Feb 3 10:00:18 1998 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * numeric.c (fix_rshift): use `sizeof(INT)*8' instead of 32.
-
-Mon Feb 2 14:09:24 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ruby.c (set_arg0): grab environment region too.
-
-Thu Jan 29 18:36:25 1998 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * process.c (rb_proc_exec): check `sh' to be exist.
-
-Thu Jan 29 18:18:19 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (io_stdio_set): assignment to $stdin or $stdout does
- reopen() as well as $stderr.
-
-Thu Jan 29 14:18:40 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * class.c (mod_ancestors): should not include singleton classes.
-
- * object.c (obj_type): should not return internal class.
-
- * io.c (io_reopen): unwillingly closes stdio streams.
-
-Thu Jan 29 11:50:35 1998 Toshihiko SHIMOKAWA <toshi@csce.kyushu-u.ac.jp>
-
- * ext/socket/socket.c (udp_addrsetup): forgot to use htons().
-
-Tue Jan 27 23:15:24 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * keywords: __FILE__, __LINE__ are available again.
-
-Fri Jan 23 14:19:28 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1b6 released.
-
- * object.c (mod_to_s): need to duplicate classpath.
-
- * error.c (exc_inspect): need to duplicate classpath.
-
-Thu Jan 22 00:37:47 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ruby.h (STR2CSTR): new macro to retrieve char*.
-
- * class.c (rb_define_method): `initialize' should always be
- private, even if it defined by C extensions.
-
- * eval.c (rb_eval): `initialize' should always be private.
-
-Thu Jan 22 16:21:08 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_eval): some singleton class def cause SEGV.
-
- * eval.c (TMP_ALLOC): replace ALLOCA_N, where thread context
- switch may happen.
-
-Wed Jan 21 01:43:42 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (PUSH_FRAME): do not use ALLOCA_N(). crash on some
- platforms that use missing/alloca.c.
-
- * regex.c (re_compile_pattern): too many pops for non register
- subexpr.
-
- * parse.y (yylex): open parentheses after identifiers are argument
- list, even if whitespaces have seen.
-
-Tue Jan 20 15:19:59 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (terms): quoted word list by %w(a b c).
-
- * ext/tcltklib/extconf.rb: more accurate check for tcl/tk libs.
-
- * file.c (rb_stat): most of the FileTest methods (and function
- `test') accept File objects as the argument.
-
-Tue Jan 19 18:19:24 1998 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * ext/extmk.rb.in (install): there should be no newline after install:
-
- * re.c (MIN): renamed from min(). there's a local variable named
- min in the file, so that some cpp will raise an error.
-
-Mon Jan 19 16:30:05 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1b5 released.
-
- * process.c (rb_syswait): no exception raised.
-
-Fri Jan 16 00:43:43 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ruby.h (CLONESETUP): copies its singleton classes too.
-
- * class.c (singleton_class_attached): saves binded object in the
- singleton classes.
-
- * eval.c (rb_eval): calls singleton_method_added even in the
- singleton class clauses.
-
-Fri Jan 15 23:22:43 1998 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * ruby.c (proc_options): -S does not recognize PATH.
-
-Thu Jan 15 02:03:12 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_clear_cache_by_id): clear only affected cache
- entries.
-
-Wed Jan 14 02:14:48 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/socket/socket.c: new UDP/IP socket classes.
-
-Tue Jan 13 10:00:18 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (str_cmp): ignorecase($=) works wrong.
-
-Fri Jan 9 13:19:55 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1b4 released.
-
- * eval.c (f_missing): class name omitted from the error message.
-
- * error.c (exc_inspect): description changed.
-
- * string.c (Init_String): GlobalExit's superclass did not filled,
- since GlobalExit created earlier than String.
-
-Thu Jan 8 12:10:09 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (aryset): expr in the brackets can be null.
-
-Wed Jan 7 21:13:56 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (io_reopen): keep stderr unclosed.
-
- * io.c (io_errset): keep stderr unclosed.
-
-Tue Jan 6 00:27:43 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y: syntax modified for `while expr do .. end' etc.
-
- * process.c (f_exec,f_system): can supply arbitrary name for the
- new process.
-
-Mon Jan 5 16:59:13 1998 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * file.c (file_s_basename): removes any extension by ".*".
-
-Sun Jan 4 19:36:22 1998 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * parse.y (yylex): needed to update lex_p (reading point).
-
-Sat Jan 3 19:14:14 1998 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * class.c,object.c: duplicate defines mKernel and cFinxnum.
-
-Fri Jan 2 20:38:59 1998 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/curses/curses.c (NUM2CHAR): uses the first character for
- string arguments.
-
- * array.c (ary_fill): did not extend array for ranges.
-
- * array.c (beg_len): did not return end pos bigger than size.
-
-Fri Jan 2 02:09:16 1998 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * dir.c (dir_s_chdir): bug in nil check.
-
- * array.c (ary_fill): bug in nil check.
-
-Tue Dec 30 11:46:23 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * hash.c (env_path_tainted): checks directories in PATH
- environment variable are not world writable.
-
- * ruby.c (load_file): invoke specified interpreter if the #! line
- does not contain the word `ruby'.
-
-Fri Dec 26 03:26:41 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (uscore_get): type information included in the error
- message.
-
- * variable.c (f_untrace_var): does not free trace-data within
- trace procedure.
-
-Thu Dec 25 02:50:29 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1b3 released.
-
- * ruby.h: inlining some functions on gcc 2.x
-
-Tue Dec 23 02:47:33 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_eval): public/private information kept in the current
- scope, to remove undesired state from the class/module.
-
- * time.c (time_strftime): remove hidden limit of 100 bytes of
- result string, using malloc'ed buffer.
-
- * hash.c (hash_update): merges the contents of another hash,
- overriding existing keys.
-
- * regex.c (must_instr): totally re-written.
-
- * io.c (read_all): try to allocate proper sized buffer using
- fstat(2) for speedup.
-
-Sat Dec 20 00:27:28 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (must_instr): need to skip 2 bytes for mbchars.
-
-Fri Dec 19 01:18:29 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1b2 released.
-
- * eval.c (check_errat): check and convert (if necessary) traceback
- information before assigning to the variable $@.
-
- * eval.c (f_raise): optional third argument to specify traceback
- information.
-
- * io.c (f_open): prevent infinite recursive call.
-
-Thu Dec 18 19:33:47 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (str_rindex): now accepts regexp as index.
-
-Thu Dec 18 18:42:50 1997 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * ext/socket/extconf.rb: modified to detect win32 socket lib.
-
-Thu Dec 18 00:25:03 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * re.c (reg_equal): checks for source and casefold and kcode matching.
-
- * marshal.c: became built-in module.
-
- * ext/marshal/marshal.c (r_object): displays struct name for
- non-compatible struct.
-
- * string.c (str_index_method): now searches character (fixnum) in
- the string.
-
- * string.c (str_include): redefine `include?'.
-
- * regex.c (re_match): start_nowidth saves current stack position
- to stop_nowidth.
-
- * regex.c (re_compile_pattern): add space to stop_nowidth to save
- runtime stack position.
-
-Tue Dec 16 14:57:43 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (scan_once): wrong exception for regexp that match with
- null string (use substr instead of subseq).
-
-Sat Dec 13 00:13:32 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (expr): remove bare assocs from expr rule.
-
- * rbconfig.rb: renamed from config.rb (it was too generic name).
-
-Fri Dec 12 00:50:25 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (expr): warns if BEGIN or END appear in the method
- bodies.
-
- * string.c (str_match): calls y =~ x if y is neither String nor
- Regexp so that eregex.rb works.
-
- * eval.c (f_at_exit): to register end proc.
-
- * class.c (rb_define_module_function): define 'function' method
- for the Module, not private method.
-
- * class.c (rb_define_function): function to define `function' method.
-
- * eval.c (rb_eval): inherit visibility from superclass's method
- except when it is set to `function'
-
- * eval.c (rb_eval): new visibility status `function'.
-
- * parse.y (yycompile): do not clear eval_tree. thus enable multiple
- command line script by option `-e'.
-
- * eval.c (rb_eval): END execute just once.
-
- * parse.y (expr): BEGIN/END built in the syntax.
-
-Thu Dec 11 13:14:35 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * object.c (mod_le): Module (or Class) comparison.
-
- * eval.c (rb_remove_method): raises NameError if named method does
- not exist.
-
- * ext/curses/curses.c: remove CHECK macro for BSD curses.
-
-Thu Dec 11 12:44:01 1997 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * pack.c: sun4 cc patch
-
-Wed Dec 10 15:21:36 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/marshal/marshal.c (marshal_load): can supply evolution proc
- object as optional second argument.
-
- * re.c (reg_source): get source string of the regular expression.
-
-Tue Dec 9 10:05:17 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1b1 released.
-
- * parse.y (tokadd): token buffer overrun.
-
- * ruby.c (ruby_prog_init): forgot to protect rb_argv0 from gc.
-
- * eval.c (ruby_run): call finalizers at process termination.
-
- * gc.c (gc_call_finalizer_at_exit): call free proc for every Data
- Wrapper, and finalizer for specified objects at termination.
-
- * version.c (show_version): version format changed.
-
- * regex.c (re_match): wrong match with non-greedy if they appear
- more than once in regular expressions.
-
- * sample/ruby-mode.el (ruby-expr-beg): forgot to handle modifiers.
-
-Mon Dec 8 19:00:15 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (io_puts): just put a newline if no argument given.
-
- * ext/tcltklib/tcltklib.c (lib_mainloop): thread-aware tk handle
- when $tk_thread_safe is set.
-
- * ext/tcltklib/tcltklib.c (lib_mainloop): use Tcl_DoOneEvent()
- instead of Tk_MainLoop().
-
-Mon Dec 6 07:11:16 1997 MAEDA shugo <shugo@po.aianet.ne.jp>
-
- * io.c (io_puts): core dumped without any argument.
-
-Fri Dec 5 18:17:17 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (mod_remove_method): remove (not undef) a method from the
- class/module.
-
- * variable.c (obj_remove_instance_variable): method to remove
- instance variables.
-
-Thu Dec 4 13:50:29 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1b0 released.
-
- * string.c (str_aref): called str_index for regexp.
-
-Mon Dec 1 15:24:41 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * compar.c (cmp_between): wrong comparison made.
-
-Wed Nov 26 18:18:05 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * lib/mkmf.rb: generate Makefile for extension modules out of ruby
- source tree. use like `ruby -r mkmf extconf.rb'.
-
- * numeric.c (fix2str): enlarge buffer to prevent overflow on some
- machines.
-
- * parse.y (here_document): wrong line number generated after here-doc.
-
-Fri Nov 21 13:17:12 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (yylex): skip multibyte characters in comments.
-
-Wed Nov 19 17:19:20 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * object.c (nil_to_a): nil.to_a => [].
-
- * parse.y (call_args): wrong node generation.
-
-Tue Nov 18 10:13:08 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * array.c (Init_Array): Array#=== works as Array#include?
-
- * regex.c (re_compile_pattern): insert initialize code for jump_n,
- before entering loops.
-
- * re.c (reg_search): does not save registers unless $& etc appear
- in the script.
-
-Mon Nov 17 13:01:43 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (is_defined): add defined? check for receivers and
- arguments for calls.
-
- * re.c (reg_search): cache last match object.
-
- * re.c (match_aref): $[0] etc. are available.
-
-Sat Nov 15 00:11:36 1997 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * io.c (io_s_popen): "rb" detection
-
-Fri Nov 14 18:28:40 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (scan_once): returns whole match if the pattern does
- not contain any parentheses.
-
-Thu Nov 13 14:39:06 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (str_sub): returns copy of the receiver string, even if
- any substitution occurred.
-
- * regex.c (re_compile_pattern): no-width match by (?=..), (?!..).
-
-Wed Nov 12 13:44:47 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * time.c: remove coerce from Time class.
-
- * regex.c (re_match): non-greedy match by ??, *? +?, {n,m}?.
-
-Mon Nov 10 11:24:51 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_compile_pattern): non-registering parens (?:..).
-
- * regex.c (re_compile_pattern): new meta character \< (wordbeg)
- and \> (wordend).
-
- * regex.c (re_compile_pattern): embedded comment for regular
- expression by (?#...).
-
-Fri Nov 7 16:58:24 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_compile_pattern): perl5 regxp \A and \Z available.
-
- * regex.c (re_compile_pattern): can expand compile stack dynamically.
-
- * regex.c (PUSH_FAILURE_POINT): wrong compare condition.
-
-Wed Nov 2 16:00:00 1997 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * string.c (str_sub_s): "".sub! "", "" => "\000"
-
-Fri Oct 31 15:52:10 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (assoc): keyword assoc like {fg->"black"}.
-
-Thu Oct 30 17:33:38 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (io_println): print with newline, which is not affected by
- the values of $/ and $\.
-
-Thu Oct 30 16:54:01 1997 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * string.c (str_chop_bang): "".chop caused SEGV.
-
- * string.c (str_chomp_bang): method to chop out last newline.
-
-Mon Oct 27 13:49:13 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/extmk.rb.in: library may have pathname contains `.'
-
- * eval.c (rb_rescue): should not protect SystemError.
-
-Fri Oct 24 10:58:53 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (io_s_with_open_stream): ensures to close stream.
-
-Thu Oct 23 11:17:44 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (io_errset): value of $stderr can be changed (to any IO
- object).
-
- * io.c (next_argv): $< can be anything that responds to `write'.
-
- * file.c (file_s_with_open_file): ensures to close file.
-
- * error.c (exception): create error under the current class/module.
-
- * range.c (range_eqq): fixnum check for last needed too.
-
-Wed Oct 22 12:52:30 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/socket/socket.c: Socket::Constants added.
-
- * file.c: File::Constants added for inclusion.
-
- * array.c (ary_join): call ary_join() recursively for the 1st
- array element.
-
-Mon Oct 20 12:18:29 1997 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * ruby.c (load_file): wrong condition for #! check with -x.
-
- * file.c (file_s_dirname): did return "" for "/a".
-
-Fri Oct 17 14:29:09 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ruby.c: now works on alpha-linux.
-
- * bignum.c (bigadd): some undefined side effect order assumed.
-
-Wed Oct 15 17:49:24 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * intern.h: function prototypes added.
-
-Mon Oct 13 16:54:18 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * class.c (rb_define_class_id): call superclass's `inherited'
- method when making subclasses.
-
- * parse.y (nextc): clear lex_lastline at the end of file.
-
- * object.c (Init_Object): need to undef Class#append_features.
-
- * eval.c (rb_eval): no warning on extending classes or modules.
-
-Thu Oct 9 11:17:50 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (error_print): the exception name follows after the error
- message.
-
- * eval.c (compile_error): error message slightly changed.
-
- * parse.y (nextc): script parsing will be terminated by __END__ at
- beginning of line.
-
- * eval.c (compile_error): `__END__' is no longer a keyword.
-
- * parse.y (nextc): protect lastline read from script stream.
-
-Tue Oct 7 14:06:06 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1 alpha9 released.
-
- * eval.c (mod_append_features): renamed from extend_class.
-
- * eval.c (rb_eval): defining method calls `method_added'.
-
- * eval.c (ruby_options): exception while processing options must
- terminate the interpreter.
-
- * error.c (Init_Exception): wrong method configuration. `new'
- should have been a singleton method.
-
-Mon Oct 6 18:55:38 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/kconv/kconv.c (kconv_guess): code to guess character code
- from string.
-
-Mon Oct 6 18:38:17 1997 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * pack.c: now encode/decode base64 by `m' template.
-
-Fri Oct 3 10:51:10 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * MANIFEST: needed to include lex.c in the distribution.
-
- * eval.c (ruby_options): f_require() called too early.
-
- * eval.c (rb_provide): module extensions should always be `.o'.
-
-Thu Oct 2 11:38:31 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1 alpha8 released.
-
- * ext/marshal/marshal.c (r_object): remove temporal regist for
- structs. (caused problem if structs form cycles.)
-
- * parse.y (match_gen): static binding for match(=~) calls
- with regexp literals.
-
-Wed Oct 1 15:26:55 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c: protect retval in struct tag from GC for C_ALLOCA.
-
- * eval.c: no more pointer value from setjmp/longjmp.
-
-Wed Oct 1 14:01:49 1997 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * ext/marshal/marshal.c (w_byte): argument must be char.
-
-Wed Oct 1 10:30:22 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * variable.c (mod_const_at): global constants now belongs to the
- class Object.
-
- * object.c (Init_Object): new global constant NIL.
-
- * ext/marshal/marshal.c (marshal_dump): try to set binmode.
-
- * ext/marshal/marshal.c (r_object): forgot to re-regist structs in
- the object table.
-
- * eval.c (ruby_options): call Init_ext() before any require()
- calls by `-r'.
-
-Fri Sep 30 14:29:22 1997 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * ext/marshal/marshal.c (w_object): marshal dumped core.
-
-Tue Sep 30 10:27:39 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * sample/test.rb: bignum test suits added.
-
- * eval.c (rb_eval): new pseudo variable `true' and `false'.
-
- * parse.y: new keywords `true' and `false' added.
-
-Mon Sep 29 13:37:58 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ruby.c (forbid_setid): forbid some options in suid mode.
-
- * ruby.h (NUM2DBL): new macro to convert into doubles.
-
-Mon Sep 27 09:53:48 1997 EGUCHI Osamu <eguchi@shizuokanet.or.jp>
-
- * bignum.c: modified for speeding.
-
-Fri Sep 26 18:27:59 1997 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * sample/from.rb: some extensions.
-
-Mon Sep 29 13:15:56 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (lhs): no more syntax error on `obj.CONSTANT = value'.
-
-Fri Sep 26 14:41:46 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (ruby_run): deferred calling Init_ext() just before eval_node.
-
-Fri Sep 26 13:27:24 1997 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * io.c (io_isatty): forgot to return TRUE value.
-
-Fri Sep 25 11:10:58 1997 EGUCHI Osamu <eguchi@shizuokanet.or.jp>
-
- * eval.c: use _setjmp/_longjmp instead of setjmp/longjmp on some
- platforms.
-
-Wed Sep 24 17:43:13 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * string.c (Init_String): String#taint and String#taint? added.
-
- * class.c (mod_ancestors): ancestors include the class itself.
-
-Wed Sep 24 00:57:00 1997 Katsuyuki Okabe <HGC02147@niftyserve.or.jp>
-
- * X68000 patch.
-
-Tue Sep 23 20:42:30 1997 EGUCHI Osamu <eguchi@shizuokanet.or.jp>
-
- * parse.y (node_newnode): SEGV on null node setup.
-
-Mon Sep 22 11:22:46 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ruby.c (ruby_prog_init): wrong safe condition check.
-
-Sun Sep 21 14:46:02 1997 MAEDA shugo <shugo@po.aianet.ne.jp>
-
- * error.c (exc_inspect): garbage added to classpath.
-
-Fri Sep 19 11:49:23 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (newtok): forgot to adjust buffer size when shrinking
- the token buffer.
-
- * enum.c (enum_find): rb_eval_cmd() does not return value.
-
- * io.c (pipe_open): close fds on pipe exec. fcntl(fd, F_SETFD, 1)
- no longer used.
-
-Tue Sep 16 17:54:25 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * file.c (f_test): problem if wrong command specified.
-
- * ruby.c (ruby_prog_init): close stdaux and stdprn for MSDOS.
-
- * ruby.c (ruby_prog_init): should not add path from environment
- variable, if ruby is running under setuid.
-
- * process.c (init_ids): check suid check for setuid/seteuid etc.
-
-Mon Sep 15 00:42:04 1997 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * regex.c (re_compile_pattern): \w{3} and \W{3} did not work.
-
-Thu Sep 11 10:31:48 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1 alpha7 released.
-
- * ext/socket/socket.c (sock_new): no setbuf() for NT.
-
- * io.c (rb_fopen,rb_fdopen): set close-on-exec for every fd.
-
-Wed Sep 10 15:55:31 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ext/marshal/marshal.c (r_bytes0): extra big length check.
-
-Tue Sep 9 16:27:14 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (pipe_fptr_atexit): clean up popen()'ed fptr.
-
- * error.c (set_syserr): some system has error code that is bigger
- than sys_nerr. grrr.
-
-Mon Sep 8 18:33:33 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * io.c (io_s_new): dereferenced nil for optional mode.
-
-Fri Sep 5 10:26:03 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * class.c (class_instance_methods): do not include methods which
- are changed to private in subclasses.
-
-Thu Sep 4 12:38:53 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * variable.c (f_global_variables): list name of the global
- variables.
-
- * object.c (obj_id): returns unique integer.
-
-Wed Sep 3 14:05:16 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1 alpha6 released.
-
- * eval.c (mod_s_constants): context sensitive constant list.
-
- * variable.c (mod_constants): no more `all' option.
-
- * variable.c (mod_const_of): the values for autoload classes are
- their name strings.
-
- * class.c (class_instance_methods): no special treatment for
- singleton classes.
-
- * object.c (obj_singleton_methods): returns list of singleton
- method names.
-
- * parse.y (yylex): no here document after `class' keyword.
-
- * eval.c (f_load): expand path if fname begins with `~'.
-
-Tue Sep 2 13:19:48 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * class.c (ins_methods_i): do not list undef'ed methods.
-
-Mon Sep 1 13:42:48 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1 alpha5 released.
-
- * object.c (mod_attr_reader): create methods to define attribute
- reader/write/accessor.
-
- * class.c (rb_define_attr): always defines accessors.
-
- * eval.c (rb_call): alias occurred in the module body caused SEGV.
-
- * parse.y: did not generate here document strings properly.
-
-Mon Sep 1 11:43:57 1997 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * parse.y (yylex): heredoc dropped an extra character.
-
-Fri Aug 29 11:10:21 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * class.c (class_instance_methods): same method names should not
- appear more than once.
-
- * parse.y (yylex): spaces can follow =begin/=end.
-
- * variable.c (find_class_path): look for class_tbl also for
- unnamed fundamental classes, such as Object, String, etc.
-
- * variable.c (rb_name_class): can't name class before String class
- is initialized.
-
- * inits.c (rb_call_inits): unrecognized dependency from GC to
- Array.
-
- * variable.c (find_class_path): could not find class if Object's
- iv_tbl is NULL.
-
-Thu Aug 28 13:12:05 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1 alpha4 released.
-
- * variable.c (mod_constants): wrong condition for singleton
- class.
-
- * parse.y (yylex): revised `=begin' skip code.
-
- * parse.y (here_document): forgot to free(eos).
-
- * parse.y (yylex): spaces after `<<' prohibited for here
- documents to avoid confusing with operator `<<'.
-
- * eval.c (is_defined): separated from rb_eval().
-
-Wed Aug 27 11:32:42 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1 alpha3 released.
-
- * variable.c (mod_name): returns name of the class/module.
-
- * parse.y (here_document): finally here document available now.
-
- * variable.c (fc_i): some classes/modules does not have iv_tbl.
-
- * variable.c (find_class_path): avoid infinite loop.
-
-Tue Aug 26 13:43:47 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (rb_eval): undef'ing non-existing method will raise
- NameError exception.
-
- * object.c (class_s_new): needed to create metaclass too.
-
- * eval.c (error_print): no class name print for anonymous class.
-
- * eval.c (rb_longjmp): proper exception raised if raise() called
- without arguments, with $! or $@ set.
-
- * object.c (Init_Object): superclass()'s method argument setting
- was wrong again.
-
- * class.c (mod_ancestors): list superclasses and included modules
- in priority order.
-
-Mon Aug 25 11:53:11 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1 alpha2 released.
-
- * sample/ruby-mode.el (ruby-parse-region): auto-indent now
- supports "\\" in the strings.
-
- * struct.c (struct_getmember): new API to get member value from C
- language side.
-
-Sat Aug 23 21:39:05 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * parse.y (assignable): remove unnecessary local variable
- initialize by nil.
-
-Fri Aug 22 14:26:40 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (error_print): modified exception print format.
-
-Thu Aug 21 16:10:58 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * sample/ruby-mode.el (ruby-calculate-indent): wrong indent level
- calculated with keyword operators.
-
-Thu Aug 21 11:36:58 1997 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * parse.y (arg): ary[0] += 1 cause SEGV
-
-Wed Aug 20 17:28:50 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * ruby.c (ruby_process_options): require() all modules after
- processing all options
-
- * process.c (rb_proc_exec): more security checks added.
-
- * process.c (rb_proc_exec): insecure path on exec.
-
- * hash.c (f_getenv): PATH modification security check.
-
-Tue Aug 19 00:15:38 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1 alpha1 released.
-
- * eval.c (mod_eval): work as normal eval() if second binding
- argument given.
-
- * eval.c (rb_call): did not raise ArgumentError if too many
- arguments more than optional arguments (without rest arg).
-
- * eval.c (rb_eval): did not work well for op_asgn2 (attribute
- self assignment).
-
- * eval.c (Init_Thread): returns main thread.
-
-Mon Aug 18 09:25:56 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * object.c (inspect_i): did not display T_DATA instance variables.
-
- * parse.y: provides more accurate line number information.
-
- * eval.c (thread_value): include value's backtrace information in
- the variable `$@'.
-
- * eval.c (f_abort): print backtrace and exit.
-
-Sat Aug 16 00:17:44 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (class_new_instance): do not make instance from virtual
- classes.
-
- * object.c (class_s_new): do not make subclass of singleton class.
-
-Fri Aug 15 15:49:46 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * eval.c (call_trace_func): block context switch in the trace
- function.
-
- * eval.c (rb_eval): clear method cache at class extension.
-
- * object.c (obj_type): returns object's class even if it defines
- singleton methods.
-
-Fri Aug 15 19:40:43 1997 WATANABE Hirofumi <watanabe@ase.ptg.sony.co.jp>
-
- * ext/socket/socket.c (Init_socket): small typo caused SEGV.
-
-Wed Aug 13 17:51:46 1997 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * version 1.1 alpha0 released.
diff --git a/GPL b/GPL
deleted file mode 100644
index 5b6e7c66c2..0000000000
--- a/GPL
+++ /dev/null
@@ -1,340 +0,0 @@
- GNU GENERAL PUBLIC LICENSE
- Version 2, June 1991
-
- Copyright (C) 1989, 1991 Free Software Foundation, Inc.
- 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The licenses for most software are designed to take away your
-freedom to share and change it. By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software--to make sure the software is free for all its users. This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it. (Some other Free Software Foundation software is covered by
-the GNU Library General Public License instead.) You can apply it to
-your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it
-if you want it, that you can change the software or use pieces of it
-in new free programs; and that you know you can do these things.
-
- To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have. You must make sure that they, too, receive or can get the
-source code. And you must show them these terms so they know their
-rights.
-
- We protect your rights with two steps: (1) copyright the software, and
-(2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
-
- Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software. If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
-
- Finally, any free program is threatened constantly by software
-patents. We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary. To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- GNU GENERAL PUBLIC LICENSE
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
- 0. This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License. The "Program", below,
-refers to any such program or work, and a "work based on the Program"
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it,
-either verbatim or with modifications and/or translated into another
-language. (Hereinafter, translation is included without limitation in
-the term "modification".) Each licensee is addressed as "you".
-
-Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope. The act of
-running the Program is not restricted, and the output from the Program
-is covered only if its contents constitute a work based on the
-Program (independent of having been made by running the Program).
-Whether that is true depends on what the Program does.
-
- 1. You may copy and distribute verbatim copies of the Program's
-source code as you receive it, in any medium, provided that you
-conspicuously and appropriately publish on each copy an appropriate
-copyright notice and disclaimer of warranty; keep intact all the
-notices that refer to this License and to the absence of any warranty;
-and give any other recipients of the Program a copy of this License
-along with the Program.
-
-You may charge a fee for the physical act of transferring a copy, and
-you may at your option offer warranty protection in exchange for a fee.
-
- 2. You may modify your copy or copies of the Program or any portion
-of it, thus forming a work based on the Program, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
- a) You must cause the modified files to carry prominent notices
- stating that you changed the files and the date of any change.
-
- b) You must cause any work that you distribute or publish, that in
- whole or in part contains or is derived from the Program or any
- part thereof, to be licensed as a whole at no charge to all third
- parties under the terms of this License.
-
- c) If the modified program normally reads commands interactively
- when run, you must cause it, when started running for such
- interactive use in the most ordinary way, to print or display an
- announcement including an appropriate copyright notice and a
- notice that there is no warranty (or else, saying that you provide
- a warranty) and that users may redistribute the program under
- these conditions, and telling the user how to view a copy of this
- License. (Exception: if the Program itself is interactive but
- does not normally print such an announcement, your work based on
- the Program is not required to print an announcement.)
-
-These requirements apply to the modified work as a whole. If
-identifiable sections of that work are not derived from the Program,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works. But when you
-distribute the same sections as part of a whole which is a work based
-on the Program, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Program.
-
-In addition, mere aggregation of another work not based on the Program
-with the Program (or with a work based on the Program) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
- 3. You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
-
- a) Accompany it with the complete corresponding machine-readable
- source code, which must be distributed under the terms of Sections
- 1 and 2 above on a medium customarily used for software interchange; or,
-
- b) Accompany it with a written offer, valid for at least three
- years, to give any third party, for a charge no more than your
- cost of physically performing source distribution, a complete
- machine-readable copy of the corresponding source code, to be
- distributed under the terms of Sections 1 and 2 above on a medium
- customarily used for software interchange; or,
-
- c) Accompany it with the information you received as to the offer
- to distribute corresponding source code. (This alternative is
- allowed only for noncommercial distribution and only if you
- received the program in object code or executable form with such
- an offer, in accord with Subsection b above.)
-
-The source code for a work means the preferred form of the work for
-making modifications to it. For an executable work, complete source
-code means all the source code for all modules it contains, plus any
-associated interface definition files, plus the scripts used to
-control compilation and installation of the executable. However, as a
-special exception, the source code distributed need not include
-anything that is normally distributed (in either source or binary
-form) with the major components (compiler, kernel, and so on) of the
-operating system on which the executable runs, unless that component
-itself accompanies the executable.
-
-If distribution of executable or object code is made by offering
-access to copy from a designated place, then offering equivalent
-access to copy the source code from the same place counts as
-distribution of the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
- 4. You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License. Any attempt
-otherwise to copy, modify, sublicense or distribute the Program is
-void, and will automatically terminate your rights under this License.
-However, parties who have received copies, or rights, from you under
-this License will not have their licenses terminated so long as such
-parties remain in full compliance.
-
- 5. You are not required to accept this License, since you have not
-signed it. However, nothing else grants you permission to modify or
-distribute the Program or its derivative works. These actions are
-prohibited by law if you do not accept this License. Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Program or works based on it.
-
- 6. Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program subject to
-these terms and conditions. You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties to
-this License.
-
- 7. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Program at all. For example, if a patent
-license would not permit royalty-free redistribution of the Program by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Program.
-
-If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply and the section as a whole is intended to apply in other
-circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system, which is
-implemented by public license practices. Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
- 8. If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program under this License
-may add an explicit geographical distribution limitation excluding
-those countries, so that distribution is permitted only in or among
-countries not thus excluded. In such case, this License incorporates
-the limitation as if written in the body of this License.
-
- 9. The Free Software Foundation may publish revised and/or new versions
-of the General Public License from time to time. Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-Each version is given a distinguishing version number. If the Program
-specifies a version number of this License which applies to it and "any
-later version", you have the option of following the terms and conditions
-either of that version or of any later version published by the Free
-Software Foundation. If the Program does not specify a version number of
-this License, you may choose any version ever published by the Free Software
-Foundation.
-
- 10. If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, write to the author
-to ask for permission. For software which is copyrighted by the Free
-Software Foundation, write to the Free Software Foundation; we sometimes
-make exceptions for this. Our decision will be guided by the two goals
-of preserving the free status of all derivatives of our free software and
-of promoting the sharing and reuse of software generally.
-
- NO WARRANTY
-
- 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
-PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
-OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
-TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
-REPAIR OR CORRECTION.
-
- 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
-REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
-OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
-TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
-YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
- <one line to give the program's name and a brief idea of what it does.>
- Copyright (C) <year> <name of author>
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-
-Also add information on how to contact you by electronic and paper mail.
-
-If the program is interactive, make it output a short notice like this
-when it starts in an interactive mode:
-
- Gnomovision version 69, Copyright (C) year name of author
- Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, the commands you use may
-be called something other than `show w' and `show c'; they could even be
-mouse-clicks or menu items--whatever suits your program.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the program, if
-necessary. Here is a sample; alter the names:
-
- Yoyodyne, Inc., hereby disclaims all copyright interest in the program
- `Gnomovision' (which makes passes at compilers) written by James Hacker.
-
- <signature of Ty Coon>, 1 April 1989
- Ty Coon, President of Vice
-
-This General Public License does not permit incorporating your program into
-proprietary programs. If your program is a subroutine library, you may
-consider it more useful to permit linking proprietary applications with the
-library. If this is what you want to do, use the GNU Library General
-Public License instead of this License.
diff --git a/LEGAL b/LEGAL
deleted file mode 100644
index 57dbea8258..0000000000
--- a/LEGAL
+++ /dev/null
@@ -1,308 +0,0 @@
-LEGAL NOTICE INFORMATION
-------------------------
-
-All the files in this distribution are covered under either the Ruby's
-license (see the file COPYING) or public-domain except some files
-mentioned below.
-
-regex.[ch]:
-
- These files are under LGPL. Treat them as LGPL says. (See the file
- LGPL for details)
-
- Extended regular expression matching and search library.
- Copyright (C) 1993, 94, 95, 96, 97, 98 Free Software Foundation, Inc.
-
- The GNU C Library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public License as
- published by the Free Software Foundation; either version 2 of the
- License, or (at your option) any later version.
-
- The GNU C Library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public
- License along with the GNU C Library; see the file LGPL. If not,
- write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
- Boston, MA 02111-1307, USA. */
-
- Multi-byte extension added May, 1993 by t^2 (Takahiro Tanimoto)
- Last change: May 21, 1993 by t^2
- removed gapped buffer support, multiple syntax support by matz <matz@nts.co.jp>
- Perl5 extension added by matz <matz@caelum.co.jp>
- UTF-8 extension added Jan 16 1999 by Yoshida Masato <yoshidam@tau.bekkoame.ne.jp>
-
-configure:
-
- This file is free software.
-
- Copyright (C) 1992, 93, 94, 95, 96 Free Software Foundation, Inc.
-
- This configure script is free software; the Free Software Foundation
- gives unlimited permission to copy, distribute and modify it.
-
-config.guess:
-config.sub:
-parse.c:
-
- As long as you distribute these files with the file configure, they
- are covered under the Ruby's license.
-
- Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999
- Free Software Foundation, Inc.
-
- This file is free software; you can redistribute it and/or modify it
- under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful, but
- WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-
- As a special exception to the GNU General Public License, if you
- distribute this file as part of a program that contains a
- configuration script generated by Autoconf, you may include it under
- the same distribution terms that you use for the rest of that program.
-
-util.c (partly):
-win32/win32.[ch]:
-
- You can apply the Artistic License to these files. (or GPL,
- alternatively)
-
- Copyright (c) 1993, Intergraph Corporation
-
- You may distribute under the terms of either the GNU General Public
- License or the Artistic License, as specified in the perl README file.
-
-st.[ch]:
-x68/*:
-missing/alloca.c:
-missing/dup2.c:
-missing/finite.c:
-missing/hypot.c:
-missing/isinf.c:
-missing/isnan.c:
-missing/memcmp.c:
-missing/memmove.c:
-missing/mkdir.c:
-missing/strcasecmp.c:
-missing/strchr.c:
-missing/streror.c:
-missing/strftime.c:
-missing/strncasecmp.c:
-missing/strstr.c:
-missing/strtol.c:
-ext/digest/sha1/sha1.[ch]:
-
- These files are all under public domain.
-
-missing/strtod.c:
-
- This file will not be used on most platforms depending on how the
- configure script results. In any case you must not receive any fee
- with the file itself.
-
- Copyright (c) 1988-1993 The Regents of the University of California.
- Copyright (c) 1994 Sun Microsystems, Inc.
-
- Permission to use, copy, modify, and distribute this
- software and its documentation for any purpose and without
- fee is hereby granted, provided that the above copyright
- notice appear in all copies. The University of California
- makes no representations about the suitability of this
- software for any purpose. It is provided "as is" without
- express or implied warranty.
-
-missing/strtoul.c:
-
- This file will not be used on most platforms depending on how the
- configure script results. In any case you must not receive any fee
- with the file itself.
-
- Copyright 1988 Regents of the University of California
-
- Permission to use, copy, modify, and distribute this
- software and its documentation for any purpose and without
- fee is hereby granted, provided that the above copyright
- notice appear in all copies. The University of California
- makes no representations about the suitability of this
- software for any purpose. It is provided "as is" without
- express or implied warranty.
-
-missing/vsnprintf.c:
-
- This file is under the old-style BSD license. Note that the
- paragraph 3 below is now null and void.
-
- Copyright (c) 1990, 1993
- The Regents of the University of California. All rights reserved.
-
- This code is derived from software contributed to Berkeley by
- Chris Torek.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions
- are met:
- 1. Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- 2. Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
- 3. All advertising materials mentioning features or use of this software
- must display the following acknowledgement:
- This product includes software developed by the University of
- California, Berkeley and its contributors.
- 4. Neither the name of the University nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- SUCH DAMAGE.
-
- IMPORTANT NOTE:
- --------------
- From ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change
- paragraph 3 above is now null and void.
-
-ext/digest/md5/md5.[ch]:
-
- These files are under the following license. Ruby uses modified
- versions of them.
-
- Copyright (C) 1999, 2000 Aladdin Enterprises. All rights reserved.
-
- This software is provided 'as-is', without any express or implied
- warranty. In no event will the authors be held liable for any damages
- arising from the use of this software.
-
- Permission is granted to anyone to use this software for any purpose,
- including commercial applications, and to alter it and redistribute it
- freely, subject to the following restrictions:
-
- 1. The origin of this software must not be misrepresented; you must not
- claim that you wrote the original software. If you use this software
- in a product, an acknowledgment in the product documentation would be
- appreciated but is not required.
- 2. Altered source versions must be plainly marked as such, and must not be
- misrepresented as being the original software.
- 3. This notice may not be removed or altered from any source distribution.
-
- L. Peter Deutsch
- ghost@aladdin.com
-
-ext/digest/rmd160/rmd160.[ch]:
-
- These files have the following copyright information, and by the
- author we are allowed to use it under the new-style BSD license.
-
- AUTHOR: Antoon Bosselaers, ESAT-COSIC
- (Arranged for libc by Todd C. Miller)
- DATE: 1 March 1996
-
- Copyright (c) Katholieke Universiteit Leuven
- 1996, All Rights Reserved
-
-ext/digest/rmd160/rmd160hl.c:
-ext/digest/sha1/sha1hl.c:
-
- These files are under the beer-ware license.
-
- "THE BEER-WARE LICENSE" (Revision 42):
- <phk@login.dkuug.dk> wrote this file. As long as you retain this notice you
- can do whatever you want with this stuff. If we meet some day, and you think
- this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp
-
-ext/digest/sha2/sha2.[ch]:
-ext/digest/sha2/sha2hl.c:
-
- These files are under the new-style BSD license.
-
- Copyright 2000 Aaron D. Gifford. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions
- are met:
- 1. Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- 2. Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
- 3. Neither the name of the copyright holder nor the names of contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) AND CONTRIBUTOR(S) ``AS IS'' AND
- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) OR CONTRIBUTOR(S) BE LIABLE
- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- SUCH DAMAGE.
-
-ext/nkf/nkf1.7/nkf.c:
-
- This file is under the following license. So to speak, it is
- copyrighted semi-public-domain software.
-
- Copyright (C) 1987, Fujitsu LTD. (Itaru ICHIKAWA)
- Everyone is permitted to do anything on this program
- including copying, modifying, improving.
- as long as you don't try to pretend that you wrote it.
- i.e., the above copyright notice has to appear in all copies.
- You don't have to ask before copying or publishing.
- THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE.
-
-ext/socket/addrinfo.h:
-ext/socket/getaddrinfo.c:
-ext/socket/getnameinfo.c:
-
- These files are under the new-style BSD license.
-
- Copyright (C) 1995, 1996, 1997, 1998, and 1999 WIDE Project.
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions
- are met:
- 1. Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- 2. Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
- 3. Neither the name of the project nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- SUCH DAMAGE.
diff --git a/LGPL b/LGPL
deleted file mode 100644
index b1e3f5a263..0000000000
--- a/LGPL
+++ /dev/null
@@ -1,504 +0,0 @@
- GNU LESSER GENERAL PUBLIC LICENSE
- Version 2.1, February 1999
-
- Copyright (C) 1991, 1999 Free Software Foundation, Inc.
- 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-[This is the first released version of the Lesser GPL. It also counts
- as the successor of the GNU Library Public License, version 2, hence
- the version number 2.1.]
-
- Preamble
-
- The licenses for most software are designed to take away your
-freedom to share and change it. By contrast, the GNU General Public
-Licenses are intended to guarantee your freedom to share and change
-free software--to make sure the software is free for all its users.
-
- This license, the Lesser General Public License, applies to some
-specially designated software packages--typically libraries--of the
-Free Software Foundation and other authors who decide to use it. You
-can use it too, but we suggest you first think carefully about whether
-this license or the ordinary General Public License is the better
-strategy to use in any particular case, based on the explanations below.
-
- When we speak of free software, we are referring to freedom of use,
-not price. Our General Public Licenses are designed to make sure that
-you have the freedom to distribute copies of free software (and charge
-for this service if you wish); that you receive source code or can get
-it if you want it; that you can change the software and use pieces of
-it in new free programs; and that you are informed that you can do
-these things.
-
- To protect your rights, we need to make restrictions that forbid
-distributors to deny you these rights or to ask you to surrender these
-rights. These restrictions translate to certain responsibilities for
-you if you distribute copies of the library or if you modify it.
-
- For example, if you distribute copies of the library, whether gratis
-or for a fee, you must give the recipients all the rights that we gave
-you. You must make sure that they, too, receive or can get the source
-code. If you link other code with the library, you must provide
-complete object files to the recipients, so that they can relink them
-with the library after making changes to the library and recompiling
-it. And you must show them these terms so they know their rights.
-
- We protect your rights with a two-step method: (1) we copyright the
-library, and (2) we offer you this license, which gives you legal
-permission to copy, distribute and/or modify the library.
-
- To protect each distributor, we want to make it very clear that
-there is no warranty for the free library. Also, if the library is
-modified by someone else and passed on, the recipients should know
-that what they have is not the original version, so that the original
-author's reputation will not be affected by problems that might be
-introduced by others.
-
- Finally, software patents pose a constant threat to the existence of
-any free program. We wish to make sure that a company cannot
-effectively restrict the users of a free program by obtaining a
-restrictive license from a patent holder. Therefore, we insist that
-any patent license obtained for a version of the library must be
-consistent with the full freedom of use specified in this license.
-
- Most GNU software, including some libraries, is covered by the
-ordinary GNU General Public License. This license, the GNU Lesser
-General Public License, applies to certain designated libraries, and
-is quite different from the ordinary General Public License. We use
-this license for certain libraries in order to permit linking those
-libraries into non-free programs.
-
- When a program is linked with a library, whether statically or using
-a shared library, the combination of the two is legally speaking a
-combined work, a derivative of the original library. The ordinary
-General Public License therefore permits such linking only if the
-entire combination fits its criteria of freedom. The Lesser General
-Public License permits more lax criteria for linking other code with
-the library.
-
- We call this license the "Lesser" General Public License because it
-does Less to protect the user's freedom than the ordinary General
-Public License. It also provides other free software developers Less
-of an advantage over competing non-free programs. These disadvantages
-are the reason we use the ordinary General Public License for many
-libraries. However, the Lesser license provides advantages in certain
-special circumstances.
-
- For example, on rare occasions, there may be a special need to
-encourage the widest possible use of a certain library, so that it becomes
-a de-facto standard. To achieve this, non-free programs must be
-allowed to use the library. A more frequent case is that a free
-library does the same job as widely used non-free libraries. In this
-case, there is little to gain by limiting the free library to free
-software only, so we use the Lesser General Public License.
-
- In other cases, permission to use a particular library in non-free
-programs enables a greater number of people to use a large body of
-free software. For example, permission to use the GNU C Library in
-non-free programs enables many more people to use the whole GNU
-operating system, as well as its variant, the GNU/Linux operating
-system.
-
- Although the Lesser General Public License is Less protective of the
-users' freedom, it does ensure that the user of a program that is
-linked with the Library has the freedom and the wherewithal to run
-that program using a modified version of the Library.
-
- The precise terms and conditions for copying, distribution and
-modification follow. Pay close attention to the difference between a
-"work based on the library" and a "work that uses the library". The
-former contains code derived from the library, whereas the latter must
-be combined with the library in order to run.
-
- GNU LESSER GENERAL PUBLIC LICENSE
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
- 0. This License Agreement applies to any software library or other
-program which contains a notice placed by the copyright holder or
-other authorized party saying it may be distributed under the terms of
-this Lesser General Public License (also called "this License").
-Each licensee is addressed as "you".
-
- A "library" means a collection of software functions and/or data
-prepared so as to be conveniently linked with application programs
-(which use some of those functions and data) to form executables.
-
- The "Library", below, refers to any such software library or work
-which has been distributed under these terms. A "work based on the
-Library" means either the Library or any derivative work under
-copyright law: that is to say, a work containing the Library or a
-portion of it, either verbatim or with modifications and/or translated
-straightforwardly into another language. (Hereinafter, translation is
-included without limitation in the term "modification".)
-
- "Source code" for a work means the preferred form of the work for
-making modifications to it. For a library, complete source code means
-all the source code for all modules it contains, plus any associated
-interface definition files, plus the scripts used to control compilation
-and installation of the library.
-
- Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope. The act of
-running a program using the Library is not restricted, and output from
-such a program is covered only if its contents constitute a work based
-on the Library (independent of the use of the Library in a tool for
-writing it). Whether that is true depends on what the Library does
-and what the program that uses the Library does.
-
- 1. You may copy and distribute verbatim copies of the Library's
-complete source code as you receive it, in any medium, provided that
-you conspicuously and appropriately publish on each copy an
-appropriate copyright notice and disclaimer of warranty; keep intact
-all the notices that refer to this License and to the absence of any
-warranty; and distribute a copy of this License along with the
-Library.
-
- You may charge a fee for the physical act of transferring a copy,
-and you may at your option offer warranty protection in exchange for a
-fee.
-
- 2. You may modify your copy or copies of the Library or any portion
-of it, thus forming a work based on the Library, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
- a) The modified work must itself be a software library.
-
- b) You must cause the files modified to carry prominent notices
- stating that you changed the files and the date of any change.
-
- c) You must cause the whole of the work to be licensed at no
- charge to all third parties under the terms of this License.
-
- d) If a facility in the modified Library refers to a function or a
- table of data to be supplied by an application program that uses
- the facility, other than as an argument passed when the facility
- is invoked, then you must make a good faith effort to ensure that,
- in the event an application does not supply such function or
- table, the facility still operates, and performs whatever part of
- its purpose remains meaningful.
-
- (For example, a function in a library to compute square roots has
- a purpose that is entirely well-defined independent of the
- application. Therefore, Subsection 2d requires that any
- application-supplied function or table used by this function must
- be optional: if the application does not supply it, the square
- root function must still compute square roots.)
-
-These requirements apply to the modified work as a whole. If
-identifiable sections of that work are not derived from the Library,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works. But when you
-distribute the same sections as part of a whole which is a work based
-on the Library, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote
-it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Library.
-
-In addition, mere aggregation of another work not based on the Library
-with the Library (or with a work based on the Library) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
- 3. You may opt to apply the terms of the ordinary GNU General Public
-License instead of this License to a given copy of the Library. To do
-this, you must alter all the notices that refer to this License, so
-that they refer to the ordinary GNU General Public License, version 2,
-instead of to this License. (If a newer version than version 2 of the
-ordinary GNU General Public License has appeared, then you can specify
-that version instead if you wish.) Do not make any other change in
-these notices.
-
- Once this change is made in a given copy, it is irreversible for
-that copy, so the ordinary GNU General Public License applies to all
-subsequent copies and derivative works made from that copy.
-
- This option is useful when you wish to copy part of the code of
-the Library into a program that is not a library.
-
- 4. You may copy and distribute the Library (or a portion or
-derivative of it, under Section 2) in object code or executable form
-under the terms of Sections 1 and 2 above provided that you accompany
-it with the complete corresponding machine-readable source code, which
-must be distributed under the terms of Sections 1 and 2 above on a
-medium customarily used for software interchange.
-
- If distribution of object code is made by offering access to copy
-from a designated place, then offering equivalent access to copy the
-source code from the same place satisfies the requirement to
-distribute the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
- 5. A program that contains no derivative of any portion of the
-Library, but is designed to work with the Library by being compiled or
-linked with it, is called a "work that uses the Library". Such a
-work, in isolation, is not a derivative work of the Library, and
-therefore falls outside the scope of this License.
-
- However, linking a "work that uses the Library" with the Library
-creates an executable that is a derivative of the Library (because it
-contains portions of the Library), rather than a "work that uses the
-library". The executable is therefore covered by this License.
-Section 6 states terms for distribution of such executables.
-
- When a "work that uses the Library" uses material from a header file
-that is part of the Library, the object code for the work may be a
-derivative work of the Library even though the source code is not.
-Whether this is true is especially significant if the work can be
-linked without the Library, or if the work is itself a library. The
-threshold for this to be true is not precisely defined by law.
-
- If such an object file uses only numerical parameters, data
-structure layouts and accessors, and small macros and small inline
-functions (ten lines or less in length), then the use of the object
-file is unrestricted, regardless of whether it is legally a derivative
-work. (Executables containing this object code plus portions of the
-Library will still fall under Section 6.)
-
- Otherwise, if the work is a derivative of the Library, you may
-distribute the object code for the work under the terms of Section 6.
-Any executables containing that work also fall under Section 6,
-whether or not they are linked directly with the Library itself.
-
- 6. As an exception to the Sections above, you may also combine or
-link a "work that uses the Library" with the Library to produce a
-work containing portions of the Library, and distribute that work
-under terms of your choice, provided that the terms permit
-modification of the work for the customer's own use and reverse
-engineering for debugging such modifications.
-
- You must give prominent notice with each copy of the work that the
-Library is used in it and that the Library and its use are covered by
-this License. You must supply a copy of this License. If the work
-during execution displays copyright notices, you must include the
-copyright notice for the Library among them, as well as a reference
-directing the user to the copy of this License. Also, you must do one
-of these things:
-
- a) Accompany the work with the complete corresponding
- machine-readable source code for the Library including whatever
- changes were used in the work (which must be distributed under
- Sections 1 and 2 above); and, if the work is an executable linked
- with the Library, with the complete machine-readable "work that
- uses the Library", as object code and/or source code, so that the
- user can modify the Library and then relink to produce a modified
- executable containing the modified Library. (It is understood
- that the user who changes the contents of definitions files in the
- Library will not necessarily be able to recompile the application
- to use the modified definitions.)
-
- b) Use a suitable shared library mechanism for linking with the
- Library. A suitable mechanism is one that (1) uses at run time a
- copy of the library already present on the user's computer system,
- rather than copying library functions into the executable, and (2)
- will operate properly with a modified version of the library, if
- the user installs one, as long as the modified version is
- interface-compatible with the version that the work was made with.
-
- c) Accompany the work with a written offer, valid for at
- least three years, to give the same user the materials
- specified in Subsection 6a, above, for a charge no more
- than the cost of performing this distribution.
-
- d) If distribution of the work is made by offering access to copy
- from a designated place, offer equivalent access to copy the above
- specified materials from the same place.
-
- e) Verify that the user has already received a copy of these
- materials or that you have already sent this user a copy.
-
- For an executable, the required form of the "work that uses the
-Library" must include any data and utility programs needed for
-reproducing the executable from it. However, as a special exception,
-the materials to be distributed need not include anything that is
-normally distributed (in either source or binary form) with the major
-components (compiler, kernel, and so on) of the operating system on
-which the executable runs, unless that component itself accompanies
-the executable.
-
- It may happen that this requirement contradicts the license
-restrictions of other proprietary libraries that do not normally
-accompany the operating system. Such a contradiction means you cannot
-use both them and the Library together in an executable that you
-distribute.
-
- 7. You may place library facilities that are a work based on the
-Library side-by-side in a single library together with other library
-facilities not covered by this License, and distribute such a combined
-library, provided that the separate distribution of the work based on
-the Library and of the other library facilities is otherwise
-permitted, and provided that you do these two things:
-
- a) Accompany the combined library with a copy of the same work
- based on the Library, uncombined with any other library
- facilities. This must be distributed under the terms of the
- Sections above.
-
- b) Give prominent notice with the combined library of the fact
- that part of it is a work based on the Library, and explaining
- where to find the accompanying uncombined form of the same work.
-
- 8. You may not copy, modify, sublicense, link with, or distribute
-the Library except as expressly provided under this License. Any
-attempt otherwise to copy, modify, sublicense, link with, or
-distribute the Library is void, and will automatically terminate your
-rights under this License. However, parties who have received copies,
-or rights, from you under this License will not have their licenses
-terminated so long as such parties remain in full compliance.
-
- 9. You are not required to accept this License, since you have not
-signed it. However, nothing else grants you permission to modify or
-distribute the Library or its derivative works. These actions are
-prohibited by law if you do not accept this License. Therefore, by
-modifying or distributing the Library (or any work based on the
-Library), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Library or works based on it.
-
- 10. Each time you redistribute the Library (or any work based on the
-Library), the recipient automatically receives a license from the
-original licensor to copy, distribute, link with or modify the Library
-subject to these terms and conditions. You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties with
-this License.
-
- 11. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Library at all. For example, if a patent
-license would not permit royalty-free redistribution of the Library by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Library.
-
-If any portion of this section is held invalid or unenforceable under any
-particular circumstance, the balance of the section is intended to apply,
-and the section as a whole is intended to apply in other circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system which is
-implemented by public license practices. Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
- 12. If the distribution and/or use of the Library is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Library under this License may add
-an explicit geographical distribution limitation excluding those countries,
-so that distribution is permitted only in or among countries not thus
-excluded. In such case, this License incorporates the limitation as if
-written in the body of this License.
-
- 13. The Free Software Foundation may publish revised and/or new
-versions of the Lesser General Public License from time to time.
-Such new versions will be similar in spirit to the present version,
-but may differ in detail to address new problems or concerns.
-
-Each version is given a distinguishing version number. If the Library
-specifies a version number of this License which applies to it and
-"any later version", you have the option of following the terms and
-conditions either of that version or of any later version published by
-the Free Software Foundation. If the Library does not specify a
-license version number, you may choose any version ever published by
-the Free Software Foundation.
-
- 14. If you wish to incorporate parts of the Library into other free
-programs whose distribution conditions are incompatible with these,
-write to the author to ask for permission. For software which is
-copyrighted by the Free Software Foundation, write to the Free
-Software Foundation; we sometimes make exceptions for this. Our
-decision will be guided by the two goals of preserving the free status
-of all derivatives of our free software and of promoting the sharing
-and reuse of software generally.
-
- NO WARRANTY
-
- 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
-WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
-EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
-OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
-KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
-LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
-THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
-WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
-AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
-FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
-CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
-LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
-RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
-FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
-SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
-DAMAGES.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Libraries
-
- If you develop a new library, and you want it to be of the greatest
-possible use to the public, we recommend making it free software that
-everyone can redistribute and change. You can do so by permitting
-redistribution under these terms (or, alternatively, under the terms of the
-ordinary General Public License).
-
- To apply these terms, attach the following notices to the library. It is
-safest to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least the
-"copyright" line and a pointer to where the full notice is found.
-
- <one line to give the library's name and a brief idea of what it does.>
- Copyright (C) <year> <name of author>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License as published by the Free Software Foundation; either
- version 2.1 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public
- License along with this library; if not, write to the Free Software
- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-Also add information on how to contact you by electronic and paper mail.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the library, if
-necessary. Here is a sample; alter the names:
-
- Yoyodyne, Inc., hereby disclaims all copyright interest in the
- library `Frob' (a library for tweaking knobs) written by James Random Hacker.
-
- <signature of Ty Coon>, 1 April 1990
- Ty Coon, President of Vice
-
-That's all there is to it!
-
-
diff --git a/MANIFEST b/MANIFEST
deleted file mode 100644
index e9ba1c25ae..0000000000
--- a/MANIFEST
+++ /dev/null
@@ -1,297 +0,0 @@
-COPYING
-COPYING.ja
-ChangeLog
-GPL
-LEGAL
-LGPL
-MANIFEST
-Makefile.in
-README
-README.ja
-README.EXT
-README.EXT.ja
-ToDo
-array.c
-bignum.c
-class.c
-compar.c
-configure
-configure.in
-config.guess
-config.sub
-defines.h
-dir.c
-dln.c
-dln.h
-dmyext.c
-enum.c
-env.h
-error.c
-eval.c
-file.c
-gc.c
-hash.c
-inits.c
-install-sh
-instruby.rb
-intern.h
-io.c
-keywords
-lex.c
-main.c
-marshal.c
-math.c
-mkconfig.rb
-node.h
-numeric.c
-object.c
-pack.c
-parse.c
-parse.y
-prec.c
-process.c
-random.c
-range.c
-re.c
-re.h
-regex.c
-regex.h
-ruby.1
-ruby.c
-ruby.h
-rubyio.h
-rubysig.h
-rubytest.rb
-signal.c
-sprintf.c
-st.c
-st.h
-string.c
-struct.c
-time.c
-util.h
-util.c
-variable.c
-version.c
-version.h
-djgpp/README.djgpp
-djgpp/config.hin
-djgpp/config.sed
-djgpp/configure.bat
-djgpp/mkver.sed
-cygwin/GNUmakefile.in
-doc/NEWS
-doc/forwardable.rd
-doc/forwardable.rd.ja
-doc/irb/irb-tools.rd.ja
-doc/irb/irb.rd
-doc/irb/irb.rd.ja
-doc/net/http.rd.ja
-doc/net/pop.rd.ja
-doc/net/smtp.rd.ja
-doc/shell.rd
-doc/shell.rd.ja
-ext/Setup
-ext/Setup.dj
-ext/Setup.emx
-ext/Setup.nt
-ext/Setup.x68
-ext/aix_mksym.rb
-ext/configsub.rb
-ext/extmk.rb.in
-lib/English.rb
-lib/Env.rb
-lib/README
-lib/base64.rb
-lib/benchmark.rb
-lib/cgi.rb
-lib/cgi/session.rb
-lib/cgi-lib.rb
-lib/complex.rb
-lib/date.rb
-lib/date2.rb
-lib/debug.rb
-lib/delegate.rb
-lib/e2mmap.rb
-lib/eregex.rb
-lib/find.rb
-lib/final.rb
-lib/finalize.rb
-lib/forwardable.rb
-lib/ftplib.rb
-lib/ftools.rb
-lib/getopts.rb
-lib/getoptlong.rb
-lib/importenv.rb
-lib/irb.rb
-lib/irb/completion.rb
-lib/irb/context.rb
-lib/irb/extend-command.rb
-lib/irb/frame.rb
-lib/irb/help.rb
-lib/irb/init.rb
-lib/irb/input-method.rb
-lib/irb/lc/error.rb
-lib/irb/lc/help-message
-lib/irb/lc/ja/error.rb
-lib/irb/lc/ja/help-message
-lib/irb/loader.rb
-lib/irb/locale.rb
-lib/irb/multi-irb.rb
-lib/irb/ruby-lex.rb
-lib/irb/ruby-token.rb
-lib/irb/slex.rb
-lib/irb/version.rb
-lib/irb/workspace.rb
-lib/irb/ws-for-case-2.rb
-lib/irb/xmp.rb
-lib/jcode.rb
-lib/mailread.rb
-lib/mathn.rb
-lib/matrix.rb
-lib/mkmf.rb
-lib/monitor.rb
-lib/mutex_m.rb
-lib/net/ftp.rb
-lib/net/http.rb
-lib/net/imap.rb
-lib/net/pop.rb
-lib/net/protocol.rb
-lib/net/smtp.rb
-lib/net/telnet.rb
-lib/observer.rb
-lib/open3.rb
-lib/ostruct.rb
-lib/parsearg.rb
-lib/parsedate.rb
-lib/ping.rb
-lib/pp.rb
-lib/prettyprint.rb
-lib/profile.rb
-lib/pstore.rb
-lib/rational.rb
-lib/readbytes.rb
-lib/shell.rb
-lib/shell/builtin-command.rb
-lib/shell/command-processor.rb
-lib/shell/error.rb
-lib/shell/filter.rb
-lib/shell/process-controller.rb
-lib/shell/system-command.rb
-lib/shell/version.rb
-lib/shellwords.rb
-lib/singleton.rb
-lib/sync.rb
-lib/telnet.rb
-lib/tempfile.rb
-lib/thread.rb
-lib/thwait.rb
-lib/time.rb
-lib/timeout.rb
-lib/tracer.rb
-lib/tsort.rb
-lib/uri.rb
-lib/uri/common.rb
-lib/uri/ftp.rb
-lib/uri/generic.rb
-lib/uri/http.rb
-lib/uri/https.rb
-lib/uri/ldap.rb
-lib/uri/mailto.rb
-lib/weakref.rb
-misc/README
-misc/inf-ruby.el
-misc/ruby-mode.el
-misc/rubydb2x.el
-misc/rubydb3x.el
-missing/alloca.c
-missing/crypt.c
-missing/dup2.c
-missing/file.h
-missing/finite.c
-missing/fileblocks.c
-missing/flock.c
-missing/hypot.c
-missing/isinf.c
-missing/isnan.c
-missing/memcmp.c
-missing/memmove.c
-missing/mkdir.c
-missing/os2.c
-missing/strcasecmp.c
-missing/strncasecmp.c
-missing/strchr.c
-missing/strerror.c
-missing/strftime.c
-missing/strstr.c
-missing/strtod.c
-missing/strtol.c
-missing/strtoul.c
-missing/vsnprintf.c
-missing/x68.c
-sample/README
-sample/biorhythm.rb
-sample/cal.rb
-sample/cbreak.rb
-sample/clnt.rb
-sample/dbmtest.rb
-sample/dir.rb
-sample/dualstack-fetch.rb
-sample/dualstack-httpd.rb
-sample/eval.rb
-sample/export.rb
-sample/exyacc.rb
-sample/fact.rb
-sample/fib.awk
-sample/fib.pl
-sample/fib.py
-sample/fib.rb
-sample/fib.scm
-sample/freq.rb
-sample/from.rb
-sample/fullpath.rb
-sample/getopts.test
-sample/goodfriday.rb
-sample/irb.rb
-sample/less.rb
-sample/list.rb
-sample/list2.rb
-sample/list3.rb
-sample/mine.rb
-sample/mkproto.rb
-sample/mpart.rb
-sample/mrshtest.rb
-sample/observ.rb
-sample/occur.pl
-sample/occur.rb
-sample/occur2.rb
-sample/philos.rb
-sample/pi.rb
-sample/rename.rb
-sample/rcs.awk
-sample/rcs.dat
-sample/rcs.rb
-sample/regx.rb
-sample/sieve.rb
-sample/svr.rb
-sample/test.rb
-sample/time.rb
-sample/trojan.rb
-sample/tsvr.rb
-sample/uumerge.rb
-win32/Makefile.sub
-win32/README.win32
-win32/config.h.in
-win32/config.status.in
-win32/configure.bat
-win32/dir.h
-win32/mkexports.rb
-win32/resource.rb
-win32/setup.mak
-win32/win32.c
-win32/win32.h
-win32/winmain.c
-x68/fconvert.c
-x68/select.c
-x68/_dtos18.c
-x68/_round.c
diff --git a/Makefile.in b/Makefile.in
deleted file mode 100644
index 5fad5c3a47..0000000000
--- a/Makefile.in
+++ /dev/null
@@ -1,284 +0,0 @@
-SHELL = /bin/sh
-
-#### Start of system configuration section. ####
-
-srcdir = @srcdir@
-VPATH = $(srcdir):$(srcdir)/missing
-
-CC = @CC@
-YACC = @YACC@
-PURIFY =
-AUTOCONF = autoconf
-@SET_MAKE@
-
-prefix = @prefix@
-CFLAGS = @CFLAGS@
-CPPFLAGS = -I. -I$(srcdir) -I@includedir@
-LDFLAGS = @STATIC@ $(CFLAGS) @LDFLAGS@
-XLDFLAGS = @XLDFLAGS@
-EXTLIBS =
-LIBS = @LIBS@ $(EXTLIBS)
-MISSING = @LIBOBJS@ @ALLOCA@
-LDSHARED = @LIBRUBY_LDSHARED@
-DLDFLAGS = @LIBRUBY_DLDFLAGS@
-SOLIBS = @SOLIBS@
-MAINLIBS = @MAINLIBS@
-
-RUBY_INSTALL_NAME=@RUBY_INSTALL_NAME@
-RUBY_SO_NAME=@RUBY_SO_NAME@
-EXEEXT = @EXEEXT@
-PROGRAM=$(RUBY_INSTALL_NAME)$(EXEEXT)
-
-#### End of system configuration section. ####
-
-MAJOR= @MAJOR@
-MINOR= @MINOR@
-TEENY= @TEENY@
-
-LIBRUBY_A = @LIBRUBY_A@
-LIBRUBY_SO = @LIBRUBY_SO@
-LIBRUBY_ALIASES= @LIBRUBY_ALIASES@
-LIBRUBY = @LIBRUBY@
-LIBRUBYARG = @LIBRUBYARG@
-
-EXTOBJS =
-
-MAINOBJ = main.@OBJEXT@
-
-OBJS = array.@OBJEXT@ \
- bignum.@OBJEXT@ \
- class.@OBJEXT@ \
- compar.@OBJEXT@ \
- dir.@OBJEXT@ \
- dln.@OBJEXT@ \
- enum.@OBJEXT@ \
- error.@OBJEXT@ \
- eval.@OBJEXT@ \
- file.@OBJEXT@ \
- gc.@OBJEXT@ \
- hash.@OBJEXT@ \
- inits.@OBJEXT@ \
- io.@OBJEXT@ \
- marshal.@OBJEXT@ \
- math.@OBJEXT@ \
- numeric.@OBJEXT@ \
- object.@OBJEXT@ \
- pack.@OBJEXT@ \
- parse.@OBJEXT@ \
- process.@OBJEXT@ \
- prec.@OBJEXT@ \
- random.@OBJEXT@ \
- range.@OBJEXT@ \
- re.@OBJEXT@ \
- regex.@OBJEXT@ \
- ruby.@OBJEXT@ \
- signal.@OBJEXT@ \
- sprintf.@OBJEXT@ \
- st.@OBJEXT@ \
- string.@OBJEXT@ \
- struct.@OBJEXT@ \
- time.@OBJEXT@ \
- util.@OBJEXT@ \
- variable.@OBJEXT@ \
- version.@OBJEXT@ \
- $(MISSING)
-
-all: miniruby$(EXEEXT) @PREP@ rbconfig.rb $(LIBRUBY)
- @@MINIRUBY@ -Cext extmk.rb @EXTSTATIC@
-
-miniruby$(EXEEXT): config.status $(LIBRUBY_A) $(MAINOBJ) dmyext.@OBJEXT@
- @rm -f $@
- $(PURIFY) $(CC) $(LDFLAGS) $(MAINOBJ) dmyext.@OBJEXT@ $(LIBRUBY_A) $(LIBS) -o $@
-
-$(PROGRAM): $(LIBRUBY) $(MAINOBJ) $(EXTOBJS)
- @rm -f $@
- $(PURIFY) $(CC) $(LDFLAGS) $(XLDFLAGS) $(MAINLIBS) $(MAINOBJ) $(EXTOBJS) $(LIBRUBYARG) $(LIBS) -o $@
-
-$(LIBRUBY_A): $(OBJS) dmyext.@OBJEXT@
- @AR@ rcu $@ $(OBJS) dmyext.@OBJEXT@
- @-@RANLIB@ $@ 2> /dev/null || true
-
-$(LIBRUBY_SO): $(OBJS) dmyext.@OBJEXT@ miniruby$(EXEEXT)
- $(LDSHARED) $(DLDFLAGS) $(OBJS) dmyext.@OBJEXT@ $(SOLIBS) -o $@
- @-@MINIRUBY@ -e 'ARGV.each{|link| File.delete link if File.exist? link; \
- File.symlink "$(LIBRUBY_SO)", link}' \
- $(LIBRUBY_ALIASES) || true
-
-install: rbconfig.rb
- @MINIRUBY@ $(srcdir)/instruby.rb $(DESTDIR)
-
-clean-ext:; @-@MINIRUBY@ -Cext extmk.rb clean 2> /dev/null || true
-
-clean-local:
- @rm -f $(OBJS) $(MAINOBJ) $(LIBRUBY_A) $(LIBRUBY_SO) $(LIBRUBY_ALIASES)
- @rm -f ext/extinit.c ext/extinit.@OBJEXT@ dmyext.@OBJEXT@
- @rm -f $(PROGRAM) miniruby$(EXEEXT)
-
-clean: clean-ext clean-local
-
-distclean-ext:
- @-@MINIRUBY@ -Cext extmk.rb distclean 2> /dev/null || true
-
-distclean-local: clean-local
- @rm -f Makefile ext/extmk.rb config.h rbconfig.rb
- @rm -f ext/config.cache config.cache config.log config.status
- @rm -f *~ core *.core gmon.out y.tab.c y.output ruby.imp
-
-distclean: distclean-ext distclean-local
-
-realclean: distclean
- @rm -f parse.c
- @rm -f lex.c
-
-test: miniruby$(EXEEXT) rbconfig.rb
- @./miniruby$(EXEEXT) $(srcdir)/rubytest.rb
-
-rbconfig.rb: miniruby$(EXEEXT) $(srcdir)/mkconfig.rb config.status
- @@MINIRUBY@ $(srcdir)/mkconfig.rb rbconfig.rb
-
-fake.rb: miniruby$(EXEEXT)
- @echo ' \
- class Object; \
- remove_const :RUBY_PLATFORM; \
- remove_const :RUBY_VERSION; \
- RUBY_PLATFORM = "@arch@"; \
- RUBY_VERSION = "@MAJOR@.@MINOR@.@TEENY@"; \
- CROSS_COMPILING = true; \
- end \
- ' > $@
-
-config.status: $(srcdir)/configure
- $(SHELL) ./config.status --recheck
-
-$(srcdir)/configure: $(srcdir)/configure.in
- cd $(srcdir) && $(AUTOCONF)
-
-.c.@OBJEXT@:
- $(CC) $(CFLAGS) $(CPPFLAGS) -c $<
-
-lex.c: keywords
- gperf -p -j1 -i 1 -g -o -t -N rb_reserved_word -k1,3,$$ $(srcdir)/keywords > lex.c
-
-parse.c: parse.y
- $(YACC) $<
- mv -f y.tab.c parse.c
-
-parse.@OBJEXT@: parse.c
-
-alloca.@OBJEXT@: $(srcdir)/missing/alloca.c
- $(CC) -I. $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/alloca.c
-
-crypt.@OBJEXT@: $(srcdir)/missing/crypt.c
- $(CC) -I. $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/crypt.c
-
-dup2.@OBJEXT@: $(srcdir)/missing/dup2.c
- $(CC) -I. $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/dup2.c
-
-finite.@OBJEXT@: $(srcdir)/missing/finite.c
- $(CC) -I. $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/finite.c
-
-flock.@OBJEXT@: $(srcdir)/missing/flock.c
- $(CC) -I. $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/flock.c
-
-isinf.@OBJEXT@: $(srcdir)/missing/isinf.c
- $(CC) -I. $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/isinf.c
-
-isnan.@OBJEXT@: $(srcdir)/missing/isnan.c
- $(CC) -I. $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/isnan.c
-
-fnmatch.@OBJEXT@: $(srcdir)/missing/fnmatch.c
- $(CC) -I. $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/fnmatch.c
-
-memcmp.@OBJEXT@: $(srcdir)/missing/memcmp.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/memcmp.c
-
-memmove.@OBJEXT@: $(srcdir)/missing/memmove.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/memmove.c
-
-mkdir.@OBJEXT@: $(srcdir)/missing/mkdir.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/mkdir.c
-
-vsnprintf.@OBJEXT@: $(srcdir)/missing/vsnprintf.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/vsnprintf.c
-
-strcasecmp.@OBJEXT@: $(srcdir)/missing/strcasecmp.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/strcasecmp.c
-
-strncasecmp.@OBJEXT@: $(srcdir)/missing/strncasecmp.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/strncasecmp.c
-
-strchr.@OBJEXT@: $(srcdir)/missing/strchr.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/strchr.c
-
-strerror.@OBJEXT@: $(srcdir)/missing/strerror.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/strerror.c
-
-strftime.@OBJEXT@: $(srcdir)/missing/strftime.c
- $(CC) -I. $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/strftime.c
-
-strstr.@OBJEXT@: $(srcdir)/missing/strstr.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/strstr.c
-
-strtod.@OBJEXT@: $(srcdir)/missing/strtod.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/strtod.c
-
-strtol.@OBJEXT@: $(srcdir)/missing/strtol.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/strtol.c
-
-strtoul.@OBJEXT@: $(srcdir)/missing/strtoul.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/strtoul.c
-
-x68.@OBJEXT@: $(srcdir)/missing/x68.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/x68.c
-
-os2.@OBJEXT@: $(srcdir)/missing/os2.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/os2.c
-
-dl_os2.@OBJEXT@: $(srcdir)/missing/dl_os2.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/dl_os2.c
-
-win32.@OBJEXT@: $(srcdir)/win32/win32.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -I$(srcdir)/win32 -c $(srcdir)/win32/win32.c
-
-# Prevent GNU make v3 from overflowing arg limit on SysV.
-.NOEXPORT:
-###
-parse.@OBJEXT@: parse.y ruby.h config.h defines.h intern.h env.h node.h st.h regex.h util.h lex.c
-###
-array.@OBJEXT@: array.c ruby.h config.h defines.h intern.h util.h st.h
-bignum.@OBJEXT@: bignum.c ruby.h config.h defines.h intern.h
-class.@OBJEXT@: class.c ruby.h config.h defines.h intern.h rubysig.h node.h st.h
-compar.@OBJEXT@: compar.c ruby.h config.h defines.h intern.h
-dir.@OBJEXT@: dir.c ruby.h config.h defines.h intern.h
-dln.@OBJEXT@: dln.c config.h defines.h dln.h
-dmyext.@OBJEXT@: dmyext.c
-enum.@OBJEXT@: enum.c ruby.h config.h defines.h intern.h node.h
-error.@OBJEXT@: error.c ruby.h config.h defines.h intern.h env.h version.h
-eval.@OBJEXT@: eval.c ruby.h config.h defines.h intern.h node.h env.h rubysig.h st.h dln.h
-file.@OBJEXT@: file.c ruby.h config.h defines.h intern.h rubyio.h rubysig.h dln.h util.h
-gc.@OBJEXT@: gc.c ruby.h config.h defines.h intern.h rubysig.h st.h node.h env.h re.h regex.h
-hash.@OBJEXT@: hash.c ruby.h config.h defines.h intern.h st.h rubysig.h util.h
-inits.@OBJEXT@: inits.c ruby.h config.h defines.h intern.h
-io.@OBJEXT@: io.c ruby.h config.h defines.h intern.h rubyio.h rubysig.h env.h util.h
-main.@OBJEXT@: main.c ruby.h config.h defines.h intern.h
-marshal.@OBJEXT@: marshal.c ruby.h config.h defines.h intern.h rubyio.h st.h
-prec.@OBJEXT@: prec.c ruby.h config.h defines.h intern.h
-math.@OBJEXT@: math.c ruby.h config.h defines.h intern.h
-numeric.@OBJEXT@: numeric.c ruby.h config.h defines.h intern.h
-object.@OBJEXT@: object.c ruby.h config.h defines.h intern.h st.h
-pack.@OBJEXT@: pack.c ruby.h config.h defines.h intern.h
-process.@OBJEXT@: process.c ruby.h config.h defines.h intern.h rubysig.h st.h
-random.@OBJEXT@: random.c ruby.h config.h defines.h intern.h
-range.@OBJEXT@: range.c ruby.h config.h defines.h intern.h
-re.@OBJEXT@: re.c ruby.h config.h defines.h intern.h re.h regex.h
-regex.@OBJEXT@: regex.c config.h regex.h
-ruby.@OBJEXT@: ruby.c ruby.h config.h defines.h intern.h dln.h node.h util.h
-signal.@OBJEXT@: signal.c ruby.h config.h defines.h intern.h rubysig.h
-sprintf.@OBJEXT@: sprintf.c ruby.h config.h defines.h intern.h
-st.@OBJEXT@: st.c config.h st.h
-string.@OBJEXT@: string.c ruby.h config.h defines.h intern.h re.h regex.h
-struct.@OBJEXT@: struct.c ruby.h config.h defines.h intern.h
-time.@OBJEXT@: time.c ruby.h config.h defines.h intern.h
-util.@OBJEXT@: util.c ruby.h config.h defines.h intern.h util.h
-variable.@OBJEXT@: variable.c ruby.h config.h defines.h intern.h env.h node.h st.h
-version.@OBJEXT@: version.c ruby.h config.h defines.h intern.h version.h
diff --git a/README b/README
deleted file mode 100644
index bde22dff78..0000000000
--- a/README
+++ /dev/null
@@ -1,106 +0,0 @@
-* What's Ruby
-
-Ruby is the interpreted scripting language for quick and
-easy object-oriented programming. It has many features to
-process text files and to do system management tasks (as in
-Perl). It is simple, straight-forward, and extensible.
-
-
-* Features of Ruby
-
- + Simple Syntax
- + *Normal* Object-Oriented features(ex. class, method calls)
- + *Advanced* Object-Oriented features(ex. Mix-in, Singleton-method)
- + Operator Overloading
- + Exception Handling
- + Iterators and Closures
- + Garbage Collection
- + Dynamic Loading of Object files(on some architecture)
- + Highly Portable(works on many UNIX machines, and on DOS,
- Windows, Mac, BeOS etc.)
-
-
-* How to get Ruby
-
-The Ruby distribution can be found on:
-
- ftp://ftp.ruby-lang.org/pub/ruby/
-
-You can get it by anonymous CVS. How to check out is:
-
- $ cvs -d :pserver:anonymous@cvs.ruby-lang.org:/src login
- (Logging in to anonymous@cvs.ruby-lang.org)
- CVS password: anonymous
- $ cvs -z4 -d :pserver:anonymous@cvs.ruby-lang.org:/src checkout ruby
-
-
-* Ruby home-page
-
-The URL of the Ruby home-page is:
-
- http://www.ruby-lang.org/
-
-
-* Mailing list
-
-There is a mailing list to talk about Ruby.
-To subscribe this list, please send the following phrase
-
- subscribe YourFirstName YourFamilyName
-e.g.
- subscribe Joseph Smith
-
-in the mail body (not subject) to the address <ruby-talk-ctl@ruby-lang.org>.
-
-
-* How to compile and install
-
-This is what you need to do to compile and install Ruby:
-
- 1. If ./configure does not exist or is older than configure.in,
- run autoconf to (re)generate configure.
-
- 2. Run ./configure, which will generate config.h and Makefile.
-
- 3. Edit defines.h if you need. Probably this step will not need.
-
- 4. Remove comment mark(#) before the module names from ext/Setup (or
- add module names if not present), if you want to link modules
- statically.
-
- If you don't want to compile non static extension modules
- (probably on architectures which does not allow dynamic loading),
- remove comment mark from the line "#option nodynamic" in
- ext/Setup.
-
- 5. Run make.
-
- 6. Optionally, run 'make test' to check whether the compiled Ruby
- interpreter works well. If you see the message "test succeeded",
- your ruby works as it should (hopefully).
-
- 7. Run 'make install'
-
- You may have to be a super user to install ruby.
-
-If you fail to compile ruby, please send the detailed error report with
-the error log and machine/OS type, to help others.
-
-
-* Copying
-
-See the file COPYING.
-
-
-* The Author
-
-Feel free to send comments and bug reports to the author. Here is the
-author's latest mail address:
-
- matz@netlab.jp
-
--------------------------------------------------------
-created at: Thu Aug 3 11:57:36 JST 1995
-Local variables:
-mode: indented-text
-end:
diff --git a/README.EXT b/README.EXT
deleted file mode 100644
index 49279db73f..0000000000
--- a/README.EXT
+++ /dev/null
@@ -1,1026 +0,0 @@
-.\" README.EXT - -*- Text -*- created at: Mon Aug 7 16:45:54 JST 1995
-
-This document explains how to make extension libraries for Ruby.
-
-1. Basic knowledge
-
-In C, variables have types and data do not have types. In contrast,
-Ruby variables do not have static type and data themselves have
-types. So, data need to be converted across the languages.
-
-Data in Ruby represented C type `VALUE'. Each VALUE data have its
-data-type.
-
-To retrieve an C data from the VALUE, you need to:
-
- (1) Identify VALUE's data type
- (2) Convert VALUE into C data
-
-Converting to wrong data type may cause serious problems.
-
-
-1.1 Data-types
-
-Ruby interpreter has data-types as below:
-
- T_NIL nil
- T_OBJECT ordinary object
- T_CLASS class
- T_MODULE module
- T_FLOAT floating point number
- T_STRING string
- T_REGEXP regular expression
- T_ARRAY array
- T_FIXNUM Fixnum(31bit integer)
- T_HASH associative array
- T_STRUCT (Ruby) structure
- T_BIGNUM multi precision integer
- T_TRUE true
- T_FALSE false
- T_DATA data
- T_SYMBOL symbol
-
-Otherwise, there are several other types used internally:
-
- T_ICLASS
- T_MATCH
- T_UNDEF
- T_VARMAP
- T_SCOPE
- T_NODE
-
-Most of the types are represented by C structures.
-
-1.2 Check Data Type of the VALUE
-
-The macro TYPE() defined in ruby.h shows data-type of the VALUE.
-TYPE() returns the constant number T_XXXX described above. To handle
-data-types, the code will be like:
-
- switch (TYPE(obj)) {
- case T_FIXNUM:
- /* process Fixnum */
- break;
- case T_STRING:
- /* process String */
- break;
- case T_ARRAY:
- /* process Array */
- break;
- default:
- /* raise exception */
- rb_raise(rb_eTypeError, "not valid value");
- break;
- }
-
-There is the data-type check function.
-
- void Check_Type(VALUE value, int type)
-
-It raises an exception, if the VALUE does not have the type specified.
-
-There are faster check-macros for fixnums and nil.
-
- FIXNUM_P(obj)
- NIL_P(obj)
-
-1.3 Convert VALUE into C data
-
-The data for type T_NIL, T_FALSE, T_TRUE are nil, true, false
-respectively. They are singletons for the data type.
-
-The T_FIXNUM data is the 31bit length fixed integer (63bit length on
-some machines), which can be convert to the C integer by using
-FIX2INT() macro. There also be NUM2INT() which converts any Ruby
-numbers into C integer. The NUM2INT() macro includes type check, so
-the exception will be raised if conversion failed.
-
-Other data types have corresponding C structures, e.g. struct RArray
-for T_ARRAY etc. VALUE of the type which has corresponding structure
-can be cast to retrieve the pointer to the struct. The casting macro
-RXXXX for each data type like RARRAY(obj). see "ruby.h".
-
-For example, `RSTRING(size)->len' is the way to get the size of the
-Ruby String object. The allocated region can be accessed by
-`RSTRING(str)->ptr'. For arrays, `RARRAY(ary)->len' and
-`RARRAY(ary)->ptr' respectively.
-
-Notice: Do not change the value of the structure directly, unless you
-are responsible about the result. It will be the cause of interesting
-bugs.
-
-1.4 Convert C data into VALUE
-
-To convert C data to the values of Ruby:
-
- * FIXNUM
-
- left shift 1 bit, and turn on LSB.
-
- * Other pointer values
-
- cast to VALUE.
-
-You can determine whether VALUE is pointer or not, by checking LSB.
-
-Notice Ruby does not allow arbitrary pointer value to be VALUE. They
-should be pointers to the structures which Ruby knows. The known
-structures are defined in <ruby.h>.
-
-To convert C numbers to Ruby value, use these macros.
-
- INT2FIX() for integers within 31bits.
- INT2NUM() for arbitrary sized integer.
-
-INT2NUM() converts integers into Bignums, if it is out of FIXNUM
-range, but bit slower.
-
-1.5 Manipulate Ruby data
-
-As I already told, it is not recommended to modify object's internal
-structure. To manipulate objects, use functions supplied by Ruby
-interpreter. Useful functions are listed below (not all):
-
- String functions
-
- rb_str_new(const char *ptr, long len)
-
- Creates a new Ruby string.
-
- rb_str_new2(const char *ptr)
-
- Creates a new Ruby string from C string. This is equivalent to
- rb_str_new(ptr, strlen(ptr)).
-
- rb_tainted_str_new(const char *ptr, long len)
-
- Creates a new tainted Ruby string. Strings from external data
- should be tainted.
-
- rb_tainted_str_new2(const char *ptr)
-
- Creates a new tainted Ruby string from C string.
-
- rb_str_cat(VALUE str, const char *ptr, long len)
-
- Appends len bytes data from ptr to the Ruby string.
-
- Array functions
-
- rb_ary_new()
-
- Creates an array with no element.
-
- rb_ary_new2(long len)
-
- Creates an array with no element, with allocating internal buffer
- for len elements.
-
- rb_ary_new3(long n, ...)
-
- Creates an n-elements array from arguments.
-
- rb_ary_new4(long n, VALUE *elts)
-
- Creates an n-elements array from C array.
-
- rb_ary_push(VALUE ary, VALUE val)
- rb_ary_pop(VALUE ary)
- rb_ary_shift(VALUE ary)
- rb_ary_unshift(VALUE ary, VALUE val)
-
- Array operations. The first argument to each functions must be an
- array. They may dump core if other types given.
-
-2. Extend Ruby with C
-
-2.1 Add new features to Ruby
-
-You can add new features (classes, methods, etc.) to the Ruby
-interpreter. Ruby provides the API to define things below:
-
- * Classes, Modules
- * Methods, Singleton Methods
- * Constants
-
-2.1.1 Class/module definition
-
-To define class or module, use functions below:
-
- VALUE rb_define_class(const char *name, VALUE super)
- VALUE rb_define_module(const char *name)
-
-These functions return the newly created class or module. You may
-want to save this reference into the variable to use later.
-
-To define nested class or module, use functions below:
-
- VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
- VALUE rb_define_module_under(VALUE outer, const char *name)
-
-2.1.2 Method/singleton method definition
-
-To define methods or singleton methods, use functions below:
-
- void rb_define_method(VALUE klass, const char *name,
- VALUE (*func)(), int argc)
-
- void rb_define_singleton_method(VALUE object, const char *name,
- VALUE (*func)(), int argc)
-
-The `argc' represents the number of the arguments to the C function,
-which must be less than 17. But I believe you don't need that much. :-)
-
-If `argc' is negative, it specifies calling sequence, not number of
-the arguments.
-
-If argc is -1, the function will be called like:
-
- VALUE func(int argc, VALUE *argv, VALUE obj)
-
-where argc is the actual number of arguments, argv is the C array of
-the arguments, and obj is the receiver.
-
-if argc is -2, the arguments are passed in Ruby array. The function
-will be called like:
-
- VALUE func(VALUE obj, VALUE args)
-
-where obj is the receiver, and args is the Ruby array containing
-actual arguments.
-
-There're two more functions to define method. One is to define
-private method:
-
- void rb_define_private_method(VALUE klass, const char *name,
- VALUE (*func)(), int argc)
-
-The other is to define module function, which is private AND singleton
-method of the module. For example, sqrt is the module function
-defined in Math module. It can be call in the form like:
-
- Math.sqrt(4)
-
-or
-
- include Math
- sqrt(4)
-
-To define module function
-
- void rb_define_module_function(VALUE module, const char *name,
- VALUE (*func)(), int argc)
-
-Oh, in addition, function-like method, which is private method defined
-in Kernel module, can be defined using:
-
- void rb_define_global_function(const char *name, VALUE (*func)(), int argc)
-
-To define alias to the method,
-
- void rb_define_alias(VALUE module, const char* new, const char* old);
-
-2.1.3 Constant definition
-
-We have 2 functions to define constants:
-
- void rb_define_const(VALUE klass, const char *name, VALUE val)
- void rb_define_global_const(const char *name, VALUE val)
-
-The former is to define constant under specified class/module. The
-latter is to define global constant.
-
-2.2 Use Ruby features from C
-
-There are several ways to invoke Ruby's features from C code.
-
-2.2.1 Evaluate Ruby Program in String
-
-Easiest way to call Ruby's function from C program is to evaluate the
-string as Ruby program. This function will do the job.
-
- VALUE rb_eval_string(const char *str)
-
-Evaluation is done under current context, thus current local variables
-of the innermost method (which is defined by Ruby) can be accessed.
-
-2.2.2 ID or Symbol
-
-You can invoke methods directly, without parsing the string. First I
-need to explain about symbols (which data type is ID). ID is the
-integer number to represent Ruby's identifiers such as variable names.
-It can be accessed from Ruby in the form like:
-
- :Identifier
-
-You can get the symbol value from string within C code, by using
-
- rb_intern(const char *name)
-
-2.2.3 Invoke Ruby method from C
-
-To invoke methods directly, you can use the function below
-
- VALUE rb_funcall(VALUE recv, ID mid, int argc, ...)
-
-This function invokes the method of the recv, which name is specified
-by the symbol mid.
-
-2.2.4 Accessing the variables and constants
-
-You can access class variables, and instance variables using access
-functions. Also, global variables can be shared between both worlds.
-There's no way to access Ruby's local variables.
-
-The functions to access/modify instance variables are below:
-
- VALUE rb_ivar_get(VALUE obj, ID id)
- VALUE rb_ivar_set(VALUE obj, ID id, VALUE val)
-
-id must be the symbol, which can be retrieved by rb_intern().
-
-To access the constants of the class/module:
-
- VALUE rb_const_get(VALUE obj, ID id)
-
-See 2.1.3 for defining new constant.
-
-3. Information sharing between Ruby and C
-
-3.1 Ruby constant that C can be accessed from C
-
-Following Ruby constants can be referred from C.
-
- Qtrue
- Qfalse
-
-Boolean values. Qfalse is false in the C also (i.e. 0).
-
- Qnil
-
-Ruby nil in C scope.
-
-3.2 Global variables shared between C and Ruby
-
-Information can be shared between two worlds, using shared global
-variables. To define them, you can use functions listed below:
-
- void rb_define_variable(const char *name, VALUE *var)
-
-This function defines the variable which is shared by the both world.
-The value of the global variable pointed by `var', can be accessed
-through Ruby's global variable named `name'.
-
-You can define read-only (from Ruby, of course) variable by the
-function below.
-
- void rb_define_readonly_variable(const char *name, VALUE *var)
-
-You can defined hooked variables. The accessor functions (getter and
-setter) are called on access to the hooked variables.
-
- void rb_define_hooked_variable(constchar *name, VALUE *var,
- VALUE (*getter)(), void (*setter)())
-
-If you need to supply either setter or getter, just supply 0 for the
-hook you don't need. If both hooks are 0, rb_define_hooked_variable()
-works just like rb_define_variable().
-
- void rb_define_virtual_variable(const char *name,
- VALUE (*getter)(), void (*setter)())
-
-This function defines the Ruby global variable without corresponding C
-variable. The value of the variable will be set/get only by hooks.
-
-The prototypes of the getter and setter functions are as following:
-
- (*getter)(ID id, void *data, struct global_entry* entry);
- (*setter)(VALUE val, ID id, void *data, struct global_entry* entry);
-
-3.3 Encapsulate C data into Ruby object
-
-To wrapping and objectify the C pointer as Ruby object (so called
-DATA), use Data_Wrap_Struct().
-
- Data_Wrap_Struct(klass, mark, free, ptr)
-
-Data_Wrap_Struct() returns a created DATA object. The klass argument
-is the class for the DATA object. The mark argument is the function
-to mark Ruby objects pointed by this data. The free argument is the
-function to free the pointer allocation. The functions, mark and
-free, will be called from garbage collector.
-
-You can allocate and wrap the structure in one step.
-
- Data_Make_Struct(klass, type, mark, free, sval)
-
-This macro returns an allocated Data object, wrapping the pointer to
-the structure, which is also allocated. This macro works like:
-
- (sval = ALLOC(type), Data_Wrap_Struct(klass, mark, free, sval))
-
-Arguments, klass, mark, free, works like their counterpart of
-Data_Wrap_Struct(). The pointer to allocated structure will be
-assigned to sval, which should be the pointer to the type specified.
-
-To retrieve the C pointer from the Data object, use the macro
-Data_Get_Struct().
-
- Data_Get_Struct(obj, type, sval)
-
-The pointer to the structure will be assigned to the variable sval.
-
-See example below for detail.
-
-4. Example - Creating dbm extension
-
-OK, here's the example to make extension library. This is the
-extension to access dbm. The full source is included in ext/
-directory in the Ruby's source tree.
-
-(1) make the directory
-
- % mkdir ext/dbm
-
-Make a directory for the extension library under ext directory.
-
-(2) create MANIFEST file
-
- % cd ext/dbm
- % touch MANIFEST
-
-There should be MANIFEST file in the directory for the extension
-library. Make empty file now.
-
-(3) design the library
-
-You need to design the library features, before making it.
-
-(4) write C code.
-
-You need to write C code for your extension library. If your library
-has only one source file, choosing ``LIBRARY.c'' as a file name is
-preferred. On the other hand, in case your library has plural source
-files, avoid choosing ``LIBRARY.c'' for a file name. It may conflict
-with intermediate file ``LIBRARY.o'' on some platforms.
-
-Ruby will execute the initializing function named ``Init_LIBRARY'' in
-the library. For example, ``Init_dbm()'' will be executed when loading
-the library.
-
-Here's the example of an initializing function.
-
---
-Init_dbm()
-{
- /* define DBM class */
- cDBM = rb_define_class("DBM", rb_cObject);
- /* DBM includes Enumerate module */
- rb_include_module(cDBM, rb_mEnumerable);
-
- /* DBM has class method open(): arguments are received as C array */
- rb_define_singleton_method(cDBM, "open", fdbm_s_open, -1);
-
- /* DBM instance method close(): no args */
- rb_define_method(cDBM, "close", fdbm_close, 0);
- /* DBM instance method []: 1 argument */
- rb_define_method(cDBM, "[]", fdbm_fetch, 1);
- :
-
-}
---
-
-The dbm extension wrap dbm struct in C world using Data_Make_Struct.
-
---
-struct dbmdata {
- int di_size;
- DBM *di_dbm;
-};
-
-
-obj = Data_Make_Struct(klass, struct dbmdata, 0, free_dbm, dbmp);
---
-
-This code wraps dbmdata structure into Ruby object. We avoid wrapping
-DBM* directly, because we want to cache size information.
-
-To retrieve dbmdata structure from Ruby object, we define the macro below:
-
---
-#define GetDBM(obj, dbmp) {\
- Data_Get_Struct(obj, struct dbmdata, dbmp);\
- if (dbmp->di_dbm == 0) closed_dbm();\
-}
---
-
-This sort of complicated macro do the retrieving and close check for
-the DBM.
-
-There are three kind of way to receiving method arguments. First, the
-methods with fixed number of arguments receives arguments like this:
-
---
-static VALUE
-fdbm_delete(obj, keystr)
- VALUE obj, keystr;
-{
- :
-}
---
-
-The first argument of the C function is the self, the rest are the
-arguments to the method.
-
-Second, the methods with arbitrary number of arguments receives
-arguments like this:
-
---
-static VALUE
-fdbm_s_open(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- :
- if (rb_scan_args(argc, argv, "11", &file, &vmode) == 1) {
- mode = 0666; /* default value */
- }
- :
-}
---
-
-The first argument is the number of method arguments. the second
-argument is the C array of the method arguments. And the third
-argument is the receiver of the method.
-
-You can use the function rb_scan_args() to check and retrieve the
-arguments. For example "11" means, the method requires at least one
-argument, and at most receives two arguments.
-
-The methods with arbitrary number of arguments can receives arguments
-by Ruby's array, like this:
-
---
-static VALUE
-fdbm_indexes(obj, args)
- VALUE obj, args;
-{
- :
-}
---
-
-The first argument is the receiver, the second one is the Ruby array
-which contains the arguments to the method.
-
-** Notice
-
-GC should know about global variables which refers Ruby's objects, but
-not exported to the Ruby world. You need to protect them by
-
- void rb_global_variable(VALUE *var)
-
-(5) prepare extconf.rb
-
-If there exists the file named extconf.rb, it will be executed to
-generate Makefile. If not, compilation scheme try to generate
-Makefile anyway.
-
-The extconf.rb is the file to check compilation condition etc. You
-need to put
-
- require 'mkmf'
-
-at the top of the file. You can use the functions below to check the
-condition.
-
- have_library(lib, func): check whether library containing function exists.
- have_func(func, header): check whether function exists
- have_header(header): check whether header file exists
- create_makefile(target): generate Makefile
-
-The value of variables below will affect Makefile.
-
- $CFLAGS: included in CFLAGS make variable (such as -I)
- $LDFLAGS: included in LDFLAGS make variable (such as -L)
-
-If compilation condition is not fulfilled, you do not call
-``create_makefile''. Makefile will not generated, compilation will
-not be done.
-
-(6) prepare depend (optional)
-
-If the file named depend exists, Makefile will include that file to
-check dependency. You can make this file by invoking
-
- % gcc -MM *.c > depend
-
-It's no harm. Prepare it.
-
-(7) put file names into MANIFEST (optional)
-
- % find * -type f -print > MANIFEST
- % vi MANIFEST
-
-Append file names into MANIFEST. The compilation scheme requires
-MANIFEST only to be exist. But, you'd better take this step to
-distinguish required files.
-
-(8) generate Makefile
-
-Try generate Makefile by:
-
- ruby extconf.rb
-
-You don't need this step, if you put extension library under ext
-directory of the ruby source tree. In that case, compilation of the
-interpreter will do this step for you.
-
-(9) make
-
-Type
-
- make
-
-to compile your extension. You don't need this step neither, if you
-put extension library under ext directory of the ruby source tree.
-
-(9) debug
-
-You may need to rb_debug the extension. The extensions can be linked
-statically by adding directory name in the ext/Setup file, so that you
-can inspect the extension with the debugger.
-
-(10) done, now you have the extension library
-
-You can do anything you want with your library. The author of Ruby
-will not claim any restriction about your code depending Ruby API.
-Feel free to use, modify, distribute or sell your program.
-
-Appendix A. Ruby source files overview
-
-ruby language core
-
- class.c
- error.c
- eval.c
- gc.c
- object.c
- parse.y
- variable.c
-
-utility functions
-
- dln.c
- regex.c
- st.c
- util.c
-
-ruby interpreter implementation
-
- dmyext.c
- inits.c
- main.c
- ruby.c
- version.c
-
-class library
-
- array.c
- bignum.c
- compar.c
- dir.c
- enum.c
- file.c
- hash.c
- io.c
- marshal.c
- math.c
- numeric.c
- pack.c
- prec.c
- process.c
- random.c
- range.c
- re.c
- signal.c
- sprintf.c
- string.c
- struct.c
- time.c
-
-Appendix B. Ruby extension API reference
-
-** Types
-
- VALUE
-
-The type for Ruby object. Actual structures are defined in ruby.h,
-such as struct RString, etc. To refer the values in structures, use
-casting macros like RSTRING(obj).
-
-** Variables and constants
-
- Qnil
-
-const: nil object
-
- Qtrue
-
-const: true object(default true value)
-
- Qfalse
-
-const: false object
-
-** C pointer wrapping
-
- Data_Wrap_Struct(VALUE klass, void (*mark)(), void (*free)(), void *sval)
-
-Wrap C pointer into Ruby object. If object has references to other
-Ruby object, they should be marked by using mark function during GC
-process. Otherwise, mark should be 0. When this object is no longer
-referred by anywhere, the pointer will be discarded by free function.
-
- Data_Make_Struct(klass, type, mark, free, sval)
-
-This macro allocates memory using malloc(), assigns it to the variable
-sval, and returns the DATA encapsulating the pointer to memory region.
-
- Data_Get_Struct(data, type, sval)
-
-This macro retrieves the pointer value from DATA, and assigns it to
-the variable sval.
-
-** defining class/module
-
- VALUE rb_define_class(const char *name, VALUE super)
-
-Defines new Ruby class as subclass of super.
-
- VALUE rb_define_class_under(VALUE module, const char *name, VALUE super)
-
-Creates new Ruby class as subclass of super, under the module's
-namespace.
-
- VALUE rb_define_module(const char *name)
-
-Defines new Ruby module.
-
- VALUE rb_define_module_under(VALUE module, const char *name, VALUE super)
-
-Defines new Ruby module, under the module's namespace.
-
- void rb_include_module(VALUE klass, VALUE module)
-
-Includes module into class. If class already includes it, just
-ignore.
-
- void rb_extend_object(VALUE object, VALUE module)
-
-Extend the object with module's attribute.
-
-** Defining Global Variables
-
- void rb_define_variable(const char *name, VALUE *var)
-
-Defines a global variable which is shared between C and Ruby. If name
-contains the character which is not allowed to be part of the symbol,
-it can't be seen from Ruby programs.
-
- void rb_define_readonly_variable(const char *name, VALUE *var)
-
-Defines a read-only global variable. Works just like
-rb_define_variable(), except defined variable is read-only.
-
- void rb_define_virtual_variable(const char *name,
- VALUE (*getter)(), VALUE (*setter)())
-
-Defines a virtual variable, whose behavior is defined by pair of C
-functions. The getter function is called when the variable is
-referred. The setter function is called when the value is set to the
-variable. The prototype for getter/setter functions are:
-
- VALUE getter(ID id)
- void setter(VALUE val, ID id)
-
-The getter function must return the value for the access.
-
- void rb_define_hooked_variable(const char *name, VALUE *var,
- VALUE (*getter)(), VALUE (*setter)())
-
-Defines hooked variable. It's virtual variable with C variable. The
-getter is called as
-
- VALUE getter(ID id, VALUE *var)
-
-returning new value. The setter is called as
-
- void setter(VALUE val, ID id, VALUE *var)
-
-GC requires to mark the C global variables which hold Ruby values.
-
- void rb_global_variable(VALUE *var)
-
-Tells GC to protect these variables.
-
-** Constant Definition
-
- void rb_define_const(VALUE klass, const char *name, VALUE val)
-
-Defines a new constant under the class/module.
-
- void rb_define_global_const(const char *name, VALUE val)
-
-Defines global constant. This is just work as
-
- rb_define_const(cKernal, name, val)
-
-** Method Definition
-
- rb_define_method(VALUE klass, const char *name, VALUE (*func)(), int argc)
-
-Defines a method for the class. func is the function pointer. argc
-is the number of arguments. if argc is -1, the function will receive
-3 arguments argc, argv, and self. if argc is -2, the function will
-receive 2 arguments, self and args, where args is the Ruby array of
-the method arguments.
-
- rb_define_private_method(VALUE klass, const char *name, VALUE (*func)(), int argc)
-
-Defines a private method for the class. Arguments are same as
-rb_define_method().
-
- rb_define_singleton_method(VALUE klass, const char *name, VALUE (*func)(), int argc)
-
-Defines a singleton method. Arguments are same as rb_define_method().
-
- rb_scan_args(int argc, VALUE *argv, const char *fmt, ...)
-
-Retrieve argument from argc, argv. The fmt is the format string for
-the arguments, such as "12" for 1 non-optional argument, 2 optional
-arguments. If `*' appears at the end of fmt, it means the rest of
-the arguments are assigned to corresponding variable, packed in
-array.
-
-** Invoking Ruby method
-
- VALUE rb_funcall(VALUE recv, ID mid, int narg, ...)
-
-Invokes the method. To retrieve mid from method name, use rb_intern().
-
- VALUE rb_funcall2(VALUE recv, ID mid, int argc, VALUE *argv)
-
-Invokes method, passing arguments by array of values.
-
- VALUE rb_eval_string(const char *str)
-
-Compiles and executes the string as Ruby program.
-
- ID rb_intern(const char *name)
-
-Returns ID corresponding the name.
-
- char *rb_id2name(ID id)
-
-Returns the name corresponding ID.
-
- char *rb_class2name(VALUE klass)
-
-Returns the name of the class.
-
- int rb_respond_to(VALUE object, ID id)
-
-Returns true if the object responds to the message specified by id.
-
-** Instance Variables
-
- VALUE rb_iv_get(VALUE obj, const char *name)
-
-Retrieve the value of the instance variable. If the name is not
-prefixed by `@', that variable shall be inaccessible from Ruby.
-
- VALUE rb_iv_set(VALUE obj, const char *name, VALUE val)
-
-Sets the value of the instance variable.
-
-** Control Structure
-
- VALUE rb_iterate(VALUE (*func1)(), void *arg1, VALUE (*func2)(), void *arg2)
-
-Calls the function func1, supplying func2 as the block. func1 will be
-called with the argument arg1. func2 receives the value from yield as
-the first argument, arg2 as the second argument.
-
- VALUE rb_yield(VALUE val)
-
-Evaluates the block with value val.
-
- VALUE rb_rescue(VALUE (*func1)(), void *arg1, VALUE (*func2)(), void *arg2)
-
-Calls the function func1, with arg1 as the argument. If exception
-occurs during func1, it calls func2 with arg2 as the argument. The
-return value of rb_rescue() is the return value from func1 if no
-exception occurs, from func2 otherwise.
-
- VALUE rb_ensure(VALUE (*func1)(), void *arg1, void (*func2)(), void *arg2)
-
-Calls the function func1 with arg1 as the argument, then calls func2
-with arg2, whenever execution terminated. The return value from
-rb_ensure() is that of func1.
-
-** Exceptions and Errors
-
- void rb_warn(const char *fmt, ...)
-
-Prints warning message according to the printf-like format.
-
- void rb_warning(const char *fmt, ...)
-
-Prints warning message according to the printf-like format, if
-$VERBOSE is true.
-
- void rb_raise(VALUE exception, const char *fmt, ...)
-
-Raises an exception of class exception. The fmt is the format string
-just like printf().
-
- void rb_fatal(const char *fmt, ...)
-
-Raises fatal error, terminates the interpreter. No exception handling
-will be done for fatal error, but ensure blocks will be executed.
-
- void rb_bug(const char *fmt, ...)
-
-Terminates the interpreter immediately. This function should be
-called under the situation caused by the bug in the interpreter. No
-exception handling nor ensure execution will be done.
-
-** Initialize and Starts the Interpreter
-
-The embedding API are below (not needed for extension libraries):
-
- void ruby_init()
-
-Initializes the interpreter.
-
- void ruby_options(int argc, char **argv)
-
-Process command line arguments for the interpreter.
-
- void ruby_run()
-
-Starts execution of the interpreter.
-
- void ruby_script(char *name)
-
-Specifies the name of the script ($0).
-
-Appendix C. Functions Available in extconf.rb
-
-These functions are available in extconf.rb:
-
- have_library(lib, func)
-
-Checks whether library which contains specified function exists.
-Returns true if the library exists.
-
- find_library(lib, func, path...)
-
-Checks whether library which contains specified function exists in
-path. Returns true if the library exists.
-
- have_func(func, header)
-
-Checks whether func exists with header. Returns true if the function
-exists. To check functions in the additional library, you need to
-check that library first using have_library().
-
- have_header(header)
-
-Checks whether header exists. Returns true if the header file exists.
-
- create_makefile(target)
-
-Generates the Makefile for the extension library. If you don't invoke
-this method, the compilation will not be done.
-
- with_config(withval[, default=nil])
-
-Parses the command line options and returns the value specified by
---with-<withval>.
-
- dir_config(target[, default_dir])
- dir_config(target[, default_include, default_lib])
-
-Parses the command line options and adds the directories specified by
---with-<target>-dir, --with-<target>-include, and/or --with-<target>-lib
-to $CFLAGS and/or $LDFLAGS. --with-<target>-dir=/path is equivalent to
---with-<target>-include=/path/include --with-<target>-lib=/path/lib.
-Returns an array of the added directories ([include_dir, lib_dir]).
-
-/*
- * Local variables:
- * fill-column: 70
- * end:
- */
diff --git a/README.EXT.ja b/README.EXT.ja
deleted file mode 100644
index 0ef67497ce..0000000000
--- a/README.EXT.ja
+++ /dev/null
@@ -1,1187 +0,0 @@
-.\" README.EXT.ja - -*- Text -*- created at: Mon Aug 7 16:45:54 JST 1995
-
-Rubyの拡張ライブラリの作り方を説明します.
-
-1.基礎知識
-
-Cの変数には型があり,データには型がありません.ですから,た
-とえばポインタをintの変数に代入すると,その値は整数として取
-り扱われます.逆にRubyの変数には型がなく,データに型がありま
-す.この違いのため,CとRubyは相互に変換しなければ,お互いの
-データをアクセスできません.
-
-RubyのデータはVALUEというCの型で表現されます.VALUE型のデー
-タはそのデータタイプを自分で知っています.このデータタイプと
-いうのはデータ(オブジェクト)の実際の構造を意味していて,Ruby
-のクラスとはまた違ったものです.
-
-VALUEからCにとって意味のあるデータを取り出すためには
-
- (1) VALUEのデータタイプを知る
- (2) VALUEをCのデータに変換する
-
-の両方が必要です.(1)を忘れると間違ったデータの変換が行われ
-て,最悪プログラムがcore dumpします.
-
-1.1 データタイプ
-
-Rubyにはユーザが使う可能性のある以下のタイプがあります.
-
- T_NIL nil
- T_OBJECT 通常のオブジェクト
- T_CLASS クラス
- T_MODULE モジュール
- T_FLOAT 浮動小数点数
- T_STRING 文字列
- T_REGEXP 正規表現
- T_ARRAY 配列
- T_FIXNUM Fixnum(31bit長整数)
- T_HASH 連想配列
- T_STRUCT (Rubyの)構造体
- T_BIGNUM 多倍長整数
- T_FILE 入出力
- T_TRUE 真
- T_FALSE 偽
- T_DATA データ
- T_SYMBOL シンボル
-
-その他に内部で利用されている以下のタイプがあります.
-
- T_ICLASS
- T_MATCH
- T_UNDEF
- T_VARMAP
- T_SCOPE
- T_NODE
-
-ほとんどのタイプはCの構造体で実装されています.
-
-1.2 VALUEのデータタイプをチェックする
-
-ruby.hではTYPE()というマクロが定義されていて,VALUEのデータ
-タイプを知ることが出来ます.TYPE()マクロは上で紹介したT_XXXX
-の形式の定数を返します.VALUEのデータタイプに応じて処理する
-場合には,TYPE()の値で分岐することになります.
-
- switch (TYPE(obj)) {
- case T_FIXNUM:
- /* FIXNUMの処理 */
- break;
- case T_STRING:
- /* 文字列の処理 */
- break;
- case T_ARRAY:
- /* 配列の処理 */
- break;
- default:
- /* 例外を発生させる */
- rb_raise(rb_eTypeError, "not valid value");
- break;
- }
-
-それとデータタイプをチェックして,正しくなければ例外を発生す
-る関数が用意されています.
-
- void Check_Type(VALUE value, int type)
-
-この関数はvalueがtypeで無ければ,例外を発生させます.引数と
-して与えられたVALUEのデータタイプが正しいかどうかチェックす
-るためには,この関数を使います.
-
-FIXNUMとNILに関してはより高速な判別マクロが用意されています.
-
- FIXNUM_P(obj)
- NIL_P(obj)
-
-1.3 VALUEをCのデータに変換する
-
-データタイプがT_NIL, T_FALSE, T_TRUEである時,データはそれぞ
-れnil, false, trueです.このデータタイプのオブジェクトはひと
-つずつしか存在しません.
-
-データタイプがT_FIXNUMの時,これは31bitのサイズを持つ整数で
-す.FIXNUMをCの整数に変換するためにはマクロ「FIX2INT()」を使
-います.それから,FIXNUMに限らずRubyのデータを整数に変換する
-「NUM2INT()」というマクロがあります.このマクロはデータタイ
-プのチェック無しで使えます(整数に変換できない場合には例外が
-発生する).
-
-同様にチェック無しで使える変換マクロはdoubleを取り出す
-「NUM2DBL()」とchar*を取り出す「STR2CSTR()」があります.
-
-それ以外のデータタイプは対応するCの構造体があります.対応す
-る構造体のあるVALUEはそのままキャスト(型変換)すれば構造体の
-ポインタに変換できます.
-
-構造体は「struct RXxxxx」という名前でruby.hで定義されていま
-す.例えば文字列は「struct RString」です.実際に使う可能性が
-あるのは文字列と配列くらいだと思います.
-
-ruby.hでは構造体へキャストするマクロも「RXXXXX()」(全部大文
-字にしたもの)という名前で提供されています(例: RSTRING()).
-
-例えば,文字列strの長さを得るためには「RSTRING(str)->len」と
-し,文字列strをchar*として得るためには「RSTRING(str)->ptr」
-とします.配列の場合には,それぞれ「RARRAY(ary)->len」,
-「RARRAY(ary)->ptr」となります.
-
-Rubyの構造体を直接アクセスする時に気をつけなければならないこ
-とは,配列や文字列の構造体の中身は参照するだけで,直接変更し
-ないことです.直接変更した場合,オブジェクトの内容の整合性が
-とれなくなって,思わぬバグの原因になります.
-
-1.4 CのデータをVALUEに変換する
-
-VALUEの実際の構造は
-
- * FIXNUMの場合
-
- 1bit左シフトして,LSBを立てる.
-
- * その他のポインタの場合
-
- そのままVALUEにキャストする.
-
-となっています.よって,LSBをチェックすればVALUEがFIXNUMかど
-うかわかるわけです(ポインタのLSBが立っていないことを仮定して
-いる).
-
-ですから,FIXNUM以外のRubyのオブジェクトの構造体は単にVALUE
-にキャストするだけでVALUEに変換出来ます.ただし,任意の構造
-体がVALUEにキャスト出来るわけではありません.キャストするの
-はRubyの知っている構造体(ruby.hで定義されているstruct RXxxx
-のもの)だけです.
-
-FIXNUMに関しては変換マクロを経由する必要があります.Cの整数
-からVALUEに変換するマクロは以下のものがあります.必要に応じ
-て使い分けてください.
-
- INT2FIX() もとの整数が31bit以内に収まる自信がある時
- INT2NUM() 任意の整数からVALUEへ
-
-INT2NUM()は整数がFIXNUMの範囲に収まらない場合,Bignumに変換
-してくれます(が,少し遅い).
-
-1.5 Rubyのデータを操作する
-
-先程も述べた通り,Rubyの構造体をアクセスする時に内容の更新を
-行うことは勧められません.で,Rubyのデータを操作する時には
-Rubyが用意している関数を用いてください.
-
-ここではもっとも使われるであろう文字列と配列の生成/操作を行
-い関数をあげます(全部ではないです).
-
- 文字列に対する関数
-
- rb_str_new(const char *ptr, long len)
-
- 新しいRubyの文字列を生成する.
-
- rb_str_new2(const char *ptr)
-
- Cの文字列からRubyの文字列を生成する.この関数の機能は
- rb_str_new(ptr, strlen(ptr))と同等である.
-
- rb_tainted_str_new(const char *ptr, long len)
-
- 汚染マークが付加された新しいRubyの文字列を生成する.外部
- からのデータに基づく文字列には汚染マークが付加されるべき
- である.
-
- rb_tainted_str_new2(const char *ptr)
-
- Cの文字列から汚染マークが付加されたRubyの文字列を生成する.
-
- rb_str_cat(VALUE str, const char *ptr, long len)
-
- Rubyの文字列strにlenバイトの文字列ptrを追加する.
-
- 配列に対する関数
-
- rb_ary_new()
-
- 要素が0の配列を生成する.
-
- rb_ary_new2(long len)
-
- 要素が0の配列を生成する.len要素分の領域をあらかじめ割り
- 当てておく.
-
- rb_ary_new3(long n, ...)
-
- 引数で指定したn要素を含む配列を生成する.
-
- rb_ary_new4(long n, VALUE *elts)
-
- 配列で与えたn要素の配列を生成する.
-
- rb_ary_push(VALUE ary, VALUE val)
- rb_ary_pop(VALUE ary)
- rb_ary_shift(VALUE ary)
- rb_ary_unshift(VALUE ary, VALUE val)
-
- Arrayの同名のメソッドと同じ働きをする関数.第1引数は必ず
- 配列でなければならない.
-
-2.Rubyの機能を使う
-
-原理的にRubyで書けることはCでも書けます.RubyそのものがCで記
-述されているんですから,当然といえば当然なんですけど.ここで
-はRubyの拡張に使うことが多いだろうと予測される機能を中心に紹
-介します.
-
-2.1 Rubyに機能を追加する
-
-Rubyで提供されている関数を使えばRubyインタプリタに新しい機能
-を追加することができます.Rubyでは以下の機能を追加する関数が
-提供されています.
-
- * クラス,モジュール
- * メソッド,特異メソッドなど
- * 定数
-
-では順に紹介します.
-
-2.1.1 クラス/モジュール定義
-
-クラスやモジュールを定義するためには,以下の関数を使います.
-
- VALUE rb_define_class(const char *name, VALUE super)
- VALUE rb_define_module(const char *name)
-
-これらの関数は新しく定義されたクラスやモジュールを返します.
-メソッドや定数の定義にこれらの値が必要なので,ほとんどの場合
-は戻り値を変数に格納しておく必要があるでしょう.
-
-クラスやモジュールを他のクラスの内部にネストして定義する時に
-は以下の関数を使います.
-
- VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
- VALUE rb_define_module_under(VALUE outer, const char *name)
-
-2.1.2 メソッド/特異メソッド定義
-
-メソッドや特異メソッドを定義するには以下の関数を使います.
-
- void rb_define_method(VALUE klass, const char *name,
- VALUE (*func)(), int argc)
-
- void rb_define_singleton_method(VALUE object, const char *name,
- VALUE (*func)(), int argc)
-
-
-念のため説明すると「特異メソッド」とは,その特定のオブジェク
-トに対してだけ有効なメソッドです.RubyではよくSmalltalkにお
-けるクラスメソッドとして,クラスに対する特異メソッドが使われ
-ます.
-
-これらの関数の argcという引数はCの関数へ渡される引数の数(と
-形式)を決めます.argcが0以上の時は関数に引き渡す引数の数を意
-味します.16個以上の引数は使えません(が,要りませんよね,そ
-んなに).実際の関数には先頭の引数としてselfが与えられますの
-で,指定した数より1多い引数を持つことになります.
-
-argcが負の時は引数の数ではなく,形式を指定したことになります.
-argcが-1の時は引数を配列に入れて渡されます.argcが-2の時は引
-数はRubyの配列として渡されます.
-
-メソッドを定義する関数はもう二つあります.ひとつはprivateメ
-ソッドを定義する関数で,引数はrb_define_method()と同じです.
-
- void rb_define_private_method(VALUE klass, const char *name,
- VALUE (*func)(), int argc)
-
-privateメソッドとは関数形式でしか呼び出すことの出来ないメソッ
-ドです.
-
-もうひとつはモジュール関数を定義するものです.モジュール関数
-とはモジュールの特異メソッドであり,同時にprivateメソッドで
-もあるものです.例をあげるとMathモジュールのsqrt()などがあげ
-られます.このメソッドは
-
- Math.sqrt(4)
-
-という形式でも
-
- include Math
- sqrt(4)
-
-という形式でも使えます.モジュール関数を定義する関数は以下の
-通りです.
-
- void rb_define_module_function(VALUE module, const char *name,
- VALUE (*func)(), int argc)
-
-関数的メソッド(Kernelモジュールのprivate method)を定義するた
-めの関数は以下の通りです.
-
- void rb_define_global_function(const char *name, VALUE (*func)(), int argc)
-
-
-メソッドの別名を定義するための関数は以下の通りです。
-
- void rb_define_alias(VALUE module, const char* new, const char* old);
-
-2.1.3 定数定義
-
-拡張ライブラリが必要な定数はあらかじめ定義しておいた方が良い
-でしょう.定数を定義する関数は二つあります.
-
- void rb_define_const(VALUE klass, const char *name, VALUE val)
- void rb_define_global_const(const char *name, VALUE val)
-
-前者は特定のクラス/モジュールに属する定数を定義するもの,後
-者はグローバルな定数を定義するものです.
-
-2.2 Rubyの機能をCから呼び出す
-
-既に『1.5 Rubyのデータを操作する』で一部紹介したような関数を
-使えば,Rubyの機能を実現している関数を直接呼び出すことが出来
-ます.
-
-# このような関数の一覧表はいまのところありません.ソースを見
-# るしかないですね.
-
-それ以外にもRubyの機能を呼び出す方法はいくつかあります.
-
-2.2.1 Rubyのプログラムをevalする
-
-CからRubyの機能を呼び出すもっとも簡単な方法として,文字列で
-与えられたRubyのプログラムを評価する以下の関数があります.
-
- VALUE rb_eval_string(const char *str)
-
-この評価は現在の環境で行われます.つまり,現在のローカル変数
-などを受け継ぎます.
-
-2.2.2 IDまたはシンボル
-
-Cから文字列を経由せずにRubyのメソッドを呼び出すこともできま
-す.その前に,Rubyインタプリタ内でメソッドや変数名を指定する
-時に使われているIDについて説明しておきましょう.
-
-IDとは変数名,メソッド名を表す整数です.Rubyの中では
-
- :識別子
-
-でアクセスできます.Cからこの整数を得るためには関数
-
- rb_intern(const char *name)
-
-を使います.Rubyから引数として与えられたシンボル(または文字
-列)をIDに変換するには以下の関数を使います.
-
- rb_to_id(VALUE symbol)
-
-2.2.3 CからRubyのメソッドを呼び出す
-
-Cから文字列を経由せずにRubyのメソッドを呼び出すためには以下
-の関数を使います.
-
- VALUE rb_funcall(VALUE recv, ID mid, int argc, ...)
-
-この関数はオブジェクトrecvのmidで指定されるメソッドを呼び出
-します.その他に引数の指定の仕方が違う以下の関数もあります.
-
- VALUE rb_funcall2(VALUE recv, ID mid, int argc, VALUE *argv)
- VALUE rb_apply(VALUE recv, ID mid, VALUE args)
-
-applyには引数としてRubyの配列を与えます.
-
-2.2.4 変数/定数を参照/更新する
-
-Cから関数を使って参照・更新できるのは,定数,インスタンス変
-数です.大域変数は一部のものはCの大域変数としてアクセスでき
-ます.ローカル変数を参照する方法は公開していません.
-
-オブジェクトのインスタンス変数を参照・更新する関数は以下の通
-りです.
-
- VALUE rb_ivar_get(VALUE obj, ID id)
- VALUE rb_ivar_set(VALUE obj, ID id, VALUE val)
-
-idはrb_intern()で得られるものを使ってください.
-
-定数を参照するには以下の関数を使ってください.
-
- VALUE rb_const_get(VALUE obj, ID id)
-
-定数を新しく定義するためには『2.1.3 定数定義』で紹介さ
-れている関数を使ってください.
-
-3.RubyとCとの情報共有
-
-C言語とRubyの間で情報を共有する方法について解説します.
-
-3.1 Cから参照できるRubyの定数
-
-以下のRubyの定数はCのレベルから参照できます.
-
- Qtrue
- Qfalse
-
- 真偽値.QfalseはC言語でも偽とみなされます(つまり0).
-
- Qnil
-
- C言語から見た「nil」.
-
-3.2 CとRubyで共有される大域変数
-
-CとRubyで大域変数を使って情報を共有できます.共有できる大域
-変数にはいくつかの種類があります.そのなかでもっとも良く使わ
-れると思われるのはrb_define_variable()です.
-
- void rb_define_variable(const char *name, VALUE *var)
-
-この関数はRubyとCとで共有する大域変数を定義します.変数名が
-`$'で始まらない時には自動的に追加されます.この変数の値を変
-更すると自動的にRubyの対応する変数の値も変わります.
-
-またRuby側からは更新できない変数もあります.このread onlyの
-変数は以下の関数で定義します.
-
- void rb_define_readonly_variable(const char *name, VALUE *var)
-
-これら変数の他にhookをつけた大域変数を定義できます.hook付き
-の大域変数は以下の関数を用いて定義します.hook付き大域変数の
-値の参照や設定はhookで行う必要があります.
-
- void rb_define_hooked_variable(const char *name, VALUE *var,
- VALUE (*getter)(), void (*setter)())
-
-この関数はCの関数によってhookのつけられた大域変数を定義しま
-す.変数が参照された時には関数getterが,変数に値がセットされ
-た時には関数setterが呼ばれる.hookを指定しない場合はgetterや
-setterに0を指定します.
-
-# getterもsetterも0ならばrb_define_variable()と同じになる.
-
-それから,Cの関数によって実現されるRubyの大域変数を定義する
-関数があります.
-
- void rb_define_virtual_variable(const char *name,
- VALUE (*getter)(), void (*setter)())
-
-この関数によって定義されたRubyの大域変数が参照された時には
-getterが,変数に値がセットされた時にはsetterが呼ばれます.
-
-getterとsetterの仕様は以下の通りです.
-
- (*getter)(ID id, void *data, struct global_entry* entry);
- (*setter)(VALUE val, ID id, void *data, struct global_entry* entry);
-
-3.3 CのデータをRubyオブジェクトにする
-
-Cの世界で定義されたデータ(構造体)をRubyのオブジェクトとして
-取り扱いたい場合がありえます.このような場合には,Dataという
-RubyオブジェクトにCの構造体(へのポインタ)をくるむことでRuby
-オブジェクトとして取り扱えるようになります.
-
-Dataオブジェクトを生成して構造体をRubyオブジェクトにカプセル
-化するためには,以下のマクロを使います.
-
- Data_Wrap_Struct(klass, mark, free, ptr)
-
-このマクロの戻り値は生成されたDataオブジェクトです.
-
-klassはこのDataオブジェクトのクラスです.ptrはカプセル化する
-Cの構造体へのポインタです.markはこの構造体がRubyのオブジェ
-クトへの参照がある時に使う関数です.そのような参照を含まない
-時には0を指定します.
-
-# そのような参照は勧められません.
-
-freeはこの構造体がもう不要になった時に呼ばれる関数です.この
-関数がガーベージコレクタから呼ばれます.
-
-Cの構造体の割当とDataオブジェクトの生成を同時に行うマクロと
-して以下のものが提供されています.
-
- Data_Make_Struct(klass, type, mark, free, sval)
-
-このマクロの戻り値は生成されたDataオブジェクトです.
-
-klass, mark, freeはData_Wrap_Structと同じ働きをします.type
-は割り当てるC構造体の型です.割り当てられた構造体は変数sval
-に代入されます.この変数の型は (type*) である必要があります.
-
-Dataオブジェクトからポインタを取り出すのは以下のマクロを用い
-ます.
-
- Data_Get_Struct(obj, type, sval)
-
-Cの構造体へのポインタは変数svalに代入されます.
-
-これらのDataの使い方はちょっと分かりにくいので,後で説明する
-例題を参照してください.
-
-4.例題 - dbmパッケージを作る
-
-ここまでの説明でとりあえず拡張ライブラリは作れるはずです.
-Rubyのextディレクトリにすでに含まれているdbmライブラリを例に
-して段階的に説明します.
-
-(1) ディレクトリを作る
-
- % mkdir ext/dbm
-
-Ruby 1.1からは任意のディレクトリでダイナミックライブラリを作
-ることができるようになりました.Rubyに静的にリンクする場合に
-はRubyを展開したディレクトリの下,extディレクトリの中に拡張
-ライブラリ用のディレクトリを作る必要があります.名前は適当に
-選んで構いません.
-
-(2) MANIFESTファイルを作る
-
- % cd ext/dbm
- % touch MANIFEST
-
-拡張ライブラリのディレクトリの下にはMANIFESTというファイルが
-必要なので,とりあえず空のファイルを作っておきます.後でこの
-ファイルには必要なファイル一覧が入ることになります.
-
-MANIFESTというファイルは,静的リンクのmakeの時にディレクトリ
-が拡張ライブラリを含んでいるかどうか判定するために使われれて
-います.ダイナミックライブラリを作る場合には必ずしも必要では
-ありません.
-
-(3) 設計する
-
-まあ,当然なんですけど,どういう機能を実現するかどうかまず設
-計する必要があります.どんなクラスをつくるか,そのクラスには
-どんなメソッドがあるか,クラスが提供する定数などについて設計
-します.
-
-(4) Cコードを書く
-
-拡張ライブラリ本体となるC言語のソースを書きます.C言語のソー
-スがひとつの時には「ライブラリ名.c」を選ぶと良いでしょう.C
-言語のソースが複数の場合には逆に「ライブラリ名.c」というファ
-イル名は避ける必要があります.オブジェクトファイルとモジュー
-ル生成時に中間的に生成される「ライブラリ名.o」というファイル
-とが衝突するからです.
-
-Rubyは拡張ライブラリをロードする時に「Init_ライブラリ名」と
-いう関数を自動的に実行します.dbmライブラリの場合「Init_dbm」
-です.この関数の中でクラス,モジュール,メソッド,定数などの
-定義を行います.dbm.cから一部引用します.
-
---
-Init_dbm()
-{
- /* DBMクラスを定義する */
- cDBM = rb_define_class("DBM", rb_cObject);
- /* DBMはEnumerateモジュールをインクルードする */
- rb_include_module(cDBM, rb_mEnumerable);
-
- /* DBMクラスのクラスメソッドopen(): 引数はCの配列で受ける */
- rb_define_singleton_method(cDBM, "open", fdbm_s_open, -1);
-
- /* DBMクラスのメソッドclose(): 引数はなし */
- rb_define_method(cDBM, "close", fdbm_close, 0);
- /* DBMクラスのメソッド[]: 引数は1個 */
- rb_define_method(cDBM, "[]", fdbm_fetch, 1);
- :
-
- /* DBMデータを格納するインスタンス変数名のためのID */
- id_dbm = rb_intern("dbm");
-}
---
-
-DBMライブラリはdbmのデータと対応するオブジェクトになるはずで
-すから,Cの世界のdbmをRubyの世界に取り込む必要があります.
-
-
-dbm.cではData_Make_Structを以下のように使っています.
-
---
-struct dbmdata {
- int di_size;
- DBM *di_dbm;
-};
-
-
-obj = Data_Make_Struct(klass, struct dbmdata, 0, free_dbm, dbmp);
---
-
-ここではdbmstruct構造体へのポインタをDataにカプセル化してい
-ます.DBM*を直接カプセル化しないのはclose()した時の処理を考
-えてのことです.
-
-Dataオブジェクトからdbmstruct構造体のポインタを取り出すため
-に以下のマクロを使っています.
-
---
-#define GetDBM(obj, dbmp) {\
- Data_Get_Struct(obj, struct dbmdata, dbmp);\
- if (dbmp->di_dbm == 0) closed_dbm();\
-}
---
-
-ちょっと複雑なマクロですが,要するにdbmdata構造体のポインタ
-の取り出しと,closeされているかどうかのチェックをまとめてい
-るだけです.
-
-DBMクラスにはたくさんメソッドがありますが,分類すると3種類の
-引数の受け方があります.ひとつは引数の数が固定のもので,例と
-してはdeleteメソッドがあります.deleteメソッドを実装している
-fdbm_delete()はこのようになっています.
-
---
-static VALUE
-fdbm_delete(obj, keystr)
- VALUE obj, keystr;
-{
- :
-}
---
-
-引数の数が固定のタイプは第1引数がself,第2引数以降がメソッド
-の引数となります.
-
-引数の数が不定のものはCの配列で受けるものとRubyの配列で受け
-るものとがあります.dbmライブラリの中で,Cの配列で受けるもの
-はDBMのクラスメソッドであるopen()です.これを実装している関
-数fdbm_s_open()はこうなっています.
-
---
-static VALUE
-fdbm_s_open(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- :
- if (rb_scan_args(argc, argv, "11", &file, &vmode) == 1) {
- mode = 0666; /* default value */
- }
- :
-}
---
-
-このタイプの関数は第1引数が与えられた引数の数,第2引数が与え
-られた引数の入っている配列になります.selfは第3引数として与
-えられます.
-
-この配列で与えられた引数を解析するための関数がopen()でも使わ
-れているrb_scan_args()です.第3引数に指定したフォーマットに
-従い,第4変数以降に指定した変数に値を代入してくれます.この
-フォーマットは,第1文字目が省略できない引数の数,第2文字目が
-省略できる引数の数,第3文字目が対応する相手が無いあまりの引
-数があるかどうかを示す"*"です.2文字目と3文字目は省略できま
-す.dbm.cの例では,フォーマットは"11"ですから,引数は最低1つ
-で,2つまで許されるという意味になります.省略されている時の
-変数の値はnil(C言語のレベルではQnil)になります.
-
-Rubyの配列で引数を受け取るものはindexesがあります.実装はこ
-うです.
-
---
-static VALUE
-fdbm_indexes(obj, args)
- VALUE obj, args;
-{
- :
-}
---
-
-第1引数はself,第2引数はRubyの配列です.
-
-** 注意事項
-
-Rubyと共有はしないがRubyのオブジェクトを格納する可能性のある
-Cの大域変数は以下の関数を使ってRubyインタプリタに変数の存在
-を教えてあげてください.でないとGCでトラブルを起こします.
-
- void rb_global_variable(VALUE *var)
-
-(5) extconf.rbを用意する
-
-Makefileを作る場合の雛型になるextconf.rbというファイルを作り
-ます.extconf.rbはライブラリのコンパイルに必要な条件のチェッ
-クなどを行うことが目的です.まず,
-
- require 'mkmf'
-
-をextconf.rbの先頭に置きます.extconf.rbの中では以下のRuby関
-数を使うことが出来ます.
-
- have_library(lib, func): ライブラリの存在チェック
- have_func(func, header): 関数の存在チェック
- have_header(header): ヘッダファイルの存在チェック
- create_makefile(target): Makefileの生成
-
-以下の変数を使うことができます.
-
- $CFLAGS: コンパイル時に追加的に指定するフラグ(-Iなど)
- $LDFLAGS: リンク時に追加的に指定するフラグ(-Lなど)
-
-ライブラリをコンパイルする条件が揃わず,そのライブラリをコン
-パイルしない時にはcreate_makefileを呼ばなければMakefileは生
-成されず,コンパイルも行われません.
-
-(6) dependを用意する
-
-もし,ディレクトリにdependというファイルが存在すれば,
-Makefileが依存関係をチェックしてくれます.
-
- % gcc -MM *.c > depend
-
-などで作ることが出来ます.あって損は無いでしょう.
-
-(7) MANIFESTファイルにファイル名を入れる
-
- % find * -type f -print > MANIFEST
- % vi MANIFEST
-
-*.o, *~など不必要なファイル以外はMANIFESTに追加しておきます.
-make時にはMANIFESTの内容は参照しませんので,空のままでも問題
-は起きませんが,パッケージングの時に参照することがあるのと,
-必要なファイルを区別できるので,用意しておいた方が良いでしょ
-う.
-
-(8) Makefileを生成する
-
-Makefileを実際に生成するためには
-
- ruby extconf.rb
-
-とします.extconf.rbに require 'mkmf' の行がない場合にはエラー
-になりますので,引数を追加して
-
- ruby -r mkmf extconf.rb
-
-としてください.
-
-ディレクトリをext以下に用意した場合にはRuby全体のmakeの時に
-自動的にMakefileが生成されますので,このステップは不要です.
-
-(9) makeする
-
-動的リンクライブラリを生成する場合にはその場でmakeしてくださ
-い.必要であれば make install でインストールされます.
-
-ext以下にディレクトリを用意した場合は,Rubyのディレクトリで
-makeを実行するとMakefileを生成からmake,必要によってはそのモ
-ジュールのRubyへのリンクまで自動的に実行してくれます.
-extconf.rbを書き換えるなどしてMakefileの再生成が必要な時はま
-たRubyディレクトリでmakeしてください.
-
-拡張ライブラリはmake installでRubyライブラリのディレクトリの
-下にコピーされます.もし拡張ライブラリと協調して使うRubyで記
-述されたプログラムがあり,Rubyライブラリに置きたい場合には,
-拡張ライブラリ用のディレクトリの下に lib というディレクトリ
-を作り,そこに 拡張子 .rb のファイルを置いておけば同時にイン
-ストールされます.
-
-(10) デバッグ
-
-まあ,デバッグしないと動かないでしょうね.ext/Setupにディレ
-クトリ名を書くと静的にリンクするのでデバッガが使えるようにな
-ります.その分コンパイルが遅くなりますけど.
-
-(11) できあがり
-
-後はこっそり使うなり,広く公開するなり,売るなり,ご自由にお
-使いください.Rubyの作者は拡張ライブラリに関して一切の権利を
-主張しません.
-
-Appendix A. Rubyのソースコードの分類
-
-Rubyのソースはいくつかに分類することが出来ます.このうちクラ
-スライブラリの部分は基本的に拡張ライブラリと同じ作り方になっ
-ています.これらのソースは今までの説明でほとんど理解できると
-思います.
-
-Ruby言語のコア
-
- class.c
- error.c
- eval.c
- gc.c
- object.c
- parse.y
- variable.c
-
-ユーティリティ関数
-
- dln.c
- regex.c
- st.c
- util.c
-
-Rubyコマンドの実装
-
- dmyext.c
- inits.c
- main.c
- ruby.c
- version.c
-
-クラスライブラリ
-
- array.c
- bignum.c
- compar.c
- dir.c
- enum.c
- file.c
- hash.c
- io.c
- marshal.c
- math.c
- numeric.c
- pack.c
- prec.c
- process.c
- random.c
- range.c
- re.c
- signal.c
- sprintf.c
- string.c
- struct.c
- time.c
-
-Appendix B. 拡張用関数リファレンス
-
-C言語からRubyの機能を利用するAPIは以下の通りである.
-
-** 型
-
-VALUE
-
- Rubyオブジェクトを表現する型.必要に応じてキャストして用いる.
- 組み込み型を表現するCの型はruby.hに記述してあるRで始まる構造
- 体である.VALUE型をこれらにキャストするためにRで始まる構造体
- 名を全て大文字にした名前のマクロが用意されている.
-
-** 変数・定数
-
-Qnil
-
- 定数: nilオブジェクト
-
-Qtrue
-
- 定数: trueオブジェクト(真のデフォルト値)
-
-Qfalse
-
- 定数: falseオブジェクト
-
-** Cデータのカプセル化
-
-Data_Wrap_Struct(VALUE klass, void (*mark)(), void (*free)(), void *sval)
-
- Cの任意のポインタをカプセル化したRubyオブジェクトを返す.こ
- のポインタがRubyからアクセスされなくなった時,freeで指定した
- 関数が呼ばれる.また,このポインタの指すデータが他のRubyオブ
- ジェクトを指している場合,markに指定する関数でマークする必要
- がある.
-
-Data_Make_Struct(klass, type, mark, free, sval)
-
- type型のメモリをmallocし,変数svalに代入した後,それをカプセ
- ル化したデータを返すマクロ.
-
-Data_Get_Struct(data, type, sval)
-
- dataからtype型のポインタを取り出し変数svalに代入するマクロ.
-
-** 型チェック
-
-TYPE(value)
-FIXNUM_P(value)
-NIL_P(value)
-void Check_Type(VALUE value, int type)
-void Check_SafeStr(VALUE value)
-
-** 型変換
-
-FIX2INT(value)
-INT2FIX(i)
-NUM2INT(value)
-INT2NUM(i)
-NUM2DBL(value)
-rb_float_new(f)
-STR2CSTR(value)
-rb_str_new2(s)
-
-** クラス/モジュール定義
-
-VALUE rb_define_class(const char *name, VALUE super)
-
- superのサブクラスとして新しいRubyクラスを定義する.
-
-VALUE rb_define_class_under(VALUE module, const char *name, VALUE super)
-
- superのサブクラスとして新しいRubyクラスを定義し,moduleの
- 定数として定義する.
-
-VALUE rb_define_module(const char *name)
-
- 新しいRubyモジュールを定義する.
-
-VALUE rb_define_module_under(VALUE module, const char *name, VALUE super)
-
- 新しいRubyモジュールを定義し,moduleの定数として定義する.
-
-void rb_include_module(VALUE klass, VALUE module)
-
- モジュールをインクルードする.classがすでにmoduleをインク
- ルードしている時には何もしない(多重インクルードの禁止).
-
-void rb_extend_object(VALUE object, VALUE module)
-
- オブジェクトをモジュール(で定義されているメソッド)で拡張する.
-
-** 大域変数定義
-
-void rb_define_variable(const char *name, VALUE *var)
-
- RubyとCとで共有するグローバル変数を定義する.変数名が`$'で
- 始まらない時には自動的に追加される.nameとしてRubyの識別子
- として許されない文字(例えば` ')を含む場合にはRubyプログラ
- ムからは見えなくなる.
-
-void rb_define_readonly_variable(const char *name, VALUE *var)
-
- RubyとCとで共有するread onlyのグローバル変数を定義する.
- read onlyであること以外はrb_define_variable()と同じ.
-
-void rb_define_virtual_variable(const char *name,
- VALUE (*getter)(), void (*setter)())
-
- 関数によって実現されるRuby変数を定義する.変数が参照された
- 時にはgetterが,変数に値がセットされた時にはsetterが呼ばれ
- る.
-
-void rb_define_hooked_variable(const char *name, VALUE *var,
- VALUE (*getter)(), void (*setter)())
-
- 関数によってhookのつけられたグローバル変数を定義する.変数
- が参照された時にはgetterが,関数に値がセットされた時には
- setterが呼ばれる.getterやsetterに0を指定した時にはhookを
- 指定しないのと同じ事になる.
-
-void rb_global_variable(VALUE *var)
-
- GCのため,Rubyプログラムからはアクセスされないが, Rubyオブ
- ジェクトを含む大域変数をマークする.
-
-** 定数
-
-void rb_define_const(VALUE klass, const char *name, VALUE val)
-
- 定数を定義する.
-
-void rb_define_global_const(const char *name, VALUE val)
-
- 大域定数を定義する.
-
- rb_define_const(rb_cObject, name, val)
-
- と同じ意味.
-
-** メソッド定義
-
-rb_define_method(VALUE klass, const char *name, VALUE (*func)(), int argc)
-
- メソッドを定義する.argcはselfを除く引数の数.argcが-1の時,
- 関数には引数の数(selfを含まない)を第1引数, 引数の配列を第2
- 引数とする形式で与えられる(第3引数はself).argcが-2の時,
- 第1引数がself, 第2引数がargs(argsは引数を含むRubyの配列)と
- いう形式で与えられる.
-
-rb_define_private_method(VALUE klass, const char *name, VALUE (*func)(), int argc)
-
- privateメソッドを定義する.引数はrb_define_method()と同じ.
-
-rb_define_singleton_method(VALUE klass, const char *name, VALUE (*func)(), int argc)
-
- 特異メソッドを定義する.引数はrb_define_method()と同じ.
-
-rb_scan_args(int argc, VALUE *argv, const char *fmt, ...)
-
- argc, argv形式で与えられた引数を分解する.fmtは必須引数の数,
- 付加引数の数, 残りの引数があるかを指定する文字列で, "数字
- 数字*"という形式である. 2 番目の数字と"*"はそれぞれ省略可
- 能である.必須引数が一つもない場合は0を指定する.第3引数以
- 降は変数へのポインタで, 該当する要素がその変数に格納される.
- 付加引数に対応する引数が与えられていない場合は変数にQnilが
- 代入される.
-
-** Rubyメソッド呼び出し
-
-VALUE rb_funcall(VALUE recv, ID mid, int narg, ...)
-
- メソッド呼び出し.文字列からmidを得るためにはrb_intern()を
- 使う.
-
-VALUE rb_funcall2(VALUE recv, ID mid, int argc, VALUE *argv)
-
- メソッド呼び出し.引数をargc, argv形式で渡す.
-
-VALUE rb_eval_string(const char *str)
-
- 文字列をRubyスクリプトとしてコンパイル・実行する.
-
-ID rb_intern(const char *name)
-
- 文字列に対応するIDを返す.
-
-char *rb_id2name(ID id)
-
- IDに対応する文字列を返す(デバッグ用).
-
-char *rb_class2name(VALUE klass)
-
- クラスの名前を返す(デバッグ用).クラスが名前を持たない時には,
- 祖先を遡って名前を持つクラスの名前を返す.
-
-int rb_respond_to(VALUE obj, ID id)
-
- objがidで示されるメソッドを持つかどうかを返す。
-
-** インスタンス変数
-
-VALUE rb_iv_get(VALUE obj, const char *name)
-
- objのインスタンス変数の値を得る.`@'で始まらないインスタン
- ス変数は Rubyプログラムからアクセスできない「隠れた」イン
- スタンス変数になる.定数は大文字の名前を持つクラス(または
- モジュール)のインスタンス変数として実装されている.
-
-VALUE rb_iv_set(VALUE obj, const char *name, VALUE val)
-
- objのインスタンス変数をvalにセットする.
-
-** 制御構造
-
-VALUE rb_iterate(VALUE (*func1)(), VALUE arg1, VALUE (*func2)(), VALUE arg2)
-
- func2をブロックとして設定し, func1をイテレータとして呼ぶ.
- func1には arg1が引数として渡され, func2には第1引数にイテレー
- タから与えられた値, 第2引数にarg2が渡される.
-
-VALUE rb_yield(VALUE val)
-
- valを値としてイテレータブロックを呼び出す.
-
-VALUE rb_rescue(VALUE (*func1)(), VALUE arg1, VALUE (*func2)(), VALUE arg2)
-
- 関数func1をarg1を引数に呼び出す.func1の実行中に例外が発生
- した時には func2をarg2を引数として呼ぶ.戻り値は例外が発生
- しなかった時はfunc1の戻り値, 例外が発生した時にはfunc2の戻
- り値である.
-
-VALUE rb_ensure(VALUE (*func1)(), VALUE arg1, void (*func2)(), VALUE arg2)
-
- 関数func1をarg1を引数として実行し, 実行終了後(たとえ例外が
- 発生しても) func2をarg2を引数として実行する.戻り値はfunc1
- の戻り値である(例外が発生した時は戻らない).
-
-** 例外・エラー
-
-void rb_warning(const char *fmt, ...)
-
- rb_verbose時に標準エラー出力に警告情報を表示する.引数は
- printf()と同じ.
-
-void rb_raise(rb_eRuntimeError, const char *fmt, ...)
-
- RuntimeError例外を発生させる.引数はprintf()と同じ.
-
-void rb_raise(VALUE exception, const char *fmt, ...)
-
- exceptionで指定した例外を発生させる.fmt以下の引数は
- printf()と同じ.
-
-void rb_fatal(const char *fmt, ...)
-
- 致命的例外を発生させる.通常の例外処理は行なわれず, インター
- プリタが終了する(ただしensureで指定されたコードは終了前に
- 実行される).
-
-void rb_bug(const char *fmt, ...)
-
- インタープリタなどプログラムのバグでしか発生するはずのない
- 状況の時呼ぶ.インタープリタはコアダンプし直ちに終了する.
- 例外処理は一切行なわれない.
-
-** Rubyの初期化・実行
-
-Rubyをアプリケーションに埋め込む場合には以下のインタフェース
-を使う.通常の拡張ライブラリには必要ない.
-
-void ruby_init()
-
- Rubyインタプリタの初期化を行なう.
-
-void ruby_options(int argc, char **argv)
-
- Rubyインタプリタのコマンドライン引数の処理を行なう.
-
-void ruby_run()
-
- Rubyインタプリタを実行する.
-
-void ruby_script(char *name)
-
- Rubyのスクリプト名($0)を設定する.
-
-
-Appendix C. extconf.rbで使える関数たち
-
-extconf.rbの中では利用可能なコンパイル条件チェックの関数は以
-下の通りである.
-
-have_library(lib, func)
-
- 関数funcを定義しているライブラリlibの存在をチェックする.
- ライブラリが存在する時,trueを返す.
-
-find_library(lib, func, path...)
-
- 関数funcを定義しているライブラリlibの存在を -Lpath を追加
- しながらチェックする.ライブラリが見付かった時,trueを返す.
-
-have_func(func, header)
-
- ヘッダファイルheaderをインクルードして関数funcの存在をチェッ
- クする.funcが標準ではリンクされないライブラリ内のものであ
- る時には先にhave_libraryでそのライブラリをチェックしておく
- 事.関数が存在する時trueを返す.
-
-have_header(header)
-
- ヘッダファイルの存在をチェックする.ヘッダファイルが存在す
- る時trueを返す.
-
-create_makefile(target)
-
- 拡張ライブラリ用のMakefileを生成する.この関数を呼ばなけれ
- ばそのライブラリはコンパイルされない.targetはモジュール名
- を表す.
-
-with_config(withval[, default=nil])
-
- コマンドライン上の--with-<withval>で指定されたオプション値を得る.
-
-dir_config(target[, default_dir])
-dir_config(target[, default_include, default_lib])
-
- コマンドライン上の--with-<target>-dir, --with-<target>-include,
- --with-<target>-libのいずれかで指定されるディレクトリを
- $CFLAGS や $LDFLAGS に追加する.--with-<target>-dir=/pathは
- --with-<target>-include=/path/include --with-<target>-lib=/path/lib
- と等価である.追加された include ディレクトリと lib ディレクトリの
- 配列を返す. ([include_dir, lib_dir])
-
-/*
- * Local variables:
- * fill-column: 60
- * end:
- */
diff --git a/README.ja b/README.ja
deleted file mode 100644
index fc502dd440..0000000000
--- a/README.ja
+++ /dev/null
@@ -1,153 +0,0 @@
-* Rubyとは
-
-Rubyはシンプルかつ強力なオブジェクト指向スクリプト言語です.
-Rubyは最初から純粋なオブジェクト指向言語として設計されていま
-すから,オブジェクト指向プログラミングを手軽に行う事が出来ま
-す.もちろん通常の手続き型のプログラミングも可能です.
-
-Rubyはテキスト処理関係の能力などに優れ,Perlと同じくらい強力
-です.さらにシンプルな文法と,例外処理やイテレータなどの機構
-によって,より分かりやすいプログラミングが出来ます.
-
-
-* Rubyの特長
-
- + シンプルな文法
- + 普通のオブジェクト指向機能(クラス,メソッドコールなど)
- + 特殊なオブジェクト指向機能(Mixin, 特異メソッドなど)
- + 演算子オーバーロード
- + 例外処理機能
- + イテレータとクロージャ
- + ガーベージコレクタ
- + ダイナミックローディング (アーキテクチャによる)
- + 移植性が高い.多くのUNIX上で動くだけでなく,DOSやWindows,
- Mac,BeOSなどの上でも動く
-
-
-* 入手法
-
-** ftpで
-
-以下の場所においてあります.
-
- ftp://ftp.ruby-lang.org/pub/ruby/
-
-** CVSで
-
- $ cvs -d :pserver:anonymous@cvs.ruby-lang.org:/src login
- (Logging in to anonymous@cvs.ruby-lang.org)
- CVS password: anonymous
- $ cvs -z4 -d :pserver:anonymous@cvs.ruby-lang.org:src checkout ruby
-
-
-* ホームページ
-
-RubyのホームページのURLは
-
- http://www.ruby-lang.org/
-
-です.
-
-
-* メーリングリスト
-
-Rubyのメーリングリストがあります。参加希望の方は
-
- ruby-list-ctl@ruby-lang.org
-
-まで本文に
-
- subscribe YourFirstName YourFamilyName
-
-と書いて送って下さい。
-
-Ruby開発者向けメーリングリストもあります。こちらではrubyのバ
-グ、将来の仕様拡張など実装上の問題について議論されています。
-参加希望の方は
-
- ruby-dev-ctl@ruby-lang.org
-
-までruby-listと同様の方法でメールしてください。
-
-Ruby拡張モジュールについて話し合うruby-extメーリングリストと
-数学関係の話題について話し合うruby-mathメーリングリストと
-英語で話し合うruby-talkメーリングリストもあります。参加方法
-はどれも同じです。
-
-
-* コンパイル・インストール
-
-以下の手順で行ってください.
-
- 1. もしconfigureファイルが見つからない、もしくは
- configure.inより古いようなら、autoconfを実行して
- 新しくconfigureを生成する
-
- 2. configureを実行してMakefileなどを生成する
-
- 3. (必要ならば)defines.hを編集する
-
- 多分,必要無いと思います.
-
- 4. (必要ならば)ext/Setupに静的にリンクする拡張モジュールを
- 指定する
-
- ext/Setupに記述したモジュールは静的にリンクされます.
-
- ダイナミックローディングをサポートしていないアーキテク
- チャではSetupの1行目の「option nodynamic」という行のコ
- メントを外す必要があります.また,このアーキテクチャで
- 拡張モジュールを利用するためには,あらかじめ静的にリン
- クしておく必要があります.
-
- 5. makeを実行してコンパイルする
-
- 6. make testでテストを行う.
-
- 「test succeeded」と表示されれば成功です.ただしテスト
- に成功しても完璧だと保証されている訳ではありません.
-
- 7. make install
-
- rootで作業する必要があるかもしれません.
-
-もし,コンパイル時にエラーが発生した場合にはエラーのログとマ
-シン,OSの種類を含むできるだけ詳しいレポートを作者に送ってく
-ださると他の方のためにもなります.
-
-
-* 移植
-
-UNIXであればconfigureがほとんどの差異を吸収してくれるはずで
-すが,思わぬ見落としがあった場合(あるに違いない),作者にその
-ことをレポートすれば,解決できるかも知れません.
-
-アーキテクチャにもっとも依存するのはGC部です.RubyのGCは対象
-のアーキテクチャがsetjmp()によって全てのレジスタを jmp_bufに
-格納することと,jmp_bufとスタックが32bitアラインメントされて
-いることを仮定しています.特に前者が成立しない場合の対応は非
-常に困難でしょう.後者の解決は比較的簡単で,gc.cでスタックを
-マークしている部分にアラインメントのバイト数だけずらしてマー
-クするコードを追加するだけで済みます.「defined(THINK_C)」で
-括られている部分を参考にしてください
-
-# 実際にはRubyはThink Cではコンパイルできません.
-
-レジスタウィンドウを持つCPUでは,レジスタウィンドウをスタッ
-クにフラッシュするアセンブラコードを追加する必要があるかも知
-れません.
-
-
-* 配布条件
-
-COPYING.jaファイルを参照してください。
-
-
-* 著者
-
-コメント,バグレポートその他は matz@netlab.jp まで.
--------------------------------------------------------
-created at: Thu Aug 3 11:57:36 JST 1995
-Local variables:
-mode: indented-text
-end:
diff --git a/ToDo b/ToDo
deleted file mode 100644
index 20d5236265..0000000000
--- a/ToDo
+++ /dev/null
@@ -1,127 +0,0 @@
-Language Spec.
-
-- Class#allocate - basicNew
-* operator !! for rescue. ???
-* objectify characters
-* ../... outside condition invokes operator method too.
-* ... inside condition turns off just before right condition.???
-* package or access control for global variables??
-* named arguments like foo(nation:="german") or foo(nation: "german").
-* method to retrieve argument information (needs new C API)
-* multiple return values, yield values. maybe incompatible ???
-* cascading method invocation ???
-* def Class#method .. end ??
-* class Foo::Bar<Baz .. end, module Boo::Bar .. end
-* def Foo::Bar::baz() .. end ??
-* I18N (or M17N) script/string/regexp
-* Fixnum 0 as false ????
-* discourage use of symbol variables (e.g. $/, etc.) in manual
-* discourage use of Perlish features by giving warnings.
-* non confusing in-block local variable (is it possible?)
- + remove scope by block
- + variables appears within block may have independent values.
-* Regexp: make /o thread safe.
-* decide whether begin with rescue or ensure make do..while loop.
-* a +1 to be a+1, not a(+1).
-* unify == and eql? again
-* to_i returns nil if str contains no digit.
-* raise exception by `` error
-* jar like combined library package. -> RubyGems?
-* resumable Exception via Exception#resume.
-* method combination, e.g. before, after, around, etc.
-* .. or something like defadvice in Emacs.
-* property - for methods, or for objects in general.
-* "in" modifier, to annotate, or to encourage assertion.
-* selector namespace - something like generic-flet in CLOS, to help RubyBehevior
-* private instance variable (as in Python?) @_foo in class Foo => @_Foo_foo
-* warn/error "bare word" method, like "foo", you should type "foo()"
-
-Hacking Interpreter
-
-- generational GC
-* non-blocking open (e.g. for named pipe) for thread
-* avoid blocking with gethostbyname/gethostbyaddr (use fork ???)
-* objectify interpreters ???
-* remove rb_eval() recursions
-* syntax tree -> bytecode ???
-* scrambled script, or script filter
-* setuid ruby
-* performance tune for in-block (dynamic) local variables.
-* give warnings to assign magic variables.
-* export rb_io_{addstr,printf,puts,print}
-* autoload should work with threads [ruby-talk:4589]
-* remove stdio dependency from IOs.
-* warn for inconsistent local variable usage (lv m and method m at the same time).
-* MicroRuby
-* Built-in Interactive Ruby.
-* Parser API
-* trap every method invocation, which can be enabled by e.g. trap_call :method.
-* unify Errno exceptions of same errno, or new exception comparison scheme.
-* 2.times{|i| if i==0 then a = 15 else puts eval("a") end} should print nil.
-* Thread#max_stack_size attribute (possible??)
-
-Standard Libraries
-
-- Module#define_method which takes a name and a body (block, proc or method).
-- Enume#inject
-- Array#fetch
-- IO::for_fd
-- Process::waitall [ruby-talk:4557]
-- Process::Status
-- File::lchown, File::lchmod; xxx - still need work for non existing platforms
-- move Time::times to Process.
-- Enumerable#sort_by for Schwartzian transformation
-- fork_and_kill_other_threads.
-- signal list (Signal::trap, Signal::list).
-- move NameError under StandardError.
-- Integer#to_s(base)
-- Hash::new{default}
-- hash etc. should handle self referenceing array/hash
-- Array#select(n1,n2...) works like Array#indexes(n1,n2...)
-* String#scanf(?)
-* Object#fmt(?)
-* Time::strptime
-* Integer[num], Float[num]; Fixnum[num]?
-* method to retrieve non-number trailer for to_i/to_f.
-* Stream or Port, abstract superclass of IO ?
-* String#{pred,prev}, String#downto
-* optional stepsize argument for succ()
-* Ruby module -- Ruby::Version, Ruby::Interpreter
-* introduce Boolean class; super of TrueClass, FalseClass
-* synchronized method - synchronized{...}, synchronized :foo, :bar
-* Array#&, Array#| to allow duplication. ???
-* way to specify immortal (fork endurance) thread;
-* or raise ForkException to every thread but fork caller.
-* new user-defined marshal scheme. _dump(dumper), _load(restorer)
-* library to load per-user profile seeking .ruby_profile or ruby.ini file.
-* warning framework (warn, warning for Ruby level)
-* marshal should not depend on sprintf/strtod (works bad with locale).
-* ternary arg pow: a.pow(b,c) == a**b%c
-* new caller(), e.g. call_stack; needs better name.
-* remove dependency on MAXPATHLEN.
-* pointer share mechanism similar to one in String for Array.
-* deprecate Array#indexes, and Array#indices.
-* require "1.6" etc. by /usr/lib/ruby/1.6/1.6.rb ;-)
-
-Extension Libraries
-
-* ptk.rb pTk wrapper that is compatible to tk.rb
-* Berkeley DB extension
-* BitVector
-* thread-safe fcgi
-
-Ruby Libraries
-
-* add uri.rb
-* urllib.rb, nttplib.rb, etc.
-* format like perl's
-
-Tools
-
-* freeze or undump to bundle everything
-* bundle using zlib
-
-Misc
-
-- publish Ruby books
-- publish Ruby books in English
diff --git a/array.c b/array.c
deleted file mode 100644
index 18f08ce532..0000000000
--- a/array.c
+++ /dev/null
@@ -1,1944 +0,0 @@
-/**********************************************************************
-
- array.c -
-
- $Author$
- $Date$
- created at: Fri Aug 6 09:46:12 JST 1993
-
- Copyright (C) 1993-2002 Yukihiro Matsumoto
- Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
- Copyright (C) 2000 Information-technology Promotion Agency, Japan
-
-**********************************************************************/
-
-#include "ruby.h"
-#include "util.h"
-#include "st.h"
-
-VALUE rb_cArray;
-static ID id_cmp;
-
-#define ARY_DEFAULT_SIZE 16
-
-void
-rb_mem_clear(mem, size)
- register VALUE *mem;
- register long size;
-{
- while (size--) {
- *mem++ = Qnil;
- }
-}
-
-static void
-memfill(mem, size, val)
- register VALUE *mem;
- register long size;
- register VALUE val;
-{
- while (size--) {
- *mem++ = val;
- }
-}
-
-#define ARY_TMPLOCK FL_USER1
-
-static void
-rb_ary_modify_check(ary)
- VALUE ary;
-{
- if (OBJ_FROZEN(ary)) rb_error_frozen("array");
- if (FL_TEST(ary, ARY_TMPLOCK))
- rb_raise(rb_eTypeError, "can't modify array during sort");
- if (!OBJ_TAINTED(ary) && rb_safe_level() >= 4)
- rb_raise(rb_eSecurityError, "Insecure: can't modify array");
-}
-
-static void
-rb_ary_modify(ary)
- VALUE ary;
-{
- VALUE *ptr;
-
- rb_ary_modify_check(ary);
- if (!FL_TEST(ary, ELTS_SHARED)) return;
- ptr = ALLOC_N(VALUE, RARRAY(ary)->len);
- FL_UNSET(ary, ELTS_SHARED);
- RARRAY(ary)->aux.capa = RARRAY(ary)->len;
- MEMCPY(ptr, RARRAY(ary)->ptr, VALUE, RARRAY(ary)->len);
- RARRAY(ary)->ptr = ptr;
-}
-
-VALUE
-rb_ary_freeze(ary)
- VALUE ary;
-{
- return rb_obj_freeze(ary);
-}
-
-static VALUE
-rb_ary_frozen_p(ary)
- VALUE ary;
-{
- if (FL_TEST(ary, FL_FREEZE|ARY_TMPLOCK))
- return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-rb_ary_s_alloc(klass)
- VALUE klass;
-{
- NEWOBJ(ary, struct RArray);
- OBJSETUP(ary, klass, T_ARRAY);
-
- ary->len = 0;
- ary->ptr = 0;
- ary->aux.capa = 0;
-
- return (VALUE)ary;
-}
-
-static VALUE
-ary_new(klass, len)
- VALUE klass;
- long len;
-{
- VALUE ary = rb_obj_alloc(klass);
-
- if (len < 0) {
- rb_raise(rb_eArgError, "negative array size (or size too big)");
- }
- if (len > 0 && len*sizeof(VALUE) <= 0) {
- rb_raise(rb_eArgError, "array size too big");
- }
- if (len == 0) len++;
- RARRAY(ary)->ptr = ALLOC_N(VALUE, len);
- RARRAY(ary)->aux.capa = len;
-
- return ary;
-}
-
-VALUE
-rb_ary_new2(len)
- long len;
-{
- return ary_new(rb_cArray, len);
-}
-
-
-VALUE
-rb_ary_new()
-{
- return rb_ary_new2(ARY_DEFAULT_SIZE);
-}
-
-#ifdef HAVE_STDARG_PROTOTYPES
-#include <stdarg.h>
-#define va_init_list(a,b) va_start(a,b)
-#else
-#include <varargs.h>
-#define va_init_list(a,b) va_start(a)
-#endif
-
-VALUE
-#ifdef HAVE_STDARG_PROTOTYPES
-rb_ary_new3(long n, ...)
-#else
-rb_ary_new3(n, va_alist)
- long n;
- va_dcl
-#endif
-{
- va_list ar;
- VALUE ary;
- long i;
-
- if (n < 0) {
- rb_raise(rb_eIndexError, "negative number of items(%d)", n);
- }
- ary = rb_ary_new2(n<ARY_DEFAULT_SIZE?ARY_DEFAULT_SIZE:n);
-
- va_init_list(ar, n);
- for (i=0; i<n; i++) {
- RARRAY(ary)->ptr[i] = va_arg(ar, VALUE);
- }
- va_end(ar);
-
- RARRAY(ary)->len = n;
- return ary;
-}
-
-VALUE
-rb_ary_new4(n, elts)
- long n;
- VALUE *elts;
-{
- VALUE ary;
-
- ary = rb_ary_new2(n);
- if (n > 0 && elts) {
- MEMCPY(RARRAY(ary)->ptr, elts, VALUE, n);
- }
- RARRAY(ary)->len = n;
-
- return ary;
-}
-
-VALUE
-rb_assoc_new(car, cdr)
- VALUE car, cdr;
-{
- VALUE ary;
-
- ary = rb_ary_new2(2);
- RARRAY(ary)->ptr[0] = car;
- RARRAY(ary)->ptr[1] = cdr;
- RARRAY(ary)->len = 2;
-
- return ary;
-}
-
-static VALUE
-to_ary(ary)
- VALUE ary;
-{
- return rb_convert_type(ary, T_ARRAY, "Array", "to_ary");
-}
-
-static VALUE
-to_ary_failed(failed)
- int *failed;
-{
- *failed = Qtrue;
-}
-
-static VALUE rb_ary_replace _((VALUE, VALUE));
-
-static VALUE
-rb_ary_initialize(argc, argv, ary)
- int argc;
- VALUE *argv;
- VALUE ary;
-{
- long len;
- VALUE size, val;
-
- rb_ary_modify(ary);
- if (rb_scan_args(argc, argv, "02", &size, &val) == 0) {
- RARRAY(ary)->len = 0;
- if (rb_block_given_p()) {
- rb_warning("given block not used");
- }
- return ary;
- }
-
- if (argc == 1 && !FIXNUM_P(size)) {
- val = rb_check_convert_type(size, T_ARRAY, "Array", "to_ary");
- if (!NIL_P(val)) {
- rb_ary_replace(ary, val);
- return ary;
- }
- }
-
- len = NUM2LONG(size);
- if (len < 0) {
- rb_raise(rb_eArgError, "negative array size");
- }
- if (len > 0 && len*sizeof(VALUE) <= 0) {
- rb_raise(rb_eArgError, "array size too big");
- }
- if (len > RARRAY(ary)->aux.capa) {
- RARRAY(ary)->aux.capa = len;
- REALLOC_N(RARRAY(ary)->ptr, VALUE, RARRAY(ary)->aux.capa);
- }
- if (rb_block_given_p()) {
- long i;
-
- if (argc > 1) {
- rb_raise(rb_eArgError, "wrong number of arguments");
- }
- for (i=0; i<len; i++) {
- RARRAY(ary)->ptr[i] = rb_yield(INT2NUM(i));
- RARRAY(ary)->len = i+1;
- }
- }
- else {
- memfill(RARRAY(ary)->ptr, len, val);
- RARRAY(ary)->len = len;
- }
-
- return ary;
-}
-
-static VALUE
-rb_ary_s_create(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- VALUE ary = rb_obj_alloc(klass);
-
- if (argc != 0) {
- RARRAY(ary)->ptr = ALLOC_N(VALUE, argc);
- MEMCPY(RARRAY(ary)->ptr, argv, VALUE, argc);
- }
- RARRAY(ary)->len = RARRAY(ary)->aux.capa = argc;
-
- return ary;
-}
-
-void
-rb_ary_store(ary, idx, val)
- VALUE ary;
- long idx;
- VALUE val;
-{
- rb_ary_modify(ary);
- if (idx < 0) {
- idx += RARRAY(ary)->len;
- if (idx < 0) {
- rb_raise(rb_eIndexError, "index %d out of array",
- idx - RARRAY(ary)->len);
- }
- }
-
- if (idx >= RARRAY(ary)->aux.capa) {
- long capa_inc = RARRAY(ary)->aux.capa / 2;
- if (capa_inc < ARY_DEFAULT_SIZE) {
- capa_inc = ARY_DEFAULT_SIZE;
- }
- RARRAY(ary)->aux.capa = idx + capa_inc;
- REALLOC_N(RARRAY(ary)->ptr, VALUE, RARRAY(ary)->aux.capa);
- }
- if (idx > RARRAY(ary)->len) {
- rb_mem_clear(RARRAY(ary)->ptr+RARRAY(ary)->len,
- idx-RARRAY(ary)->len+1);
- }
-
- if (idx >= RARRAY(ary)->len) {
- RARRAY(ary)->len = idx + 1;
- }
- RARRAY(ary)->ptr[idx] = val;
-}
-
-VALUE
-rb_ary_push(ary, item)
- VALUE ary;
- VALUE item;
-{
- rb_ary_store(ary, RARRAY(ary)->len, item);
- return ary;
-}
-
-static VALUE
-rb_ary_push_m(argc, argv, ary)
- int argc;
- VALUE *argv;
- VALUE ary;
-{
- if (argc == 0) {
- rb_raise(rb_eArgError, "wrong number arguments(at least 1)");
- }
- if (argc > 0) {
- while (argc--) {
- rb_ary_push(ary, *argv++);
- }
- }
- return ary;
-}
-
-VALUE
-rb_ary_pop(ary)
- VALUE ary;
-{
- rb_ary_modify_check(ary);
- if (RARRAY(ary)->len == 0) return Qnil;
- if (!FL_TEST(ary, ELTS_SHARED) &&
- RARRAY(ary)->len * 10 < RARRAY(ary)->aux.capa &&
- RARRAY(ary)->aux.capa > ARY_DEFAULT_SIZE) {
- RARRAY(ary)->aux.capa = RARRAY(ary)->len * 2;
- REALLOC_N(RARRAY(ary)->ptr, VALUE, RARRAY(ary)->aux.capa);
- }
- return RARRAY(ary)->ptr[--RARRAY(ary)->len];
-}
-
-static void
-ary_make_shared(ary)
- VALUE ary;
-{
- if (FL_TEST(ary, ELTS_SHARED)) return;
- else {
- NEWOBJ(shared, struct RArray);
- OBJSETUP(shared, rb_cArray, T_ARRAY);
-
- shared->len = RARRAY(ary)->len;
- shared->ptr = RARRAY(ary)->ptr;
- shared->aux.capa = RARRAY(ary)->aux.capa;
- RARRAY(ary)->aux.shared = (VALUE)shared;
- FL_SET(ary, ELTS_SHARED);
- }
-}
-
-VALUE
-rb_ary_shift(ary)
- VALUE ary;
-{
- VALUE top;
-
- rb_ary_modify_check(ary);
- if (RARRAY(ary)->len == 0) return Qnil;
- top = RARRAY(ary)->ptr[0];
- ary_make_shared(ary);
- RARRAY(ary)->ptr++; /* shift ptr */
- RARRAY(ary)->len--;
-
- return top;
-}
-
-VALUE
-rb_ary_unshift(ary, item)
- VALUE ary, item;
-{
- rb_ary_modify(ary);
- if (RARRAY(ary)->len == RARRAY(ary)->aux.capa) {
- long capa_inc = RARRAY(ary)->aux.capa / 2;
- if (capa_inc < ARY_DEFAULT_SIZE) {
- capa_inc = ARY_DEFAULT_SIZE;
- }
- RARRAY(ary)->aux.capa+=capa_inc;
- REALLOC_N(RARRAY(ary)->ptr, VALUE, RARRAY(ary)->aux.capa);
- }
-
- /* sliding items */
- MEMMOVE(RARRAY(ary)->ptr+1, RARRAY(ary)->ptr, VALUE, RARRAY(ary)->len);
-
- RARRAY(ary)->len++;
- RARRAY(ary)->ptr[0] = item;
-
- return ary;
-}
-
-static VALUE
-rb_ary_unshift_m(argc, argv, ary)
- int argc;
- VALUE *argv;
- VALUE ary;
-{
- if (argc == 0) {
- rb_raise(rb_eArgError, "wrong number of arguments(at least 1)");
- }
- if (argc > 0) {
- long len = RARRAY(ary)->len;
-
- /* make rooms by setting the last item */
- rb_ary_store(ary, len + argc - 1, Qnil);
-
- /* sliding items */
- MEMMOVE(RARRAY(ary)->ptr + argc, RARRAY(ary)->ptr, VALUE, len);
- MEMCPY(RARRAY(ary)->ptr, argv, VALUE, argc);
- }
- return ary;
-}
-
-VALUE
-rb_ary_entry(ary, offset)
- VALUE ary;
- long offset;
-{
- if (RARRAY(ary)->len == 0) return Qnil;
-
- if (offset < 0) {
- offset += RARRAY(ary)->len;
- }
- if (offset < 0 || RARRAY(ary)->len <= offset) {
- return Qnil;
- }
-
- return RARRAY(ary)->ptr[offset];
-}
-
-static VALUE
-rb_ary_subseq(ary, beg, len)
- VALUE ary;
- long beg, len;
-{
- VALUE klass, ary2;
-
- if (beg > RARRAY(ary)->len) return Qnil;
- if (beg < 0 || len < 0) return Qnil;
-
- if (beg + len > RARRAY(ary)->len) {
- len = RARRAY(ary)->len - beg;
- }
- if (len < 0) {
- len = 0;
- }
- klass = rb_obj_class(ary);
- if (len == 0) return ary_new(klass,0);
-
- ary_make_shared(ary);
- ary2 = rb_obj_alloc(klass);
- RARRAY(ary2)->ptr = RARRAY(ary)->ptr+beg;
- RARRAY(ary2)->len = len;
- RARRAY(ary2)->aux.shared = RARRAY(ary)->aux.shared;
- FL_SET(ary2, ELTS_SHARED);
-
- return ary2;
-}
-
-VALUE
-rb_ary_aref(argc, argv, ary)
- int argc;
- VALUE *argv;
- VALUE ary;
-{
- VALUE arg;
- long beg, len;
-
- if (argc == 2) {
- beg = NUM2LONG(argv[0]);
- len = NUM2LONG(argv[1]);
- if (beg < 0) {
- beg += RARRAY(ary)->len;
- }
- return rb_ary_subseq(ary, beg, len);
- }
- if (argc != 1) {
- rb_scan_args(argc, argv, "11", 0, 0);
- }
- arg = argv[0];
- /* special case - speeding up */
- if (FIXNUM_P(arg)) {
- return rb_ary_entry(ary, FIX2LONG(arg));
- }
- else if (TYPE(arg) == T_BIGNUM) {
- rb_raise(rb_eIndexError, "index too big");
- }
- else {
- /* check if idx is Range */
- switch (rb_range_beg_len(arg, &beg, &len, RARRAY(ary)->len, 0)) {
- case Qfalse:
- break;
- case Qnil:
- return Qnil;
- default:
- return rb_ary_subseq(ary, beg, len);
- }
- }
- return rb_ary_entry(ary, NUM2LONG(arg));
-}
-
-static VALUE
-rb_ary_at(ary, pos)
- VALUE ary, pos;
-{
- return rb_ary_entry(ary, NUM2LONG(pos));
-}
-
-static VALUE
-rb_ary_first(ary)
- VALUE ary;
-{
- if (RARRAY(ary)->len == 0) return Qnil;
- return RARRAY(ary)->ptr[0];
-}
-
-static VALUE
-rb_ary_last(ary)
- VALUE ary;
-{
- if (RARRAY(ary)->len == 0) return Qnil;
- return RARRAY(ary)->ptr[RARRAY(ary)->len-1];
-}
-
-static VALUE
-rb_ary_fetch(argc, argv, ary)
- int argc;
- VALUE *argv;
- VALUE ary;
-{
- VALUE pos, ifnone;
- long idx;
-
- rb_scan_args(argc, argv, "11", &pos, &ifnone);
- idx = NUM2LONG(pos);
-
- if (idx < 0) {
- idx += RARRAY(ary)->len;
- }
- if (idx < 0 || RARRAY(ary)->len <= idx) {
- if (rb_block_given_p()) {
- if (argc > 1) {
- rb_raise(rb_eArgError, "wrong number of arguments");
- }
- return rb_yield(pos);
- }
- if (argc == 1) {
- rb_raise(rb_eIndexError, "index %d out of array", idx);
- }
- return ifnone;
- }
- return RARRAY(ary)->ptr[idx];
-}
-
-static VALUE
-rb_ary_index(ary, val)
- VALUE ary;
- VALUE val;
-{
- long i;
-
- for (i=0; i<RARRAY(ary)->len; i++) {
- if (rb_equal(RARRAY(ary)->ptr[i], val))
- return INT2NUM(i);
- }
- return Qnil;
-}
-
-static VALUE
-rb_ary_rindex(ary, val)
- VALUE ary;
- VALUE val;
-{
- long i = RARRAY(ary)->len;
-
- while (i--) {
- if (rb_equal(RARRAY(ary)->ptr[i], val))
- return INT2NUM(i);
- }
- return Qnil;
-}
-
-static VALUE
-rb_ary_indexes(argc, argv, ary)
- int argc;
- VALUE *argv;
- VALUE ary;
-{
- VALUE new_ary;
- long i;
-
- rb_warn("Array#%s is deprecated; use Array#select",
- rb_id2name(rb_frame_last_func()));
- new_ary = rb_ary_new2(argc);
- for (i=0; i<argc; i++) {
- rb_ary_push(new_ary, rb_ary_aref(1, argv+i, ary));
- }
-
- return new_ary;
-}
-
-VALUE
-rb_ary_to_ary(obj)
- VALUE obj;
-{
- if (NIL_P(obj)) return rb_ary_new2(0);
- if (TYPE(obj) == T_ARRAY) {
- return obj;
- }
- if (rb_respond_to(obj, rb_intern("to_ary"))) {
- return rb_convert_type(obj, T_ARRAY, "Array", "to_ary");
- }
- return rb_ary_new3(1, obj);
-}
-
-static void
-rb_ary_update(ary, beg, len, rpl)
- VALUE ary;
- long beg, len;
- VALUE rpl;
-{
- long rlen;
-
- rpl = rb_ary_to_ary(rpl);
- rlen = RARRAY(rpl)->len;
-
- if (len < 0) rb_raise(rb_eIndexError, "negative length %d", len);
- if (beg < 0) {
- beg += RARRAY(ary)->len;
- }
- if (beg < 0) {
- beg -= RARRAY(ary)->len;
- rb_raise(rb_eIndexError, "index %d out of array", beg);
- }
- if (beg + len > RARRAY(ary)->len) {
- len = RARRAY(ary)->len - beg;
- }
-
- rb_ary_modify(ary);
- if (beg >= RARRAY(ary)->len) {
- len = beg + rlen;
- if (len >= RARRAY(ary)->aux.capa) {
- RARRAY(ary)->aux.capa=len;
- REALLOC_N(RARRAY(ary)->ptr, VALUE, RARRAY(ary)->aux.capa);
- }
- rb_mem_clear(RARRAY(ary)->ptr+RARRAY(ary)->len, beg-RARRAY(ary)->len);
- MEMCPY(RARRAY(ary)->ptr+beg, RARRAY(rpl)->ptr, VALUE, rlen);
- RARRAY(ary)->len = len;
- }
- else {
- long alen;
-
- if (beg + len > RARRAY(ary)->len) {
- len = RARRAY(ary)->len - beg;
- }
-
- alen = RARRAY(ary)->len + rlen - len;
- if (alen >= RARRAY(ary)->aux.capa) {
- RARRAY(ary)->aux.capa = alen;
- REALLOC_N(RARRAY(ary)->ptr, VALUE, RARRAY(ary)->aux.capa);
- }
-
- if (len != rlen) {
- MEMMOVE(RARRAY(ary)->ptr+beg+rlen, RARRAY(ary)->ptr+beg+len,
- VALUE, RARRAY(ary)->len-(beg+len));
- RARRAY(ary)->len = alen;
- }
- MEMMOVE(RARRAY(ary)->ptr+beg, RARRAY(rpl)->ptr, VALUE, rlen);
- }
-}
-
-static VALUE
-rb_ary_aset(argc, argv, ary)
- int argc;
- VALUE *argv;
- VALUE ary;
-{
- long offset, beg, len;
-
- if (argc == 3) {
- rb_ary_update(ary, NUM2LONG(argv[0]), NUM2LONG(argv[1]), argv[2]);
- return argv[2];
- }
- if (argc != 2) {
- rb_raise(rb_eArgError, "wrong number of arguments(%d for 2)", argc);
- }
- if (FIXNUM_P(argv[0])) {
- offset = FIX2LONG(argv[0]);
- goto fixnum;
- }
- else if (rb_range_beg_len(argv[0], &beg, &len, RARRAY(ary)->len, 1)) {
- /* check if idx is Range */
- rb_ary_update(ary, beg, len, argv[1]);
- return argv[1];
- }
- if (TYPE(argv[0]) == T_BIGNUM) {
- rb_raise(rb_eIndexError, "index too big");
- }
-
- offset = NUM2LONG(argv[0]);
- fixnum:
- rb_ary_store(ary, offset, argv[1]);
- return argv[1];
-}
-
-static VALUE
-rb_ary_insert(argc, argv, ary)
- int argc;
- VALUE *argv;
- VALUE ary;
-{
- long pos;
-
- if (argc < 2) {
- rb_raise(rb_eArgError, "wrong number of arguments(at least 2)");
- }
- pos = NUM2LONG(argv[0]);
- if (pos == -1) {
- pos = RSTRING(ary)->len;
- }
- else if (pos < 0) {
- pos++;
- }
-
- rb_ary_update(ary, pos, 0, rb_ary_new4(argc-1, argv+1));
- return ary;
-}
-
-VALUE
-rb_ary_each(ary)
- VALUE ary;
-{
- long i;
-
- for (i=0; i<RARRAY(ary)->len; i++) {
- rb_yield(RARRAY(ary)->ptr[i]);
- }
- return ary;
-}
-
-static VALUE
-rb_ary_each_index(ary)
- VALUE ary;
-{
- long i;
-
- for (i=0; i<RARRAY(ary)->len; i++) {
- rb_yield(INT2NUM(i));
- }
- return ary;
-}
-
-static VALUE
-rb_ary_reverse_each(ary)
- VALUE ary;
-{
- long len = RARRAY(ary)->len;
-
- while (len--) {
- rb_yield(RARRAY(ary)->ptr[len]);
- }
- return ary;
-}
-
-static VALUE
-rb_ary_length(ary)
- VALUE ary;
-{
- return INT2NUM(RARRAY(ary)->len);
-}
-
-static VALUE
-rb_ary_empty_p(ary)
- VALUE ary;
-{
- if (RARRAY(ary)->len == 0)
- return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-ary_copy(ary, clone)
- VALUE ary;
- int clone;
-{
- VALUE copy;
-
- ary_make_shared(ary);
- copy = rb_obj_alloc(rb_cArray);
- if (clone) CLONESETUP(copy, ary);
- else DUPSETUP(copy, ary);
- RARRAY(copy)->ptr = RARRAY(ary)->ptr;
- RARRAY(copy)->len = RARRAY(ary)->len;
- RARRAY(copy)->aux.shared = RARRAY(ary)->aux.shared;
- FL_SET(copy, ELTS_SHARED);
-
- return copy;
-}
-
-static VALUE
-rb_ary_clone(ary)
- VALUE ary;
-{
- return ary_copy(ary, Qtrue);
-}
-
-VALUE
-rb_ary_dup(ary)
- VALUE ary;
-{
- return ary_copy(ary, Qfalse);
-}
-
-static VALUE
-ary_dup(ary)
- VALUE ary;
-{
- VALUE dup = rb_ary_new2(RARRAY(ary)->len);
-
- DUPSETUP(dup, ary);
- MEMCPY(RARRAY(dup)->ptr, RARRAY(ary)->ptr, VALUE, RARRAY(ary)->len);
- RARRAY(dup)->len = RARRAY(ary)->len;
- return dup;
-}
-
-extern VALUE rb_output_fs;
-
-static VALUE
-inspect_join(ary, arg)
- VALUE ary;
- VALUE *arg;
-{
- return rb_ary_join(arg[0], arg[1]);
-}
-
-VALUE
-rb_ary_join(ary, sep)
- VALUE ary, sep;
-{
- long len, i;
- int taint = 0;
- VALUE result, tmp;
-
- if (RARRAY(ary)->len == 0) return rb_str_new(0, 0);
- if (OBJ_TAINTED(ary)) taint = 1;
- if (OBJ_TAINTED(sep)) taint = 1;
-
- len = 1;
- for (i=0; i<RARRAY(ary)->len; i++) {
- if (TYPE(RARRAY(ary)->ptr[i]) == T_STRING) {
- len += RSTRING(RARRAY(ary)->ptr[i])->len;
- }
- else {
- len += 10;
- }
- }
- if (!NIL_P(sep)) {
- StringValue(sep);
- len += RSTRING(sep)->len * (RARRAY(ary)->len - 1);
- }
- result = rb_str_buf_new(len);
- for (i=0; i<RARRAY(ary)->len; i++) {
- tmp = RARRAY(ary)->ptr[i];
- switch (TYPE(tmp)) {
- case T_STRING:
- break;
- case T_ARRAY:
- if (rb_inspecting_p(tmp)) {
- tmp = rb_str_new2("[...]");
- }
- else {
- VALUE args[2];
-
- args[0] = tmp;
- args[1] = sep;
- tmp = rb_protect_inspect(inspect_join, ary, (VALUE)args);
- }
- break;
- default:
- tmp = rb_obj_as_string(tmp);
- }
- if (i > 0 && !NIL_P(sep))
- rb_str_buf_append(result, sep);
- rb_str_buf_append(result, tmp);
- if (OBJ_TAINTED(tmp)) taint = 1;
- }
-
- if (taint) OBJ_TAINT(result);
- return result;
-}
-
-static VALUE
-rb_ary_join_m(argc, argv, ary)
- int argc;
- VALUE *argv;
- VALUE ary;
-{
- VALUE sep;
-
- rb_scan_args(argc, argv, "01", &sep);
- if (NIL_P(sep)) sep = rb_output_fs;
- return rb_ary_join(ary, sep);
-}
-
-VALUE
-rb_ary_to_s(ary)
- VALUE ary;
-{
- VALUE str, sep;
-
- if (RARRAY(ary)->len == 0) return rb_str_new(0, 0);
- sep = rb_output_fs;
- str = rb_ary_join(ary, sep);
- return str;
-}
-
-static ID inspect_key;
-
-struct inspect_arg {
- VALUE (*func)();
- VALUE arg1, arg2;
-};
-
-static VALUE
-inspect_call(arg)
- struct inspect_arg *arg;
-{
- return (*arg->func)(arg->arg1, arg->arg2);
-}
-
-static VALUE
-inspect_ensure(obj)
- VALUE obj;
-{
- VALUE inspect_tbl;
-
- inspect_tbl = rb_thread_local_aref(rb_thread_current(), inspect_key);
- rb_ary_pop(inspect_tbl);
- return 0;
-}
-
-VALUE
-rb_protect_inspect(func, obj, arg)
- VALUE (*func)(ANYARGS);
- VALUE obj, arg;
-{
- struct inspect_arg iarg;
- VALUE inspect_tbl;
- VALUE id;
-
- if (!inspect_key) {
- inspect_key = rb_intern("__inspect_key__");
- }
- inspect_tbl = rb_thread_local_aref(rb_thread_current(), inspect_key);
- if (NIL_P(inspect_tbl)) {
- inspect_tbl = rb_ary_new();
- rb_thread_local_aset(rb_thread_current(), inspect_key, inspect_tbl);
- }
- id = rb_obj_id(obj);
- if (rb_ary_includes(inspect_tbl, id)) {
- return (*func)(obj, arg);
- }
- rb_ary_push(inspect_tbl, id);
- iarg.func = func;
- iarg.arg1 = obj;
- iarg.arg2 = arg;
-
- return rb_ensure(inspect_call, (VALUE)&iarg, inspect_ensure, obj);
-}
-
-VALUE
-rb_inspecting_p(obj)
- VALUE obj;
-{
- VALUE inspect_tbl;
-
- if (!inspect_key) {
- inspect_key = rb_intern("__inspect_key__");
- }
- inspect_tbl = rb_thread_local_aref(rb_thread_current(), inspect_key);
- if (NIL_P(inspect_tbl)) return Qfalse;
- return rb_ary_includes(inspect_tbl, rb_obj_id(obj));
-}
-
-static VALUE
-inspect_ary(ary)
- VALUE ary;
-{
- int tainted = OBJ_TAINTED(ary);
- long i = 0;
- VALUE s, str;
-
- str = rb_str_buf_new2("[");
- for (i=0; i<RARRAY(ary)->len; i++) {
- s = rb_inspect(RARRAY(ary)->ptr[i]);
- if (OBJ_TAINTED(s)) tainted = 1;
- if (i > 0) rb_str_buf_cat2(str, ", ");
- rb_str_buf_append(str, s);
- }
- rb_str_buf_cat2(str, "]");
- if (tainted) OBJ_TAINT(str);
- return str;
-}
-
-static VALUE
-rb_ary_inspect(ary)
- VALUE ary;
-{
- if (RARRAY(ary)->len == 0) return rb_str_new2("[]");
- if (rb_inspecting_p(ary)) return rb_str_new2("[...]");
- return rb_protect_inspect(inspect_ary, ary, 0);
-}
-
-static VALUE
-rb_ary_to_a(ary)
- VALUE ary;
-{
- return ary;
-}
-
-VALUE
-rb_ary_reverse(ary)
- VALUE ary;
-{
- VALUE *p1, *p2;
- VALUE tmp;
-
- if (RARRAY(ary)->len <= 1) return ary;
- rb_ary_modify(ary);
-
- p1 = RARRAY(ary)->ptr;
- p2 = p1 + RARRAY(ary)->len - 1; /* points last item */
-
- while (p1 < p2) {
- tmp = *p1;
- *p1++ = *p2;
- *p2-- = tmp;
- }
-
- return ary;
-}
-
-static VALUE
-rb_ary_reverse_bang(ary)
- VALUE ary;
-{
- if (RARRAY(ary)->len <= 1) return Qnil;
- return rb_ary_reverse(ary);
-}
-
-static VALUE
-rb_ary_reverse_m(ary)
- VALUE ary;
-{
- return rb_ary_reverse(ary_dup(ary));
-}
-
-int
-rb_cmpint(cmp)
- VALUE cmp;
-{
- if (FIXNUM_P(cmp)) return NUM2LONG(cmp);
- if (TYPE(cmp) == T_BIGNUM) {
- if (RBIGNUM(cmp)->sign) return 1;
- return -1;
- }
- if (rb_funcall(cmp, '>', 1, INT2FIX(0))) return 1;
- if (rb_funcall(cmp, '<', 1, INT2FIX(0))) return -1;
- return 0;
-}
-
-static int
-sort_1(a, b)
- VALUE *a, *b;
-{
- VALUE retval = rb_yield(rb_assoc_new(*a, *b));
- return rb_cmpint(retval);
-}
-
-static int
-sort_2(a, b)
- VALUE *a, *b;
-{
- VALUE retval;
-
- if (FIXNUM_P(*a)) {
- if (FIXNUM_P(*b)) return *a - *b;
- }
- else if (TYPE(*a) == T_STRING && TYPE(*b) == T_STRING) {
- return rb_str_cmp(*a, *b);
- }
-
- retval = rb_funcall(*a, id_cmp, 1, *b);
- return rb_cmpint(retval);
-}
-
-static VALUE
-sort_internal(ary)
- VALUE ary;
-{
- qsort(RARRAY(ary)->ptr, RARRAY(ary)->len, sizeof(VALUE),
- rb_block_given_p()?sort_1:sort_2);
- return ary;
-}
-
-static VALUE
-sort_unlock(ary)
- VALUE ary;
-{
- FL_UNSET(ary, ARY_TMPLOCK);
- return ary;
-}
-
-VALUE
-rb_ary_sort_bang(ary)
- VALUE ary;
-{
- rb_ary_modify(ary);
- if (RARRAY(ary)->len <= 1) return ary;
-
- FL_SET(ary, ARY_TMPLOCK); /* prohibit modification during sort */
- rb_ensure(sort_internal, ary, sort_unlock, ary);
- return ary;
-}
-
-VALUE
-rb_ary_sort(ary)
- VALUE ary;
-{
- ary = ary_dup(ary);
- rb_ary_sort_bang(ary);
- return ary;
-}
-
-static VALUE
-rb_ary_collect(ary)
- VALUE ary;
-{
- long len, i;
- VALUE collect;
-
- if (!rb_block_given_p()) {
- return rb_ary_new4(RARRAY(ary)->len, RARRAY(ary)->ptr);
- }
-
- len = RARRAY(ary)->len;
- collect = rb_ary_new2(len);
- for (i=0; i<len; i++) {
- rb_ary_push(collect, rb_yield(RARRAY(ary)->ptr[i]));
- }
- return collect;
-}
-
-static VALUE
-rb_ary_collect_bang(ary)
- VALUE ary;
-{
- long i;
-
- rb_ary_modify(ary);
- for (i = 0; i < RARRAY(ary)->len; i++) {
- RARRAY(ary)->ptr[i] = rb_yield(RARRAY(ary)->ptr[i]);
- }
- return ary;
-}
-
-static VALUE
-rb_ary_select(argc, argv, ary)
- int argc;
- VALUE *argv;
- VALUE ary;
-{
- VALUE result = rb_ary_new();
- long i;
-
- if (rb_block_given_p()) {
- if (argc > 0) {
- rb_raise(rb_eArgError, "wrong number arguments(%d for 0)", argc);
- }
- for (i = 0; i < RARRAY(ary)->len; i++) {
- if (RTEST(rb_yield(RARRAY(ary)->ptr[i]))) {
- rb_ary_push(result, RARRAY(ary)->ptr[i]);
- }
- }
- }
- else {
- for (i=0; i<argc; i++) {
- rb_ary_push(result, rb_ary_entry(ary, NUM2LONG(argv[i])));
- }
- }
- return result;
-}
-
-VALUE
-rb_ary_delete(ary, item)
- VALUE ary;
- VALUE item;
-{
- long i1, i2;
-
- rb_ary_modify(ary);
- for (i1 = i2 = 0; i1 < RARRAY(ary)->len; i1++) {
- if (rb_equal(RARRAY(ary)->ptr[i1], item)) continue;
- if (i1 != i2) {
- RARRAY(ary)->ptr[i2] = RARRAY(ary)->ptr[i1];
- }
- i2++;
- }
- if (RARRAY(ary)->len == i2) {
- if (rb_block_given_p()) {
- return rb_yield(item);
- }
- return Qnil;
- }
- else {
- RARRAY(ary)->len = i2;
- }
-
- return item;
-}
-
-VALUE
-rb_ary_delete_at(ary, pos)
- VALUE ary;
- long pos;
-{
- long i, len = RARRAY(ary)->len;
- VALUE del = Qnil;
-
- rb_ary_modify(ary);
- if (pos >= len) return Qnil;
- if (pos < 0) pos += len;
- if (pos < 0) return Qnil;
-
- del = RARRAY(ary)->ptr[pos];
- for (i = pos + 1; i < len; i++, pos++) {
- RARRAY(ary)->ptr[pos] = RARRAY(ary)->ptr[i];
- }
- RARRAY(ary)->len = pos;
-
- return del;
-}
-
-static VALUE
-rb_ary_delete_at_m(ary, pos)
- VALUE ary, pos;
-{
- return rb_ary_delete_at(ary, NUM2LONG(pos));
-}
-
-static VALUE
-rb_ary_slice_bang(argc, argv, ary)
- int argc;
- VALUE *argv;
- VALUE ary;
-{
- VALUE arg1, arg2;
- long pos, len, i;
-
- rb_ary_modify(ary);
- if (rb_scan_args(argc, argv, "11", &arg1, &arg2) == 2) {
- pos = NUM2LONG(arg1);
- len = NUM2LONG(arg2);
- delete_pos_len:
- if (pos < 0) {
- pos = RARRAY(ary)->len + pos;
- }
- arg2 = rb_ary_subseq(ary, pos, len);
- rb_ary_update(ary, pos, len, Qnil); /* Qnil/rb_ary_new2(0) */
- return arg2;
- }
-
- if (!FIXNUM_P(arg1) && rb_range_beg_len(arg1, &pos, &len, RARRAY(ary)->len, 1)) {
- goto delete_pos_len;
- }
-
- pos = NUM2LONG(arg1);
- len = RARRAY(ary)->len;
-
- if (pos >= len) return Qnil;
- if (pos < 0) pos += len;
- if (pos < 0) return Qnil;
-
- arg2 = RARRAY(ary)->ptr[pos];
- for (i = pos + 1; i < len; i++, pos++) {
- RARRAY(ary)->ptr[pos] = RARRAY(ary)->ptr[i];
- }
- RARRAY(ary)->len = pos;
-
- return arg2;
-}
-
-static VALUE
-rb_ary_reject_bang(ary)
- VALUE ary;
-{
- long i1, i2;
-
- rb_ary_modify(ary);
- for (i1 = i2 = 0; i1 < RARRAY(ary)->len; i1++) {
- if (RTEST(rb_yield(RARRAY(ary)->ptr[i1]))) continue;
- if (i1 != i2) {
- RARRAY(ary)->ptr[i2] = RARRAY(ary)->ptr[i1];
- }
- i2++;
- }
- if (RARRAY(ary)->len == i2) return Qnil;
- RARRAY(ary)->len = i2;
-
- return ary;
-}
-
-static VALUE
-rb_ary_reject(ary)
- VALUE ary;
-{
- ary = ary_dup(ary);
- rb_ary_reject_bang(ary);
- return ary;
-}
-
-static VALUE
-rb_ary_delete_if(ary)
- VALUE ary;
-{
- rb_ary_reject_bang(ary);
- return ary;
-}
-
-static VALUE
-rb_ary_replace(ary, ary2)
- VALUE ary, ary2;
-{
- if (ary == ary2) return ary;
- ary2 = to_ary(ary2);
- rb_ary_update(ary, 0, RARRAY(ary)->len, ary2);
- return ary;
-}
-
-VALUE
-rb_ary_clear(ary)
- VALUE ary;
-{
- rb_ary_modify(ary);
- RARRAY(ary)->len = 0;
- if (ARY_DEFAULT_SIZE*3 < RARRAY(ary)->aux.capa) {
- RARRAY(ary)->aux.capa = ARY_DEFAULT_SIZE * 2;
- REALLOC_N(RARRAY(ary)->ptr, VALUE, RARRAY(ary)->aux.capa);
- }
- return ary;
-}
-
-static VALUE
-rb_ary_fill(argc, argv, ary)
- int argc;
- VALUE *argv;
- VALUE ary;
-{
- VALUE item, arg1, arg2;
- long beg, end, len;
- VALUE *p, *pend;
- int block_p = Qfalse;
-
- if (rb_block_given_p()) {
- block_p = Qtrue;
- rb_scan_args(argc, argv, "02", &arg1, &arg2);
- argc += 1; /* hackish */
- }
- else {
- rb_scan_args(argc, argv, "12", &item, &arg1, &arg2);
- }
- switch (argc) {
- case 1:
- beg = 0;
- len = RARRAY(ary)->len;
- break;
- case 2:
- if (rb_range_beg_len(arg1, &beg, &len, RARRAY(ary)->len, 1)) {
- break;
- }
- /* fall through */
- case 3:
- beg = NIL_P(arg1)?0:NUM2LONG(arg1);
- if (beg < 0) {
- beg = RARRAY(ary)->len + beg;
- if (beg < 0) beg = 0;
- }
- len = NIL_P(arg2)?RARRAY(ary)->len - beg:NUM2LONG(arg2);
- break;
- }
- rb_ary_modify(ary);
- end = beg + len;
- if (end > RARRAY(ary)->len) {
- if (end >= RARRAY(ary)->aux.capa) {
- RARRAY(ary)->aux.capa = end;
- REALLOC_N(RARRAY(ary)->ptr, VALUE, RARRAY(ary)->aux.capa);
- }
- if (beg > RARRAY(ary)->len) {
- rb_mem_clear(RARRAY(ary)->ptr+RARRAY(ary)->len,end-RARRAY(ary)->len);
- }
- RARRAY(ary)->len = end;
- }
- p = RARRAY(ary)->ptr + beg; pend = p + len;
-
- if (block_p) {
- while (p < pend) {
- *p++ = rb_yield(INT2NUM(beg));
- beg++;
- }
- }
- else {
- while (p < pend) {
- *p++ = item;
- }
- }
- return ary;
-}
-
-VALUE
-rb_ary_plus(x, y)
- VALUE x, y;
-{
- VALUE z;
-
- y = to_ary(y);
- z = rb_ary_new2(RARRAY(x)->len + RARRAY(y)->len);
- MEMCPY(RARRAY(z)->ptr, RARRAY(x)->ptr, VALUE, RARRAY(x)->len);
- MEMCPY(RARRAY(z)->ptr+RARRAY(x)->len, RARRAY(y)->ptr, VALUE, RARRAY(y)->len);
- RARRAY(z)->len = RARRAY(x)->len + RARRAY(y)->len;
- return z;
-}
-
-VALUE
-rb_ary_concat(x, y)
- VALUE x, y;
-{
- y = to_ary(y);
- if (RARRAY(y)->len > 0) {
- rb_ary_update(x, RARRAY(x)->len, 0, y);
- }
- return x;
-}
-
-static VALUE
-rb_ary_times(ary, times)
- VALUE ary;
- VALUE times;
-{
- VALUE ary2;
- long i, len;
-
- if (TYPE(times) == T_STRING) {
- return rb_ary_join(ary, times);
- }
-
- len = NUM2LONG(times);
- if (len < 0) {
- rb_raise(rb_eArgError, "negative argument");
- }
- len *= RARRAY(ary)->len;
-
- ary2 = ary_new(rb_obj_class(ary), len);
- RARRAY(ary2)->len = len;
-
- for (i=0; i<len; i+=RARRAY(ary)->len) {
- MEMCPY(RARRAY(ary2)->ptr+i, RARRAY(ary)->ptr, VALUE, RARRAY(ary)->len);
- }
- OBJ_INFECT(ary2, ary);
-
- return ary2;
-}
-
-VALUE
-rb_ary_assoc(ary, key)
- VALUE ary;
- VALUE key;
-{
- VALUE *p, *pend;
-
- p = RARRAY(ary)->ptr; pend = p + RARRAY(ary)->len;
- while (p < pend) {
- if (TYPE(*p) == T_ARRAY
- && RARRAY(*p)->len > 0
- && rb_equal(RARRAY(*p)->ptr[0], key))
- return *p;
- p++;
- }
- return Qnil;
-}
-
-VALUE
-rb_ary_rassoc(ary, value)
- VALUE ary;
- VALUE value;
-{
- VALUE *p, *pend;
-
- p = RARRAY(ary)->ptr; pend = p + RARRAY(ary)->len;
- while (p < pend) {
- if (TYPE(*p) == T_ARRAY
- && RARRAY(*p)->len > 1
- && rb_equal(RARRAY(*p)->ptr[1], value))
- return *p;
- p++;
- }
- return Qnil;
-}
-
-static VALUE
-rb_ary_equal(ary1, ary2)
- VALUE ary1, ary2;
-{
- long i;
-
- if (ary1 == ary2) return Qtrue;
- if (TYPE(ary2) != T_ARRAY) return Qfalse;
- if (RARRAY(ary1)->len != RARRAY(ary2)->len) return Qfalse;
- for (i=0; i<RARRAY(ary1)->len; i++) {
- if (!rb_equal(RARRAY(ary1)->ptr[i], RARRAY(ary2)->ptr[i]))
- return Qfalse;
- }
- return Qtrue;
-}
-
-static VALUE
-rb_ary_eql(ary1, ary2)
- VALUE ary1, ary2;
-{
- long i;
-
- if (TYPE(ary2) != T_ARRAY) return Qfalse;
- if (RARRAY(ary1)->len != RARRAY(ary2)->len) return Qfalse;
- for (i=0; i<RARRAY(ary1)->len; i++) {
- if (!rb_eql(RARRAY(ary1)->ptr[i], RARRAY(ary2)->ptr[i]))
- return Qfalse;
- }
- return Qtrue;
-}
-
-static VALUE
-rb_ary_hash(ary)
- VALUE ary;
-{
- long i;
- VALUE n;
- long h;
-
- h = RARRAY(ary)->len;
- for (i=0; i<RARRAY(ary)->len; i++) {
- h = (h<<1) | (h<0 ? 1 : 0);
- n = rb_hash(RARRAY(ary)->ptr[i]);
- h ^= NUM2LONG(n);
- }
- return INT2FIX(h);
-}
-
-VALUE
-rb_ary_includes(ary, item)
- VALUE ary;
- VALUE item;
-{
- long i;
- for (i=0; i<RARRAY(ary)->len; i++) {
- if (rb_equal(RARRAY(ary)->ptr[i], item)) {
- return Qtrue;
- }
- }
- return Qfalse;
-}
-
-VALUE
-rb_ary_cmp(ary, ary2)
- VALUE ary;
- VALUE ary2;
-{
- long i, len;
-
- if (TYPE(ary2) != T_ARRAY) {
- ary2 = to_ary(ary2);
- }
- len = RARRAY(ary)->len;
- if (len > RARRAY(ary2)->len) {
- len = RARRAY(ary2)->len;
- }
- for (i=0; i<len; i++) {
- VALUE v = rb_funcall(RARRAY(ary)->ptr[i],id_cmp,1,RARRAY(ary2)->ptr[i]);
- if (v != INT2FIX(0)) {
- return v;
- }
- }
- len = RARRAY(ary)->len - RARRAY(ary2)->len;
- if (len == 0) return INT2FIX(0);
- if (len > 0) return INT2FIX(1);
- return INT2FIX(-1);
-}
-
-static VALUE
-rb_ary_diff(ary1, ary2)
- VALUE ary1, ary2;
-{
- VALUE ary3;
- long i;
-
- ary2 = to_ary(ary2);
- ary3 = rb_ary_new();
- for (i=0; i<RARRAY(ary1)->len; i++) {
- if (rb_ary_includes(ary2, RARRAY(ary1)->ptr[i])) continue;
- if (rb_ary_includes(ary3, RARRAY(ary1)->ptr[i])) continue;
- rb_ary_push(ary3, RARRAY(ary1)->ptr[i]);
- }
- return ary3;
-}
-
-static VALUE
-ary_make_hash(ary1, ary2)
- VALUE ary1, ary2;
-{
- VALUE hash = rb_hash_new();
- int i;
-
- for (i=0; i<RARRAY(ary1)->len; i++) {
- rb_hash_aset(hash, RARRAY(ary1)->ptr[i], Qtrue);
- }
- if (ary2) {
- for (i=0; i<RARRAY(ary2)->len; i++) {
- rb_hash_aset(hash, RARRAY(ary2)->ptr[i], Qtrue);
- }
- }
- return hash;
-}
-
-static VALUE
-rb_ary_and(ary1, ary2)
- VALUE ary1, ary2;
-{
- VALUE hash;
- VALUE ary3 = rb_ary_new();
- long i;
-
- ary2 = to_ary(ary2);
- hash = ary_make_hash(ary2, 0);
-
- for (i=0; i<RARRAY(ary1)->len; i++) {
- VALUE v = RARRAY(ary1)->ptr[i];
- if (st_delete(RHASH(hash)->tbl, &v, 0)) {
- rb_ary_push(ary3, RARRAY(ary1)->ptr[i]);
- }
- }
-
- return ary3;
-}
-
-static VALUE
-rb_ary_or(ary1, ary2)
- VALUE ary1, ary2;
-{
- VALUE hash;
- VALUE ary3 = rb_ary_new();
- VALUE v;
- long i;
-
- ary2 = to_ary(ary2);
- hash = ary_make_hash(ary1, ary2);
-
- for (i=0; i<RARRAY(ary1)->len; i++) {
- v = RARRAY(ary1)->ptr[i];
- if (st_delete(RHASH(hash)->tbl, &v, 0)) {
- rb_ary_push(ary3, RARRAY(ary1)->ptr[i]);
- }
- }
- for (i=0; i<RARRAY(ary2)->len; i++) {
- v = RARRAY(ary2)->ptr[i];
- if (st_delete(RHASH(hash)->tbl, &v, 0)) {
- rb_ary_push(ary3, RARRAY(ary2)->ptr[i]);
- }
- }
-
- return ary3;
-}
-
-static VALUE
-rb_ary_uniq_bang(ary)
- VALUE ary;
-{
- VALUE hash = ary_make_hash(ary, 0);
- VALUE *p, *q, *end;
-
- if (RARRAY(ary)->len == RHASH(hash)->tbl->num_entries) {
- return Qnil;
- }
-
- rb_ary_modify(ary);
- p = q = RARRAY(ary)->ptr;
- end = p + RARRAY(ary)->len;
- while (p < end) {
- VALUE v = *p;
- if (st_delete(RHASH(hash)->tbl, &v, 0)) {
- *q++ = *p;
- }
- p++;
- }
- RARRAY(ary)->len = (q - RARRAY(ary)->ptr);
-
- return ary;
-}
-
-static VALUE
-rb_ary_uniq(ary)
- VALUE ary;
-{
- ary = ary_dup(ary);
- rb_ary_uniq_bang(ary);
- return ary;
-}
-
-static VALUE
-rb_ary_compact_bang(ary)
- VALUE ary;
-{
- VALUE *p, *t, *end;
-
- rb_ary_modify(ary);
- p = t = RARRAY(ary)->ptr;
- end = p + RARRAY(ary)->len;
- while (t < end) {
- if (NIL_P(*t)) t++;
- else *p++ = *t++;
- }
- if (RARRAY(ary)->len == (p - RARRAY(ary)->ptr)) {
- return Qnil;
- }
- RARRAY(ary)->len = RARRAY(ary)->aux.capa = (p - RARRAY(ary)->ptr);
- REALLOC_N(RARRAY(ary)->ptr, VALUE, RARRAY(ary)->len);
-
- return ary;
-}
-
-static VALUE
-rb_ary_compact(ary)
- VALUE ary;
-{
- ary = ary_dup(ary);
- rb_ary_compact_bang(ary);
- return ary;
-}
-
-static VALUE
-rb_ary_nitems(ary)
- VALUE ary;
-{
- long n = 0;
- VALUE *p, *pend;
-
- p = RARRAY(ary)->ptr;
- pend = p + RARRAY(ary)->len;
- while (p < pend) {
- if (!NIL_P(*p)) n++;
- p++;
- }
- return INT2NUM(n);
-}
-
-static int
-flatten(ary, idx, ary2, memo)
- VALUE ary;
- long idx;
- VALUE ary2, memo;
-{
- VALUE id;
- long i = idx;
- long n, lim = idx + RARRAY(ary2)->len;
-
- id = rb_obj_id(ary2);
- if (rb_ary_includes(memo, id)) {
- rb_raise(rb_eArgError, "tried to flatten recursive array");
- }
- rb_ary_push(memo, id);
- rb_ary_update(ary, idx, 1, ary2);
- while (i < lim) {
- if (TYPE(RARRAY(ary)->ptr[i]) == T_ARRAY) {
- n = flatten(ary, i, RARRAY(ary)->ptr[i], memo);
- i += n; lim += n;
- }
- i++;
- }
- rb_ary_pop(memo);
-
- return lim - idx - 1; /* returns number of increased items */
-}
-
-static VALUE
-rb_ary_flatten_bang(ary)
- VALUE ary;
-{
- long i = 0;
- int mod = 0;
- VALUE memo = Qnil;
-
- rb_ary_modify(ary);
- while (i<RARRAY(ary)->len) {
- VALUE ary2 = RARRAY(ary)->ptr[i];
-
- if (TYPE(ary2) == T_ARRAY) {
- if (NIL_P(memo)) {
- memo = rb_ary_new();
- }
- i += flatten(ary, i, ary2, memo);
- mod = 1;
- }
- i++;
- }
- if (mod == 0) return Qnil;
- return ary;
-}
-
-static VALUE
-rb_ary_flatten(ary)
- VALUE ary;
-{
- ary = ary_dup(ary);
- rb_ary_flatten_bang(ary);
- return ary;
-}
-
-void
-Init_Array()
-{
- rb_cArray = rb_define_class("Array", rb_cObject);
- rb_include_module(rb_cArray, rb_mEnumerable);
-
- rb_define_singleton_method(rb_cArray, "allocate", rb_ary_s_alloc, 0);
- rb_define_singleton_method(rb_cArray, "[]", rb_ary_s_create, -1);
- rb_define_method(rb_cArray, "initialize", rb_ary_initialize, -1);
- rb_define_method(rb_cArray, "to_s", rb_ary_to_s, 0);
- rb_define_method(rb_cArray, "inspect", rb_ary_inspect, 0);
- rb_define_method(rb_cArray, "to_a", rb_ary_to_a, 0);
- rb_define_method(rb_cArray, "to_ary", rb_ary_to_a, 0);
- rb_define_method(rb_cArray, "frozen?", rb_ary_frozen_p, 0);
-
- rb_define_method(rb_cArray, "==", rb_ary_equal, 1);
- rb_define_method(rb_cArray, "eql?", rb_ary_eql, 1);
- rb_define_method(rb_cArray, "hash", rb_ary_hash, 0);
- rb_define_method(rb_cArray, "===", rb_ary_equal, 1);
-
- rb_define_method(rb_cArray, "[]", rb_ary_aref, -1);
- rb_define_method(rb_cArray, "[]=", rb_ary_aset, -1);
- rb_define_method(rb_cArray, "at", rb_ary_at, 1);
- rb_define_method(rb_cArray, "fetch", rb_ary_fetch, -1);
- rb_define_method(rb_cArray, "first", rb_ary_first, 0);
- rb_define_method(rb_cArray, "last", rb_ary_last, 0);
- rb_define_method(rb_cArray, "concat", rb_ary_concat, 1);
- rb_define_method(rb_cArray, "<<", rb_ary_push, 1);
- rb_define_method(rb_cArray, "push", rb_ary_push_m, -1);
- rb_define_method(rb_cArray, "pop", rb_ary_pop, 0);
- rb_define_method(rb_cArray, "shift", rb_ary_shift, 0);
- rb_define_method(rb_cArray, "unshift", rb_ary_unshift_m, -1);
- rb_define_method(rb_cArray, "insert", rb_ary_insert, -1);
- rb_define_method(rb_cArray, "each", rb_ary_each, 0);
- rb_define_method(rb_cArray, "each_index", rb_ary_each_index, 0);
- rb_define_method(rb_cArray, "reverse_each", rb_ary_reverse_each, 0);
- rb_define_method(rb_cArray, "length", rb_ary_length, 0);
- rb_define_alias(rb_cArray, "size", "length");
- rb_define_method(rb_cArray, "empty?", rb_ary_empty_p, 0);
- rb_define_method(rb_cArray, "index", rb_ary_index, 1);
- rb_define_method(rb_cArray, "rindex", rb_ary_rindex, 1);
- rb_define_method(rb_cArray, "indexes", rb_ary_indexes, -1);
- rb_define_method(rb_cArray, "indices", rb_ary_indexes, -1);
- rb_define_method(rb_cArray, "clone", rb_ary_clone, 0);
- rb_define_method(rb_cArray, "dup", rb_ary_dup, 0);
- rb_define_method(rb_cArray, "join", rb_ary_join_m, -1);
- rb_define_method(rb_cArray, "reverse", rb_ary_reverse_m, 0);
- rb_define_method(rb_cArray, "reverse!", rb_ary_reverse_bang, 0);
- rb_define_method(rb_cArray, "sort", rb_ary_sort, 0);
- rb_define_method(rb_cArray, "sort!", rb_ary_sort_bang, 0);
- rb_define_method(rb_cArray, "collect", rb_ary_collect, 0);
- rb_define_method(rb_cArray, "collect!", rb_ary_collect_bang, 0);
- rb_define_method(rb_cArray, "select", rb_ary_select, -1);
- rb_define_method(rb_cArray, "map", rb_ary_collect, 0);
- rb_define_method(rb_cArray, "map!", rb_ary_collect_bang, 0);
- rb_define_method(rb_cArray, "delete", rb_ary_delete, 1);
- rb_define_method(rb_cArray, "delete_at", rb_ary_delete_at_m, 1);
- rb_define_method(rb_cArray, "delete_if", rb_ary_delete_if, 0);
- rb_define_method(rb_cArray, "reject", rb_ary_reject, 0);
- rb_define_method(rb_cArray, "reject!", rb_ary_reject_bang, 0);
- rb_define_method(rb_cArray, "replace", rb_ary_replace, 1);
- rb_define_method(rb_cArray, "clear", rb_ary_clear, 0);
- rb_define_method(rb_cArray, "fill", rb_ary_fill, -1);
- rb_define_method(rb_cArray, "include?", rb_ary_includes, 1);
- rb_define_method(rb_cArray, "<=>", rb_ary_cmp, 1);
-
- rb_define_method(rb_cArray, "slice", rb_ary_aref, -1);
- rb_define_method(rb_cArray, "slice!", rb_ary_slice_bang, -1);
-
- rb_define_method(rb_cArray, "assoc", rb_ary_assoc, 1);
- rb_define_method(rb_cArray, "rassoc", rb_ary_rassoc, 1);
-
- rb_define_method(rb_cArray, "+", rb_ary_plus, 1);
- rb_define_method(rb_cArray, "*", rb_ary_times, 1);
-
- rb_define_method(rb_cArray, "-", rb_ary_diff, 1);
- rb_define_method(rb_cArray, "&", rb_ary_and, 1);
- rb_define_method(rb_cArray, "|", rb_ary_or, 1);
-
- rb_define_method(rb_cArray, "uniq", rb_ary_uniq, 0);
- rb_define_method(rb_cArray, "uniq!", rb_ary_uniq_bang, 0);
- rb_define_method(rb_cArray, "compact", rb_ary_compact, 0);
- rb_define_method(rb_cArray, "compact!", rb_ary_compact_bang, 0);
- rb_define_method(rb_cArray, "flatten", rb_ary_flatten, 0);
- rb_define_method(rb_cArray, "flatten!", rb_ary_flatten_bang, 0);
- rb_define_method(rb_cArray, "nitems", rb_ary_nitems, 0);
-
- id_cmp = rb_intern("<=>");
-}
diff --git a/bignum.c b/bignum.c
deleted file mode 100644
index e090f9b0dc..0000000000
--- a/bignum.c
+++ /dev/null
@@ -1,1760 +0,0 @@
-/**********************************************************************
-
- bignum.c -
-
- $Author$
- $Date$
- created at: Fri Jun 10 00:48:55 JST 1994
-
- Copyright (C) 1993-2002 Yukihiro Matsumoto
-
-**********************************************************************/
-
-#include <math.h>
-#include <ctype.h>
-#include "ruby.h"
-
-VALUE rb_cBignum;
-
-#if defined __MINGW32__
-#define USHORT _USHORT
-#endif
-
-#if SIZEOF_INT*2 <= SIZEOF_LONG_LONG
-typedef unsigned int BDIGIT;
-typedef unsigned LONG_LONG BDIGIT_DBL;
-typedef LONG_LONG BDIGIT_DBL_SIGNED;
-#elif SIZEOF_INT*2 <= SIZEOF_LONG
-typedef unsigned int BDIGIT;
-typedef unsigned long BDIGIT_DBL;
-typedef LONG_LONG BDIGIT_DBL_SIGNED;
-#else
-typedef unsigned short BDIGIT;
-typedef unsigned long BDIGIT_DBL;
-typedef long BDIGIT_DBL_SIGNED;
-#endif
-
-#define BDIGITS(x) ((BDIGIT*)RBIGNUM(x)->digits)
-#define BITSPERDIG (sizeof(BDIGIT)*CHAR_BIT)
-#define BIGRAD ((BDIGIT_DBL)1 << BITSPERDIG)
-#define DIGSPERLONG ((unsigned int)(sizeof(long)/sizeof(BDIGIT)))
-#if HAVE_LONG_LONG
-# define DIGSPERLL ((unsigned int)(sizeof(LONG_LONG)/sizeof(BDIGIT)))
-#endif
-#define BIGUP(x) ((BDIGIT_DBL)(x) << BITSPERDIG)
-#define BIGDN(x) RSHIFT(x,BITSPERDIG)
-#define BIGLO(x) ((BDIGIT)((x) & (BIGRAD-1)))
-
-static VALUE
-bignew_1(klass, len, sign)
- VALUE klass;
- long len;
- char sign;
-{
- NEWOBJ(big, struct RBignum);
- OBJSETUP(big, klass, T_BIGNUM);
- big->sign = sign;
- big->len = len;
- big->digits = ALLOC_N(BDIGIT, len);
-
- return (VALUE)big;
-}
-
-#define bignew(len,sign) bignew_1(rb_cBignum,len,sign)
-
-VALUE
-rb_big_clone(x)
- VALUE x;
-{
- VALUE z = bignew_1(CLASS_OF(x), RBIGNUM(x)->len, RBIGNUM(x)->sign);
-
- MEMCPY(BDIGITS(z), BDIGITS(x), BDIGIT, RBIGNUM(x)->len);
- return z;
-}
-
-static void
-get2comp(x, carry) /* get 2's complement */
- VALUE x;
- int carry;
-{
- long i = RBIGNUM(x)->len;
- BDIGIT *ds = BDIGITS(x);
- BDIGIT_DBL num;
-
- while (i--) ds[i] = ~ds[i];
- i = 0; num = 1;
- do {
- num += ds[i];
- ds[i++] = BIGLO(num);
- num = BIGDN(num);
- } while (i < RBIGNUM(x)->len);
- if (!carry) return;
- if (ds[0] == 1 || ds[0] == 0) {
- if (RBIGNUM(x)->len == 1) return;
- for (i=1; i<RBIGNUM(x)->len; i++) {
- if (ds[i] != 0) return;
- }
- REALLOC_N(RBIGNUM(x)->digits, BDIGIT, RBIGNUM(x)->len++);
- ds = BDIGITS(x);
- ds[RBIGNUM(x)->len-1] = 1;
- }
-}
-
-void
-rb_big_2comp(x) /* get 2's complement */
- VALUE x;
-{
- get2comp(x, Qtrue);
-}
-
-static VALUE
-bignorm(x)
- VALUE x;
-{
- if (!FIXNUM_P(x)) {
- long len = RBIGNUM(x)->len;
- BDIGIT *ds = BDIGITS(x);
-
- while (len-- && !ds[len]) ;
- RBIGNUM(x)->len = ++len;
-
- if (len*sizeof(BDIGIT) <= sizeof(VALUE)) {
- long num = 0;
- while (len--) {
- num = BIGUP(num) + ds[len];
- }
- if (num >= 0) {
- if (RBIGNUM(x)->sign) {
- if (POSFIXABLE(num)) return INT2FIX(num);
- }
- else if (NEGFIXABLE(-(long)num)) return INT2FIX(-(long)num);
- }
- }
- }
- return x;
-}
-
-VALUE
-rb_big_norm(x)
- VALUE x;
-{
- return bignorm(x);
-}
-
-VALUE
-rb_uint2big(n)
- unsigned long n;
-{
- BDIGIT_DBL num = n;
- long i = 0;
- BDIGIT *digits;
- VALUE big;
-
- i = 0;
- big = bignew(DIGSPERLONG, 1);
- digits = BDIGITS(big);
- while (i < DIGSPERLONG) {
- digits[i++] = BIGLO(num);
- num = BIGDN(num);
- }
-
- i = DIGSPERLONG;
- while (i-- && !digits[i]) ;
- RBIGNUM(big)->len = i+1;
- return big;
-}
-
-VALUE
-rb_int2big(n)
- long n;
-{
- long neg = 0;
- VALUE big;
-
- if (n < 0) {
- n = -n;
- neg = 1;
- }
- big = rb_uint2big(n);
- if (neg) {
- RBIGNUM(big)->sign = 0;
- }
- return big;
-}
-
-VALUE
-rb_uint2inum(n)
- unsigned long n;
-{
- if (POSFIXABLE(n)) return INT2FIX(n);
- return rb_uint2big(n);
-}
-
-VALUE
-rb_int2inum(n)
- long n;
-{
- if (FIXABLE(n)) return INT2FIX(n);
- return rb_int2big(n);
-}
-
-#ifdef HAVE_LONG_LONG
-
-#define DIGSPERLONGLONG ((unsigned int)(sizeof(LONG_LONG)/sizeof(BDIGIT)))
-
-void
-rb_quad_pack(buf, val)
- char *buf;
- VALUE val;
-{
- LONG_LONG q;
-
- val = rb_to_int(val);
- if (FIXNUM_P(val)) {
- q = FIX2LONG(val);
- }
- else {
- long len = RBIGNUM(val)->len;
- BDIGIT *ds;
-
- ds = BDIGITS(val);
- q = 0;
- while (len--) {
- q = BIGUP(q);
- q += ds[len];
- }
- }
- memcpy(buf, (char*)&q, sizeof(LONG_LONG));
-}
-
-VALUE
-rb_quad_unpack(buf, sign)
- const char *buf;
- int sign;
-{
- unsigned LONG_LONG q;
- long neg = 0;
- long i = 0;
- BDIGIT *digits;
- VALUE big;
-
- memcpy(&q, buf, sizeof(LONG_LONG));
- if (sign) {
- if (FIXABLE((LONG_LONG)q)) return INT2FIX((LONG_LONG)q);
- if ((LONG_LONG)q < 0) {
- q = -(LONG_LONG)q;
- neg = 1;
- }
- }
- else {
- if (POSFIXABLE(q)) return INT2FIX(q);
- }
-
- i = 0;
- big = bignew(DIGSPERLONGLONG, 1);
- digits = BDIGITS(big);
- while (i < DIGSPERLONGLONG) {
- digits[i++] = BIGLO(q);
- q = BIGDN(q);
- }
-
- i = DIGSPERLONGLONG;
- while (i-- && !digits[i]) ;
- RBIGNUM(big)->len = i+1;
-
- if (neg) {
- RBIGNUM(big)->sign = 0;
- }
- return bignorm(big);
-}
-
-#else
-
-#define QUAD_SIZE 8
-
-void
-rb_quad_pack(buf, val)
- char *buf;
- VALUE val;
-{
- long len;
-
- memset(buf, 0, QUAD_SIZE);
- val = rb_to_int(val);
- if (FIXNUM_P(val)) {
- val = rb_int2big(FIX2LONG(val));
- }
- len = RBIGNUM(val)->len * sizeof(BDIGIT);
- if (len > QUAD_SIZE) len = QUAD_SIZE;
- memcpy(buf, (char*)BDIGITS(val), len);
- if (!RBIGNUM(val)->sign) {
- len = QUAD_SIZE;
- while (len--) {
- *buf = ~*buf++;
- }
- }
-}
-
-#define BNEG(b) (RSHIFT(((BDIGIT*)b)[QUAD_SIZE/sizeof(BDIGIT)-1],BITSPERDIG-1) != 0)
-
-VALUE
-rb_quad_unpack(buf, sign)
- const char *buf;
- int sign;
-{
- VALUE big = bignew(QUAD_SIZE/sizeof(BDIGIT), 1);
-
- memcpy((char*)BDIGITS(big), buf, QUAD_SIZE);
- if (sign && BNEG(buf)) {
- long len = QUAD_SIZE;
- char *tmp = (char*)BDIGITS(big);
-
- RBIGNUM(big)->sign = 0;
- while (len--) {
- *tmp = ~*tmp++;
- }
- }
-
- return bignorm(big);
-}
-
-#endif
-
-VALUE
-rb_cstr_to_inum(str, base, badcheck)
- const char *str;
- int base;
- int badcheck;
-{
- const char *s = str;
- char *end;
- char sign = 1, c, nondigit = 0;
- BDIGIT_DBL num;
- long len, blen = 1;
- long i;
- VALUE z;
- BDIGIT *zds;
-
- if (badcheck) {
- while (ISSPACE(*str)) str++;
- }
- else {
- while (ISSPACE(*str) || *str == '_') str++;
- }
-
- if (str[0] == '+') {
- str++;
- }
- else if (str[0] == '-') {
- str++;
- sign = 0;
- }
- if (str[0] == '+' || str[0] == '-') {
- if (badcheck) goto bad;
- return INT2FIX(0);
- }
- if (base <= 0) {
- if (str[0] == '0') {
- if (str[1] == 'x' || str[1] == 'X') {
- base = 16;
- }
- else if (str[1] == 'b' || str[1] == 'B') {
- base = 2;
- }
- else {
- base = 8;
- }
- }
- else if (base < -1) {
- base = -base;
- }
- else {
- base = 10;
- }
- }
- if (base == 8) {
- len = 3;
- }
- else { /* base == 10, 2 or 16 */
- if (base == 16 && str[0] == '0' && (str[1] == 'x'||str[1] == 'X')) {
- str += 2;
- }
- else if (base == 2 && str[0] == '0' && (str[1] == 'b'||str[1] == 'B')) {
- str += 2;
- }
- len = 4;
- }
- if (*str == '0') { /* squeeze preceeding 0s */
- while (*++str == '0');
- --str;
- }
- len *= strlen(str)*sizeof(char);
-
- if (len <= (sizeof(VALUE)*CHAR_BIT)) {
- unsigned long val = strtoul((char*)str, &end, base);
-
- if (*end == '_') goto bigparse;
- if (badcheck) {
- if (end == str) goto bad; /* no number */
- while (*end && ISSPACE(*end)) end++;
- if (*end) { /* trailing garbage */
- bad:
- rb_invalid_str(s, "Integer");
- }
- }
-
- if (POSFIXABLE(val)) {
- if (sign) return INT2FIX(val);
- else {
- long result = -(long)val;
- return INT2FIX(result);
- }
- }
- else {
- VALUE big = rb_uint2big(val);
- RBIGNUM(big)->sign = sign;
- return big;
- }
- }
- bigparse:
- len = (len/BITSPERDIG)+1;
- if (badcheck && *str == '_') goto bad;
-
- z = bignew(len, sign);
- zds = BDIGITS(z);
- for (i=len;i--;) zds[i]=0;
- while (c = *str++) {
- switch (c) {
- case '8': case '9':
- if (base == 8) {
- c = base;
- break;
- }
- case '0': case '1': case '2': case '3': case '4':
- case '5': case '6': case '7':
- c = c - '0';
- nondigit = 0;
- break;
- case 'a': case 'b': case 'c':
- case 'd': case 'e': case 'f':
- c -= 'a' - 'A';
- case 'A': case 'B': case 'C':
- case 'D': case 'E': case 'F':
- if (base != 16) {
- nondigit = c;
- c = base;
- }
- else {
- c = c - 'A' + 10;
- nondigit = 0;
- }
- break;
- case '_':
- if (badcheck) {
- if (nondigit) goto bad;
- nondigit = c;
- }
- continue;
- default:
- c = base;
- break;
- }
- if (c >= base) break;
- i = 0;
- num = c;
- for (;;) {
- while (i<blen) {
- num += (BDIGIT_DBL)zds[i]*base;
- zds[i++] = BIGLO(num);
- num = BIGDN(num);
- }
- if (num) {
- blen++;
- continue;
- }
- break;
- }
- }
- if (badcheck) {
- str--;
- if (s+1 < str && str[-1] == '_') goto bad;
- while (*str && ISSPACE(*str)) str++;
- if (*str) goto bad;
- }
-
- return bignorm(z);
-}
-
-VALUE
-rb_str_to_inum(str, base, badcheck)
- VALUE str;
- int base;
- int badcheck;
-{
- char *s;
- int len;
-
- StringValue(str);
- s = RSTRING(str)->ptr;
- len = RSTRING(str)->len;
- if (s[len]) { /* no sentinel somehow */
- char *p = ALLOCA_N(char, len+1);
-
- MEMCPY(p, s, char, len);
- p[len] = '\0';
- s = p;
- }
- if (badcheck && len != strlen(s)) {
- rb_raise(rb_eArgError, "string for Integer contains null byte");
- }
- return rb_cstr_to_inum(s, base, badcheck);
-}
-
-#if HAVE_LONG_LONG
-
-VALUE
-rb_ull2big(n)
- unsigned LONG_LONG n;
-{
- BDIGIT_DBL num = n;
- long i = 0;
- BDIGIT *digits;
- VALUE big;
-
- i = 0;
- big = bignew(DIGSPERLL, 1);
- digits = BDIGITS(big);
- while (i < DIGSPERLL) {
- digits[i++] = BIGLO(num);
- num = BIGDN(num);
- }
-
- i = DIGSPERLL;
- while (i-- && !digits[i]) ;
- RBIGNUM(big)->len = i+1;
- return big;
-}
-
-VALUE
-rb_ll2big(n)
- LONG_LONG n;
-{
- long neg = 0;
- VALUE big;
-
- if (n < 0) {
- n = -n;
- neg = 1;
- }
- big = rb_ull2big(n);
- if (neg) {
- RBIGNUM(big)->sign = 0;
- }
- return big;
-}
-
-VALUE
-rb_ull2inum(n)
- unsigned LONG_LONG n;
-{
- if (POSFIXABLE(n)) return INT2FIX(n);
- return rb_ull2big(n);
-}
-
-VALUE
-rb_ll2inum(n)
- LONG_LONG n;
-{
- if (FIXABLE(n)) return INT2FIX(n);
- return rb_ll2big(n);
-}
-
-#endif /* HAVE_LONG_LONG */
-
-VALUE
-rb_cstr2inum(str, base)
- const char *str;
- int base;
-{
- return rb_cstr_to_inum(str, base, base==0);
-}
-
-VALUE
-rb_str2inum(str, base)
- VALUE str;
- int base;
-{
- return rb_str_to_inum(str, base, base==0);
-}
-
-static char hexmap[] = "0123456789abcdef";
-VALUE
-rb_big2str(x, base)
- VALUE x;
- int base;
-{
- volatile VALUE t;
- BDIGIT *ds;
- long i, j, hbase;
- VALUE ss;
- char *s, c;
-
- if (FIXNUM_P(x)) {
- return rb_fix2str(x, base);
- }
- i = RBIGNUM(x)->len;
- if (i == 0) return rb_str_new2("0");
- if (base == 10) {
- j = (sizeof(BDIGIT)/sizeof(char)*CHAR_BIT*i*241L)/800+2;
- hbase = 10000;
- }
- else if (base == 16) {
- j = (sizeof(BDIGIT)/sizeof(char)*CHAR_BIT*i)/4+2;
- hbase = 0x10000;
- }
- else if (base == 8) {
- j = (sizeof(BDIGIT)/sizeof(char)*CHAR_BIT*i)+2;
- hbase = 010000;
- }
- else if (base == 2) {
- j = (sizeof(BDIGIT)*CHAR_BIT*i)+2;
- hbase = 020;
- }
- else {
- rb_raise(rb_eArgError, "illegal radix %d", base);
- }
-
- t = rb_big_clone(x);
- ds = BDIGITS(t);
- ss = rb_str_new(0, j);
- s = RSTRING(ss)->ptr;
-
- s[0] = RBIGNUM(x)->sign ? '+' : '-';
- while (i && j) {
- long k = i;
- BDIGIT_DBL num = 0;
-
- while (k--) {
- num = BIGUP(num) + ds[k];
- ds[k] = (BDIGIT)(num / hbase);
- num %= hbase;
- }
- if (ds[i-1] == 0) i--;
- k = 4;
- while (k--) {
- c = (char)(num % base);
- s[--j] = hexmap[(int)c];
- num /= base;
- if (i == 0 && num == 0) break;
- }
- }
- while (s[j] == '0') j++;
- RSTRING(ss)->len -= RBIGNUM(x)->sign?j:j-1;
- memmove(RBIGNUM(x)->sign?s:s+1, s+j, RSTRING(ss)->len);
- s[RSTRING(ss)->len] = '\0';
-
- return ss;
-}
-
-static VALUE
-rb_big_to_s(argc, argv, x)
- int argc;
- VALUE *argv;
- VALUE x;
-{
- VALUE b;
- int base;
-
- rb_scan_args(argc, argv, "01", &b);
- if (argc == 0) base = 10;
- else base = NUM2INT(b);
- return rb_big2str(x, base);
-}
-
-static unsigned long
-big2ulong(x, type)
- VALUE x;
- char *type;
-{
- long len = RBIGNUM(x)->len;
- BDIGIT_DBL num;
- BDIGIT *ds;
-
- if (len > sizeof(long)/sizeof(BDIGIT))
- rb_raise(rb_eRangeError, "bignum too big to convert into `%s'", type);
- ds = BDIGITS(x);
- num = 0;
- while (len--) {
- num = BIGUP(num);
- num += ds[len];
- }
- return num;
-}
-
-unsigned long
-rb_big2ulong(x)
- VALUE x;
-{
- unsigned long num = big2ulong(x, "unsigned long");
-
- if (!RBIGNUM(x)->sign) return -num;
- return num;
-}
-
-long
-rb_big2long(x)
- VALUE x;
-{
- unsigned long num = big2ulong(x, "int");
-
- if ((long)num < 0 && (RBIGNUM(x)->sign || (long)num != LONG_MIN)) {
- rb_raise(rb_eRangeError, "bignum too big to convert into `int'");
- }
- if (!RBIGNUM(x)->sign) return -(long)num;
- return num;
-}
-
-#if HAVE_LONG_LONG
-
-static unsigned LONG_LONG
-big2ull(x, type)
- VALUE x;
- char *type;
-{
- long len = RBIGNUM(x)->len;
- BDIGIT_DBL num;
- BDIGIT *ds;
-
- if (len > sizeof(LONG_LONG)/sizeof(BDIGIT))
- rb_raise(rb_eRangeError, "bignum too big to convert into `%s'", type);
- ds = BDIGITS(x);
- num = 0;
- while (len--) {
- num = BIGUP(num);
- num += ds[len];
- }
- return num;
-}
-
-unsigned LONG_LONG
-rb_big2ull(x)
- VALUE x;
-{
- unsigned LONG_LONG num = big2ull(x, "unsigned long long");
-
- if (!RBIGNUM(x)->sign) return -num;
- return num;
-}
-
-LONG_LONG
-rb_big2ll(x)
- VALUE x;
-{
- unsigned LONG_LONG num = big2ull(x, "long long");
-
- if ((LONG_LONG)num < 0 && (RBIGNUM(x)->sign
- || (LONG_LONG)num != LLONG_MIN)) {
- rb_raise(rb_eRangeError, "bignum too big to convert into `long long'");
- }
- if (!RBIGNUM(x)->sign) return -(LONG_LONG)num;
- return num;
-}
-
-#endif /* HAVE_LONG_LONG */
-
-static VALUE
-dbl2big(d)
- double d;
-{
- long i = 0;
- BDIGIT c;
- BDIGIT *digits;
- VALUE z;
- double u = (d < 0)?-d:d;
-
- if (isinf(d)) {
- rb_raise(rb_eFloatDomainError, d < 0 ? "-Infinity" : "Infinity");
- }
- if (isnan(d)) {
- rb_raise(rb_eFloatDomainError, "NaN");
- }
-
- while (!POSFIXABLE(u) || 0 != (long)u) {
- u /= (double)(BIGRAD);
- i++;
- }
- z = bignew(i, d>=0);
- digits = BDIGITS(z);
- while (i--) {
- u *= BIGRAD;
- c = (BDIGIT)u;
- u -= c;
- digits[i] = c;
- }
-
- return z;
-}
-
-VALUE
-rb_dbl2big(d)
- double d;
-{
- return bignorm(dbl2big(d));
-}
-
-double
-rb_big2dbl(x)
- VALUE x;
-{
- double d = 0.0;
- long i = RBIGNUM(x)->len;
- BDIGIT *ds = BDIGITS(x);
-
- while (i--) {
- d = ds[i] + BIGRAD*d;
- }
- if (!RBIGNUM(x)->sign) d = -d;
- return d;
-}
-
-static VALUE
-rb_big_to_f(x)
- VALUE x;
-{
- return rb_float_new(rb_big2dbl(x));
-}
-
-static VALUE
-rb_big_cmp(x, y)
- VALUE x, y;
-{
- long xlen = RBIGNUM(x)->len;
-
- switch (TYPE(y)) {
- case T_FIXNUM:
- y = rb_int2big(FIX2LONG(y));
- break;
-
- case T_BIGNUM:
- break;
-
- case T_FLOAT:
- {
- double d = rb_big2dbl(x);
-
- if (d == RFLOAT(y)->value) return INT2FIX(0);
- if (d > RFLOAT(y)->value) return INT2FIX(1);
- if (d < RFLOAT(y)->value) return INT2FIX(-1);
- }
- break;
-
- default:
- return rb_num_coerce_bin(x, y);
- }
-
- if (RBIGNUM(x)->sign > RBIGNUM(y)->sign) return INT2FIX(1);
- if (RBIGNUM(x)->sign < RBIGNUM(y)->sign) return INT2FIX(-1);
- if (xlen < RBIGNUM(y)->len)
- return (RBIGNUM(x)->sign) ? INT2FIX(-1) : INT2FIX(1);
- if (xlen > RBIGNUM(y)->len)
- return (RBIGNUM(x)->sign) ? INT2FIX(1) : INT2FIX(-1);
-
- while(xlen-- && (BDIGITS(x)[xlen]==BDIGITS(y)[xlen]));
- if (-1 == xlen) return INT2FIX(0);
- return (BDIGITS(x)[xlen] > BDIGITS(y)[xlen]) ?
- (RBIGNUM(x)->sign ? INT2FIX(1) : INT2FIX(-1)) :
- (RBIGNUM(x)->sign ? INT2FIX(-1) : INT2FIX(1));
-}
-
-static VALUE
-rb_big_eq(x, y)
- VALUE x, y;
-{
- switch (TYPE(y)) {
- case T_FIXNUM:
- y = rb_int2big(FIX2LONG(y));
- break;
- case T_BIGNUM:
- break;
- case T_FLOAT:
- return (rb_big2dbl(x) == RFLOAT(y)->value)?Qtrue:Qfalse;
- default:
- return Qfalse;
- }
- if (RBIGNUM(x)->sign != RBIGNUM(y)->sign) return Qfalse;
- if (RBIGNUM(x)->len != RBIGNUM(y)->len) return Qfalse;
- if (MEMCMP(BDIGITS(x),BDIGITS(y),BDIGIT,RBIGNUM(y)->len) != 0) return Qfalse;
- return Qtrue;
-}
-
-static VALUE
-rb_big_eql(x, y)
- VALUE x, y;
-{
- if (TYPE(y) != T_BIGNUM) return Qfalse;
- if (RBIGNUM(x)->sign != RBIGNUM(y)->sign) return Qfalse;
- if (RBIGNUM(x)->len != RBIGNUM(y)->len) return Qfalse;
- if (MEMCMP(BDIGITS(x),BDIGITS(y),BDIGIT,RBIGNUM(y)->len) != 0) return Qfalse;
- return Qtrue;
-}
-
-static VALUE
-rb_big_uminus(x)
- VALUE x;
-{
- VALUE z = rb_big_clone(x);
-
- RBIGNUM(z)->sign = !RBIGNUM(x)->sign;
-
- return bignorm(z);
-}
-
-static VALUE
-rb_big_neg(x)
- VALUE x;
-{
- VALUE z = rb_big_clone(x);
- long i = RBIGNUM(x)->len;
- BDIGIT *ds = BDIGITS(z);
-
- if (!RBIGNUM(x)->sign) get2comp(z, Qtrue);
- while (i--) ds[i] = ~ds[i];
- if (RBIGNUM(x)->sign) get2comp(z, Qfalse);
- RBIGNUM(z)->sign = !RBIGNUM(z)->sign;
-
- return bignorm(z);
-}
-
-static VALUE
-bigsub(x, y)
- VALUE x, y;
-{
- VALUE z = 0;
- BDIGIT *zds;
- BDIGIT_DBL_SIGNED num;
- long i;
-
- i = RBIGNUM(x)->len;
- /* if x is larger than y, swap */
- if (RBIGNUM(x)->len < RBIGNUM(y)->len) {
- z = x; x = y; y = z; /* swap x y */
- }
- else if (RBIGNUM(x)->len == RBIGNUM(y)->len) {
- while (i > 0) {
- i--;
- if (BDIGITS(x)[i] > BDIGITS(y)[i]) {
- break;
- }
- if (BDIGITS(x)[i] < BDIGITS(y)[i]) {
- z = x; x = y; y = z; /* swap x y */
- break;
- }
- }
- }
-
- z = bignew(RBIGNUM(x)->len, (z == 0)?1:0);
- zds = BDIGITS(z);
-
- for (i = 0, num = 0; i < RBIGNUM(y)->len; i++) {
- num += (BDIGIT_DBL_SIGNED)BDIGITS(x)[i] - BDIGITS(y)[i];
- zds[i] = BIGLO(num);
- num = BIGDN(num);
- }
- while (num && i < RBIGNUM(x)->len) {
- num += BDIGITS(x)[i];
- zds[i++] = BIGLO(num);
- num = BIGDN(num);
- }
- while (i < RBIGNUM(x)->len) {
- zds[i] = BDIGITS(x)[i];
- i++;
- }
-
- return z;
-}
-
-static VALUE
-bigadd(x, y, sign)
- VALUE x, y;
- char sign;
-{
- VALUE z;
- BDIGIT_DBL num;
- long i, len;
-
- sign = (sign == RBIGNUM(y)->sign);
- if (RBIGNUM(x)->sign != sign) {
- if (sign) return bigsub(y, x);
- return bigsub(x, y);
- }
-
- if (RBIGNUM(x)->len > RBIGNUM(y)->len) {
- len = RBIGNUM(x)->len + 1;
- z = x; x = y; y = z;
- }
- else {
- len = RBIGNUM(y)->len + 1;
- }
- z = bignew(len, sign);
-
- len = RBIGNUM(x)->len;
- for (i = 0, num = 0; i < len; i++) {
- num += (BDIGIT_DBL)BDIGITS(x)[i] + BDIGITS(y)[i];
- BDIGITS(z)[i] = BIGLO(num);
- num = BIGDN(num);
- }
- len = RBIGNUM(y)->len;
- while (num && i < len) {
- num += BDIGITS(y)[i];
- BDIGITS(z)[i++] = BIGLO(num);
- num = BIGDN(num);
- }
- while (i < len) {
- BDIGITS(z)[i] = BDIGITS(y)[i];
- i++;
- }
- BDIGITS(z)[i] = (BDIGIT)num;
-
- return z;
-}
-
-VALUE
-rb_big_plus(x, y)
- VALUE x, y;
-{
- switch (TYPE(y)) {
- case T_FIXNUM:
- y = rb_int2big(FIX2LONG(y));
- /* fall through */
- case T_BIGNUM:
- return bignorm(bigadd(x, y, 1));
-
- case T_FLOAT:
- return rb_float_new(rb_big2dbl(x) + RFLOAT(y)->value);
-
- default:
- return rb_num_coerce_bin(x, y);
- }
-}
-
-VALUE
-rb_big_minus(x, y)
- VALUE x, y;
-{
- switch (TYPE(y)) {
- case T_FIXNUM:
- y = rb_int2big(FIX2LONG(y));
- /* fall through */
- case T_BIGNUM:
- return bignorm(bigadd(x, y, 0));
-
- case T_FLOAT:
- return rb_float_new(rb_big2dbl(x) - RFLOAT(y)->value);
-
- default:
- return rb_num_coerce_bin(x, y);
- }
-}
-
-VALUE
-rb_big_mul(x, y)
- VALUE x, y;
-{
- long i, j;
- BDIGIT_DBL n = 0;
- VALUE z;
- BDIGIT *zds;
-
- if (FIXNUM_P(x)) x = rb_int2big(FIX2LONG(x));
- switch (TYPE(y)) {
- case T_FIXNUM:
- y = rb_int2big(FIX2LONG(y));
- break;
-
- case T_BIGNUM:
- break;
-
- case T_FLOAT:
- return rb_float_new(rb_big2dbl(x) * RFLOAT(y)->value);
-
- default:
- return rb_num_coerce_bin(x, y);
- }
-
- j = RBIGNUM(x)->len + RBIGNUM(y)->len + 1;
- z = bignew(j, RBIGNUM(x)->sign==RBIGNUM(y)->sign);
- zds = BDIGITS(z);
- while (j--) zds[j] = 0;
- for (i = 0; i < RBIGNUM(x)->len; i++) {
- BDIGIT_DBL dd = BDIGITS(x)[i];
- if (dd == 0) continue;
- n = 0;
- for (j = 0; j < RBIGNUM(y)->len; j++) {
- BDIGIT_DBL ee = n + (BDIGIT_DBL)dd * BDIGITS(y)[j];
- n = zds[i + j] + ee;
- if (ee) zds[i + j] = BIGLO(n);
- n = BIGDN(n);
- }
- if (n) {
- zds[i + j] = n;
- }
- }
-
- return bignorm(z);
-}
-
-static void
-bigdivrem(x, y, divp, modp)
- VALUE x, y;
- VALUE *divp, *modp;
-{
- long nx = RBIGNUM(x)->len, ny = RBIGNUM(y)->len;
- long i, j;
- VALUE yy, z;
- BDIGIT *xds, *yds, *zds, *tds;
- BDIGIT_DBL t2;
- BDIGIT_DBL_SIGNED num;
- BDIGIT dd, q;
-
- yds = BDIGITS(y);
- if (ny == 0 && yds[0] == 0) rb_num_zerodiv();
- if (nx < ny || nx == ny && BDIGITS(x)[nx - 1] < BDIGITS(y)[ny - 1]) {
- if (divp) *divp = rb_int2big(0);
- if (modp) *modp = x;
- return;
- }
- xds = BDIGITS(x);
- if (ny == 1) {
- dd = yds[0];
- z = rb_big_clone(x);
- zds = BDIGITS(z);
- t2 = 0; i = nx;
- while (i--) {
- t2 = BIGUP(t2) + zds[i];
- zds[i] = (BDIGIT)(t2 / dd);
- t2 %= dd;
- }
- RBIGNUM(z)->sign = RBIGNUM(x)->sign==RBIGNUM(y)->sign;
- if (modp) {
- *modp = rb_uint2big((unsigned long)t2);
- RBIGNUM(*modp)->sign = RBIGNUM(x)->sign;
- }
- if (divp) *divp = z;
- return;
- }
- z = bignew(nx==ny?nx+2:nx+1, RBIGNUM(x)->sign==RBIGNUM(y)->sign);
- zds = BDIGITS(z);
- if (nx==ny) zds[nx+1] = 0;
- while (!yds[ny-1]) ny--;
-
- dd = 0;
- q = yds[ny-1];
- while ((q & (1<<(BITSPERDIG-1))) == 0) {
- q <<= 1;
- dd++;
- }
- if (dd) {
- yy = rb_big_clone(y);
- tds = BDIGITS(yy);
- j = 0;
- t2 = 0;
- while (j<ny) {
- t2 += (BDIGIT_DBL)yds[j]<<dd;
- tds[j++] = BIGLO(t2);
- t2 = BIGDN(t2);
- }
- yds = tds;
- j = 0;
- t2 = 0;
- while (j<nx) {
- t2 += (BDIGIT_DBL)xds[j]<<dd;
- zds[j++] = BIGLO(t2);
- t2 = BIGDN(t2);
- }
- zds[j] = (BDIGIT)t2;
- }
- else {
- zds[nx] = 0;
- j = nx;
- while (j--) zds[j] = xds[j];
- }
-
- j = nx==ny?nx+1:nx;
- do {
- if (zds[j] == yds[ny-1]) q = BIGRAD-1;
- else q = (BDIGIT)((BIGUP(zds[j]) + zds[j-1])/yds[ny-1]);
- if (q) {
- i = 0; num = 0; t2 = 0;
- do { /* multiply and subtract */
- BDIGIT_DBL ee;
- t2 += (BDIGIT_DBL)yds[i] * q;
- ee = num - BIGLO(t2);
- num = (BDIGIT_DBL)zds[j - ny + i] + ee;
- if (ee) zds[j - ny + i] = BIGLO(num);
- num = BIGDN(num);
- t2 = BIGDN(t2);
- } while (++i < ny);
- num += zds[j - ny + i] - t2;/* borrow from high digit; don't update */
- while (num) { /* "add back" required */
- i = 0; num = 0; q--;
- do {
- BDIGIT_DBL ee = num + yds[i];
- num = (BDIGIT_DBL)zds[j - ny + i] + ee;
- if (ee) zds[j - ny + i] = BIGLO(num);
- num = BIGDN(num);
- } while (++i < ny);
- num--;
- }
- }
- zds[j] = q;
- } while (--j >= ny);
- if (divp) { /* move quotient down in z */
- *divp = rb_big_clone(z);
- zds = BDIGITS(*divp);
- j = (nx==ny ? nx+2 : nx+1) - ny;
- for (i = 0;i < j;i++) zds[i] = zds[i+ny];
- RBIGNUM(*divp)->len = i;
- }
- if (modp) { /* just normalize remainder */
- *modp = rb_big_clone(z);
- zds = BDIGITS(*modp);
- while (ny-- && !zds[ny]); ++ny;
- if (dd) {
- t2 = 0; i = ny;
- while(i--) {
- t2 = (t2 | zds[i]) >> dd;
- q = zds[i];
- zds[i] = BIGLO(t2);
- t2 = BIGUP(q);
- }
- }
- RBIGNUM(*modp)->len = ny;
- RBIGNUM(*modp)->sign = RBIGNUM(x)->sign;
- }
-}
-
-static void
-bigdivmod(x, y, divp, modp)
- VALUE x, y;
- VALUE *divp, *modp;
-{
- VALUE mod;
-
- bigdivrem(x, y, divp, &mod);
- if (RBIGNUM(x)->sign != RBIGNUM(y)->sign && RBIGNUM(mod)->len > 0) {
- if (divp) *divp = bigadd(*divp, rb_int2big(1), 0);
- if (modp) *modp = bigadd(mod, y, 1);
- }
- else {
- if (divp) *divp = *divp;
- if (modp) *modp = mod;
- }
-}
-
-static VALUE
-rb_big_div(x, y)
- VALUE x, y;
-{
- VALUE z;
-
- switch (TYPE(y)) {
- case T_FIXNUM:
- y = rb_int2big(FIX2LONG(y));
- break;
-
- case T_BIGNUM:
- break;
-
- case T_FLOAT:
- return rb_float_new(rb_big2dbl(x) / RFLOAT(y)->value);
-
- default:
- return rb_num_coerce_bin(x, y);
- }
- bigdivmod(x, y, &z, 0);
-
- return bignorm(z);
-}
-
-
-static VALUE
-rb_big_modulo(x, y)
- VALUE x, y;
-{
- VALUE z;
-
- switch (TYPE(y)) {
- case T_FIXNUM:
- y = rb_int2big(FIX2LONG(y));
- break;
-
- case T_BIGNUM:
- break;
-
- default:
- return rb_num_coerce_bin(x, y);
- }
- bigdivmod(x, y, 0, &z);
-
- return bignorm(z);
-}
-
-static VALUE
-rb_big_remainder(x, y)
- VALUE x, y;
-{
- VALUE z;
-
- switch (TYPE(y)) {
- case T_FIXNUM:
- y = rb_int2big(FIX2LONG(y));
- break;
-
- case T_BIGNUM:
- break;
-
- default:
- return rb_num_coerce_bin(x, y);
- }
- bigdivrem(x, y, 0, &z);
-
- return bignorm(z);
-}
-
-VALUE
-rb_big_divmod(x, y)
- VALUE x, y;
-{
- VALUE div, mod;
-
- switch (TYPE(y)) {
- case T_FIXNUM:
- y = rb_int2big(FIX2LONG(y));
- break;
-
- case T_BIGNUM:
- break;
-
- default:
- return rb_num_coerce_bin(x, y);
- }
- bigdivmod(x, y, &div, &mod);
-
- return rb_assoc_new(bignorm(div), bignorm(mod));
-}
-
-VALUE
-rb_big_pow(x, y)
- VALUE x, y;
-{
- double d;
- long yy;
-
- if (y == INT2FIX(0)) return INT2FIX(1);
- switch (TYPE(y)) {
- case T_FLOAT:
- d = RFLOAT(y)->value;
- break;
-
- case T_BIGNUM:
- rb_warn("in a**b, b may be too big");
- d = rb_big2dbl(y);
- break;
-
- case T_FIXNUM:
- yy = NUM2LONG(y);
- if (yy > 0) {
- VALUE z;
-
- z = x;
- for (;;) {
- yy = yy - 1;
- if (yy == 0) break;
- while (yy % 2 == 0) {
- yy = yy / 2;
- x = rb_big_mul(x, x);
- }
- z = rb_big_mul(z, x);
- }
- if (!FIXNUM_P(z)) z = bignorm(z);
- return z;
- }
- d = (double)yy;
- break;
-
- default:
- return rb_num_coerce_bin(x, y);
- }
- return rb_float_new(pow(rb_big2dbl(x), d));
-}
-
-VALUE
-rb_big_and(x, y)
- VALUE x, y;
-{
- VALUE z;
- BDIGIT *ds1, *ds2, *zds;
- long i, l1, l2;
- char sign;
-
- if (FIXNUM_P(y)) {
- y = rb_int2big(FIX2LONG(y));
- }
- else {
- Check_Type(y, T_BIGNUM);
- }
-
- if (!RBIGNUM(y)->sign) {
- y = rb_big_clone(y);
- get2comp(y, Qtrue);
- }
- if (!RBIGNUM(x)->sign) {
- x = rb_big_clone(x);
- get2comp(x, Qtrue);
- }
- if (RBIGNUM(x)->len > RBIGNUM(y)->len) {
- l1 = RBIGNUM(y)->len;
- l2 = RBIGNUM(x)->len;
- ds1 = BDIGITS(y);
- ds2 = BDIGITS(x);
- sign = RBIGNUM(y)->sign;
- }
- else {
- l1 = RBIGNUM(x)->len;
- l2 = RBIGNUM(y)->len;
- ds1 = BDIGITS(x);
- ds2 = BDIGITS(y);
- sign = RBIGNUM(x)->sign;
- }
- z = bignew(l2, RBIGNUM(x)->sign || RBIGNUM(y)->sign);
- zds = BDIGITS(z);
-
- for (i=0; i<l1; i++) {
- zds[i] = ds1[i] & ds2[i];
- }
- for (; i<l2; i++) {
- zds[i] = sign?0:ds2[i];
- }
- if (!RBIGNUM(z)->sign) get2comp(z, Qfalse);
- return bignorm(z);
-}
-
-VALUE
-rb_big_or(x, y)
- VALUE x, y;
-{
- VALUE z;
- BDIGIT *ds1, *ds2, *zds;
- long i, l1, l2;
- char sign;
-
- if (FIXNUM_P(y)) {
- y = rb_int2big(FIX2LONG(y));
- }
- else {
- Check_Type(y, T_BIGNUM);
- }
-
- if (!RBIGNUM(y)->sign) {
- y = rb_big_clone(y);
- get2comp(y, Qtrue);
- }
- if (!RBIGNUM(x)->sign) {
- x = rb_big_clone(x);
- get2comp(x, Qtrue);
- }
- if (RBIGNUM(x)->len > RBIGNUM(y)->len) {
- l1 = RBIGNUM(y)->len;
- l2 = RBIGNUM(x)->len;
- ds1 = BDIGITS(y);
- ds2 = BDIGITS(x);
- sign = RBIGNUM(y)->sign;
- }
- else {
- l1 = RBIGNUM(x)->len;
- l2 = RBIGNUM(y)->len;
- ds1 = BDIGITS(x);
- ds2 = BDIGITS(y);
- sign = RBIGNUM(x)->sign;
- }
- z = bignew(l2, RBIGNUM(x)->sign && RBIGNUM(y)->sign);
- zds = BDIGITS(z);
-
- for (i=0; i<l1; i++) {
- zds[i] = ds1[i] | ds2[i];
- }
- for (; i<l2; i++) {
- zds[i] = sign?ds2[i]:(BIGRAD-1);
- }
- if (!RBIGNUM(z)->sign) get2comp(z, Qfalse);
-
- return bignorm(z);
-}
-
-VALUE
-rb_big_xor(x, y)
- VALUE x, y;
-{
- VALUE z;
- BDIGIT *ds1, *ds2, *zds;
- long i, l1, l2;
- char sign;
-
- if (FIXNUM_P(y)) {
- y = rb_int2big(FIX2LONG(y));
- }
- else {
- Check_Type(y, T_BIGNUM);
- }
-
- if (!RBIGNUM(y)->sign) {
- y = rb_big_clone(y);
- get2comp(y, Qtrue);
- }
- if (!RBIGNUM(x)->sign) {
- x = rb_big_clone(x);
- get2comp(x, Qtrue);
- }
- if (RBIGNUM(x)->len > RBIGNUM(y)->len) {
- l1 = RBIGNUM(y)->len;
- l2 = RBIGNUM(x)->len;
- ds1 = BDIGITS(y);
- ds2 = BDIGITS(x);
- sign = RBIGNUM(y)->sign;
- }
- else {
- l1 = RBIGNUM(x)->len;
- l2 = RBIGNUM(y)->len;
- ds1 = BDIGITS(x);
- ds2 = BDIGITS(y);
- sign = RBIGNUM(x)->sign;
- }
- RBIGNUM(x)->sign = RBIGNUM(x)->sign?1:0;
- RBIGNUM(y)->sign = RBIGNUM(y)->sign?1:0;
- z = bignew(l2, !(RBIGNUM(x)->sign ^ RBIGNUM(y)->sign));
- zds = BDIGITS(z);
-
- for (i=0; i<l1; i++) {
- zds[i] = ds1[i] ^ ds2[i];
- }
- for (; i<l2; i++) {
- zds[i] = sign?ds2[i]:~ds2[i];
- }
- if (!RBIGNUM(z)->sign) get2comp(z, Qfalse);
-
- return bignorm(z);
-}
-
-static VALUE rb_big_rshift _((VALUE,VALUE));
-
-VALUE
-rb_big_lshift(x, y)
- VALUE x, y;
-{
- BDIGIT *xds, *zds;
- int shift = NUM2INT(y);
- int s1 = shift/BITSPERDIG;
- int s2 = shift%BITSPERDIG;
- VALUE z;
- BDIGIT_DBL num = 0;
- long len, i;
-
- if (shift < 0) return rb_big_rshift(x, INT2FIX(-shift));
- len = RBIGNUM(x)->len;
- z = bignew(len+s1+1, RBIGNUM(x)->sign);
- zds = BDIGITS(z);
- for (i=0; i<s1; i++) {
- *zds++ = 0;
- }
- xds = BDIGITS(x);
- for (i=0; i<len; i++) {
- num = num | (BDIGIT_DBL)*xds++<<s2;
- *zds++ = BIGLO(num);
- num = BIGDN(num);
- }
- *zds = BIGLO(num);
- return bignorm(z);
-}
-
-static VALUE
-rb_big_rshift(x, y)
- VALUE x, y;
-{
- BDIGIT *xds, *zds;
- int shift = NUM2INT(y);
- int s1 = shift/BITSPERDIG;
- int s2 = shift%BITSPERDIG;
- VALUE z;
- BDIGIT_DBL num = 0;
- long i = RBIGNUM(x)->len;
- long j;
-
- if (shift < 0) return rb_big_lshift(x, INT2FIX(-shift));
-
- if (s1 > RBIGNUM(x)->len) {
- if (RBIGNUM(x)->sign)
- return INT2FIX(0);
- else
- return INT2FIX(-1);
- }
- if (!RBIGNUM(x)->sign) {
- x = rb_big_clone(x);
- get2comp(x, Qtrue);
- }
- xds = BDIGITS(x);
- i = RBIGNUM(x)->len; j = i - s1;
- z = bignew(j, RBIGNUM(x)->sign);
- zds = BDIGITS(z);
- while (i--, j--) {
- num = (num | xds[i]) >> s2;
- zds[j] = BIGLO(num);
- num = BIGUP(xds[i]);
- }
- if (!RBIGNUM(x)->sign) {
- get2comp(z, Qfalse);
- }
- return bignorm(z);
-}
-
-static VALUE
-rb_big_aref(x, y)
- VALUE x, y;
-{
- BDIGIT *xds;
- int shift;
- int s1, s2;
-
- if (TYPE(y) == T_BIGNUM) {
- if (!RBIGNUM(y)->sign || RBIGNUM(x)->sign)
- return INT2FIX(0);
- return INT2FIX(1);
- }
- shift = NUM2INT(y);
- if (shift < 0) return INT2FIX(0);
- s1 = shift/BITSPERDIG;
- s2 = shift%BITSPERDIG;
-
- if (!RBIGNUM(x)->sign) {
- if (s1 >= RBIGNUM(x)->len) return INT2FIX(1);
- x = rb_big_clone(x);
- get2comp(x, Qtrue);
- }
- else {
- if (s1 >= RBIGNUM(x)->len) return INT2FIX(0);
- }
- xds = BDIGITS(x);
- if (xds[s1] & (1<<s2))
- return INT2FIX(1);
- return INT2FIX(0);
-}
-
-static VALUE
-rb_big_hash(x)
- VALUE x;
-{
- long i, len, key;
- BDIGIT *digits;
-
- key = 0; digits = BDIGITS(x); len = RBIGNUM(x)->len;
- for (i=0; i<len; i++) {
- key ^= *digits++;
- }
- return INT2FIX(key);
-}
-
-static VALUE
-rb_big_coerce(x, y)
- VALUE x, y;
-{
- if (FIXNUM_P(y)) {
- return rb_assoc_new(rb_int2big(FIX2LONG(y)), x);
- }
- else {
- rb_raise(rb_eTypeError, "Can't coerce %s to Bignum",
- rb_class2name(CLASS_OF(y)));
- }
- /* not reached */
- return Qnil;
-}
-
-static VALUE
-rb_big_abs(x)
- VALUE x;
-{
- if (!RBIGNUM(x)->sign) {
- x = rb_big_clone(x);
- RBIGNUM(x)->sign = 1;
- }
- return x;
-}
-
-/* !!!warnig!!!!
- this is not really a random number!!
-*/
-
-VALUE
-rb_big_rand(max, rand)
- VALUE max;
- double rand;
-{
- VALUE v;
- long len;
-
- len = RBIGNUM(max)->len;
- v = bignew(len,1);
- while (len--) {
- BDIGITS(v)[len] = ((BDIGIT)~0) * rand;
- }
-
- return rb_big_modulo((VALUE)v, max);
-}
-
-static VALUE
-rb_big_size(big)
- VALUE big;
-{
- return INT2FIX(RBIGNUM(big)->len*sizeof(BDIGIT));
-}
-
-static VALUE
-rb_big_zero_p(big)
- VALUE big;
-{
- return Qfalse;
-}
-
-void
-Init_Bignum()
-{
- rb_cBignum = rb_define_class("Bignum", rb_cInteger);
-
- rb_define_method(rb_cBignum, "to_s", rb_big_to_s, -1);
- rb_define_method(rb_cBignum, "coerce", rb_big_coerce, 1);
- rb_define_method(rb_cBignum, "-@", rb_big_uminus, 0);
- rb_define_method(rb_cBignum, "+", rb_big_plus, 1);
- rb_define_method(rb_cBignum, "-", rb_big_minus, 1);
- rb_define_method(rb_cBignum, "*", rb_big_mul, 1);
- rb_define_method(rb_cBignum, "/", rb_big_div, 1);
- rb_define_method(rb_cBignum, "%", rb_big_modulo, 1);
- rb_define_method(rb_cBignum, "divmod", rb_big_divmod, 1);
- rb_define_method(rb_cBignum, "modulo", rb_big_modulo, 1);
- rb_define_method(rb_cBignum, "remainder", rb_big_remainder, 1);
- rb_define_method(rb_cBignum, "**", rb_big_pow, 1);
- rb_define_method(rb_cBignum, "&", rb_big_and, 1);
- rb_define_method(rb_cBignum, "|", rb_big_or, 1);
- rb_define_method(rb_cBignum, "^", rb_big_xor, 1);
- rb_define_method(rb_cBignum, "~", rb_big_neg, 0);
- rb_define_method(rb_cBignum, "<<", rb_big_lshift, 1);
- rb_define_method(rb_cBignum, ">>", rb_big_rshift, 1);
- rb_define_method(rb_cBignum, "[]", rb_big_aref, 1);
-
- rb_define_method(rb_cBignum, "<=>", rb_big_cmp, 1);
- rb_define_method(rb_cBignum, "==", rb_big_eq, 1);
- rb_define_method(rb_cBignum, "===", rb_big_eq, 1);
- rb_define_method(rb_cBignum, "eql?", rb_big_eql, 1);
- rb_define_method(rb_cBignum, "hash", rb_big_hash, 0);
- rb_define_method(rb_cBignum, "to_f", rb_big_to_f, 0);
- rb_define_method(rb_cBignum, "abs", rb_big_abs, 0);
- rb_define_method(rb_cBignum, "size", rb_big_size, 0);
- rb_define_method(rb_cBignum, "zero?", rb_big_zero_p, 0);
-}
diff --git a/class.c b/class.c
deleted file mode 100644
index 26b2ba7f28..0000000000
--- a/class.c
+++ /dev/null
@@ -1,859 +0,0 @@
-/**********************************************************************
-
- class.c -
-
- $Author$
- $Date$
- created at: Tue Aug 10 15:05:44 JST 1993
-
- Copyright (C) 1993-2002 Yukihiro Matsumoto
-
-**********************************************************************/
-
-#include "ruby.h"
-#include "rubysig.h"
-#include "node.h"
-#include "st.h"
-#include <ctype.h>
-
-extern st_table *rb_class_tbl;
-
-VALUE
-rb_class_boot(super)
- VALUE super;
-{
- NEWOBJ(klass, struct RClass);
- OBJSETUP(klass, rb_cClass, T_CLASS);
-
- klass->super = super;
- klass->iv_tbl = 0;
- klass->m_tbl = 0; /* safe GC */
- klass->m_tbl = st_init_numtable();
-
- OBJ_INFECT(klass, super);
- return (VALUE)klass;
-}
-
-VALUE
-rb_class_new(super)
- VALUE super;
-{
- Check_Type(super, T_CLASS);
- if (super == rb_cClass) {
- rb_raise(rb_eTypeError, "can't make subclass of Class");
- }
- if (FL_TEST(super, FL_SINGLETON)) {
- rb_raise(rb_eTypeError, "can't make subclass of virtual class");
- }
- return rb_class_boot(super);
-}
-
-static int
-clone_method(mid, body, tbl)
- ID mid;
- NODE *body;
- st_table *tbl;
-{
- st_insert(tbl, mid, NEW_METHOD(body->nd_body, body->nd_noex));
- return ST_CONTINUE;
-}
-
-VALUE
-rb_mod_clone(module)
- VALUE module;
-{
- NEWOBJ(clone, struct RClass);
- CLONESETUP(clone, module);
-
- RCLASS(clone)->super = RCLASS(module)->super;
- if (RCLASS(module)->iv_tbl) {
- ID id;
-
- RCLASS(clone)->iv_tbl = st_copy(RCLASS(module)->iv_tbl);
- id = rb_intern("__classpath__");
- st_delete(RCLASS(clone)->iv_tbl, &id, 0);
- id = rb_intern("__classid__");
- st_delete(RCLASS(clone)->iv_tbl, &id, 0);
- }
- if (RCLASS(module)->m_tbl) {
- RCLASS(clone)->m_tbl = st_init_numtable();
- st_foreach(RCLASS(module)->m_tbl, clone_method, RCLASS(clone)->m_tbl);
- }
-
- return (VALUE)clone;
-}
-
-VALUE
-rb_mod_dup(mod)
- VALUE mod;
-{
- VALUE dup = rb_mod_clone(mod);
-
- DUPSETUP(dup, mod);
- if (FL_TEST(mod, FL_SINGLETON)) {
- FL_SET(dup, FL_SINGLETON);
- }
- return dup;
-}
-
-VALUE
-rb_singleton_class_new(super)
- VALUE super;
-{
- VALUE klass = rb_class_boot(super);
-
- FL_SET(klass, FL_SINGLETON);
- return klass;
-}
-
-VALUE
-rb_singleton_class_clone(klass)
- VALUE klass;
-{
- if (!FL_TEST(klass, FL_SINGLETON))
- return klass;
- else {
- /* copy singleton(unnamed) class */
- NEWOBJ(clone, struct RClass);
- CLONESETUP(clone, klass);
-
- clone->super = RCLASS(klass)->super;
- clone->iv_tbl = 0;
- clone->m_tbl = 0;
- if (RCLASS(klass)->iv_tbl) {
- clone->iv_tbl = st_copy(RCLASS(klass)->iv_tbl);
- }
- clone->m_tbl = st_init_numtable();
- st_foreach(RCLASS(klass)->m_tbl, clone_method, clone->m_tbl);
- FL_SET(clone, FL_SINGLETON);
- return (VALUE)clone;
- }
-}
-
-void
-rb_singleton_class_attached(klass, obj)
- VALUE klass, obj;
-{
- if (FL_TEST(klass, FL_SINGLETON)) {
- if (!RCLASS(klass)->iv_tbl) {
- RCLASS(klass)->iv_tbl = st_init_numtable();
- }
- st_insert(RCLASS(klass)->iv_tbl, rb_intern("__attached__"), obj);
- }
-}
-
-VALUE
-rb_make_metaclass(obj, klass)
- VALUE obj, klass;
-{
- klass = rb_singleton_class_new(klass);
- RBASIC(obj)->klass = klass;
- rb_singleton_class_attached(klass, obj);
- return klass;
-}
-
-VALUE
-rb_define_class_id(id, super)
- ID id;
- VALUE super;
-{
- VALUE klass;
-
- if (!super) super = rb_cObject;
- klass = rb_class_new(super);
- rb_name_class(klass, id);
- rb_make_metaclass(klass, RBASIC(super)->klass);
-
- return klass;
-}
-
-VALUE
-rb_class_inherited(super, klass)
- VALUE super, klass;
-{
- if (!super) super = rb_cObject;
- return rb_funcall(super, rb_intern("inherited"), 1, klass);
-}
-
-VALUE
-rb_define_class(name, super)
- const char *name;
- VALUE super;
-{
- VALUE klass;
- ID id;
-
- id = rb_intern(name);
- if (rb_autoload_defined(id)) {
- rb_autoload_load(id);
- }
- if (rb_const_defined(rb_cObject, id)) {
- klass = rb_const_get(rb_cObject, id);
- if (TYPE(klass) != T_CLASS) {
- rb_raise(rb_eTypeError, "%s is not a class", name);
- }
- if (rb_class_real(RCLASS(klass)->super) != super) {
- rb_name_error(id, "%s is already defined", name);
- }
- return klass;
- }
- if (!super) {
- rb_warn("no super class for `%s', Object assumed", name);
- }
- klass = rb_define_class_id(id, super);
- rb_class_inherited(super, klass);
- st_add_direct(rb_class_tbl, id, klass);
-
- return klass;
-}
-
-VALUE
-rb_define_class_under(outer, name, super)
- VALUE outer;
- const char *name;
- VALUE super;
-{
- VALUE klass;
- ID id;
-
- id = rb_intern(name);
- if (rb_const_defined_at(outer, id)) {
- klass = rb_const_get(outer, id);
- if (TYPE(klass) != T_CLASS) {
- rb_raise(rb_eTypeError, "%s is not a class", name);
- }
- if (rb_class_real(RCLASS(klass)->super) != super) {
- rb_name_error(id, "%s is already defined", name);
- }
- return klass;
- }
- if (!super) {
- rb_warn("no super class for `%s::%s', Object assumed",
- rb_class2name(outer), name);
- }
- klass = rb_define_class_id(id, super);
- rb_set_class_path(klass, outer, name);
- rb_class_inherited(super, klass);
- rb_const_set(outer, id, klass);
-
- return klass;
-}
-
-VALUE
-rb_module_new()
-{
- NEWOBJ(mdl, struct RClass);
- OBJSETUP(mdl, rb_cModule, T_MODULE);
-
- mdl->super = 0;
- mdl->iv_tbl = 0;
- mdl->m_tbl = 0;
- mdl->m_tbl = st_init_numtable();
-
- return (VALUE)mdl;
-}
-
-VALUE
-rb_define_module_id(id)
- ID id;
-{
- VALUE mdl;
-
- mdl = rb_module_new();
- rb_name_class(mdl, id);
-
- return mdl;
-}
-
-VALUE
-rb_define_module(name)
- const char *name;
-{
- VALUE module;
- ID id;
-
- id = rb_intern(name);
- if (rb_autoload_defined(id)) {
- rb_autoload_load(id);
- }
- if (rb_const_defined(rb_cObject, id)) {
- module = rb_const_get(rb_cObject, id);
- if (TYPE(module) == T_MODULE)
- return module;
- rb_raise(rb_eTypeError, "%s is not a module", rb_class2name(CLASS_OF(module)));
- }
- module = rb_define_module_id(id);
- st_add_direct(rb_class_tbl, id, module);
-
- return module;
-}
-
-VALUE
-rb_define_module_under(outer, name)
- VALUE outer;
- const char *name;
-{
- VALUE module;
- ID id;
-
- id = rb_intern(name);
- if (rb_const_defined_at(outer, id)) {
- module = rb_const_get(outer, id);
- if (TYPE(module) == T_MODULE)
- return module;
- rb_raise(rb_eTypeError, "%s::%s is not a module",
- rb_class2name(outer), rb_class2name(CLASS_OF(module)));
- }
- module = rb_define_module_id(id);
- rb_const_set(outer, id, module);
- rb_set_class_path(module, outer, name);
-
- return module;
-}
-
-static VALUE
-include_class_new(module, super)
- VALUE module, super;
-{
- NEWOBJ(klass, struct RClass);
- OBJSETUP(klass, rb_cClass, T_ICLASS);
-
- if (!RCLASS(module)->iv_tbl) {
- RCLASS(module)->iv_tbl = st_init_numtable();
- }
- klass->iv_tbl = RCLASS(module)->iv_tbl;
- klass->m_tbl = RCLASS(module)->m_tbl;
- klass->super = super;
- if (TYPE(module) == T_ICLASS) {
- RBASIC(klass)->klass = RBASIC(module)->klass;
- }
- else {
- RBASIC(klass)->klass = module;
- }
- OBJ_INFECT(klass, module);
- OBJ_INFECT(klass, super);
-
- return (VALUE)klass;
-}
-
-void
-rb_include_module(klass, module)
- VALUE klass, module;
-{
- VALUE p, c;
- int changed = 0;
-
- rb_frozen_class_p(klass);
- if (!OBJ_TAINTED(klass)) {
- rb_secure(4);
- }
-
- if (NIL_P(module)) return;
- if (klass == module) return;
-
- switch (TYPE(module)) {
- case T_MODULE:
- case T_CLASS:
- case T_ICLASS:
- break;
- default:
- Check_Type(module, T_MODULE);
- }
-
- OBJ_INFECT(klass, module);
- c = klass;
- while (module) {
- if (RCLASS(klass)->m_tbl == RCLASS(module)->m_tbl)
- rb_raise(rb_eArgError, "cyclic include detected");
- /* ignore if the module included already in superclasses */
- for (p = RCLASS(klass)->super; p; p = RCLASS(p)->super) {
- if (BUILTIN_TYPE(p) == T_ICLASS) {
- if (RCLASS(p)->m_tbl == RCLASS(module)->m_tbl) {
- c = p; /* move insertion point */
- goto skip;
- }
- }
- }
- RCLASS(c)->super = include_class_new(module, RCLASS(c)->super);
- c = RCLASS(c)->super;
- changed = 1;
- skip:
- module = RCLASS(module)->super;
- }
- if (changed) rb_clear_cache();
-}
-
-VALUE
-rb_mod_included_modules(mod)
- VALUE mod;
-{
- VALUE ary = rb_ary_new();
- VALUE p;
-
- for (p = RCLASS(mod)->super; p; p = RCLASS(p)->super) {
- if (BUILTIN_TYPE(p) == T_ICLASS) {
- rb_ary_push(ary, RBASIC(p)->klass);
- }
- }
- return ary;
-}
-
-VALUE
-rb_mod_include_p(mod, mod2)
- VALUE mod;
- VALUE mod2;
-{
- VALUE p;
-
- Check_Type(mod2, T_MODULE);
- for (p = RCLASS(mod)->super; p; p = RCLASS(p)->super) {
- if (BUILTIN_TYPE(p) == T_ICLASS) {
- if (RBASIC(p)->klass == mod2) return Qtrue;
- }
- }
- return Qfalse;
-}
-
-VALUE
-rb_mod_ancestors(mod)
- VALUE mod;
-{
- VALUE ary = rb_ary_new();
- VALUE p;
-
- for (p = mod; p; p = RCLASS(p)->super) {
- if (FL_TEST(p, FL_SINGLETON))
- continue;
- if (BUILTIN_TYPE(p) == T_ICLASS) {
- rb_ary_push(ary, RBASIC(p)->klass);
- }
- else {
- rb_ary_push(ary, p);
- }
- }
- return ary;
-}
-
-static int
-ins_methods_i(key, body, ary)
- ID key;
- NODE *body;
- VALUE ary;
-{
- if ((body->nd_noex&(NOEX_PRIVATE|NOEX_PROTECTED)) == 0) {
- VALUE name = rb_str_new2(rb_id2name(key));
-
- if (!rb_ary_includes(ary, name)) {
- if (!body->nd_body) {
- rb_ary_push(ary, Qnil);
- }
- rb_ary_push(ary, name);
- }
- }
- else if (body->nd_body && nd_type(body->nd_body) == NODE_ZSUPER) {
- rb_ary_push(ary, Qnil);
- rb_ary_push(ary, rb_str_new2(rb_id2name(key)));
- }
- return ST_CONTINUE;
-}
-
-static int
-ins_methods_prot_i(key, body, ary)
- ID key;
- NODE *body;
- VALUE ary;
-{
- if (!body->nd_body) {
- rb_ary_push(ary, Qnil);
- rb_ary_push(ary, rb_str_new2(rb_id2name(key)));
- }
- else if (body->nd_noex & NOEX_PROTECTED) {
- VALUE name = rb_str_new2(rb_id2name(key));
-
- if (!rb_ary_includes(ary, name)) {
- rb_ary_push(ary, name);
- }
- }
- else if (nd_type(body->nd_body) == NODE_ZSUPER) {
- rb_ary_push(ary, Qnil);
- rb_ary_push(ary, rb_str_new2(rb_id2name(key)));
- }
- return ST_CONTINUE;
-}
-
-static int
-ins_methods_priv_i(key, body, ary)
- ID key;
- NODE *body;
- VALUE ary;
-{
- if (!body->nd_body) {
- rb_ary_push(ary, Qnil);
- rb_ary_push(ary, rb_str_new2(rb_id2name(key)));
- }
- else if (body->nd_noex & NOEX_PRIVATE) {
- VALUE name = rb_str_new2(rb_id2name(key));
-
- if (!rb_ary_includes(ary, name)) {
- rb_ary_push(ary, name);
- }
- }
- else if (nd_type(body->nd_body) == NODE_ZSUPER) {
- rb_ary_push(ary, Qnil);
- rb_ary_push(ary, rb_str_new2(rb_id2name(key)));
- }
- return ST_CONTINUE;
-}
-
-static VALUE
-method_list(mod, option, func)
- VALUE mod;
- int option;
- int (*func)();
-{
- VALUE ary;
- VALUE klass;
- VALUE *p, *q, *pend;
-
- ary = rb_ary_new();
- for (klass = mod; klass; klass = RCLASS(klass)->super) {
- st_foreach(RCLASS(klass)->m_tbl, func, ary);
- if (!option) break;
- }
- p = q = RARRAY(ary)->ptr; pend = p + RARRAY(ary)->len;
- while (p < pend) {
- if (*p == Qnil) {
- p+=2;
- continue;
- }
- *q++ = *p++;
- }
- RARRAY(ary)->len = q - RARRAY(ary)->ptr;
- return ary;
-}
-
-VALUE
-rb_class_instance_methods(argc, argv, mod)
- int argc;
- VALUE *argv;
- VALUE mod;
-{
- VALUE option;
-
- rb_scan_args(argc, argv, "01", &option);
- return method_list(mod, RTEST(option), ins_methods_i);
-}
-
-VALUE
-rb_class_protected_instance_methods(argc, argv, mod)
- int argc;
- VALUE *argv;
- VALUE mod;
-{
- VALUE option;
-
- rb_scan_args(argc, argv, "01", &option);
- return method_list(mod, RTEST(option), ins_methods_prot_i);
-}
-
-VALUE
-rb_class_private_instance_methods(argc, argv, mod)
- int argc;
- VALUE *argv;
- VALUE mod;
-{
- VALUE option;
-
- rb_scan_args(argc, argv, "01", &option);
- return method_list(mod, RTEST(option), ins_methods_priv_i);
-}
-
-VALUE
-rb_obj_singleton_methods(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- VALUE all;
- VALUE ary;
- VALUE klass;
- VALUE *p, *q, *pend;
-
- rb_scan_args(argc, argv, "01", &all);
- ary = rb_ary_new();
- klass = CLASS_OF(obj);
- while (klass && FL_TEST(klass, FL_SINGLETON)) {
- st_foreach(RCLASS(klass)->m_tbl, ins_methods_i, ary);
- klass = RCLASS(klass)->super;
- }
- if (RTEST(all)) {
- while (klass && TYPE(klass) == T_ICLASS) {
- st_foreach(RCLASS(klass)->m_tbl, ins_methods_i, ary);
- klass = RCLASS(klass)->super;
- }
- }
- p = q = RARRAY(ary)->ptr; pend = p + RARRAY(ary)->len;
- while (p < pend) {
- if (*p == Qnil) {
- p+=2;
- continue;
- }
- *q++ = *p++;
- }
- RARRAY(ary)->len = q - RARRAY(ary)->ptr;
-
- return ary;
-}
-
-void
-rb_define_method_id(klass, name, func, argc)
- VALUE klass;
- ID name;
- VALUE (*func)();
- int argc;
-{
- rb_add_method(klass, name, NEW_CFUNC(func,argc), NOEX_PUBLIC|NOEX_CFUNC);
-}
-
-void
-rb_define_method(klass, name, func, argc)
- VALUE klass;
- const char *name;
- VALUE (*func)();
- int argc;
-{
- ID id = rb_intern(name);
-
- rb_add_method(klass, id, NEW_CFUNC(func, argc),
- ((name[0] == 'i' && id == rb_intern("initialize"))?
- NOEX_PRIVATE:NOEX_PUBLIC)|NOEX_CFUNC);
-}
-
-void
-rb_define_protected_method(klass, name, func, argc)
- VALUE klass;
- const char *name;
- VALUE (*func)();
- int argc;
-{
- rb_add_method(klass, rb_intern(name), NEW_CFUNC(func, argc),
- NOEX_PROTECTED|NOEX_CFUNC);
-}
-
-void
-rb_define_private_method(klass, name, func, argc)
- VALUE klass;
- const char *name;
- VALUE (*func)();
- int argc;
-{
- rb_add_method(klass, rb_intern(name), NEW_CFUNC(func, argc),
- NOEX_PRIVATE|NOEX_CFUNC);
-}
-
-void
-rb_undef_method(klass, name)
- VALUE klass;
- const char *name;
-{
- rb_add_method(klass, rb_intern(name), 0, NOEX_UNDEF);
-}
-
-#if 0
-
-#define SPECIAL_SINGLETON(x,c) if (obj == (x)) {\
- if (!FL_TEST(c, FL_SINGLETON)) {\
- c = rb_singleton_class_new(c);\
- rb_singleton_class_attached(c,obj);\
- }\
- return c;\
-}
-
-#else
-
-#define SPECIAL_SINGLETON(x,c) if (obj == (x)) {\
- return c;\
-}
-
-#endif
-
-VALUE
-rb_singleton_class(obj)
- VALUE obj;
-{
- VALUE klass;
-
- if (FIXNUM_P(obj) || SYMBOL_P(obj)) {
- rb_raise(rb_eTypeError, "can't define singleton");
- }
- if (rb_special_const_p(obj)) {
- SPECIAL_SINGLETON(Qnil, rb_cNilClass);
- SPECIAL_SINGLETON(Qfalse, rb_cFalseClass);
- SPECIAL_SINGLETON(Qtrue, rb_cTrueClass);
- rb_bug("unknown immediate %d", obj);
- }
-
- DEFER_INTS;
- if (FL_TEST(RBASIC(obj)->klass, FL_SINGLETON) &&
- (BUILTIN_TYPE(obj) == T_CLASS || BUILTIN_TYPE(obj) == T_MODULE) &&
- rb_iv_get(RBASIC(obj)->klass, "__attached__") == obj) {
- klass = RBASIC(obj)->klass;
- }
- else {
- klass = rb_make_metaclass(obj, RBASIC(obj)->klass);
- RBASIC(klass)->klass = CLASS_OF(RCLASS(klass)->super);
- }
- if (OBJ_TAINTED(obj)) {
- OBJ_TAINT(klass);
- }
- else {
- FL_UNSET(klass, FL_TAINT);
- }
- if (OBJ_FROZEN(obj)) OBJ_FREEZE(klass);
- ALLOW_INTS;
-
- return klass;
-}
-
-void
-rb_define_singleton_method(obj, name, func, argc)
- VALUE obj;
- const char *name;
- VALUE (*func)();
- int argc;
-{
- rb_define_method(rb_singleton_class(obj), name, func, argc);
-}
-
-void
-rb_define_module_function(module, name, func, argc)
- VALUE module;
- const char *name;
- VALUE (*func)();
- int argc;
-{
- rb_define_private_method(module, name, func, argc);
- rb_define_singleton_method(module, name, func, argc);
-}
-
-void
-rb_define_global_function(name, func, argc)
- const char *name;
- VALUE (*func)();
- int argc;
-{
- rb_define_module_function(rb_mKernel, name, func, argc);
-}
-
-void
-rb_define_alias(klass, name1, name2)
- VALUE klass;
- const char *name1, *name2;
-{
- rb_alias(klass, rb_intern(name1), rb_intern(name2));
-}
-
-void
-rb_define_attr(klass, name, read, write)
- VALUE klass;
- const char *name;
- int read, write;
-{
- rb_attr(klass, rb_intern(name), read, write, Qfalse);
-}
-
-#ifdef HAVE_STDARG_PROTOTYPES
-#include <stdarg.h>
-#define va_init_list(a,b) va_start(a,b)
-#else
-#include <varargs.h>
-#define va_init_list(a,b) va_start(a)
-#endif
-
-int
-#ifdef HAVE_STDARG_PROTOTYPES
-rb_scan_args(int argc, VALUE *argv, const char *fmt, ...)
-#else
-rb_scan_args(argc, argv, fmt, va_alist)
- int argc;
- VALUE *argv;
- const char *fmt;
- va_dcl
-#endif
-{
- int n, i = 0;
- const char *p = fmt;
- VALUE *var;
- va_list vargs;
-
- va_init_list(vargs, fmt);
-
- if (*p == '*') goto rest_arg;
-
- if (ISDIGIT(*p)) {
- n = *p - '0';
- if (n > argc)
- rb_raise(rb_eArgError, "wrong number of arguments (%d for %d)", argc, n);
- for (i=0; i<n; i++) {
- var = va_arg(vargs, VALUE*);
- if (var) *var = argv[i];
- }
- p++;
- }
- else {
- goto error;
- }
-
- if (ISDIGIT(*p)) {
- n = i + *p - '0';
- for (; i<n; i++) {
- var = va_arg(vargs, VALUE*);
- if (argc > i) {
- if (var) *var = argv[i];
- }
- else {
- if (var) *var = Qnil;
- }
- }
- p++;
- }
-
- if(*p == '*') {
- rest_arg:
- var = va_arg(vargs, VALUE*);
- if (argc > i) {
- if (var) *var = rb_ary_new4(argc-i, argv+i);
- i = argc;
- }
- else {
- if (var) *var = rb_ary_new();
- }
- p++;
- }
-
- if (*p == '&') {
- var = va_arg(vargs, VALUE*);
- if (rb_block_given_p()) {
- *var = rb_f_lambda();
- }
- else {
- *var = Qnil;
- }
- p++;
- }
- va_end(vargs);
-
- if (*p != '\0') {
- goto error;
- }
-
- if (argc > i) {
- rb_raise(rb_eArgError, "wrong number of arguments(%d for %d)", argc, i);
- }
-
- return argc;
-
- error:
- rb_fatal("bad scan arg format: %s", fmt);
- return 0;
-}
diff --git a/compar.c b/compar.c
deleted file mode 100644
index 86494e27c5..0000000000
--- a/compar.c
+++ /dev/null
@@ -1,118 +0,0 @@
-/**********************************************************************
-
- compar.c -
-
- $Author$
- $Date$
- created at: Thu Aug 26 14:39:48 JST 1993
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
-
-**********************************************************************/
-
-#include "ruby.h"
-
-VALUE rb_mComparable;
-
-static ID cmp;
-
-static VALUE
-cmp_eq(a)
- VALUE *a;
-{
- VALUE c = rb_funcall(a[0], cmp, 1, a[1]);
- int t = NUM2INT(c);
-
- if (t == 0) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-cmp_failed()
-{
- return Qfalse;
-}
-
-static VALUE
-cmp_equal(x, y)
- VALUE x, y;
-{
- VALUE a[2];
-
- if (x == y) return Qtrue;
-
- a[0] = x; a[1] = y;
- return rb_rescue(cmp_eq, (VALUE)a, cmp_failed, 0);
-}
-
-static VALUE
-cmp_gt(x, y)
- VALUE x, y;
-{
- VALUE c = rb_funcall(x, cmp, 1, y);
- int t = NUM2INT(c);
-
- if (t > 0) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-cmp_ge(x, y)
- VALUE x, y;
-{
- VALUE c = rb_funcall(x, cmp, 1, y);
- int t = NUM2INT(c);
-
- if (t >= 0) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-cmp_lt(x, y)
- VALUE x, y;
-{
- VALUE c = rb_funcall(x, cmp, 1, y);
- int t = NUM2INT(c);
-
- if (t < 0) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-cmp_le(x, y)
- VALUE x, y;
-{
- VALUE c = rb_funcall(x, cmp, 1, y);
- int t = NUM2INT(c);
-
- if (t <= 0) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-cmp_between(x, min, max)
- VALUE x, min, max;
-{
- VALUE c = rb_funcall(x, cmp, 1, min);
- long t = NUM2LONG(c);
- if (t < 0) return Qfalse;
-
- c = rb_funcall(x, cmp, 1, max);
- t = NUM2LONG(c);
- if (t > 0) return Qfalse;
- return Qtrue;
-}
-
-void
-Init_Comparable()
-{
- rb_mComparable = rb_define_module("Comparable");
- rb_define_method(rb_mComparable, "==", cmp_equal, 1);
- rb_define_method(rb_mComparable, ">", cmp_gt, 1);
- rb_define_method(rb_mComparable, ">=", cmp_ge, 1);
- rb_define_method(rb_mComparable, "<", cmp_lt, 1);
- rb_define_method(rb_mComparable, "<=", cmp_le, 1);
- rb_define_method(rb_mComparable, "between?", cmp_between, 2);
-
- cmp = rb_intern("<=>");
-}
diff --git a/config.guess b/config.guess
deleted file mode 100644
index acf6a089e5..0000000000
--- a/config.guess
+++ /dev/null
@@ -1,1391 +0,0 @@
-#! /bin/sh
-# Attempt to guess a canonical system name.
-# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001
-# Free Software Foundation, Inc.
-
-timestamp='2001-07-13'
-
-# This file is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful, but
-# WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-# As a special exception to the GNU General Public License, if you
-# distribute this file as part of a program that contains a
-# configuration script generated by Autoconf, you may include it under
-# the same distribution terms that you use for the rest of that program.
-
-# Written by Per Bothner <bothner@cygnus.com>.
-# Please send patches to <config-patches@gnu.org>.
-#
-# This script attempts to guess a canonical system name similar to
-# config.sub. If it succeeds, it prints the system name on stdout, and
-# exits with 0. Otherwise, it exits with 1.
-#
-# The plan is that this can be called by configure scripts if you
-# don't specify an explicit build system type.
-
-me=`echo "$0" | sed -e 's,.*/,,'`
-
-usage="\
-Usage: $0 [OPTION]
-
-Output the configuration name of the system \`$me' is run on.
-
-Operation modes:
- -h, --help print this help, then exit
- -t, --time-stamp print date of last modification, then exit
- -v, --version print version number, then exit
-
-Report bugs and patches to <config-patches@gnu.org>."
-
-version="\
-GNU config.guess ($timestamp)
-
-Originally written by Per Bothner.
-Copyright (C) 1992, 93, 94, 95, 96, 97, 98, 99, 2000
-Free Software Foundation, Inc.
-
-This is free software; see the source for copying conditions. There is NO
-warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
-
-help="
-Try \`$me --help' for more information."
-
-# Parse command line
-while test $# -gt 0 ; do
- case $1 in
- --time-stamp | --time* | -t )
- echo "$timestamp" ; exit 0 ;;
- --version | -v )
- echo "$version" ; exit 0 ;;
- --help | --h* | -h )
- echo "$usage"; exit 0 ;;
- -- ) # Stop option processing
- shift; break ;;
- - ) # Use stdin as input.
- break ;;
- -* )
- echo "$me: invalid option $1$help" >&2
- exit 1 ;;
-*)
- break ;;
- esac
-done
-
-if test $# != 0; then
- echo "$me: too many arguments$help" >&2
- exit 1
-fi
-
-
-dummy=dummy-$$
-trap 'rm -f $dummy.c $dummy.o $dummy.rel $dummy; exit 1' 1 2 15
-
-# CC_FOR_BUILD -- compiler used by this script.
-# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still
-# use `HOST_CC' if defined, but it is deprecated.
-
-case $CC_FOR_BUILD,$HOST_CC,$CC in
- ,,) echo "int dummy(){}" > $dummy.c
- for c in cc gcc c89 ; do
- ($c $dummy.c -c -o $dummy.o) >/dev/null 2>&1
- if test $? = 0 ; then
- CC_FOR_BUILD="$c"; break
- fi
- done
- rm -f $dummy.c $dummy.o $dummy.rel
- if test x"$CC_FOR_BUILD" = x ; then
- CC_FOR_BUILD=no_compiler_found
- fi
- ;;
- ,,*) CC_FOR_BUILD=$CC ;;
- ,*,*) CC_FOR_BUILD=$HOST_CC ;;
-esac
-
-# Modified for Human68k by K.Okabe 1997.07.09
-# Last change: 1997.07.09
-
-case "$KSH_VERSION" in
-*X6*)
- echo m68k-sharp-human
- exit 0 ;;
-*)
- ;;
-esac
-
-# This is needed to find uname on a Pyramid OSx when run in the BSD universe.
-# (ghazi@noc.rutgers.edu 8/24/94.)
-if (test -f /.attbin/uname) >/dev/null 2>&1 ; then
- PATH=$PATH:/.attbin ; export PATH
-fi
-
-UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown
-UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown
-UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown
-UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown
-
-# Note: order is significant - the case branches are not exclusive.
-
-case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
- *:NetBSD:*:*)
- # Netbsd (nbsd) targets should (where applicable) match one or
- # more of the tupples: *-*-netbsdelf*, *-*-netbsdaout*,
- # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently
- # switched to ELF, *-*-netbsd* would select the old
- # object file format. This provides both forward
- # compatibility and a consistent mechanism for selecting the
- # object file format.
- # Determine the machine/vendor (is the vendor relevant).
- case "${UNAME_MACHINE}" in
- amiga) machine=m68k-unknown ;;
- arm32) machine=arm-unknown ;;
- atari*) machine=m68k-atari ;;
- sun3*) machine=m68k-sun ;;
- mac68k) machine=m68k-apple ;;
- macppc) machine=powerpc-apple ;;
- hp3[0-9][05]) machine=m68k-hp ;;
- ibmrt|romp-ibm) machine=romp-ibm ;;
- *) machine=${UNAME_MACHINE}-unknown ;;
- esac
- # The Operating System including object format, if it has switched
- # to ELF recently, or will in the future.
- case "${UNAME_MACHINE}" in
- i386|sparc|amiga|arm*|hp300|mvme68k|vax|atari|luna68k|mac68k|news68k|next68k|pc532|sun3*|x68k)
- if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \
- | grep __ELF__ >/dev/null
- then
- # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout).
- # Return netbsd for either. FIX?
- os=netbsd
- else
- os=netbsdelf
- fi
- ;;
- *)
- os=netbsd
- ;;
- esac
- # The OS release
- release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'`
- # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM:
- # contains redundant information, the shorter form:
- # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used.
- echo "${machine}-${os}${release}"
- exit 0;;
- alpha:OSF1:*:*)
- if test $UNAME_RELEASE = "V4.0"; then
- UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'`
- fi
- # A Vn.n version is a released version.
- # A Tn.n version is a released field test version.
- # A Xn.n version is an unreleased experimental baselevel.
- # 1.2 uses "1.2" for uname -r.
- cat <<EOF >$dummy.s
- .data
-\$Lformat:
- .byte 37,100,45,37,120,10,0 # "%d-%x\n"
-
- .text
- .globl main
- .align 4
- .ent main
-main:
- .frame \$30,16,\$26,0
- ldgp \$29,0(\$27)
- .prologue 1
- .long 0x47e03d80 # implver \$0
- lda \$2,-1
- .long 0x47e20c21 # amask \$2,\$1
- lda \$16,\$Lformat
- mov \$0,\$17
- not \$1,\$18
- jsr \$26,printf
- ldgp \$29,0(\$26)
- mov 0,\$16
- jsr \$26,exit
- .end main
-EOF
- $CC_FOR_BUILD $dummy.s -o $dummy 2>/dev/null
- if test "$?" = 0 ; then
- case `./$dummy` in
- 0-0)
- UNAME_MACHINE="alpha"
- ;;
- 1-0)
- UNAME_MACHINE="alphaev5"
- ;;
- 1-1)
- UNAME_MACHINE="alphaev56"
- ;;
- 1-101)
- UNAME_MACHINE="alphapca56"
- ;;
- 2-303)
- UNAME_MACHINE="alphaev6"
- ;;
- 2-307)
- UNAME_MACHINE="alphaev67"
- ;;
- esac
- fi
- rm -f $dummy.s $dummy
- echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[VTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
- exit 0 ;;
- Alpha\ *:Windows_NT*:*)
- # How do we know it's Interix rather than the generic POSIX subsystem?
- # Should we change UNAME_MACHINE based on the output of uname instead
- # of the specific Alpha model?
- echo alpha-pc-interix
- exit 0 ;;
- 21064:Windows_NT:50:3)
- echo alpha-dec-winnt3.5
- exit 0 ;;
- Amiga*:UNIX_System_V:4.0:*)
- echo m68k-unknown-sysv4
- exit 0 ;;
- amiga:OpenBSD:*:*)
- echo m68k-unknown-openbsd${UNAME_RELEASE}
- exit 0 ;;
- *:[Aa]miga[Oo][Ss]:*:*)
- echo ${UNAME_MACHINE}-unknown-amigaos
- exit 0 ;;
- arc64:OpenBSD:*:*)
- echo mips64el-unknown-openbsd${UNAME_RELEASE}
- exit 0 ;;
- arc:OpenBSD:*:*)
- echo mipsel-unknown-openbsd${UNAME_RELEASE}
- exit 0 ;;
- hkmips:OpenBSD:*:*)
- echo mips-unknown-openbsd${UNAME_RELEASE}
- exit 0 ;;
- pmax:OpenBSD:*:*)
- echo mipsel-unknown-openbsd${UNAME_RELEASE}
- exit 0 ;;
- sgi:OpenBSD:*:*)
- echo mips-unknown-openbsd${UNAME_RELEASE}
- exit 0 ;;
- wgrisc:OpenBSD:*:*)
- echo mipsel-unknown-openbsd${UNAME_RELEASE}
- exit 0 ;;
- *:OS/390:*:*)
- echo i370-ibm-openedition
- exit 0 ;;
- arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*)
- echo arm-acorn-riscix${UNAME_RELEASE}
- exit 0;;
- SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*)
- echo hppa1.1-hitachi-hiuxmpp
- exit 0;;
- Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*)
- # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE.
- if test "`(/bin/universe) 2>/dev/null`" = att ; then
- echo pyramid-pyramid-sysv3
- else
- echo pyramid-pyramid-bsd
- fi
- exit 0 ;;
- NILE*:*:*:dcosx)
- echo pyramid-pyramid-svr4
- exit 0 ;;
- sun4H:SunOS:5.*:*)
- echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
- exit 0 ;;
- sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*)
- echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
- exit 0 ;;
- i86pc:SunOS:5.*:*)
- echo i386-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
- exit 0 ;;
- sun4*:SunOS:6*:*)
- # According to config.sub, this is the proper way to canonicalize
- # SunOS6. Hard to guess exactly what SunOS6 will be like, but
- # it's likely to be more like Solaris than SunOS4.
- echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
- exit 0 ;;
- sun4*:SunOS:*:*)
- case "`/usr/bin/arch -k`" in
- Series*|S4*)
- UNAME_RELEASE=`uname -v`
- ;;
- esac
- # Japanese Language versions have a version number like `4.1.3-JL'.
- echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'`
- exit 0 ;;
- sun3*:SunOS:*:*)
- echo m68k-sun-sunos${UNAME_RELEASE}
- exit 0 ;;
- sun*:*:4.2BSD:*)
- UNAME_RELEASE=`(head -1 /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null`
- test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3
- case "`/bin/arch`" in
- sun3)
- echo m68k-sun-sunos${UNAME_RELEASE}
- ;;
- sun4)
- echo sparc-sun-sunos${UNAME_RELEASE}
- ;;
- esac
- exit 0 ;;
- aushp:SunOS:*:*)
- echo sparc-auspex-sunos${UNAME_RELEASE}
- exit 0 ;;
- atari*:OpenBSD:*:*)
- echo m68k-unknown-openbsd${UNAME_RELEASE}
- exit 0 ;;
- # The situation for MiNT is a little confusing. The machine name
- # can be virtually everything (everything which is not
- # "atarist" or "atariste" at least should have a processor
- # > m68000). The system name ranges from "MiNT" over "FreeMiNT"
- # to the lowercase version "mint" (or "freemint"). Finally
- # the system name "TOS" denotes a system which is actually not
- # MiNT. But MiNT is downward compatible to TOS, so this should
- # be no problem.
- atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*)
- echo m68k-atari-mint${UNAME_RELEASE}
- exit 0 ;;
- atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*)
- echo m68k-atari-mint${UNAME_RELEASE}
- exit 0 ;;
- *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*)
- echo m68k-atari-mint${UNAME_RELEASE}
- exit 0 ;;
- milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*)
- echo m68k-milan-mint${UNAME_RELEASE}
- exit 0 ;;
- hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*)
- echo m68k-hades-mint${UNAME_RELEASE}
- exit 0 ;;
- *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*)
- echo m68k-unknown-mint${UNAME_RELEASE}
- exit 0 ;;
- sun3*:NetBSD:*:*)
- echo m68k-sun-netbsd${UNAME_RELEASE}
- exit 0 ;;
- sun3*:OpenBSD:*:*)
- echo m68k-unknown-openbsd${UNAME_RELEASE}
- exit 0 ;;
- mac68k:NetBSD:*:*)
- echo m68k-apple-netbsd${UNAME_RELEASE}
- exit 0 ;;
- mac68k:OpenBSD:*:*)
- echo m68k-unknown-openbsd${UNAME_RELEASE}
- exit 0 ;;
- mvme68k:OpenBSD:*:*)
- echo m68k-unknown-openbsd${UNAME_RELEASE}
- exit 0 ;;
- mvme88k:OpenBSD:*:*)
- echo m88k-unknown-openbsd${UNAME_RELEASE}
- exit 0 ;;
- powerpc:machten:*:*)
- echo powerpc-apple-machten${UNAME_RELEASE}
- exit 0 ;;
- macppc:NetBSD:*:*)
- echo powerpc-apple-netbsd${UNAME_RELEASE}
- exit 0 ;;
- RISC*:Mach:*:*)
- echo mips-dec-mach_bsd4.3
- exit 0 ;;
- RISC*:ULTRIX:*:*)
- echo mips-dec-ultrix${UNAME_RELEASE}
- exit 0 ;;
- VAX*:ULTRIX*:*:*)
- echo vax-dec-ultrix${UNAME_RELEASE}
- exit 0 ;;
- 2020:CLIX:*:* | 2430:CLIX:*:*)
- echo clipper-intergraph-clix${UNAME_RELEASE}
- exit 0 ;;
- mips:*:*:UMIPS | mips:*:*:RISCos)
- sed 's/^ //' << EOF >$dummy.c
-#ifdef __cplusplus
-#include <stdio.h> /* for printf() prototype */
- int main (int argc, char *argv[]) {
-#else
- int main (argc, argv) int argc; char *argv[]; {
-#endif
- #if defined (host_mips) && defined (MIPSEB)
- #if defined (SYSTYPE_SYSV)
- printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0);
- #endif
- #if defined (SYSTYPE_SVR4)
- printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0);
- #endif
- #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD)
- printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0);
- #endif
- #endif
- exit (-1);
- }
-EOF
- $CC_FOR_BUILD $dummy.c -o $dummy \
- && ./$dummy `echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` \
- && rm -f $dummy.c $dummy && exit 0
- rm -f $dummy.c $dummy
- echo mips-mips-riscos${UNAME_RELEASE}
- exit 0 ;;
- Motorola:PowerMAX_OS:*:*)
- echo powerpc-motorola-powermax
- exit 0 ;;
- Night_Hawk:Power_UNIX:*:*)
- echo powerpc-harris-powerunix
- exit 0 ;;
- m88k:CX/UX:7*:*)
- echo m88k-harris-cxux7
- exit 0 ;;
- m88k:*:4*:R4*)
- echo m88k-motorola-sysv4
- exit 0 ;;
- m88k:*:3*:R3*)
- echo m88k-motorola-sysv3
- exit 0 ;;
- AViiON:dgux:*:*)
- # DG/UX returns AViiON for all architectures
- UNAME_PROCESSOR=`/usr/bin/uname -p`
- if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ]
- then
- if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \
- [ ${TARGET_BINARY_INTERFACE}x = x ]
- then
- echo m88k-dg-dgux${UNAME_RELEASE}
- else
- echo m88k-dg-dguxbcs${UNAME_RELEASE}
- fi
- else
- echo i586-dg-dgux${UNAME_RELEASE}
- fi
- exit 0 ;;
- M88*:DolphinOS:*:*) # DolphinOS (SVR3)
- echo m88k-dolphin-sysv3
- exit 0 ;;
- M88*:*:R3*:*)
- # Delta 88k system running SVR3
- echo m88k-motorola-sysv3
- exit 0 ;;
- XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3)
- echo m88k-tektronix-sysv3
- exit 0 ;;
- Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD)
- echo m68k-tektronix-bsd
- exit 0 ;;
- *:IRIX*:*:*)
- echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'`
- exit 0 ;;
- ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX.
- echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id
- exit 0 ;; # Note that: echo "'`uname -s`'" gives 'AIX '
- i*86:AIX:*:*)
- echo i386-ibm-aix
- exit 0 ;;
- ia64:AIX:*:*)
- if [ -x /usr/bin/oslevel ] ; then
- IBM_REV=`/usr/bin/oslevel`
- else
- IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
- fi
- echo ${UNAME_MACHINE}-ibm-aix${IBM_REV}
- exit 0 ;;
- *:AIX:2:3)
- if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then
- sed 's/^ //' << EOF >$dummy.c
- #include <sys/systemcfg.h>
-
- main()
- {
- if (!__power_pc())
- exit(1);
- puts("powerpc-ibm-aix3.2.5");
- exit(0);
- }
-EOF
- $CC_FOR_BUILD $dummy.c -o $dummy && ./$dummy && rm -f $dummy.c $dummy && exit 0
- rm -f $dummy.c $dummy
- echo rs6000-ibm-aix3.2.5
- elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then
- echo rs6000-ibm-aix3.2.4
- else
- echo rs6000-ibm-aix3.2
- fi
- exit 0 ;;
- *:AIX:*:[45])
- IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | head -1 | awk '{ print $1 }'`
- if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then
- IBM_ARCH=rs6000
- else
- IBM_ARCH=powerpc
- fi
- if [ -x /usr/bin/oslevel ] ; then
- IBM_REV=`/usr/bin/oslevel`
- else
- IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
- fi
- echo ${IBM_ARCH}-ibm-aix${IBM_REV}
- exit 0 ;;
- *:AIX:*:*)
- echo rs6000-ibm-aix
- exit 0 ;;
- ibmrt:4.4BSD:*|romp-ibm:BSD:*)
- echo romp-ibm-bsd4.4
- exit 0 ;;
- ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and
- echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to
- exit 0 ;; # report: romp-ibm BSD 4.3
- *:BOSX:*:*)
- echo rs6000-bull-bosx
- exit 0 ;;
- DPX/2?00:B.O.S.:*:*)
- echo m68k-bull-sysv3
- exit 0 ;;
- 9000/[34]??:4.3bsd:1.*:*)
- echo m68k-hp-bsd
- exit 0 ;;
- hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*)
- echo m68k-hp-bsd4.4
- exit 0 ;;
- 9000/[34678]??:HP-UX:*:*)
- HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
- case "${UNAME_MACHINE}" in
- 9000/31? ) HP_ARCH=m68000 ;;
- 9000/[34]?? ) HP_ARCH=m68k ;;
- 9000/[678][0-9][0-9])
- case "${HPUX_REV}" in
- 11.[0-9][0-9])
- if [ -x /usr/bin/getconf ]; then
- sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null`
- sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null`
- case "${sc_cpu_version}" in
- 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0
- 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1
- 532) # CPU_PA_RISC2_0
- case "${sc_kernel_bits}" in
- 32) HP_ARCH="hppa2.0n" ;;
- 64) HP_ARCH="hppa2.0w" ;;
- esac ;;
- esac
- fi ;;
- esac
- if [ "${HP_ARCH}" = "" ]; then
- sed 's/^ //' << EOF >$dummy.c
-
- #define _HPUX_SOURCE
- #include <stdlib.h>
- #include <unistd.h>
-
- int main ()
- {
- #if defined(_SC_KERNEL_BITS)
- long bits = sysconf(_SC_KERNEL_BITS);
- #endif
- long cpu = sysconf (_SC_CPU_VERSION);
-
- switch (cpu)
- {
- case CPU_PA_RISC1_0: puts ("hppa1.0"); break;
- case CPU_PA_RISC1_1: puts ("hppa1.1"); break;
- case CPU_PA_RISC2_0:
- #if defined(_SC_KERNEL_BITS)
- switch (bits)
- {
- case 64: puts ("hppa2.0w"); break;
- case 32: puts ("hppa2.0n"); break;
- default: puts ("hppa2.0"); break;
- } break;
- #else /* !defined(_SC_KERNEL_BITS) */
- puts ("hppa2.0"); break;
- #endif
- default: puts ("hppa1.0"); break;
- }
- exit (0);
- }
-EOF
- (CCOPTS= $CC_FOR_BUILD $dummy.c -o $dummy 2>/dev/null ) && HP_ARCH=`./$dummy`
- if test -z "$HP_ARCH"; then HP_ARCH=hppa; fi
- rm -f $dummy.c $dummy
- fi ;;
- esac
- echo ${HP_ARCH}-hp-hpux${HPUX_REV}
- exit 0 ;;
- ia64:HP-UX:*:*)
- HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
- echo ia64-hp-hpux${HPUX_REV}
- exit 0 ;;
- 3050*:HI-UX:*:*)
- sed 's/^ //' << EOF >$dummy.c
- #include <unistd.h>
- int
- main ()
- {
- long cpu = sysconf (_SC_CPU_VERSION);
- /* The order matters, because CPU_IS_HP_MC68K erroneously returns
- true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct
- results, however. */
- if (CPU_IS_PA_RISC (cpu))
- {
- switch (cpu)
- {
- case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break;
- case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break;
- case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break;
- default: puts ("hppa-hitachi-hiuxwe2"); break;
- }
- }
- else if (CPU_IS_HP_MC68K (cpu))
- puts ("m68k-hitachi-hiuxwe2");
- else puts ("unknown-hitachi-hiuxwe2");
- exit (0);
- }
-EOF
- $CC_FOR_BUILD $dummy.c -o $dummy && ./$dummy && rm -f $dummy.c $dummy && exit 0
- rm -f $dummy.c $dummy
- echo unknown-hitachi-hiuxwe2
- exit 0 ;;
- 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* )
- echo hppa1.1-hp-bsd
- exit 0 ;;
- 9000/8??:4.3bsd:*:*)
- echo hppa1.0-hp-bsd
- exit 0 ;;
- *9??*:MPE/iX:*:*)
- echo hppa1.0-hp-mpeix
- exit 0 ;;
- hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* )
- echo hppa1.1-hp-osf
- exit 0 ;;
- hp8??:OSF1:*:*)
- echo hppa1.0-hp-osf
- exit 0 ;;
- i*86:OSF1:*:*)
- if [ -x /usr/sbin/sysversion ] ; then
- echo ${UNAME_MACHINE}-unknown-osf1mk
- else
- echo ${UNAME_MACHINE}-unknown-osf1
- fi
- exit 0 ;;
- parisc*:Lites*:*:*)
- echo hppa1.1-hp-lites
- exit 0 ;;
- hppa*:OpenBSD:*:*)
- echo hppa-unknown-openbsd
- exit 0 ;;
- C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*)
- echo c1-convex-bsd
- exit 0 ;;
- C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*)
- if getsysinfo -f scalar_acc
- then echo c32-convex-bsd
- else echo c2-convex-bsd
- fi
- exit 0 ;;
- C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*)
- echo c34-convex-bsd
- exit 0 ;;
- C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*)
- echo c38-convex-bsd
- exit 0 ;;
- C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*)
- echo c4-convex-bsd
- exit 0 ;;
- CRAY*X-MP:*:*:*)
- echo xmp-cray-unicos
- exit 0 ;;
- CRAY*Y-MP:*:*:*)
- echo ymp-cray-unicos${UNAME_RELEASE}
- exit 0 ;;
- CRAY*[A-Z]90:*:*:*)
- echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \
- | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \
- -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/
- exit 0 ;;
- CRAY*TS:*:*:*)
- echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
- exit 0 ;;
- CRAY*T3D:*:*:*)
- echo alpha-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
- exit 0 ;;
- CRAY*T3E:*:*:*)
- echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
- exit 0 ;;
- CRAY*SV1:*:*:*)
- echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
- exit 0 ;;
- CRAY-2:*:*:*)
- echo cray2-cray-unicos
- exit 0 ;;
- F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*)
- FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
- FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
- FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'`
- echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
- exit 0 ;;
- hp300:OpenBSD:*:*)
- echo m68k-unknown-openbsd${UNAME_RELEASE}
- exit 0 ;;
- i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*)
- echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE}
- exit 0 ;;
- sparc*:BSD/OS:*:*)
- echo sparc-unknown-bsdi${UNAME_RELEASE}
- exit 0 ;;
- *:BSD/OS:*:*)
- echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE}
- exit 0 ;;
- *:FreeBSD:*:*)
- echo ${UNAME_MACHINE}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`
- exit 0 ;;
- *:OpenBSD:*:*)
- echo ${UNAME_MACHINE}-unknown-openbsd`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'`
- exit 0 ;;
- i*:CYGWIN*:*)
- echo ${UNAME_MACHINE}-pc-cygwin
- exit 0 ;;
- i*:MINGW*:*)
- echo ${UNAME_MACHINE}-pc-mingw32
- exit 0 ;;
- i*:PW*:*)
- echo ${UNAME_MACHINE}-pc-pw32
- exit 0 ;;
- i*:Windows_NT*:* | Pentium*:Windows_NT*:*)
- # How do we know it's Interix rather than the generic POSIX subsystem?
- # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we
- # UNAME_MACHINE based on the output of uname instead of i386?
- echo i386-pc-interix
- exit 0 ;;
- i*:UWIN*:*)
- echo ${UNAME_MACHINE}-pc-uwin
- exit 0 ;;
- p*:CYGWIN*:*)
- echo powerpcle-unknown-cygwin
- exit 0 ;;
- prep*:SunOS:5.*:*)
- echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
- exit 0 ;;
- *:GNU:*:*)
- echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'`
- exit 0 ;;
- i*86:Minix:*:*)
- echo ${UNAME_MACHINE}-pc-minix
- exit 0 ;;
- arm*:Linux:*:*)
- echo ${UNAME_MACHINE}-unknown-linux
- exit 0 ;;
- ia64:Linux:*:*)
- echo ${UNAME_MACHINE}-unknown-linux
- exit 0 ;;
- m68*:Linux:*:*)
- echo ${UNAME_MACHINE}-unknown-linux
- exit 0 ;;
- mips:Linux:*:*)
- cat >$dummy.c <<EOF
-#ifdef __cplusplus
-#include <stdio.h> /* for printf() prototype */
-int main (int argc, char *argv[]) {
-#else
-int main (argc, argv) int argc; char *argv[]; {
-#endif
-#ifdef __MIPSEB__
- printf ("%s-unknown-linux\n", argv[1]);
-#endif
-#ifdef __MIPSEL__
- printf ("%sel-unknown-linux\n", argv[1]);
-#endif
- return 0;
-}
-EOF
- $CC_FOR_BUILD $dummy.c -o $dummy 2>/dev/null && ./$dummy "${UNAME_MACHINE}" && rm -f $dummy.c $dummy && exit 0
- rm -f $dummy.c $dummy
- ;;
- ppc:Linux:*:*)
- # Determine Lib Version
- cat >$dummy.c <<EOF
-#include <features.h>
-#if defined(__GLIBC__)
-extern char __libc_version[];
-extern char __libc_release[];
-#endif
-main(argc, argv)
- int argc;
- char *argv[];
-{
-#if defined(__GLIBC__)
- printf("%s %s\n", __libc_version, __libc_release);
-#else
- printf("unknown\n");
-#endif
- return 0;
-}
-EOF
- LIBC=""
- $CC_FOR_BUILD $dummy.c -o $dummy 2>/dev/null
- if test "$?" = 0 ; then
- ./$dummy | grep 1\.99 > /dev/null
- if test "$?" = 0 ; then LIBC="libc1" ; fi
- fi
- rm -f $dummy.c $dummy
- echo powerpc-unknown-linux-${LIBC}
- exit 0 ;;
- alpha:Linux:*:*)
- cat <<EOF >$dummy.s
- .data
- \$Lformat:
- .byte 37,100,45,37,120,10,0 # "%d-%x\n"
- .text
- .globl main
- .align 4
- .ent main
- main:
- .frame \$30,16,\$26,0
- ldgp \$29,0(\$27)
- .prologue 1
- .long 0x47e03d80 # implver \$0
- lda \$2,-1
- .long 0x47e20c21 # amask \$2,\$1
- lda \$16,\$Lformat
- mov \$0,\$17
- not \$1,\$18
- jsr \$26,printf
- ldgp \$29,0(\$26)
- mov 0,\$16
- jsr \$26,exit
- .end main
-EOF
- LIBC=""
- $CC_FOR_BUILD $dummy.s -o $dummy 2>/dev/null
- if test "$?" = 0 ; then
- case `./$dummy` in
- 0-0) UNAME_MACHINE="alpha" ;;
- 1-0) UNAME_MACHINE="alphaev5" ;;
- 1-1) UNAME_MACHINE="alphaev56" ;;
- 1-101) UNAME_MACHINE="alphapca56" ;;
- 2-303) UNAME_MACHINE="alphaev6" ;;
- 2-307) UNAME_MACHINE="alphaev67" ;;
- esac
- objdump --private-headers $dummy | \
- grep ld.so.1 > /dev/null
- if test "$?" = 0 ; then
- LIBC="-libc1"
- fi
- fi
- rm -f $dummy.s $dummy
- echo ${UNAME_MACHINE}-unknown-linux${LIBC}
- exit 0 ;;
- parisc:Linux:*:* | hppa:Linux:*:*)
- # Look for CPU level
- case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in
- PA7*) echo hppa1.1-unknown-linux ;;
- PA8*) echo hppa2.0-unknown-linux ;;
- *) echo hppa-unknown-linux ;;
- esac
- exit 0 ;;
- parisc64:Linux:*:* | hppa64:Linux:*:*)
- echo hppa64-unknown-linux
- exit 0 ;;
- s390:Linux:*:* | s390x:Linux:*:*)
- echo ${UNAME_MACHINE}-ibm-linux
- exit 0 ;;
- sh*:Linux:*:*)
- echo ${UNAME_MACHINE}-unknown-linux
- exit 0 ;;
- sparc:Linux:*:* | sparc64:Linux:*:*)
- echo ${UNAME_MACHINE}-unknown-linux
- exit 0 ;;
- x86_64:Linux:*:*)
- echo x86_64-unknown-linux
- exit 0 ;;
- i*86:Linux:*:*)
- # The BFD linker knows what the default object file format is, so
- # first see if it will tell us. cd to the root directory to prevent
- # problems with other programs or directories called `ld' in the path.
- ld_supported_emulations=`cd /; ld --help 2>&1 \
- | sed -ne '/supported emulations:/!d
- s/[ ][ ]*/ /g
- s/.*supported emulations: *//
- s/ .*//
- p'`
- case "$ld_supported_emulations" in
- i*86linux)
- echo "${UNAME_MACHINE}-pc-linux-aout"
- exit 0
- ;;
- elf_i*86)
- TENTATIVE="${UNAME_MACHINE}-pc-linux"
- ;;
- i*86coff)
- echo "${UNAME_MACHINE}-pc-linux-coff"
- exit 0
- ;;
- esac
- # Either a pre-BFD a.out linker (linux-oldld)
- # or one that does not give us useful --help.
- # GCC wants to distinguish between linux-oldld and linux-aout.
- # If ld does not provide *any* "supported emulations:"
- # that means it is gnuoldld.
- test -z "$ld_supported_emulations" && echo "${UNAME_MACHINE}-pc-linux-oldld" && exit 0
- case "${UNAME_MACHINE}" in
- i*86)
- VENDOR=pc;
- ;;
- *)
- VENDOR=unknown;
- ;;
- esac
- # Determine whether the default compiler is a.out or elf
- cat >$dummy.c <<EOF
-#include <features.h>
-#ifdef __cplusplus
-#include <stdio.h> /* for printf() prototype */
- int main (int argc, char *argv[]) {
-#else
- int main (argc, argv) int argc; char *argv[]; {
-#endif
-#ifdef __ELF__
-# ifdef __GLIBC__
-# if __GLIBC__ >= 2
- printf ("%s-${VENDOR}-linux\n", argv[1]);
-# else
- printf ("%s-${VENDOR}-linux-libc1\n", argv[1]);
-# endif
-# else
- printf ("%s-${VENDOR}-linux-libc1\n", argv[1]);
-# endif
-#else
- printf ("%s-${VENDOR}-linux-aout\n", argv[1]);
-#endif
- return 0;
-}
-EOF
- $CC_FOR_BUILD $dummy.c -o $dummy 2>/dev/null && ./$dummy "${UNAME_MACHINE}" && rm -f $dummy.c $dummy && exit 0
- rm -f $dummy.c $dummy
- test x"${TENTATIVE}" != x && echo "${TENTATIVE}" && exit 0
- ;;
-# ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. earlier versions
-# are messed up and put the nodename in both sysname and nodename.
- i*86:DYNIX/ptx:4*:*)
- echo i386-sequent-sysv4
- exit 0 ;;
- i*86:UNIX_SV:4.2MP:2.*)
- # Unixware is an offshoot of SVR4, but it has its own version
- # number series starting with 2...
- # I am not positive that other SVR4 systems won't match this,
- # I just have to hope. -- rms.
- # Use sysv4.2uw... so that sysv4* matches it.
- echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION}
- exit 0 ;;
- i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*)
- UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'`
- if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then
- echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL}
- else
- echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL}
- fi
- exit 0 ;;
- i*86:*:5:7*)
- # Fixed at (any) Pentium or better
- UNAME_MACHINE=i586
- if [ ${UNAME_SYSTEM} = "UnixWare" ] ; then
- echo ${UNAME_MACHINE}-sco-sysv${UNAME_RELEASE}uw${UNAME_VERSION}
- else
- echo ${UNAME_MACHINE}-pc-sysv${UNAME_RELEASE}
- fi
- exit 0 ;;
- i*86:*:3.2:*)
- if test -f /usr/options/cb.name; then
- UNAME_REL=`sed -n 's/.*Version //p' </usr/options/cb.name`
- echo ${UNAME_MACHINE}-pc-isc$UNAME_REL
- elif /bin/uname -X 2>/dev/null >/dev/null ; then
- UNAME_REL=`(/bin/uname -X|egrep Release|sed -e 's/.*= //')`
- (/bin/uname -X|egrep i80486 >/dev/null) && UNAME_MACHINE=i486
- (/bin/uname -X|egrep '^Machine.*Pentium' >/dev/null) \
- && UNAME_MACHINE=i586
- (/bin/uname -X|egrep '^Machine.*Pent ?II' >/dev/null) \
- && UNAME_MACHINE=i686
- (/bin/uname -X|egrep '^Machine.*Pentium Pro' >/dev/null) \
- && UNAME_MACHINE=i686
- echo ${UNAME_MACHINE}-pc-sco$UNAME_REL
- else
- echo ${UNAME_MACHINE}-pc-sysv32
- fi
- exit 0 ;;
- i*86:*DOS:*:*)
- echo ${UNAME_MACHINE}-pc-msdosdjgpp
- exit 0 ;;
- pc:*:*:*)
- # Left here for compatibility:
- # uname -m prints for DJGPP always 'pc', but it prints nothing about
- # the processor, so we play safe by assuming i386.
- echo i386-pc-msdosdjgpp
- exit 0 ;;
- Intel:Mach:3*:*)
- echo i386-pc-mach3
- exit 0 ;;
- paragon:*:*:*)
- echo i860-intel-osf1
- exit 0 ;;
- i860:*:4.*:*) # i860-SVR4
- if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then
- echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4
- else # Add other i860-SVR4 vendors below as they are discovered.
- echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4
- fi
- exit 0 ;;
- mini*:CTIX:SYS*5:*)
- # "miniframe"
- echo m68010-convergent-sysv
- exit 0 ;;
- M68*:*:R3V[567]*:*)
- test -r /sysV68 && echo 'm68k-motorola-sysv' && exit 0 ;;
- 3[34]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 4850:*:4.0:3.0)
- OS_REL=''
- test -r /etc/.relid \
- && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
- /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
- && echo i486-ncr-sysv4.3${OS_REL} && exit 0
- /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
- && echo i586-ncr-sysv4.3${OS_REL} && exit 0 ;;
- 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*)
- /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
- && echo i486-ncr-sysv4 && exit 0 ;;
- m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*)
- echo m68k-unknown-lynxos${UNAME_RELEASE}
- exit 0 ;;
- mc68030:UNIX_System_V:4.*:*)
- echo m68k-atari-sysv4
- exit 0 ;;
- i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.0*:*)
- echo i386-unknown-lynxos${UNAME_RELEASE}
- exit 0 ;;
- TSUNAMI:LynxOS:2.*:*)
- echo sparc-unknown-lynxos${UNAME_RELEASE}
- exit 0 ;;
- rs6000:LynxOS:2.*:*)
- echo rs6000-unknown-lynxos${UNAME_RELEASE}
- exit 0 ;;
- PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.0*:*)
- echo powerpc-unknown-lynxos${UNAME_RELEASE}
- exit 0 ;;
- SM[BE]S:UNIX_SV:*:*)
- echo mips-dde-sysv${UNAME_RELEASE}
- exit 0 ;;
- RM*:ReliantUNIX-*:*:*)
- echo mips-sni-sysv4
- exit 0 ;;
- RM*:SINIX-*:*:*)
- echo mips-sni-sysv4
- exit 0 ;;
- *:SINIX-*:*:*)
- if uname -p 2>/dev/null >/dev/null ; then
- UNAME_MACHINE=`(uname -p) 2>/dev/null`
- echo ${UNAME_MACHINE}-sni-sysv4
- else
- echo ns32k-sni-sysv
- fi
- exit 0 ;;
- PENTIUM:CPunix:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort
- # says <Richard.M.Bartel@ccMail.Census.GOV>
- echo i586-unisys-sysv4
- exit 0 ;;
- *:UNIX_System_V:4*:FTX*)
- # From Gerald Hewes <hewes@openmarket.com>.
- # How about differentiating between stratus architectures? -djm
- echo hppa1.1-stratus-sysv4
- exit 0 ;;
- *:*:*:FTX*)
- # From seanf@swdc.stratus.com.
- echo i860-stratus-sysv4
- exit 0 ;;
- mc68*:A/UX:*:*)
- echo m68k-apple-aux${UNAME_RELEASE}
- exit 0 ;;
- news*:NEWS-OS:6*:*)
- echo mips-sony-newsos6
- exit 0 ;;
- R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*)
- if [ -d /usr/nec ]; then
- echo mips-nec-sysv${UNAME_RELEASE}
- else
- echo mips-unknown-sysv${UNAME_RELEASE}
- fi
- exit 0 ;;
- BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only.
- echo powerpc-be-beos
- exit 0 ;;
- BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only.
- echo powerpc-apple-beos
- exit 0 ;;
- BePC:BeOS:*:*) # BeOS running on Intel PC compatible.
- echo i586-pc-beos
- exit 0 ;;
- SX-4:SUPER-UX:*:*)
- echo sx4-nec-superux${UNAME_RELEASE}
- exit 0 ;;
- SX-5:SUPER-UX:*:*)
- echo sx5-nec-superux${UNAME_RELEASE}
- exit 0 ;;
- Power*:Rhapsody:*:*)
- echo powerpc-apple-rhapsody${UNAME_RELEASE}
- exit 0 ;;
- *:Rhapsody:*:*)
- echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE}
- exit 0 ;;
- *:Darwin:*:*)
- echo `uname -p`-apple-darwin${UNAME_RELEASE}
- exit 0 ;;
- *:procnto*:*:* | *:QNX:[0123456789]*:*)
- if test "${UNAME_MACHINE}" = "x86pc"; then
- UNAME_MACHINE=pc
- fi
- echo `uname -p`-${UNAME_MACHINE}-nto-qnx
- exit 0 ;;
- *:QNX:*:4*)
- echo i386-pc-qnx
- exit 0 ;;
- NSR-[KW]:NONSTOP_KERNEL:*:*)
- echo nsr-tandem-nsk${UNAME_RELEASE}
- exit 0 ;;
- *:NonStop-UX:*:*)
- echo mips-compaq-nonstopux
- exit 0 ;;
- BS2000:POSIX*:*:*)
- echo bs2000-siemens-sysv
- exit 0 ;;
- DS/*:UNIX_System_V:*:*)
- echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE}
- exit 0 ;;
- *:Plan9:*:*)
- # "uname -m" is not consistent, so use $cputype instead. 386
- # is converted to i386 for consistency with other x86
- # operating systems.
- if test "$cputype" = "386"; then
- UNAME_MACHINE=i386
- else
- UNAME_MACHINE="$cputype"
- fi
- echo ${UNAME_MACHINE}-unknown-plan9
- exit 0 ;;
- i*86:OS/2:*:*)
- # If we were able to find `uname', then EMX Unix compatibility
- # is probably installed.
- echo ${UNAME_MACHINE}-pc-os2-emx
- exit 0 ;;
- *:TOPS-10:*:*)
- echo pdp10-unknown-tops10
- exit 0 ;;
- *:TENEX:*:*)
- echo pdp10-unknown-tenex
- exit 0 ;;
- KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*)
- echo pdp10-dec-tops20
- exit 0 ;;
- XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*)
- echo pdp10-xkl-tops20
- exit 0 ;;
- *:TOPS-20:*:*)
- echo pdp10-unknown-tops20
- exit 0 ;;
- *:ITS:*:*)
- echo pdp10-unknown-its
- exit 0 ;;
-esac
-
-#echo '(No uname command or uname output not recognized.)' 1>&2
-#echo "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" 1>&2
-
-cat >$dummy.c <<EOF
-#ifdef _SEQUENT_
-# include <sys/types.h>
-# include <sys/utsname.h>
-#endif
-main ()
-{
-#if defined (sony)
-#if defined (MIPSEB)
- /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed,
- I don't know.... */
- printf ("mips-sony-bsd\n"); exit (0);
-#else
-#include <sys/param.h>
- printf ("m68k-sony-newsos%s\n",
-#ifdef NEWSOS4
- "4"
-#else
- ""
-#endif
- ); exit (0);
-#endif
-#endif
-
-#if defined (__arm) && defined (__acorn) && defined (__unix)
- printf ("arm-acorn-riscix"); exit (0);
-#endif
-
-#if defined (hp300) && !defined (hpux)
- printf ("m68k-hp-bsd\n"); exit (0);
-#endif
-
-#if defined (NeXT)
-#if !defined (__ARCHITECTURE__)
-#define __ARCHITECTURE__ "m68k"
-#endif
- int version;
- version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`;
- if (version < 4)
- printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version);
- else
- printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version);
- exit (0);
-#endif
-
-#if defined (MULTIMAX) || defined (n16)
-#if defined (UMAXV)
- printf ("ns32k-encore-sysv\n"); exit (0);
-#else
-#if defined (CMU)
- printf ("ns32k-encore-mach\n"); exit (0);
-#else
- printf ("ns32k-encore-bsd\n"); exit (0);
-#endif
-#endif
-#endif
-
-#if defined (__386BSD__)
- printf ("i386-pc-bsd\n"); exit (0);
-#endif
-
-#if defined (sequent)
-#if defined (i386)
- printf ("i386-sequent-dynix\n"); exit (0);
-#endif
-#if defined (ns32000)
- printf ("ns32k-sequent-dynix\n"); exit (0);
-#endif
-#endif
-
-#if defined (_SEQUENT_)
- struct utsname un;
-
- uname(&un);
-
- if (strncmp(un.version, "V2", 2) == 0) {
- printf ("i386-sequent-ptx2\n"); exit (0);
- }
- if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */
- printf ("i386-sequent-ptx1\n"); exit (0);
- }
- printf ("i386-sequent-ptx\n"); exit (0);
-
-#endif
-
-#if defined (vax)
-#if !defined (ultrix)
-# include <sys/param.h>
-# if defined (BSD)
-# if BSD == 43
- printf ("vax-dec-bsd4.3\n"); exit (0);
-# else
-# if BSD == 199006
- printf ("vax-dec-bsd4.3reno\n"); exit (0);
-# else
- printf ("vax-dec-bsd\n"); exit (0);
-# endif
-# endif
-# else
- printf ("vax-dec-bsd\n"); exit (0);
-# endif
-#else
- printf ("vax-dec-ultrix\n"); exit (0);
-#endif
-#endif
-
-#if defined (alliant) && defined (i860)
- printf ("i860-alliant-bsd\n"); exit (0);
-#endif
-
- exit (1);
-}
-EOF
-
-$CC_FOR_BUILD $dummy.c -o $dummy 2>/dev/null && ./$dummy && rm -f $dummy.c $dummy && exit 0
-rm -f $dummy.c $dummy
-
-# Apollos put the system type in the environment.
-
-test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit 0; }
-
-# Convex versions that predate uname can use getsysinfo(1)
-
-if [ -x /usr/convex/getsysinfo ]
-then
- case `getsysinfo -f cpu_type` in
- c1*)
- echo c1-convex-bsd
- exit 0 ;;
- c2*)
- if getsysinfo -f scalar_acc
- then echo c32-convex-bsd
- else echo c2-convex-bsd
- fi
- exit 0 ;;
- c34*)
- echo c34-convex-bsd
- exit 0 ;;
- c38*)
- echo c38-convex-bsd
- exit 0 ;;
- c4*)
- echo c4-convex-bsd
- exit 0 ;;
- esac
-fi
-
-cat >&2 <<EOF
-$0: unable to guess system type
-
-This script, last modified $timestamp, has failed to recognize
-the operating system you are using. It is advised that you
-download the most up to date version of the config scripts from
-
- ftp://ftp.gnu.org/pub/gnu/config/
-
-If the version you run ($0) is already up to date, please
-send the following data and any information you think might be
-pertinent to <config-patches@gnu.org> in order to provide the needed
-information to handle your system.
-
-config.guess timestamp = $timestamp
-
-uname -m = `(uname -m) 2>/dev/null || echo unknown`
-uname -r = `(uname -r) 2>/dev/null || echo unknown`
-uname -s = `(uname -s) 2>/dev/null || echo unknown`
-uname -v = `(uname -v) 2>/dev/null || echo unknown`
-
-/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null`
-/bin/uname -X = `(/bin/uname -X) 2>/dev/null`
-
-hostinfo = `(hostinfo) 2>/dev/null`
-/bin/universe = `(/bin/universe) 2>/dev/null`
-/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null`
-/bin/arch = `(/bin/arch) 2>/dev/null`
-/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null`
-/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null`
-
-UNAME_MACHINE = ${UNAME_MACHINE}
-UNAME_RELEASE = ${UNAME_RELEASE}
-UNAME_SYSTEM = ${UNAME_SYSTEM}
-UNAME_VERSION = ${UNAME_VERSION}
-EOF
-
-exit 1
-
-# Local variables:
-# eval: (add-hook 'write-file-hooks 'time-stamp)
-# time-stamp-start: "timestamp='"
-# time-stamp-format: "%:y-%02m-%02d"
-# time-stamp-end: "'"
-# End:
diff --git a/config.sub b/config.sub
deleted file mode 100644
index a2d8b0d596..0000000000
--- a/config.sub
+++ /dev/null
@@ -1,1367 +0,0 @@
-#! /bin/sh
-# Configuration validation subroutine script.
-# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001
-# Free Software Foundation, Inc.
-
-timestamp='2001-04-20'
-
-# This file is (in principle) common to ALL GNU software.
-# The presence of a machine in this file suggests that SOME GNU software
-# can handle that machine. It does not imply ALL GNU software can.
-#
-# This file is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330,
-# Boston, MA 02111-1307, USA.
-
-# As a special exception to the GNU General Public License, if you
-# distribute this file as part of a program that contains a
-# configuration script generated by Autoconf, you may include it under
-# the same distribution terms that you use for the rest of that program.
-
-# Please send patches to <config-patches@gnu.org>.
-#
-# Configuration subroutine to validate and canonicalize a configuration type.
-# Supply the specified configuration type as an argument.
-# If it is invalid, we print an error message on stderr and exit with code 1.
-# Otherwise, we print the canonical config type on stdout and succeed.
-
-# This file is supposed to be the same for all GNU packages
-# and recognize all the CPU types, system types and aliases
-# that are meaningful with *any* GNU software.
-# Each package is responsible for reporting which valid configurations
-# it does not support. The user should be able to distinguish
-# a failure to support a valid configuration from a meaningless
-# configuration.
-
-# The goal of this file is to map all the various variations of a given
-# machine specification into a single specification in the form:
-# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM
-# or in some cases, the newer four-part form:
-# CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM
-# It is wrong to echo any other type of specification.
-
-me=`echo "$0" | sed -e 's,.*/,,'`
-
-usage="\
-Usage: $0 [OPTION] CPU-MFR-OPSYS
- $0 [OPTION] ALIAS
-
-Canonicalize a configuration name.
-
-Operation modes:
- -h, --help print this help, then exit
- -t, --time-stamp print date of last modification, then exit
- -v, --version print version number, then exit
-
-Report bugs and patches to <config-patches@gnu.org>."
-
-version="\
-GNU config.sub ($timestamp)
-
-Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001
-Free Software Foundation, Inc.
-
-This is free software; see the source for copying conditions. There is NO
-warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
-
-help="
-Try \`$me --help' for more information."
-
-# Parse command line
-while test $# -gt 0 ; do
-case $1 in
- --time-stamp | --time* | -t )
- echo "$timestamp" ; exit 0 ;;
- --version | -v )
- echo "$version" ; exit 0 ;;
- --help | --h* | -h )
- echo "$usage"; exit 0 ;;
- -- ) # Stop option processing
- shift; break ;;
- - ) # Use stdin as input.
- break ;;
- -* )
- echo "$me: invalid option $1$help"
- exit 1 ;;
-
- *local*)
- # First pass through any local machine types.
- echo $1
- exit 0;;
-
- *)
- break ;;
- esac
-done
-
-case $# in
- 0) echo "$me: missing argument$help" >&2
- exit 1;;
- 1) ;;
- *) echo "$me: too many arguments$help" >&2
- exit 1;;
-esac
-
-# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any).
-# Here we must recognize all the valid KERNEL-OS combinations.
-maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'`
-case $maybe_os in
- nto-qnx* | linux-gnu* | linux-libc1 | storm-chaos* | os2-emx*)
- os=-$maybe_os
- basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`
- ;;
- *)
- basic_machine=`echo $1 | sed 's/-[^-]*$//'`
- if [ $basic_machine != $1 ]
- then os=`echo $1 | sed 's/.*-/-/'`
- else os=; fi
- ;;
-esac
-
-### Let's recognize common machines as not being operating systems so
-### that things like config.sub decstation-3100 work. We also
-### recognize some manufacturers as not being operating systems, so we
-### can provide default operating systems below.
-case $os in
- -sun*os*)
- # Prevent following clause from handling this invalid input.
- ;;
- -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \
- -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \
- -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \
- -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\
- -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \
- -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \
- -apple | -axis)
- os=
- basic_machine=$1
- ;;
- -sim | -cisco | -oki | -wec | -winbond)
- os=
- basic_machine=$1
- ;;
- -scout)
- ;;
- -wrs)
- os=-vxworks
- basic_machine=$1
- ;;
- -hiux*)
- os=-hiuxwe2
- ;;
- -sco5)
- os=-sco3.2v5
- basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
- ;;
- -sco4)
- os=-sco3.2v4
- basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
- ;;
- -sco3.2.[4-9]*)
- os=`echo $os | sed -e 's/sco3.2./sco3.2v/'`
- basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
- ;;
- -sco3.2v[4-9]*)
- # Don't forget version if it is 3.2v4 or newer.
- basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
- ;;
- -sco*)
- os=-sco3.2v2
- basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
- ;;
- -udk*)
- basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
- ;;
- -isc)
- os=-isc2.2
- basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
- ;;
- -clix*)
- basic_machine=clipper-intergraph
- ;;
- -isc*)
- basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
- ;;
- -lynx*)
- os=-lynxos
- ;;
- -ptx*)
- basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'`
- ;;
- -windowsnt*)
- os=`echo $os | sed -e 's/windowsnt/winnt/'`
- ;;
- -psos*)
- os=-psos
- ;;
- -mint | -mint[0-9]*)
- basic_machine=m68k-atari
- os=-mint
- ;;
-esac
-
-# Decode aliases for certain CPU-COMPANY combinations.
-case $basic_machine in
- # Recognize the basic CPU types without company name.
- # Some are omitted here because they have special meanings below.
- tahoe | i860 | ia64 | m32r | m68k | m68000 | m88k | ns32k | arc \
- | arm | arme[lb] | arm[bl]e | armv[2345] | armv[345][lb] | strongarm | xscale \
- | pyramid | mn10200 | mn10300 | tron | a29k \
- | 580 | i960 | h8300 \
- | x86 | ppcbe | mipsbe | mipsle | shbe | shle \
- | hppa | hppa1.0 | hppa1.1 | hppa2.0 | hppa2.0w | hppa2.0n \
- | hppa64 \
- | alpha | alphaev[4-8] | alphaev56 | alphapca5[67] \
- | alphaev6[78] \
- | we32k | ns16k | clipper | i370 | sh | sh[34] \
- | powerpc | powerpcle \
- | 1750a | dsp16xx | pdp10 | pdp11 \
- | mips16 | mips64 | mipsel | mips64el \
- | mips64orion | mips64orionel | mipstx39 | mipstx39el \
- | mips64vr4300 | mips64vr4300el | mips64vr4100 | mips64vr4100el \
- | mips64vr5000 | miprs64vr5000el | mcore | s390 | s390x \
- | sparc | sparclet | sparclite | sparc64 | sparcv9 | sparcv9b \
- | v850 | c4x \
- | thumb | d10v | d30v | fr30 | avr | openrisc | tic80 \
- | pj | pjl | h8500)
- basic_machine=$basic_machine-unknown
- ;;
- m6811 | m68hc11 | m6812 | m68hc12)
- # Motorola 68HC11/12.
- basic_machine=$basic_machine-unknown
- os=-none
- ;;
- m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | z8k | v70 | w65)
- ;;
-
- # We use `pc' rather than `unknown'
- # because (1) that's what they normally are, and
- # (2) the word "unknown" tends to confuse beginning users.
- i*86 | x86_64)
- basic_machine=$basic_machine-pc
- ;;
- # Object if more than one company name word.
- *-*-*)
- echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
- exit 1
- ;;
- # Recognize the basic CPU types with company name.
- # FIXME: clean up the formatting here.
- vax-* | tahoe-* | i*86-* | i860-* | ia64-* | m32r-* | m68k-* | m68000-* \
- | m88k-* | sparc-* | ns32k-* | fx80-* | arc-* | c[123]* \
- | arm-* | armbe-* | armle-* | armv*-* | strongarm-* | xscale-* \
- | mips-* | pyramid-* | tron-* | a29k-* | romp-* | rs6000-* \
- | power-* | none-* | 580-* | cray2-* | h8300-* | h8500-* | i960-* \
- | xmp-* | ymp-* \
- | x86-* | ppcbe-* | mipsbe-* | mipsle-* | shbe-* | shle-* \
- | hppa-* | hppa1.0-* | hppa1.1-* | hppa2.0-* | hppa2.0w-* \
- | hppa2.0n-* | hppa64-* \
- | alpha-* | alphaev[4-8]-* | alphaev56-* | alphapca5[67]-* \
- | alphaev6[78]-* \
- | we32k-* | cydra-* | ns16k-* | pn-* | np1-* | xps100-* \
- | clipper-* | orion-* \
- | sparclite-* | pdp10-* | pdp11-* | sh-* | powerpc-* | powerpcle-* \
- | sparc64-* | sparcv9-* | sparcv9b-* | sparc86x-* \
- | mips16-* | mips64-* | mipsel-* \
- | mips64el-* | mips64orion-* | mips64orionel-* \
- | mips64vr4100-* | mips64vr4100el-* | mips64vr4300-* | mips64vr4300el-* \
- | mipstx39-* | mipstx39el-* | mcore-* \
- | f30[01]-* | f700-* | s390-* | s390x-* | sv1-* | t3e-* \
- | [cjt]90-* \
- | m88110-* | m680[01234]0-* | m683?2-* | m68360-* | z8k-* | d10v-* \
- | thumb-* | v850-* | d30v-* | tic30-* | tic80-* | c30-* | fr30-* \
- | bs2000-* | tic54x-* | c54x-* | x86_64-* | pj-* | pjl-*)
- ;;
- # Recognize the various machine names and aliases which stand
- # for a CPU type and a company and sometimes even an OS.
- 386bsd)
- basic_machine=i386-unknown
- os=-bsd
- ;;
- 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc)
- basic_machine=m68000-att
- ;;
- 3b*)
- basic_machine=we32k-att
- ;;
- a29khif)
- basic_machine=a29k-amd
- os=-udi
- ;;
- adobe68k)
- basic_machine=m68010-adobe
- os=-scout
- ;;
- alliant | fx80)
- basic_machine=fx80-alliant
- ;;
- altos | altos3068)
- basic_machine=m68k-altos
- ;;
- am29k)
- basic_machine=a29k-none
- os=-bsd
- ;;
- amdahl)
- basic_machine=580-amdahl
- os=-sysv
- ;;
- amiga | amiga-*)
- basic_machine=m68k-unknown
- ;;
- amigaos | amigados)
- basic_machine=m68k-unknown
- os=-amigaos
- ;;
- amigaunix | amix)
- basic_machine=m68k-unknown
- os=-sysv4
- ;;
- apollo68)
- basic_machine=m68k-apollo
- os=-sysv
- ;;
- apollo68bsd)
- basic_machine=m68k-apollo
- os=-bsd
- ;;
- aux)
- basic_machine=m68k-apple
- os=-aux
- ;;
- balance)
- basic_machine=ns32k-sequent
- os=-dynix
- ;;
- convex-c1)
- basic_machine=c1-convex
- os=-bsd
- ;;
- convex-c2)
- basic_machine=c2-convex
- os=-bsd
- ;;
- convex-c32)
- basic_machine=c32-convex
- os=-bsd
- ;;
- convex-c34)
- basic_machine=c34-convex
- os=-bsd
- ;;
- convex-c38)
- basic_machine=c38-convex
- os=-bsd
- ;;
- cray | ymp)
- basic_machine=ymp-cray
- os=-unicos
- ;;
- cray2)
- basic_machine=cray2-cray
- os=-unicos
- ;;
- [cjt]90)
- basic_machine=${basic_machine}-cray
- os=-unicos
- ;;
- crds | unos)
- basic_machine=m68k-crds
- ;;
- cris | cris-* | etrax*)
- basic_machine=cris-axis
- ;;
- da30 | da30-*)
- basic_machine=m68k-da30
- ;;
- decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn)
- basic_machine=mips-dec
- ;;
- delta | 3300 | motorola-3300 | motorola-delta \
- | 3300-motorola | delta-motorola)
- basic_machine=m68k-motorola
- ;;
- delta88)
- basic_machine=m88k-motorola
- os=-sysv3
- ;;
- dpx20 | dpx20-*)
- basic_machine=rs6000-bull
- os=-bosx
- ;;
- dpx2* | dpx2*-bull)
- basic_machine=m68k-bull
- os=-sysv3
- ;;
- ebmon29k)
- basic_machine=a29k-amd
- os=-ebmon
- ;;
- elxsi)
- basic_machine=elxsi-elxsi
- os=-bsd
- ;;
- encore | umax | mmax)
- basic_machine=ns32k-encore
- ;;
- es1800 | OSE68k | ose68k | ose | OSE)
- basic_machine=m68k-ericsson
- os=-ose
- ;;
- fx2800)
- basic_machine=i860-alliant
- ;;
- genix)
- basic_machine=ns32k-ns
- ;;
- gmicro)
- basic_machine=tron-gmicro
- os=-sysv
- ;;
- go32)
- basic_machine=i386-pc
- os=-go32
- ;;
- h3050r* | hiux*)
- basic_machine=hppa1.1-hitachi
- os=-hiuxwe2
- ;;
- h8300hms)
- basic_machine=h8300-hitachi
- os=-hms
- ;;
- h8300xray)
- basic_machine=h8300-hitachi
- os=-xray
- ;;
- h8500hms)
- basic_machine=h8500-hitachi
- os=-hms
- ;;
- harris)
- basic_machine=m88k-harris
- os=-sysv3
- ;;
- hp300-*)
- basic_machine=m68k-hp
- ;;
- hp300bsd)
- basic_machine=m68k-hp
- os=-bsd
- ;;
- hp300hpux)
- basic_machine=m68k-hp
- os=-hpux
- ;;
- hp3k9[0-9][0-9] | hp9[0-9][0-9])
- basic_machine=hppa1.0-hp
- ;;
- hp9k2[0-9][0-9] | hp9k31[0-9])
- basic_machine=m68000-hp
- ;;
- hp9k3[2-9][0-9])
- basic_machine=m68k-hp
- ;;
- hp9k6[0-9][0-9] | hp6[0-9][0-9])
- basic_machine=hppa1.0-hp
- ;;
- hp9k7[0-79][0-9] | hp7[0-79][0-9])
- basic_machine=hppa1.1-hp
- ;;
- hp9k78[0-9] | hp78[0-9])
- # FIXME: really hppa2.0-hp
- basic_machine=hppa1.1-hp
- ;;
- hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893)
- # FIXME: really hppa2.0-hp
- basic_machine=hppa1.1-hp
- ;;
- hp9k8[0-9][13679] | hp8[0-9][13679])
- basic_machine=hppa1.1-hp
- ;;
- hp9k8[0-9][0-9] | hp8[0-9][0-9])
- basic_machine=hppa1.0-hp
- ;;
- hppa-next)
- os=-nextstep3
- ;;
- hppaosf)
- basic_machine=hppa1.1-hp
- os=-osf
- ;;
- hppro)
- basic_machine=hppa1.1-hp
- os=-proelf
- ;;
- i370-ibm* | ibm*)
- basic_machine=i370-ibm
- ;;
-# I'm not sure what "Sysv32" means. Should this be sysv3.2?
- i*86v32)
- basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
- os=-sysv32
- ;;
- i*86v4*)
- basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
- os=-sysv4
- ;;
- i*86v)
- basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
- os=-sysv
- ;;
- i*86sol2)
- basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
- os=-solaris2
- ;;
- i386mach)
- basic_machine=i386-mach
- os=-mach
- ;;
- i386-vsta | vsta)
- basic_machine=i386-unknown
- os=-vsta
- ;;
- iris | iris4d)
- basic_machine=mips-sgi
- case $os in
- -irix*)
- ;;
- *)
- os=-irix4
- ;;
- esac
- ;;
- isi68 | isi)
- basic_machine=m68k-isi
- os=-sysv
- ;;
- m88k-omron*)
- basic_machine=m88k-omron
- ;;
- magnum | m3230)
- basic_machine=mips-mips
- os=-sysv
- ;;
- merlin)
- basic_machine=ns32k-utek
- os=-sysv
- ;;
- mingw32)
- basic_machine=i386-pc
- os=-mingw32
- ;;
- miniframe)
- basic_machine=m68000-convergent
- ;;
- *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*)
- basic_machine=m68k-atari
- os=-mint
- ;;
- mipsel*-linux*)
- basic_machine=mipsel-unknown
- os=-linux
- ;;
- mips*-linux*)
- basic_machine=mips-unknown
- os=-linux
- ;;
- mips3*-*)
- basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`
- ;;
- mips3*)
- basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown
- ;;
- mmix*)
- basic_machine=mmix-knuth
- os=-mmixware
- ;;
- monitor)
- basic_machine=m68k-rom68k
- os=-coff
- ;;
- msdos)
- basic_machine=i386-pc
- os=-msdos
- ;;
- mvs)
- basic_machine=i370-ibm
- os=-mvs
- ;;
- ncr3000)
- basic_machine=i486-ncr
- os=-sysv4
- ;;
- netbsd386)
- basic_machine=i386-unknown
- os=-netbsd
- ;;
- netwinder)
- basic_machine=armv4l-rebel
- os=-linux
- ;;
- news | news700 | news800 | news900)
- basic_machine=m68k-sony
- os=-newsos
- ;;
- news1000)
- basic_machine=m68030-sony
- os=-newsos
- ;;
- news-3600 | risc-news)
- basic_machine=mips-sony
- os=-newsos
- ;;
- necv70)
- basic_machine=v70-nec
- os=-sysv
- ;;
- next | m*-next )
- basic_machine=m68k-next
- case $os in
- -nextstep* )
- ;;
- -ns2*)
- os=-nextstep2
- ;;
- *)
- os=-nextstep3
- ;;
- esac
- ;;
- nh3000)
- basic_machine=m68k-harris
- os=-cxux
- ;;
- nh[45]000)
- basic_machine=m88k-harris
- os=-cxux
- ;;
- nindy960)
- basic_machine=i960-intel
- os=-nindy
- ;;
- mon960)
- basic_machine=i960-intel
- os=-mon960
- ;;
- nonstopux)
- basic_machine=mips-compaq
- os=-nonstopux
- ;;
- np1)
- basic_machine=np1-gould
- ;;
- nsr-tandem)
- basic_machine=nsr-tandem
- ;;
- op50n-* | op60c-*)
- basic_machine=hppa1.1-oki
- os=-proelf
- ;;
- OSE68000 | ose68000)
- basic_machine=m68000-ericsson
- os=-ose
- ;;
- os68k)
- basic_machine=m68k-none
- os=-os68k
- ;;
- pa-hitachi)
- basic_machine=hppa1.1-hitachi
- os=-hiuxwe2
- ;;
- paragon)
- basic_machine=i860-intel
- os=-osf
- ;;
- pbd)
- basic_machine=sparc-tti
- ;;
- pbb)
- basic_machine=m68k-tti
- ;;
- pc532 | pc532-*)
- basic_machine=ns32k-pc532
- ;;
- pentium | p5 | k5 | k6 | nexgen)
- basic_machine=i586-pc
- ;;
- pentiumpro | p6 | 6x86 | athlon)
- basic_machine=i686-pc
- ;;
- pentiumii | pentium2)
- basic_machine=i686-pc
- ;;
- pentium-* | p5-* | k5-* | k6-* | nexgen-*)
- basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- pentiumpro-* | p6-* | 6x86-* | athlon-*)
- basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- pentiumii-* | pentium2-*)
- basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- pn)
- basic_machine=pn-gould
- ;;
- power) basic_machine=power-ibm
- ;;
- ppc) basic_machine=powerpc-unknown
- ;;
- ppc-*) basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- ppcle | powerpclittle | ppc-le | powerpc-little)
- basic_machine=powerpcle-unknown
- ;;
- ppcle-* | powerpclittle-*)
- basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- ps2)
- basic_machine=i386-ibm
- ;;
- pw32)
- basic_machine=i586-unknown
- os=-pw32
- ;;
- rom68k)
- basic_machine=m68k-rom68k
- os=-coff
- ;;
- rm[46]00)
- basic_machine=mips-siemens
- ;;
- rtpc | rtpc-*)
- basic_machine=romp-ibm
- ;;
- sa29200)
- basic_machine=a29k-amd
- os=-udi
- ;;
- sequent)
- basic_machine=i386-sequent
- ;;
- sh)
- basic_machine=sh-hitachi
- os=-hms
- ;;
- sparclite-wrs)
- basic_machine=sparclite-wrs
- os=-vxworks
- ;;
- sps7)
- basic_machine=m68k-bull
- os=-sysv2
- ;;
- spur)
- basic_machine=spur-unknown
- ;;
- st2000)
- basic_machine=m68k-tandem
- ;;
- stratus)
- basic_machine=i860-stratus
- os=-sysv4
- ;;
- sun2)
- basic_machine=m68000-sun
- ;;
- sun2os3)
- basic_machine=m68000-sun
- os=-sunos3
- ;;
- sun2os4)
- basic_machine=m68000-sun
- os=-sunos4
- ;;
- sun3os3)
- basic_machine=m68k-sun
- os=-sunos3
- ;;
- sun3os4)
- basic_machine=m68k-sun
- os=-sunos4
- ;;
- sun4os3)
- basic_machine=sparc-sun
- os=-sunos3
- ;;
- sun4os4)
- basic_machine=sparc-sun
- os=-sunos4
- ;;
- sun4sol2)
- basic_machine=sparc-sun
- os=-solaris2
- ;;
- sun3 | sun3-*)
- basic_machine=m68k-sun
- ;;
- sun4)
- basic_machine=sparc-sun
- ;;
- sun386 | sun386i | roadrunner)
- basic_machine=i386-sun
- ;;
- sv1)
- basic_machine=sv1-cray
- os=-unicos
- ;;
- symmetry)
- basic_machine=i386-sequent
- os=-dynix
- ;;
- t3e)
- basic_machine=t3e-cray
- os=-unicos
- ;;
- tic54x | c54x*)
- basic_machine=tic54x-unknown
- os=-coff
- ;;
- tx39)
- basic_machine=mipstx39-unknown
- ;;
- tx39el)
- basic_machine=mipstx39el-unknown
- ;;
- tower | tower-32)
- basic_machine=m68k-ncr
- ;;
- udi29k)
- basic_machine=a29k-amd
- os=-udi
- ;;
- ultra3)
- basic_machine=a29k-nyu
- os=-sym1
- ;;
- v810 | necv810)
- basic_machine=v810-nec
- os=-none
- ;;
- vaxv)
- basic_machine=vax-dec
- os=-sysv
- ;;
- vms)
- basic_machine=vax-dec
- os=-vms
- ;;
- vpp*|vx|vx-*)
- basic_machine=f301-fujitsu
- ;;
- vxworks960)
- basic_machine=i960-wrs
- os=-vxworks
- ;;
- vxworks68)
- basic_machine=m68k-wrs
- os=-vxworks
- ;;
- vxworks29k)
- basic_machine=a29k-wrs
- os=-vxworks
- ;;
- w65*)
- basic_machine=w65-wdc
- os=-none
- ;;
- w89k-*)
- basic_machine=hppa1.1-winbond
- os=-proelf
- ;;
- xmp)
- basic_machine=xmp-cray
- os=-unicos
- ;;
- xps | xps100)
- basic_machine=xps100-honeywell
- ;;
- z8k-*-coff)
- basic_machine=z8k-unknown
- os=-sim
- ;;
- none)
- basic_machine=none-none
- os=-none
- ;;
-
-# Here we handle the default manufacturer of certain CPU types. It is in
-# some cases the only manufacturer, in others, it is the most popular.
- w89k)
- basic_machine=hppa1.1-winbond
- ;;
- op50n)
- basic_machine=hppa1.1-oki
- ;;
- op60c)
- basic_machine=hppa1.1-oki
- ;;
- mips)
- if [ x$os = x-linux ]; then
- basic_machine=mips-unknown
- else
- basic_machine=mips-mips
- fi
- ;;
- romp)
- basic_machine=romp-ibm
- ;;
- rs6000)
- basic_machine=rs6000-ibm
- ;;
- vax)
- basic_machine=vax-dec
- ;;
- pdp10)
- # there are many clones, so DEC is not a safe bet
- basic_machine=pdp10-unknown
- ;;
- pdp11)
- basic_machine=pdp11-dec
- ;;
- we32k)
- basic_machine=we32k-att
- ;;
- sh3 | sh4)
- basic_machine=sh-unknown
- ;;
- sparc | sparcv9 | sparcv9b)
- basic_machine=sparc-sun
- ;;
- cydra)
- basic_machine=cydra-cydrome
- ;;
- orion)
- basic_machine=orion-highlevel
- ;;
- orion105)
- basic_machine=clipper-highlevel
- ;;
- mac | mpw | mac-mpw)
- basic_machine=m68k-apple
- ;;
- pmac | pmac-mpw)
- basic_machine=powerpc-apple
- ;;
- c4x*)
- basic_machine=c4x-none
- os=-coff
- ;;
- *-unknown)
- # Make sure to match an already-canonicalized machine name.
- ;;
- *)
- echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
- exit 1
- ;;
-esac
-
-# Here we canonicalize certain aliases for manufacturers.
-case $basic_machine in
- *-digital*)
- basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'`
- ;;
- *-commodore*)
- basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'`
- ;;
- *)
- ;;
-esac
-
-# Decode manufacturer-specific aliases for certain operating systems.
-
-if [ x"$os" != x"" ]
-then
-case $os in
- # First match some system type aliases
- # that might get confused with valid system types.
- # -solaris* is a basic system type, with this one exception.
- -solaris1 | -solaris1.*)
- os=`echo $os | sed -e 's|solaris1|sunos4|'`
- ;;
- -solaris)
- os=-solaris2
- ;;
- -svr4*)
- os=-sysv4
- ;;
- -unixware*)
- os=-sysv4.2uw
- ;;
- -gnu/linux*)
- os=`echo $os | sed -e 's|gnu/linux|linux|'`
- ;;
- # First accept the basic system types.
- # The portable systems comes first.
- # Each alternative MUST END IN A *, to match a version number.
- # -sysv* is not here because it comes later, after sysvr4.
- -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \
- | -*vms* | -sco* | -esix* | -isc* | -aix* | -sunos | -sunos[34]*\
- | -hpux* | -unos* | -osf* | -luna* | -dgux* | -solaris* | -sym* \
- | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \
- | -aos* \
- | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
- | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \
- | -hiux* | -386bsd* | -netbsd* | -openbsd* | -freebsd* | -riscix* \
- | -lynxos* | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
- | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \
- | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \
- | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
- | -mingw32* | -linux* | -uxpv* | -beos* | -mpeix* | -udk* \
- | -interix* | -uwin* | -rhapsody* | -darwin* | -opened* \
- | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \
- | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* | -os2*)
- # Remember, each alternative MUST END IN *, to match a version number.
- ;;
- -qnx*)
- case $basic_machine in
- x86-* | i*86-*)
- ;;
- *)
- os=-nto$os
- ;;
- esac
- ;;
- -nto*)
- os=-nto-qnx
- ;;
- -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \
- | -windows* | -osx | -abug | -netware* | -os9* | -beos* \
- | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*)
- ;;
- -mac*)
- os=`echo $os | sed -e 's|mac|macos|'`
- ;;
- -sunos5*)
- os=`echo $os | sed -e 's|sunos5|solaris2|'`
- ;;
- -sunos6*)
- os=`echo $os | sed -e 's|sunos6|solaris3|'`
- ;;
- -opened*)
- os=-openedition
- ;;
- -wince*)
- os=-wince
- ;;
- -osfrose*)
- os=-osfrose
- ;;
- -osf*)
- os=-osf
- ;;
- -utek*)
- os=-bsd
- ;;
- -dynix*)
- os=-bsd
- ;;
- -acis*)
- os=-aos
- ;;
- -386bsd)
- os=-bsd
- ;;
- -ctix* | -uts*)
- os=-sysv
- ;;
- -ns2 )
- os=-nextstep2
- ;;
- -nsk*)
- os=-nsk
- ;;
- # Preserve the version number of sinix5.
- -sinix5.*)
- os=`echo $os | sed -e 's|sinix|sysv|'`
- ;;
- -sinix*)
- os=-sysv4
- ;;
- -triton*)
- os=-sysv3
- ;;
- -oss*)
- os=-sysv3
- ;;
- -svr4)
- os=-sysv4
- ;;
- -svr3)
- os=-sysv3
- ;;
- -sysvr4)
- os=-sysv4
- ;;
- # This must come after -sysvr4.
- -sysv*)
- ;;
- -ose*)
- os=-ose
- ;;
- -es1800*)
- os=-ose
- ;;
- -xenix)
- os=-xenix
- ;;
- -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
- os=-mint
- ;;
- -uxpds)
- os=-uxpds
- ;;
- -human)
- ;;
- -beos)
- os=-beos
- ;;
- -none)
- ;;
- *)
- # Get rid of the `-' at the beginning of $os.
- os=`echo $os | sed 's/[^-]*-//'`
- echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2
- exit 1
- ;;
-esac
-else
-
-# Here we handle the default operating systems that come with various machines.
-# The value should be what the vendor currently ships out the door with their
-# machine or put another way, the most popular os provided with the machine.
-
-# Note that if you're going to try to match "-MANUFACTURER" here (say,
-# "-sun"), then you have to tell the case statement up towards the top
-# that MANUFACTURER isn't an operating system. Otherwise, code above
-# will signal an error saying that MANUFACTURER isn't an operating
-# system, and we'll never get to this point.
-
-case $basic_machine in
- *-acorn)
- os=-riscix1.2
- ;;
- arm*-rebel)
- os=-linux
- ;;
- arm*-semi)
- os=-aout
- ;;
- pdp10-*)
- os=-tops20
- ;;
- pdp11-*)
- os=-none
- ;;
- *-dec | vax-*)
- os=-ultrix4.2
- ;;
- m68*-apollo)
- os=-domain
- ;;
- i386-sun)
- os=-sunos4.0.2
- ;;
- m68000-sun)
- os=-sunos3
- # This also exists in the configure program, but was not the
- # default.
- # os=-sunos4
- ;;
- m68*-cisco)
- os=-aout
- ;;
- mips*-cisco)
- os=-elf
- ;;
- mips*-*)
- os=-elf
- ;;
- *-tti) # must be before sparc entry or we get the wrong os.
- os=-sysv3
- ;;
- sparc-* | *-sun)
- os=-sunos4.1.1
- ;;
- *-be)
- os=-beos
- ;;
- *-ibm)
- os=-aix
- ;;
- *-wec)
- os=-proelf
- ;;
- *-winbond)
- os=-proelf
- ;;
- *-oki)
- os=-proelf
- ;;
- *-hp)
- os=-hpux
- ;;
- *-hitachi)
- os=-hiux
- ;;
- i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent)
- os=-sysv
- ;;
- *-cbm)
- os=-amigaos
- ;;
- *-dg)
- os=-dgux
- ;;
- *-dolphin)
- os=-sysv3
- ;;
- m68k-ccur)
- os=-rtu
- ;;
- m88k-omron*)
- os=-luna
- ;;
- *-next )
- os=-nextstep
- ;;
- *-sequent)
- os=-ptx
- ;;
- *-crds)
- os=-unos
- ;;
- *-ns)
- os=-genix
- ;;
- i370-*)
- os=-mvs
- ;;
- *-next)
- os=-nextstep3
- ;;
- *-gould)
- os=-sysv
- ;;
- *-highlevel)
- os=-bsd
- ;;
- *-encore)
- os=-bsd
- ;;
- *-sgi)
- os=-irix
- ;;
- *-siemens)
- os=-sysv4
- ;;
- *-masscomp)
- os=-rtu
- ;;
- f30[01]-fujitsu | f700-fujitsu)
- os=-uxpv
- ;;
- *-rom68k)
- os=-coff
- ;;
- *-*bug)
- os=-coff
- ;;
- *-apple)
- os=-macos
- ;;
- *-atari*)
- os=-mint
- ;;
- *)
- os=-none
- ;;
-esac
-fi
-
-# Here we handle the case where we know the os, and the CPU type, but not the
-# manufacturer. We pick the logical manufacturer.
-vendor=unknown
-case $basic_machine in
- *-unknown)
- case $os in
- -riscix*)
- vendor=acorn
- ;;
- -sunos*)
- vendor=sun
- ;;
- -aix*)
- vendor=ibm
- ;;
- -beos*)
- vendor=be
- ;;
- -hpux*)
- vendor=hp
- ;;
- -mpeix*)
- vendor=hp
- ;;
- -hiux*)
- vendor=hitachi
- ;;
- -unos*)
- vendor=crds
- ;;
- -dgux*)
- vendor=dg
- ;;
- -luna*)
- vendor=omron
- ;;
- -genix*)
- vendor=ns
- ;;
- -mvs* | -opened*)
- vendor=ibm
- ;;
- -ptx*)
- vendor=sequent
- ;;
- -vxsim* | -vxworks*)
- vendor=wrs
- ;;
- -aux*)
- vendor=apple
- ;;
- -hms*)
- vendor=hitachi
- ;;
- -mpw* | -macos*)
- vendor=apple
- ;;
- -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
- vendor=atari
- ;;
- esac
- basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"`
- ;;
-esac
-
-echo $basic_machine$os
-exit 0
-
-# Local variables:
-# eval: (add-hook 'write-file-hooks 'time-stamp)
-# time-stamp-start: "timestamp='"
-# time-stamp-format: "%:y-%02m-%02d"
-# time-stamp-end: "'"
-# End:
diff --git a/configure.in b/configure.in
deleted file mode 100644
index d7c6c290d5..0000000000
--- a/configure.in
+++ /dev/null
@@ -1,1120 +0,0 @@
-dnl Process this file with autoconf to produce a configure script.
-AC_INIT(ruby.h)
-
-AC_PREREQ(2.50)
-
-rb_version=`grep RUBY_VERSION $srcdir/version.h`
-MAJOR=`expr "$rb_version" : '#define RUBY_VERSION "\([0-9][0-9]*\)\.[0-9][0-9]*\.[0-9][0-9]*"'`
-MINOR=`expr "$rb_version" : '#define RUBY_VERSION "[0-9][0-9]*\.\([0-9][0-9]*\)\.[0-9][0-9]*"'`
-TEENY=`expr "$rb_version" : '#define RUBY_VERSION "[0-9][0-9]*\.[0-9][0-9]*\.\([0-9][0-9]*\)"'`
-AC_SUBST(MAJOR)
-AC_SUBST(MINOR)
-AC_SUBST(TEENY)
-dnl checks for alternative programs
-AC_ARG_WITH(gcc, [--without-gcc never use gcc], [
- case $withval in
- no) : ${CC=cc}
- ;;
- yes) : ${CC=gcc}
- ;;
- *) CC=$withval
- ;;
- esac])
-dnl If the user switches compilers, we can't believe the cache
-if test ! -z "$ac_cv_prog_CC" -a ! -z "$CC" -a "$CC" != "$ac_cv_prog_CC"
-then
- AC_ERROR(cached CC is different -- throw away $cache_file
-(it is also a good idea to do 'make clean' before compiling))
-fi
-
-AC_DEFUN(RUBY_CANONICAL_BUILD, [AC_REQUIRE([AC_CANONICAL_BUILD])])
-
-AC_CANONICAL_HOST
-AC_CANONICAL_TARGET
-RUBY_CANONICAL_BUILD
-
-dnl checks for fat-binary
-fat_binary=no
-AC_ARG_ENABLE(fat-binary,
- [--enable-fat-binary build a NeXT/Apple Multi Architecture Binary. ],
- [fat_binary=$enableval])
- if test "$fat_binary" = yes ; then
-
- AC_MSG_CHECKING(target architecture)
-
- case "$target_os" in
- rhapsody*)
- echo -n "MacOS X Server: "
- if test "$TARGET_ARCHS" = "" ; then
- TARGET_ARCHS="ppc i386"
- fi
- ;;
- nextstep*|openstep*)
- echo -n "NeXTSTEP/OPENSTEP: "
- if test "$TARGET_ARCHS" = "" ; then
- if test `/usr/bin/arch` = "m68k" ; then
- TARGET_ARCHS="m68k i486"
- else # Black and Native one
- TARGET_ARCHS="m68k `/usr/bin/arch`"
- fi
- fi
- # to ensure AC_HEADER_SYS_WAIT works
- AC_DEFINE(_POSIX_SOURCE)
- ;;
- macos*|darwin*)
- echo -n "MacOS X (Darwin): "
- if test "$TARGET_ARCHS" = "" ; then
- TARGET_ARCHS="ppc i386"
- fi
- ;;
- esac
- # /usr/lib/arch_tool -archify_list $TARGET_ARCHS
- for archs in $TARGET_ARCHS
- do
- ARCH_FLAG="$ARCH_FLAG -arch $archs "
- echo -n " $archs"
- done
- AC_DEFINE(NEXT_FAT_BINARY)
- echo "."
-fi
-
-case $target_cpu in
- i?86) frame_address=yes;;
- *) frame_address=no;;
-esac
-AC_ARG_ENABLE(frame-address,
- [--enable-frame-address use GCC __builtin_frame_address(). ],
- [frame_address=$enableval])
-if test $frame_address = yes; then
- AC_DEFINE(USE_BUILTIN_FRAME_ADDRESS)
-fi
-
-AC_ARG_PROGRAM
-
-dnl Checks for programs.
-
-if test x"${build}" != x"${host}"; then
- AC_CHECK_TOOL(CC, gcc)
-fi
-AC_PROG_CC
-AC_PROG_GCC_TRADITIONAL
-
-AC_PROG_YACC
-AC_CHECK_TOOL(RANLIB, ranlib, :)
-AC_CHECK_TOOL(AR, ar)
-AC_CHECK_PROGS(AR, ar aal, ar)
-
-case "$target_os" in
-cygwin*|mingw*)
- AC_CHECK_TOOL(NM, nm)
- AC_CHECK_TOOL(DLLWRAP, dllwrap)
- AC_CHECK_TOOL(AS, as)
- AC_CHECK_TOOL(DLLTOOL, dlltool)
- AC_CHECK_TOOL(WINDRES, windres)
- target_cpu=`echo $target_cpu | sed s/i.86/i386/`
- : ${enable_shared=yes}
- ;;
-esac
-
-AC_PROG_LN_S
-AC_PROG_MAKE_SET
-
-# checks for UNIX variants that set C preprocessor variables
-AC_AIX
-AC_MINIX
-
-AC_EXEEXT
-AC_OBJEXT
-
-dnl check for large file stuff
-AC_SYS_LARGEFILE
-
-AC_CHECK_TYPES([long long, off_t])
-AC_CHECK_SIZEOF(int, 4)
-AC_CHECK_SIZEOF(short, 2)
-AC_CHECK_SIZEOF(long, 4)
-AC_CHECK_SIZEOF(long long, 0)
-AC_CHECK_SIZEOF(__int64, 0)
-AC_CHECK_SIZEOF(off_t, 0)
-AC_CHECK_SIZEOF(void*, 4)
-AC_CHECK_SIZEOF(float, 4)
-AC_CHECK_SIZEOF(double, 8)
-
-AC_CACHE_CHECK(for prototypes, rb_cv_have_prototypes,
- [AC_TRY_COMPILE([int foo(int x) { return 0; }], [return foo(10);],
- rb_cv_have_prototypes=yes,
- rb_cv_have_prototypes=no)])
-if test "$rb_cv_have_prototypes" = yes; then
- AC_DEFINE(HAVE_PROTOTYPES)
-fi
-
-AC_CACHE_CHECK(token paste string, rb_cv_tokenpaste,
- [AC_TRY_COMPILE([#define paste(a,b) a##b],
- [int xy = 1; return paste(x,y);],
- rb_cv_tokenpaste=ansi,
- rb_cv_tokenpaste=knr)])
-if test "$rb_cv_tokenpaste" = ansi; then
- AC_DEFINE(TOKEN_PASTE(x,y),[x##y])
-else
- AC_DEFINE(TOKEN_PASTE(x,y),[x/**/y])
-fi
-
-AC_CACHE_CHECK(for variable length prototypes and stdarg.h, rb_cv_stdarg,
- [AC_TRY_COMPILE([
-#include <stdarg.h>
-int foo(int x, ...) {
- va_list va;
- va_start(va, x);
- va_arg(va, int);
- va_arg(va, char *);
- va_arg(va, double);
- return 0;
-}
-], [return foo(10, "", 3.14);],
- rb_cv_stdarg=yes,
- rb_cv_stdarg=no)])
-if test "$rb_cv_stdarg" = yes; then
- AC_DEFINE(HAVE_STDARG_PROTOTYPES)
-fi
-
-AC_CACHE_CHECK([for noreturn], rb_cv_noreturn,
-[rb_cv_noreturn=no
-for mac in "x __attribute__ ((noreturn))" "__declspec(noreturn) x" x; do
- AC_TRY_COMPILE(
- [#define NORETURN(x) $mac
-NORETURN(void exit(int x));],
- [],
- [rb_cv_noreturn="$mac"; break])
-done])
-AC_DEFINE_UNQUOTED([NORETURN(x)], $rb_cv_noreturn)
-
-
-dnl wheather link libc_r or not
-AC_ARG_WITH(libc_r,
- [--with-libc_r link libc_r if possible (FreeBSD only)], [
- case $withval in
- yes) with_libc_r=yes;;
- *) with_libc_r=no;;
- esac], [with_libc_r=no])
-
-dnl Checks for libraries.
-case "$target_os" in
-nextstep*) ;;
-openstep*) ;;
-rhapsody*) ;;
-darwin*) LIBS="-lobjc $LIBS";;
-human*) ac_cv_func_getpgrp_void=yes;;
-beos*) ;;
-cygwin*) rb_cv_have_daylight=no
- ac_cv_var_tzname=no;;
-mingw*) LIBS="-lwsock32 -lmsvcrt $LIBS"
- ac_cv_header_a_out_h=no
- ac_cv_header_pwd_h=no
- ac_cv_header_utime_h=no
- ac_cv_header_sys_ioctl_h=no
- ac_cv_header_sys_param_h=no
- ac_cv_header_sys_resource_h=no
- ac_cv_header_sys_select_h=no
- ac_cv_header_sys_times_h=no
- ac_cv_func_times=yes
- ac_cv_func_waitpid=yes;;
-os2_emx*) LIBS="-lm $LIBS"
- ac_cv_lib_dir_opendir=no;;
-msdosdjgpp*) LIBS="-lm $LIBS"
- ac_cv_func_getpgrp_void=yes;;
-freebsd*) LIBS="-lm $LIBS"
- AC_CACHE_CHECK([whether -lxpg4 has to be linked],
- rb_cv_lib_xpg4_needed,
- [AC_TRY_CPP([
-#include <osreldate.h>
-#if __FreeBSD_version < 400020 || \
- (__FreeBSD_version >= 500000 && __FreeBSD_version < 500005)
-#error needs libxpg4
-#endif
- ],
- rb_cv_lib_xpg4_needed=no,
- rb_cv_lib_xpg4_needed=yes,
- rb_cv_lib_xpg4_needed=yes)])
- if test "$rb_cv_lib_xpg4_needed" = yes; then
- AC_CHECK_LIB(xpg4, setlocale)
- fi
- if test "$with_libc_r" = yes; then
- AC_CACHE_CHECK([whether libc_r is supplementary to libc],
- rb_cv_supplementary_lib_c_r,
- [AC_TRY_CPP([
-#include <osreldate.h>
-#if 500016 <= __FreeBSD_version
-#error libc_r is supplementary to libc
-#endif
- ],
- rb_cv_supplementary_lib_c_r=no,
- rb_cv_supplementary_lib_c_r=yes,
- rb_cv_supplementary_lib_c_r=yes)])
- if test "$rb_cv_supplementary_lib_c_r" = yes; then
- MAINLIBS="-lc_r $MAINLIBS"
- else
- MAINLIBS="-pthread $MAINLIBS"
- CFLAGS="-D_THREAD_SAFE $CFLAGS"
- fi
- fi
- ;;
-linux*) LIBS="-lm $LIBS"
- case "$target_cpu" in
- alpha*)
- CFLAGS="-mieee $CFLAGS" ;;
- esac ;;
-osf*) LIBS="-lm $LIBS"
- case "$target_cpu"::"$GCC" in
- alpha*::yes)
- CFLAGS="-mieee $CFLAGS" ;;
- alpha*::no|alpha*::)
- CFLAGS="-ieee $CFLAGS" ;;
- esac ;;
-*) LIBS="-lm $LIBS";;
-esac
-AC_CHECK_LIB(crypt, crypt)
-AC_CHECK_LIB(dl, dlopen) # Dynamic linking for SunOS/Solaris and SYSV
-AC_CHECK_LIB(dld, shl_load) # Dynamic linking for HP-UX
-
-dnl Checks for header files.
-AC_HEADER_DIRENT
-AC_HEADER_STDC
-AC_HEADER_SYS_WAIT
-AC_CHECK_HEADERS(stdlib.h string.h unistd.h limits.h sys/file.h sys/ioctl.h\
- fcntl.h sys/fcntl.h sys/select.h sys/time.h sys/times.h sys/param.h\
- syscall.h pwd.h a.out.h utime.h memory.h direct.h sys/resource.h \
- sys/mkdev.h)
-
-dnl Checks for typedefs, structures, and compiler characteristics.
-AC_TYPE_UID_T
-AC_TYPE_SIZE_T
-AC_STRUCT_ST_BLKSIZE
-AC_STRUCT_ST_BLOCKS
-AC_STRUCT_ST_RDEV
-
-dnl Checks for library functions.
-AC_TYPE_GETGROUPS
-AC_TYPE_SIGNAL
-AC_FUNC_ALLOCA
-AC_FUNC_MEMCMP
-AC_FUNC_FSEEKO
-AC_CHECK_FUNCS(ftello)
-AC_REPLACE_FUNCS(dup2 memmove mkdir strcasecmp strncasecmp strerror strftime\
- strchr strstr strtoul crypt flock vsnprintf\
- isinf isnan finite hypot)
-AC_CHECK_FUNCS(fmod killpg drand48 random wait4 waitpid syscall chroot fsync\
- truncate chsize times utimes fcntl lockf lstat symlink readlink\
- setitimer setruid seteuid setreuid setresuid setproctitle\
- setrgid setegid setregid setresgid pause lchown lchmod\
- getpgrp setpgrp getpgid setpgid getgroups getpriority getrlimit\
- dlopen sigprocmask sigaction _setjmp setsid telldir seekdir fchmod\
- mktime timegm)
-AC_STRUCT_TIMEZONE
-AC_CACHE_CHECK(for struct tm.tm_gmtoff, rb_cv_member_struct_tm_tm_gmtoff,
- [AC_TRY_COMPILE([#include <time.h>],
- [struct tm t; t.tm_gmtoff = 3600;],
- [rb_cv_member_struct_tm_tm_gmtoff=yes],
- [rb_cv_member_struct_tm_tm_gmtoff=no])])
-if test "$rb_cv_member_struct_tm_tm_gmtoff" = yes; then
- AC_DEFINE(HAVE_STRUCT_TM_TM_GMTOFF)
-fi
-AC_CACHE_CHECK(for external int daylight, rb_cv_have_daylight,
- [AC_TRY_LINK([#include <time.h>
- int i;],
- [i = daylight;],
- rb_cv_have_daylight=yes,
- rb_cv_have_daylight=no)])
-if test "$rb_cv_have_daylight" = yes; then
- AC_DEFINE(HAVE_DAYLIGHT)
-fi
-AC_CACHE_CHECK(for negative time_t for gmtime(3), rb_cv_negative_time_t,
- [AC_TRY_RUN([
-#include <time.h>
-
-void
-check(tm, y, m, d, h, s)
- struct tm *tm;
- int y, m, d, h, s;
-{
- if (!tm ||
- tm->tm_year != y ||
- tm->tm_mon != m-1 ||
- tm->tm_mday != d ||
- tm->tm_hour != h ||
- tm->tm_sec != s) {
- exit(1);
- }
-}
-
-int
-main()
-{
- time_t t = -1;
- struct tm *tm;
-
- check(gmtime(&t), 69, 12, 31, 23, 59);
- t = ~(time_t)0 << 31;
- check(gmtime(&t), 1, 12, 13, 20, 52);
- return 0;
-}
-],
- rb_cv_negative_time_t=yes,
- rb_cv_negative_time_t=no,
- rb_cv_negative_time_t=yes)])
-if test "$rb_cv_negative_time_t" = yes; then
- AC_DEFINE(NEGATIVE_TIME_T)
-fi
-
-if test "$ac_cv_func_sigprocmask" = yes && test "$ac_cv_func_sigaction" = yes; then
- AC_DEFINE(POSIX_SIGNAL)
-else
- AC_CACHE_CHECK(for BSD signal semantics, rb_cv_bsd_signal,
- [AC_TRY_RUN([
-#include <stdio.h>
-#include <signal.h>
-
-void
-sig_handler(dummy)
- int dummy;
-{
-}
-
-int
-main()
-{
- signal(SIGINT, sig_handler);
- kill(getpid(), SIGINT);
- kill(getpid(), SIGINT);
- return 0;
-}
-],
- rb_cv_bsd_signal=yes,
- rb_cv_bsd_signal=no,
- rb_cv_bsd_signal=no)])
- if test "$rb_cv_bsd_signal" = yes; then
- AC_DEFINE(BSD_SIGNAL)
- fi
-fi
-
-AC_FUNC_GETPGRP
-AC_FUNC_SETPGRP
-
-AC_CACHE_CHECK(for working strtod, rb_cv_func_strtod,
-[AC_TRY_RUN([
-double strtod ();
-int
-main()
-{
- {
- /* Some versions of Linux strtod mis-parse strings with leading '+'. */
- char *string = " +69";
- char *term;
- double value;
- value = strtod(string, &term);
- if (value != 69 || term != (string + 4))
- exit(1);
- }
-
- {
- /* Under Solaris 2.4, strtod returns the wrong value for the
- terminating character under some conditions. */
- char *string = "NaN";
- char *term;
- strtod(string, &term);
- if (term != string && *(term - 1) == 0)
- exit(1);
- }
- exit(0);
-}
-], rb_cv_func_strtod=yes, rb_cv_func_strtod=no, rb_cv_func_strtod=no)])
-test $rb_cv_func_strtod = no && AC_LIBOBJ([strtod])
-
-AC_C_BIGENDIAN
-AC_C_CONST
-AC_C_CHAR_UNSIGNED
-AC_C_INLINE
-
-AC_CACHE_CHECK(whether right shift preserve sign bit, rb_cv_rshift_sign,
- [AC_TRY_RUN([
-int
-main()
-{
- if (-1==(-1>>1))
- return 0;
- return 1;
-}
-],
- rb_cv_rshift_sign=yes,
- rb_cv_rshift_sign=no,
- rb_cv_rshift_sign=yes)])
-if test "$rb_cv_rshift_sign" = yes; then
- AC_DEFINE(RSHIFT(x,y), ((x)>>(int)y))
-else
- AC_DEFINE(RSHIFT(x,y), (((x)<0) ? ~((~(x))>>y) : (x)>>y))
-fi
-
-AC_MSG_CHECKING(count field in FILE structures)
-AC_CACHE_VAL(rb_cv_fcnt,
-[AC_TRY_COMPILE([#include <stdio.h>],
- [FILE *f = stdin; f->_cnt = 0;], rb_cv_fcnt="_cnt", )
-if test "$rb_cv_fcnt" = ""; then
- AC_TRY_COMPILE([#include <stdio.h>],
- [FILE *f = stdin; f->__cnt = 0;], rb_cv_fcnt="__cnt", )
-fi
-if test "$rb_cv_fcnt" = ""; then
- AC_TRY_COMPILE([#include <stdio.h>],
- [FILE *f = stdin; f->_r = 0;], rb_cv_fcnt="_r", )
-fi
-if test "$rb_cv_fcnt" = ""; then
- AC_TRY_COMPILE([#include <stdio.h>],
- [FILE *f = stdin; f->readCount = 0;],
- rb_cv_fcnt="readCount", )
-fi
-dnl for emx0.9c
-if test "$rb_cv_fcnt" = ""; then
- AC_TRY_COMPILE([#include <stdio.h>],
- [FILE *f = stdin; f->_rcount = 0;],
- rb_cv_fcnt="_rcount", rb_cv_fcnt="not found")
-fi])
-if test "$rb_cv_fcnt" = "not found"; then
- AC_MSG_RESULT([not found(OK if using GNU libc)])
-else
- AC_MSG_RESULT($rb_cv_fcnt)
- AC_DEFINE_UNQUOTED(FILE_COUNT, $rb_cv_fcnt)
-fi
-
-dnl default value for $KANJI
-DEFAULT_KCODE="KCODE_NONE"
-
-AC_ARG_WITH(default-kcode,
- [--with-default-kcode=CODE specify default value for \$KCODE (utf8|euc|sjis|none)],
- [case $withval in
- utf8) DEFAULT_KCODE="KCODE_UTF8";;
- euc) DEFAULT_KCODE="KCODE_EUC";;
- sjis) DEFAULT_KCODE="KCODE_SJIS";;
- none) DEFAULT_KCODE="KCODE_NONE";;
- *) AC_MSG_WARN($withval is not valid kcode; ignored);;
- esac])
-AC_DEFINE_UNQUOTED(DEFAULT_KCODE, $DEFAULT_KCODE)
-
-dnl wheather use dln_a_out or not
-AC_ARG_WITH(dln-a-out,
- [--with-dln-a-out use dln_a_out if possible], [
- case $withval in
- yes) with_dln_a_out=yes;;
- *) with_dln_a_out=no;;
- esac], [with_dln_a_out=no])
-
-AC_SUBST(XLDFLAGS)dnl
-
-AC_CACHE_CHECK(whether ELF binaries are produced, rb_cv_binary_elf,
-[AC_TRY_RUN([
-/* Test for whether ELF binaries are produced */
-#include <fcntl.h>
-#include <stdlib.h>
-main() {
- char buffer[4];
- int i=open("conftest",O_RDONLY);
- if(i==-1)
- exit(1); /* fail */
- if(read(i,&buffer[0],4)<4)
- exit(1); /* fail */
- if(buffer[0] != 127 || buffer[1] != 'E' ||
- buffer[2] != 'L' || buffer[3] != 'F')
- exit(1); /* fail */
- exit(0); /* succeed (yes, it's ELF) */
-}
-],
-rb_cv_binary_elf=yes,
-rb_cv_binary_elf=no,
-rb_cv_binary_elf=yes)])
-
-if test "$rb_cv_binary_elf" = yes; then
- AC_DEFINE(USE_ELF)
-fi
-
-case "$target_os" in
- linux*)
- if test "$rb_cv_binary_elf" = no; then
- with_dln_a_out=yes
- target_os=${target_os}-a_out
- else
- LDFLAGS="-rdynamic"
- fi;;
-netbsd*)
- if [[ "`$CC -dM -E - </dev/null | grep __ELF__`" != "" ]]
- then
- netbsd_elf=yes
- else
- netbsd_elf=no
- fi
- ;;
-esac
-
-AC_SUBST(DLDFLAGS)dnl
-
-AC_SUBST(STATIC)dnl
-AC_SUBST(CCDLFLAGS)dnl
-AC_SUBST(LDSHARED)dnl
-AC_SUBST(DLEXT)dnl
-AC_SUBST(DLEXT2)dnl
-
-STATIC=
-
-if test "$with_dln_a_out" != yes; then
- rb_cv_dlopen=unknown
- AC_MSG_CHECKING(whether OS depend dynamic link works)
- if test "$GCC" = yes; then
- case "$target_os" in
- nextstep*) ;;
- openstep*) ;;
- rhapsody*) ;;
- darwin*) CCDLFLAGS=-fno-common;;
- human*) ;;
- bsdi*) ;;
- beos*) ;;
- cygwin*) ;;
- mingw*) ;;
- netbsd*) CCDLFLAGS=-fPIC;;
- *) CCDLFLAGS=-fPIC;;
- esac
- else
- case "$target_os" in
- hpux*) CCDLFLAGS='+z';;
- solaris*|irix*) CCDLFLAGS='-KPIC' ;;
- sunos*) CCDLFLAGS='-PIC' ;;
- esix*|uxpds*) CCDLFLAGS='-KPIC' ;;
- *) CCDLFLAGS='' ;;
- esac
- fi
-
- case "$target_os" in
- hpux*) DLDFLAGS="-E"
- LDSHARED='ld -b'
- LDFLAGS="-Wl,-E"
- rb_cv_dlopen=yes;;
- solaris*) if test "$GCC" = yes; then
- LDSHARED='$(CC) -Wl,-G'
- if `$CC --print-prog-name=ld` -v 2>&1 | grep "GNU ld" > /dev/null; then
- LDFLAGS="-Wl,-E"
- LDSHARED="$LDSHARED -shared"
- fi
- else
- LDSHARED='ld -G'
- fi
- rb_cv_dlopen=yes;;
- sunos*) LDSHARED='ld -assert nodefinitions'
- rb_cv_dlopen=yes;;
- irix*) LDSHARED='ld -shared'
- rb_cv_dlopen=yes;;
- sysv4*) LDSHARED='ld -G'
- rb_cv_dlopen=yes;;
- nto-qnx*) LDSHARED="qcc -shared"
- rb_cv_dlopen=yes ;;
- esix*|uxpds*) LDSHARED="ld -G"
- rb_cv_dlopen=yes ;;
- osf*) LDSHARED="$CC -shared"
- rb_cv_dlopen=yes ;;
- linux*) LDSHARED="$CC -shared"
- rb_cv_dlopen=yes ;;
- gnu*) LDSHARED="$CC -shared"
- rb_cv_dlopen=yes
- LDFLAGS="-rdynamic" ;;
- freebsd*) LDSHARED="$CC -shared"
- if test "$rb_cv_binary_elf" = yes; then
- LDFLAGS="-rdynamic"
- DLDFLAGS='-Wl,-soname,$(.TARGET)'
- else
- test "$GCC" = yes && `$CC --print-prog-name=ld` -v 2>&1 | grep "GNU ld" > /dev/null || LDSHARED="ld -Bshareable"
- fi
- rb_cv_dlopen=yes ;;
- netbsd*) LDSHARED='${CC} -shared'
- if test "$rb_cv_binary_elf" = yes; then
- LDFLAGS="-Wl,-export-dynamic"
- fi
- rb_cv_dlopen=yes ;;
- openbsd*) LDSHARED="ld -Bforcearchive -Bshareable"
- rb_cv_dlopen=yes ;;
- bsdi3*) case "$CC" in
- *shlicc*) LDSHARED="$CC -r"
- rb_cv_dlopen=yes ;;
- esac ;;
- bsdi*) LDSHARED="ld -shared"
- LDFLAGS='-rdynamic -Wl,-rpath,$(prefix)/lib/ruby/$(MAJOR).$(MINOR)/i386-bsdi4.0'
- rb_cv_dlopen=yes ;;
- nextstep*) LDSHARED='cc -r -nostdlib'
- LDFLAGS="-u libsys_s"
- DLDFLAGS="$ARCH_FLAG"
- rb_cv_dlopen=yes ;;
- openstep*) LDSHARED='cc -dynamic -bundle -undefined suppress'
- LDFLAGS=""
- DLDFLAGS="$ARCH_FLAG"
- rb_cv_dlopen=yes ;;
- rhapsody*) LDSHARED='cc -dynamic -bundle -undefined suppress'
- LDFLAGS=""
- DLDFLAGS="$ARCH_FLAG"
- rb_cv_dlopen=yes ;;
- darwin*) LDSHARED='cc -dynamic -bundle -undefined suppress -flat_namespace'
- LDFLAGS=""
- DLDFLAGS="$ARCH_FLAG"
- rb_cv_dlopen=yes ;;
- aix*) LDSHARED='/usr/ccs/bin/ld'
- XLDFLAGS='-Wl,-bE:ruby.imp'
- DLDFLAGS='-brtl -eInit_$(TARGET) -bI:$(topdir)/ruby.imp -bM:SRE -T512 -H512 -lc'
- LDFLAGS="-brtl"
- rb_cv_dlopen=yes ;;
-
- human*) DLDFLAGS=''
- LDSHARED=''
- LDFLAGS=''
- rb_cv_dlopen=yes ;;
- beos*) case "$target_cpu" in
- powerpc*)
- LDSHARED="ld -xms"
- DLDFLAGS='-export Init_$(TARGET) -lbe -lroot glue-noinit.a init_term_dyn.o start_dyn.o'
- ;;
- i586*)
- LDSHARED="ld -shared"
- DLDFLAGS="-L/boot/develop/lib/x86 -lbe -lroot"
- ;;
- esac
- rb_cv_dlopen=yes ;;
- nto-qnx*) DLDFLAGS="-L/lib -L/usr/lib -L/usr/local/lib"
- LDSHARED='ld -Bshareable -x'
- LDFLAGS="-L/lib -L/usr/lib -L/usr/local/lib"
- rb_cv_dlopen=yes;;
- cygwin*|mingw*) : ${LDSHARED="${DLLWRAP} --target=${target_os} --as=${AS} --dlltool-name=${DLLTOOL} --driver-name=${CC} --export-all -s"}
- rb_cv_dlopen=yes ;;
- *) LDSHARED='ld' ;;
- esac
- AC_MSG_RESULT($rb_cv_dlopen)
-fi
-
-dln_a_out_works=no
-if test "$ac_cv_header_a_out_h" = yes; then
- if test "$with_dln_a_out" = yes || test "$rb_cv_dlopen" = unknown; then
- cat confdefs.h > config.h
- AC_CACHE_CHECK(whether matz's dln works, rb_cv_dln_a_out,
- [AC_TRY_COMPILE([
-#define USE_DLN_A_OUT
-#include "dln.c"
-],
- [],
- rb_cv_dln_a_out=yes,
- rb_cv_dln_a_out=no)])
- if test "$rb_cv_dln_a_out" = yes; then
- dln_a_out_works=yes
- AC_DEFINE(USE_DLN_A_OUT)
- fi
- fi
-fi
-
-if test "$dln_a_out_works" = yes; then
- if test "$GCC" = yes; then
- STATIC=-static
- else
- STATIC=-Bstatic
- fi
- DLEXT=so
- AC_DEFINE(DLEXT, ".so")
- CCDLFLAGS=
-else
- case "$target_os" in
- hpux*) DLEXT=sl
- AC_DEFINE(DLEXT, ".sl");;
- nextstep*) DLEXT=bundle
- AC_DEFINE(DLEXT, ".bundle");;
- openstep*) DLEXT=bundle
- AC_DEFINE(DLEXT, ".bundle");;
- rhapsody*) DLEXT=bundle
- AC_DEFINE(DLEXT, ".bundle");;
- darwin*) DLEXT=bundle
- AC_DEFINE(DLEXT, ".bundle");;
- os2_emx*) DLEXT=dll
- AC_DEFINE(DLEXT, ".dll");;
- cygwin*|mingw*) DLEXT=so
- AC_DEFINE(DLEXT, ".so")
- DLEXT2=dll
- AC_DEFINE(DLEXT2, ".dll");;
- *) DLEXT=so
- AC_DEFINE(DLEXT, ".so");;
- esac
-fi
-
-AC_SUBST(STRIP)dnl
-if test "$with_dln_a_out" = yes; then
- STRIP=true
-else
- STRIP=strip
-fi
-
-case "$target_os" in
- linux*)
- STRIP='strip -S -x';;
- gnu*)
- STRIP='strip -S -x';;
- nextstep*)
- STRIP='strip -A -n';;
- openstep*)
- STRIP='strip -A -n';;
- rhapsody*)
- STRIP='strip -A -n';;
- darwin*)
- STRIP='strip -A -n';;
-esac
-
-EXTSTATIC=
-AC_SUBST(EXTSTATIC)dnl
-AC_ARG_WITH(static-linked-ext,
- [--with-static-linked-ext link external modules statically],
- [case $withval in
- yes) STATIC=
- EXTSTATIC=static;;
- *) ;;
- esac])
-
-case "$target_os" in
- human*)
- AC_CHECK_LIB(signal, _harderr)
- AC_CHECK_LIB(hmem, hmemset)
- AC_CHECK_FUNCS(select gettimeofday)
- AC_CACHE_CHECK(whether PD libc _dtos18 fail to convert big number,
- rb_cv_missing__dtos18,
- [AC_TRY_RUN(
-changequote(<<, >>)dnl
-<<
-#include <stdio.h>
-main ()
-{
- char buf[256];
- sprintf (buf, "%g", 1e+300);
- exit (strcmp (buf, "1e+300") ? 0 : 1);
-}
->>,
-changequote([, ])dnl
-rb_cv_missing__dtos18=yes, rb_cv_missing__dtos18=no, rb_cv_missing__dtos18=no)])
- if test "$rb_cv_missing__dtos18" = yes; then
- AC_DEFINE(MISSING__DTOS18)
- fi
- AC_CACHE_CHECK(whether PD libc fconvert fail to round,
- rb_cv_missing_fconvert,
- [AC_TRY_RUN(
-changequote(<<, >>)dnl
-<<
-#include <stdio.h>
-#include <math.h>
-main ()
-{
- char buf[256];
- sprintf (buf, "%f", log(exp(1.0)));
- exit (strcmp (buf, "1.000000") ? 0 : 1);
-}
->>,
-changequote([, ])dnl
-rb_cv_missing_fconvert=yes, rb_cv_missing_fconvert=no, rb_cv_missing_fconvert=no)])
- if test "$rb_cv_missing_fconvert" = yes; then
- AC_DEFINE(MISSING_FCONVERT)
- fi
- AC_LIBOBJ([x68.o])
- CFLAGS="$CFLAGS -fansi-only -cc1-stack=262144 -cpp-stack=2694144"
- EXEEXT=.x
- OBJEXT=o
- setup=Setup.x68
- ;;
- dnl OS/2 environment w/ Autoconf 2.1x for EMX
- os2_emx)
- AC_LIBOBJ([os2])
- setup=Setup.emx
- ;;
- *djgpp*)
- setup=Setup.dj
- ;;
- *)
- setup=Setup
- ;;
-esac
-
-AC_SUBST(setup)
-
-if test "$prefix" = NONE; then
- prefix=$ac_default_prefix
-fi
-
-if test "$fat_binary" = yes ; then
- CFLAGS="$CFLAGS $ARCH_FLAG"
-fi
-
-if test x"$cross_compiling" = xyes; then
- MINIRUBY="ruby -I`pwd` -rfake"
- PREP=fake.rb
-else
- MINIRUBY='./miniruby$(EXEEXT)'
- PREP=''
-fi
-AC_SUBST(MINIRUBY)
-AC_SUBST(PREP)
-
-FIRSTMAKEFILE=""
-LIBRUBY_A='lib$(RUBY_INSTALL_NAME).a'
-LIBRUBY='$(LIBRUBY_A)'
-LIBRUBYARG='$(LIBRUBY_A)'
-SOLIBS=
-
-case "$target_os" in
- cygwin*|mingw*|beos*|openstep*|nextstep*|rhapsody*|darwin*|os2_emx*)
- DLDLIBS=""
- ;;
- *)
- DLDLIBS="-lc"
- ;;
-esac
-
-LIBRUBY_LDSHARED=$LDSHARED
-LIBRUBY_DLDFLAGS=$DLDFLAGS
-LIBRUBY_SO='lib$(RUBY_INSTALL_NAME).so.$(MAJOR).$(MINOR).$(TEENY)'
-LIBRUBY_ALIASES='lib$(RUBY_INSTALL_NAME).so'
-ENABLE_SHARED=no
-
-AC_ARG_ENABLE(shared,
- [--enable-shared build a shared library for Ruby. ],
- [enable_shared=$enableval])
-if test "$enable_shared" = 'yes'; then
- LIBRUBY='$(LIBRUBY_SO)'
- LIBRUBYARG='-L. -l$(RUBY_INSTALL_NAME)'
- CFLAGS="$CFLAGS $CCDLFLAGS"
- ENABLE_SHARED=yes
- if test "$rb_cv_binary_elf" = yes; then
- SOLIBS='$(LIBS)'
- fi
- case "$target_os" in
- sunos4*)
- LIBRUBY_ALIASES='lib$(RUBY_INSTALL_NAME).so.$(MAJOR).$(MINOR) lib$(RUBY_INSTALL_NAME).so'
- ;;
- linux*)
- LIBRUBY_DLDFLAGS='-Wl,-soname,lib$(RUBY_INSTALL_NAME).so.$(MAJOR).$(MINOR)'
- LIBRUBY_ALIASES='lib$(RUBY_INSTALL_NAME).so.$(MAJOR).$(MINOR) lib$(RUBY_INSTALL_NAME).so'
- ;;
- gnu*)
- LIBRUBY_DLDFLAGS='-Wl,-soname,lib$(RUBY_INSTALL_NAME).so.$(MAJOR).$(MINOR)'
- LIBRUBY_ALIASES='lib$(RUBY_INSTALL_NAME).so.$(MAJOR).$(MINOR) lib$(RUBY_INSTALL_NAME).so'
- ;;
- freebsd*)
- SOLIBS='$(LIBS)'
- LIBRUBY_SO='lib$(RUBY_INSTALL_NAME).so.$(MAJOR)$(MINOR)'
- if test "$rb_cv_binary_elf" != "yes" ; then
- LIBRUBY_SO="$LIBRUBY_SO.\$(TEENY)"
- LIBRUBY_ALIASES=''
- fi
- ;;
- netbsd*)
- SOLIBS='$(LIBS)'
- LIBRUBY_SO='lib$(RUBY_INSTALL_NAME).so.$(MAJOR)$(MINOR).$(TEENY)'
- LIBRUBY_DLDFLAGS='-Wl,-soname,lib$(RUBY_INSTALL_NAME).so.$(MAJOR)$(MINOR)'
- LIBRUBYARG='-Wl,-R -Wl,${prefix}/lib -L${prefix}/lib -L. -l$(RUBY_INSTALL_NAME)'
- if test "$rb_cv_binary_elf" = yes; then # ELF platforms
- LIBRUBY_ALIASES='lib$(RUBY_INSTALL_NAME).so.$(MAJOR)$(MINOR) lib$(RUBY_INSTALL_NAME).so'
- else # a.out platforms
- LIBRUBY_ALIASES=""
- fi
- ;;
- openbsd*)
- SOLIBS='$(LIBS)'
- ;;
- solaris*)
- XLDFLAGS='-R${prefix}/lib'
- ;;
- hpux*)
- XLDFLAGS='-Wl,+s,+b,$(prefix)/lib'
- LIBRUBY_SO='lib$(RUBY_INSTALL_NAME).sl.$(MAJOR).$(MINOR).$(TEENY)'
- LIBRUBY_ALIASES='lib$(RUBY_INSTALL_NAME).sl.$(MAJOR).$(MINOR) lib$(RUBY_INSTALL_NAME).sl'
- ;;
- aix*)
- if test "$GCC" = yes; then
- LIBRUBY_LDSHARED='$(CC) -shared'
- LIBRUBY_DLDFLAGS='-Wl,-bE:ruby.imp'
- else
- LIBRUBY_LDSHARED='/usr/ccs/bin/ld'
- LIBRUBY_DLDFLAGS='-bE:ruby.imp -bM:SRE -bnoentry'
- fi
- LIBRUBYARG='-L${prefix}/lib -Wl,lib$(RUBY_INSTALL_NAME).so'
- SOLIBS='-lm -lc'
- ;;
- beos*)
- case "$target_cpu" in
- powerpc*)
- LIBRUBY_DLDFLAGS='-f ruby.exp -lnet -lbe -lroot glue-noinit.a init_term_dyn.o start_dyn.o'
- ;;
- esac
- ;;
- darwin*)
- LIBRUBY_SO='lib$(RUBY_INSTALL_NAME).$(MAJOR).$(MINOR).$(TEENY).dylib'
- LIBRUBY_LDSHARED='cc -dynamiclib -undefined suppress -flat_namespace'
- LIBRUBY_DLDFLAGS='-install_name lib$(RUBY_INSTALL_NAME).dylib -current_version $(MAJOR).$(MINOR).$(TEENY) -compatibility_version $(MAJOR).$(MINOR)'
- LIBRUBY_ALIASES='lib$(RUBY_INSTALL_NAME).$(MAJOR).$(MINOR).dylib lib$(RUBY_INSTALL_NAME).dylib'
- ;;
- *)
- ;;
- esac
-fi
-
-case "$target_os" in
- netbsd*)
- CFLAGS="$CFLAGS -pipe"
- ;;
- nextstep*)
- CFLAGS="$CFLAGS -pipe"
- ;;
- openstep*)
- CFLAGS="$CFLAGS -pipe"
- ;;
- rhapsody*)
- CFLAGS="$CFLAGS -pipe -no-precomp"
- ;;
- darwin*)
- CFLAGS="$CFLAGS -pipe -no-precomp"
- ;;
- os2_emx)
- CFLAGS="$CFLAGS -DOS2"
- ;;
- osf*)
- if test "$GCC" != "yes" ; then
- # compile something small: taint.c is fine for this.
- # the main point is the '-v' flag of 'cc'.
- case "`cc -v -I. -c main.c -o /tmp/main.o 2>&1`" in
- */gemc_cc*) # we have the new DEC GEM CC
- CFLAGS="$CFLAGS -oldc"
- ;;
- *) # we have the old MIPS CC
- ;;
- esac
- # cleanup
- rm -f /tmp/main.o
- CFLAGS="$CFLAGS -std"
- fi
- ;;
- beos*)
- case "$target_cpu" in
- powerpc*)
- CFLAGS="$CFLAGS -relax_pointers"
- ;;
- esac
- ;;
- cygwin*|mingw*)
- RUBY_SO_NAME=$target_os-'$(RUBY_INSTALL_NAME)'${MAJOR}${MINOR}
- if test x"$enable_shared" = xyes; then
- LIBRUBY_SO='$(RUBY_SO_NAME)'.dll
- LIBRUBY_DLDFLAGS='--dllname=$@ --output-lib=$(LIBRUBY) --add-stdcall-alias --def=$(RUBYDEF)'
- else
- LIBRUBY_SO=dummy
- LIBRUBY_DLDFLAGS='--output-exp=$(RUBY_INSTALL_NAME).exp --dllname=$(RUBY_INSTALL_NAME)$(EXEEXT) --output-lib=$(LIBRUBY) --add-stdcall-alias --def=$(RUBYDEF)'
- fi
- LIBRUBY_ALIASES=''
- LIBRUBY_A='lib$(RUBY_INSTALL_NAME)s.a'
- LIBRUBY='lib$(RUBY_SO_NAME).a'
- LIBRUBYARG='-L. -l$(RUBY_SO_NAME)'
- FIRSTMAKEFILE=GNUmakefile:cygwin/GNUmakefile.in
- SOLIBS='$(LIBS)'
- case "$target_os" in
- cygwin*)
- AC_LIBOBJ([strftime])
- CCDLFLAGS=-DUSEIMPORTLIB ;;
- mingw*)
- AC_LIBOBJ([win32])
- CFLAGS="-DNT -D__MSVCRT__ $CFLAGS"
- CCDLFLAGS=-DIMPORT ;;
- esac
- ;;
- *)
- ;;
-esac
-
-AC_SUBST(LIBRUBY_LDSHARED)
-AC_SUBST(LIBRUBY_DLDFLAGS)
-AC_SUBST(RUBY_INSTALL_NAME)
-AC_SUBST(RUBY_SO_NAME)
-AC_SUBST(LIBRUBY_A)
-AC_SUBST(LIBRUBY_SO)
-AC_SUBST(LIBRUBY_ALIASES)
-AC_SUBST(LIBRUBY)
-AC_SUBST(LIBRUBYARG)
-AC_SUBST(SOLIBS)
-AC_SUBST(DLDLIBS)
-AC_SUBST(ENABLE_SHARED)
-AC_SUBST(MAINLIBS)
-
-ri_prefix=
-test "$program_prefix" != NONE &&
- ri_prefix=$program_prefix
-
-ri_suffix=
-test "$program_suffix" != NONE &&
- ri_suffix=$program_suffix
-
-RUBY_INSTALL_NAME="${ri_prefix}ruby${ri_suffix}"
-case "$target_os" in
- cygwin*|mingw*|*djgpp*|os2_emx*)
- RUBY_LIB_PREFIX="/lib/ruby"
- ;;
- *)
- RUBY_LIB_PREFIX="${prefix}/lib/ruby"
- ;;
-esac
-RUBY_LIB_PATH="${RUBY_LIB_PREFIX}/${MAJOR}.${MINOR}"
-
-AC_ARG_WITH(sitedir,
- [--with-sitedir=DIR site libraries in DIR [PREFIX/lib/ruby/site_ruby]],
- [sitedir=$withval],
- [sitedir='${prefix}/lib/ruby/site_ruby'])
-SITE_DIR="`eval \"echo ${sitedir}\"`"
-case "$target_os" in
- cygwin*|mingw*|*djgpp*|os2_emx*)
- RUBY_SITE_LIB_PATH="`expr "$SITE_DIR" : "$prefix\(/.*\)"`" ||
- RUBY_SITE_LIB_PATH="$SITE_DIR";;
- *)
- RUBY_SITE_LIB_PATH="$SITE_DIR";;
-esac
-RUBY_SITE_LIB_PATH2="${RUBY_SITE_LIB_PATH}/${MAJOR}.${MINOR}"
-
-AC_DEFINE_UNQUOTED(RUBY_LIB, "${RUBY_LIB_PATH}")
-AC_DEFINE_UNQUOTED(RUBY_SITE_LIB, "${RUBY_SITE_LIB_PATH}")
-AC_DEFINE_UNQUOTED(RUBY_SITE_LIB2, "${RUBY_SITE_LIB_PATH2}")
-
-AC_SUBST(arch)dnl
-AC_SUBST(sitedir)dnl
-
-configure_args=$ac_configure_args
-AC_SUBST(configure_args)dnl
-
-if test "$fat_binary" = yes ; then
- arch="fat-${target_os}"
-
- AC_DEFINE_UNQUOTED(RUBY_THIN_ARCHLIB,
- "${RUBY_LIB_PATH}/" __ARCHITECTURE__ "-${target_os}")
-
- AC_DEFINE_UNQUOTED(RUBY_SITE_THIN_ARCHLIB,
- "${RUBY_SITE_LIB_PATH}/" __ARCHITECTURE__ "-${target_os}")
- AC_DEFINE_UNQUOTED(RUBY_PLATFORM, __ARCHITECTURE__ "-${target_os}")
-else
- arch="${target_cpu}-${target_os}"
- AC_DEFINE_UNQUOTED(RUBY_PLATFORM, "${arch}")
-fi
-
-AC_DEFINE_UNQUOTED(RUBY_ARCHLIB, "${RUBY_LIB_PATH}/${arch}")
-AC_DEFINE_UNQUOTED(RUBY_SITE_ARCHLIB, "${RUBY_SITE_LIB_PATH2}/${arch}")
-
-AC_ARG_WITH(search-path,
- [--with-search-path=DIR specify the additional search path],
- [search_path=$withval])
-if test "$search_path" != ""; then
- AC_DEFINE_UNQUOTED(RUBY_SEARCH_PATH,"$search_path")
-fi
-
-if test -f config.h && tr -d '\015' < confdefs.h | cmp -s config.h -; then
- echo "config.h unchanged"
-else
- echo "creating config.h"
- tr -d '\015' < confdefs.h > config.h
-fi
-: > confdefs.h
-
-AC_OUTPUT($FIRSTMAKEFILE Makefile ext/extmk.rb)
diff --git a/cygwin/GNUmakefile.in b/cygwin/GNUmakefile.in
deleted file mode 100644
index 4fc628f4da..0000000000
--- a/cygwin/GNUmakefile.in
+++ /dev/null
@@ -1,43 +0,0 @@
-include Makefile
-
-ENABLE_SHARED=@ENABLE_SHARED@
-
-ifneq (,$(findstring no, $(ENABLE_SHARED)))
- EXTOBJS = $(RUBY_INSTALL_NAME).exp
- LIBRUBYARG = $(LIBRUBY_A)
-else
- CPPFLAGS += -DLIBRUBY_SO=\"$(LIBRUBY_SO)\"
-endif
-
-ifneq (,$(findstring ruby, $(RUBY_INSTALL_NAME)))
- RUBYW_INSTALL_NAME = $(subst ruby,rubyw,$(RUBY_INSTALL_NAME))
-else
- RUBYW_INSTALL_NAME = $(RUBY_INSTALL_NAME)w
-endif
-WPROGRAM = $(RUBYW_INSTALL_NAME)$(EXEEXT)
-RUBYDEF = $(RUBY_INSTALL_NAME).def
-SOLIBS := $(LIBRUBY_SO).res.@OBJEXT@ $(SOLIBS)
-EXTOBJS += $(@:$(EXEEXT)=.res.@OBJEXT@)
-
-$(LIBRUBY_SO): $(RUBYDEF) $(LIBRUBY_SO).res.@OBJEXT@
-$(LIBRUBY): $(LIBRUBY_SO)
-
-%.res.@OBJEXT@: %.rc
- @WINDRES@ --include-dir . --include-dir $(<D) --include-dir $(srcdir)/win32 $< $@
-
-$(RUBY_INSTALL_NAME).rc $(RUBYW_INSTALL_NAME).rc $(LIBRUBY_SO).rc: rbconfig.rb
- @@MINIRUBY@ $(srcdir)/win32/resource.rb \
- -ruby_name=$(RUBY_INSTALL_NAME) -rubyw_name=$(RUBYW_INSTALL_NAME) \
- -so_name=$(LIBRUBY_SO) \
- . $(icondirs) $(srcdir)/win32
-
-$(PROGRAM): $(RUBY_INSTALL_NAME).res.@OBJEXT@
-$(WPROGRAM): $(RUBYW_INSTALL_NAME).res.@OBJEXT@
- @rm -f $@
- $(PURIFY) $(CC) -mwindows -e _mainCRTStartup $(LDFLAGS) $(XLDFLAGS) \
- $(MAINOBJ) $(EXTOBJS) $(LIBRUBYARG) $(LIBS) -o $@
-
-$(RUBYDEF): $(LIBRUBY_A)
- echo EXPORTS > $(RUBYDEF)
- @NM@ --extern-only --defined-only $(LIBRUBY_A) | \
- @MINIRUBY@ -ne 'puts $$1 if / [CDT] _(.*)$$/' >> $(RUBYDEF)
diff --git a/defines.h b/defines.h
deleted file mode 100644
index d8b7242daa..0000000000
--- a/defines.h
+++ /dev/null
@@ -1,140 +0,0 @@
-/************************************************
-
- defines.h -
-
- $Author$
- $Date$
- created at: Wed May 18 00:21:44 JST 1994
-
-************************************************/
-#ifndef DEFINES_H
-#define DEFINES_H
-
-#define RUBY
-
-#if !defined(__STDC__) && !defined(_MSC_VER)
-# define volatile
-#endif
-
-#ifdef __cplusplus
-# ifndef HAVE_PROTOTYPES
-# define HAVE_PROTOTYPES 1
-# endif
-# ifndef HAVE_STDARG_PROTOTYPES
-# define HAVE_STDARG_PROTOTYPES 1
-# endif
-#endif
-
-#undef _
-#ifdef HAVE_PROTOTYPES
-# define _(args) args
-#else
-# define _(args) ()
-#endif
-
-#undef __
-#ifdef HAVE_STDARG_PROTOTYPES
-# define __(args) args
-#else
-# define __(args) ()
-#endif
-
-#ifdef __cplusplus
-#define ANYARGS ...
-#else
-#define ANYARGS
-#endif
-
-#define xmalloc ruby_xmalloc
-#define xcalloc ruby_xcalloc
-#define xrealloc ruby_xrealloc
-#define xfree ruby_xfree
-
-void *xmalloc _((long));
-void *xcalloc _((long,long));
-void *xrealloc _((void*,long));
-void xfree _((void*));
-
-#if SIZEOF_LONG_LONG > 0
-# define LONG_LONG long long
-#elif SIZEOF___INT64 > 0
-# define HAVE_LONG_LONG 1
-# define LONG_LONG __int64
-# undef SIZEOF_LONG_LONG
-# define SIZEOF_LONG_LONG SIZEOF___INT64
-#endif
-
-/* define RUBY_USE_EUC/SJIS for default kanji-code */
-#ifndef DEFAULT_KCODE
-#if defined(MSDOS) || defined(__CYGWIN__) || defined(__human68k__) || defined(__MACOS__) || defined(__EMX__) || defined(OS2) || defined(NT)
-#define DEFAULT_KCODE KCODE_SJIS
-#else
-#define DEFAULT_KCODE KCODE_EUC
-#endif
-#endif
-
-#ifdef NeXT
-#define DYNAMIC_ENDIAN /* determine endian at runtime */
-#ifndef __APPLE__
-#define S_IXUSR _S_IXUSR /* execute/search permission, owner */
-#endif
-#define S_IXGRP 0000010 /* execute/search permission, group */
-#define S_IXOTH 0000001 /* execute/search permission, other */
-
-#define HAVE_SYS_WAIT_H /* configure fails to find this */
-#endif /* NeXT */
-
-#ifdef NT
-#include "win32/win32.h"
-#endif
-
-#if defined __CYGWIN__
-# undef EXTERN
-# if defined USEIMPORTLIB
-# define EXTERN extern __declspec(dllimport)
-# else
-# define EXTERN extern __declspec(dllexport)
-# endif
-#endif
-
-#ifndef EXTERN
-#define EXTERN extern
-#endif
-
-#if defined(sparc) || defined(__sparc__)
-# if defined(linux) || defined(__linux__)
-#define FLUSH_REGISTER_WINDOWS asm("ta 0x83")
-# else /* Solaris, not sparc linux */
-#define FLUSH_REGISTER_WINDOWS asm("ta 0x03")
-# endif /* trap always to flush register windows if we are on a Sparc system */
-#else /* Not a sparc, so */
-#define FLUSH_REGISTER_WINDOWS /* empty -- nothing to do here */
-#endif
-
-#if defined(MSDOS) || defined(_WIN32) || defined(__human68k__) || defined(__EMX__)
-#define DOSISH 1
-#endif
-
-#if defined(MSDOS) || defined(NT) || defined(__human68k__) || defined(OS2)
-#define PATH_SEP ";"
-#elif defined(riscos)
-#define PATH_SEP ","
-#else
-#define PATH_SEP ":"
-#endif
-#define PATH_SEP_CHAR PATH_SEP[0]
-
-#if defined(__human68k__)
-#undef HAVE_RANDOM
-#undef HAVE_SETITIMER
-#endif
-
-#if defined(DJGPP) || defined(__BOW__)
-#undef HAVE_SETITIMER
-#endif
-
-#ifndef RUBY_PLATFORM
-#define RUBY_PLATFORM "unknown-unknown"
-#endif
-
-#endif
diff --git a/dir.c b/dir.c
deleted file mode 100644
index 22dba86c8b..0000000000
--- a/dir.c
+++ /dev/null
@@ -1,1063 +0,0 @@
-/**********************************************************************
-
- dir.c -
-
- $Author$
- $Date$
- created at: Wed Jan 5 09:51:01 JST 1994
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
- Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
- Copyright (C) 2000 Information-technology Promotion Agency, Japan
-
-**********************************************************************/
-
-#include "ruby.h"
-
-#include <sys/types.h>
-#include <sys/stat.h>
-
-#ifdef HAVE_SYS_PARAM_H
-# include <sys/param.h>
-#else
-# define MAXPATHLEN 1024
-#endif
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-
-#if defined HAVE_DIRENT_H && !defined NT
-# include <dirent.h>
-# define NAMLEN(dirent) strlen((dirent)->d_name)
-#elif defined HAVE_DIRECT_H && !defined NT
-# include <direct.h>
-# define NAMLEN(dirent) strlen((dirent)->d_name)
-#else
-# define dirent direct
-# define NAMLEN(dirent) (dirent)->d_namlen
-# if HAVE_SYS_NDIR_H
-# include <sys/ndir.h>
-# endif
-# if HAVE_SYS_DIR_H
-# include <sys/dir.h>
-# endif
-# if HAVE_NDIR_H
-# include <ndir.h>
-# endif
-# if defined(NT)
-# include "win32/dir.h"
-# endif
-#endif
-
-#include <errno.h>
-
-#ifndef HAVE_STDLIB_H
-char *getenv();
-#endif
-
-#ifndef HAVE_STRING_H
-char *strchr _((char*,char));
-#endif
-
-#include <ctype.h>
-
-#include "util.h"
-
-#ifndef HAVE_LSTAT
-#define lstat(path,st) stat(path,st)
-#endif
-
-#define FNM_NOESCAPE 0x01
-#define FNM_PATHNAME 0x02
-#define FNM_DOTMATCH 0x04
-#define FNM_CASEFOLD 0x08
-
-#define FNM_NOMATCH 1
-#define FNM_ERROR 2
-
-#define downcase(c) (nocase && ISUPPER(c) ? tolower(c) : (c))
-
-#ifndef CharNext /* defined as CharNext[AW] on Windows. */
-# if defined(DJGPP)
-# define CharNext(p) ((p) + mblen(p, MB_CUR_MAX))
-# else
-# define CharNext(p) ((p) + 1)
-# endif
-#endif
-#if defined DOSISH
-#define isdirsep(c) ((c) == '/' || (c) == '\\')
-static char *
-find_dirsep(s)
- char *s;
-{
- while (*s) {
- if (isdirsep(*s))
- return s;
- s = CharNext(s);
- }
- return 0;
-}
-#else
-#define isdirsep(c) ((c) == '/')
-#define find_dirsep(s) strchr(s, '/')
-#endif
-
-static char *
-range(pat, test, flags)
- char *pat;
- char test;
- int flags;
-{
- int not, ok = 0;
- int nocase = flags & FNM_CASEFOLD;
- int escape = !(flags & FNM_NOESCAPE);
-
- not = *pat == '!' || *pat == '^';
- if (not)
- pat++;
-
- test = downcase(test);
-
- while (*pat) {
- int cstart, cend;
- cstart = cend = *pat++;
- if (cstart == ']')
- return ok == not ? 0 : pat;
- else if (escape && cstart == '\\')
- cstart = cend = *pat++;
- if (*pat == '-' && pat[1] != ']') {
- if (escape && pat[1] == '\\')
- pat++;
- cend = pat[1];
- if (!cend)
- return 0;
- pat += 2;
- }
- if (downcase(cstart) <= test && test <= downcase(cend))
- ok = 1;
- }
- return 0;
-}
-
-#define ISDIRSEP(c) (pathname && isdirsep(c))
-#define PERIOD(s) (period && *(s) == '.' && \
- ((s) == string || ISDIRSEP((s)[-1])))
-static int
-fnmatch(pat, string, flags)
- const char *pat;
- const char *string;
- int flags;
-{
- int c;
- int test;
- const char *s = string;
- int escape = !(flags & FNM_NOESCAPE);
- int pathname = flags & FNM_PATHNAME;
- int period = !(flags & FNM_DOTMATCH);
- int nocase = flags & FNM_CASEFOLD;
-
- while (c = *pat++) {
- switch (c) {
- case '?':
- if (!*s || ISDIRSEP(*s) || PERIOD(s))
- return FNM_NOMATCH;
- s++;
- break;
- case '*':
- while ((c = *pat++) == '*')
- ;
-
- if (PERIOD(s))
- return FNM_NOMATCH;
-
- if (!c) {
- if (pathname && find_dirsep(s))
- return FNM_NOMATCH;
- else
- return 0;
- }
- else if (ISDIRSEP(c)) {
- s = find_dirsep(s);
- if (s)
- break;
- return FNM_NOMATCH;
- }
-
- test = escape && c == '\\' ? *pat : c;
- test = downcase(test);
- pat--;
- while (*s) {
- if ((c == '[' || downcase(*s) == test) &&
- !fnmatch(pat, s, flags | FNM_DOTMATCH))
- return 0;
- else if (ISDIRSEP(*s))
- break;
- s++;
- }
- return FNM_NOMATCH;
-
- case '[':
- if (!*s || ISDIRSEP(*s) || PERIOD(s))
- return FNM_NOMATCH;
- pat = range(pat, *s, flags);
- if (!pat)
- return FNM_NOMATCH;
- s++;
- break;
-
- case '\\':
- if (escape
-#if defined DOSISH
- && *pat && strchr("*?[\\", *pat)
-#endif
- ) {
- c = *pat;
- if (!c)
- c = '\\';
- else
- pat++;
- }
- /* FALLTHROUGH */
-
- default:
-#if defined DOSISH
- if (ISDIRSEP(c) && isdirsep(*s))
- ;
- else
-#endif
- if(downcase(c) != downcase(*s))
- return FNM_NOMATCH;
- s++;
- break;
- }
- }
- return !*s ? 0 : FNM_NOMATCH;
-}
-
-VALUE rb_cDir;
-
-struct dir_data {
- DIR *dir;
- char *path;
-};
-
-static void
-free_dir(dir)
- struct dir_data *dir;
-{
- if (dir && dir->dir) closedir(dir->dir);
-}
-
-static VALUE dir_close _((VALUE));
-
-static VALUE
-dir_s_alloc(klass)
- VALUE klass;
-{
- struct dir_data *dirp;
- VALUE obj = Data_Make_Struct(klass, struct dir_data, 0, free_dir, dirp);
-
- dirp->dir = NULL;
- dirp->path = NULL;
-
- return obj;
-}
-
-static VALUE
-dir_initialize(dir, dirname)
- VALUE dir, dirname;
-{
- struct dir_data *dp;
-
- SafeStringValue(dirname);
- Data_Get_Struct(dir, struct dir_data, dp);
- if (dp->dir) closedir(dp->dir);
- if (dp->path) free(dp->path);
- dp->dir = NULL;
- dp->path = NULL;
- dp->dir = opendir(RSTRING(dirname)->ptr);
- if (dp->dir == NULL) {
- if (errno == EMFILE || errno == ENFILE) {
- rb_gc();
- dp->dir = opendir(RSTRING(dirname)->ptr);
- }
- if (dp->dir == NULL) {
- rb_sys_fail(RSTRING(dirname)->ptr);
- }
- }
- dp->path = strdup(RSTRING(dirname)->ptr);
-
- return dir;
-}
-
-static VALUE
-dir_s_open(klass, dirname)
- VALUE klass, dirname;
-{
- struct dir_data *dp;
- VALUE dir = Data_Make_Struct(klass, struct dir_data, 0, free_dir, dp);
-
- dir_initialize(dir, dirname);
- if (rb_block_given_p()) {
- return rb_ensure(rb_yield, dir, dir_close, dir);
- }
-
- return dir;
-}
-
-static void
-dir_closed()
-{
- rb_raise(rb_eIOError, "closed directory");
-}
-
-#define GetDIR(obj, dirp) {\
- Data_Get_Struct(obj, struct dir_data, dirp);\
- if (dirp->dir == NULL) dir_closed();\
-}
-
-static VALUE
-dir_path(dir)
- VALUE dir;
-{
- struct dir_data *dirp;
-
- GetDIR(dir, dirp);
- if (!dirp->path) return Qnil;
- return rb_str_new2(dirp->path);
-}
-
-static VALUE
-dir_read(dir)
- VALUE dir;
-{
- struct dir_data *dirp;
- struct dirent *dp;
-
- GetDIR(dir, dirp);
- errno = 0;
- dp = readdir(dirp->dir);
- if (dp) {
- return rb_tainted_str_new(dp->d_name, NAMLEN(dp));
- }
- else if (errno == 0) { /* end of stream */
- return Qnil;
- }
- else {
- rb_sys_fail(0);
- }
- return Qnil; /* not reached */
-}
-
-static VALUE
-dir_each(dir)
- VALUE dir;
-{
- struct dir_data *dirp;
- struct dirent *dp;
-
- GetDIR(dir, dirp);
- for (dp = readdir(dirp->dir); dp != NULL; dp = readdir(dirp->dir)) {
- rb_yield(rb_tainted_str_new(dp->d_name, NAMLEN(dp)));
- if (dirp->dir == NULL) dir_closed();
- }
- return dir;
-}
-
-static VALUE
-dir_tell(dir)
- VALUE dir;
-{
-#ifdef HAVE_TELLDIR
- struct dir_data *dirp;
- long pos;
-
- GetDIR(dir, dirp);
- pos = telldir(dirp->dir);
- return rb_int2inum(pos);
-#else
- rb_notimplement();
-#endif
-}
-
-static VALUE
-dir_seek(dir, pos)
- VALUE dir, pos;
-{
- struct dir_data *dirp;
-
-#ifdef HAVE_SEEKDIR
- GetDIR(dir, dirp);
- seekdir(dirp->dir, NUM2INT(pos));
- return dir;
-#else
- rb_notimplement();
-#endif
-}
-
-static VALUE
-dir_set_pos(dir, pos)
- VALUE dir, pos;
-{
- dir_seek(dir, pos);
- return pos;
-}
-
-static VALUE
-dir_rewind(dir)
- VALUE dir;
-{
- struct dir_data *dirp;
-
- GetDIR(dir, dirp);
- rewinddir(dirp->dir);
- return dir;
-}
-
-static VALUE
-dir_close(dir)
- VALUE dir;
-{
- struct dir_data *dirp;
-
- GetDIR(dir, dirp);
- closedir(dirp->dir);
- dirp->dir = NULL;
-
- return Qnil;
-}
-
-static void
-dir_chdir(path)
- const char *path;
-{
- if (chdir(path) < 0)
- rb_sys_fail(path);
-}
-
-static int chdir_blocking = 0;
-static VALUE chdir_thread = Qnil;
-
-static VALUE
-chdir_restore(path)
- char *path;
-{
- chdir_blocking--;
- if (chdir_blocking == 0)
- chdir_thread = Qnil;
- dir_chdir(path);
- free(path);
- return Qnil;
-}
-
-static VALUE
-dir_s_chdir(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- VALUE path = Qnil;
- char *dist = "";
-
- rb_secure(2);
- if (rb_scan_args(argc, argv, "01", &path) == 1) {
- SafeStringValue(path);
- dist = RSTRING(path)->ptr;
- }
- else {
- dist = getenv("HOME");
- if (!dist) {
- dist = getenv("LOGDIR");
- if (!dist) rb_raise(rb_eArgError, "HOME/LOGDIR not set");
- }
- }
-
- if (chdir_blocking > 0) {
- if (!rb_block_given_p() || rb_thread_current() != chdir_thread)
- rb_warn("conflicting chdir during another chdir block");
- }
-
- if (rb_block_given_p()) {
- char *cwd = my_getcwd();
- chdir_blocking++;
- if (chdir_thread == Qnil)
- chdir_thread = rb_thread_current();
- dir_chdir(dist);
- return rb_ensure(rb_yield, path, chdir_restore, (VALUE)cwd);
- }
- dir_chdir(dist);
-
- return INT2FIX(0);
-}
-
-static VALUE
-dir_s_getwd(dir)
- VALUE dir;
-{
- char *path = my_getcwd();
- VALUE cwd = rb_tainted_str_new2(path);
-
- free(path);
- return cwd;
-}
-
-static VALUE
-dir_s_chroot(dir, path)
- VALUE dir, path;
-{
-#if defined(HAVE_CHROOT) && !defined(__CHECKER__)
- rb_secure(2);
- SafeStringValue(path);
-
- if (chroot(RSTRING(path)->ptr) == -1)
- rb_sys_fail(RSTRING(path)->ptr);
-
- return INT2FIX(0);
-#else
- rb_notimplement();
- return Qnil; /* not reached */
-#endif
-}
-
-static VALUE
-dir_s_mkdir(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- VALUE path, vmode;
- int mode;
-
- if (rb_scan_args(argc, argv, "11", &path, &vmode) == 2) {
- mode = NUM2INT(vmode);
- }
- else {
- mode = 0777;
- }
-
- SafeStringValue(path);
- rb_secure(2);
-#if !defined(NT)
- if (mkdir(RSTRING(path)->ptr, mode) == -1)
- rb_sys_fail(RSTRING(path)->ptr);
-#else
- if (mkdir(RSTRING(path)->ptr) == -1)
- rb_sys_fail(RSTRING(path)->ptr);
-#endif
-
- return INT2FIX(0);
-}
-
-static VALUE
-dir_s_rmdir(obj, dir)
- VALUE obj, dir;
-{
- SafeStringValue(dir);
- rb_secure(2);
- if (rmdir(RSTRING(dir)->ptr) < 0)
- rb_sys_fail(RSTRING(dir)->ptr);
-
- return INT2FIX(0);
-}
-
-/* Return nonzero if S has any special globbing chars in it. */
-static int
-has_magic(s, send, flags)
- char *s, *send;
- int flags;
-{
- register char *p = s;
- register char c;
- int open = 0;
- int escape = !(flags & FNM_NOESCAPE);
-
- while ((c = *p++) != '\0') {
- switch (c) {
- case '?':
- case '*':
- return Qtrue;
-
- case '[': /* Only accept an open brace if there is a close */
- open++; /* brace to match it. Bracket expressions must be */
- continue; /* complete, according to Posix.2 */
- case ']':
- if (open)
- return Qtrue;
- continue;
-
- case '\\':
- if (escape && *p++ == '\0')
- return Qfalse;
- }
-
- if (send && p >= send) break;
- }
- return Qfalse;
-}
-
-static char*
-extract_path(p, pend)
- char *p, *pend;
-{
- char *alloc;
- int len;
-
- len = pend - p;
- alloc = ALLOC_N(char, len+1);
- memcpy(alloc, p, len);
- if (len > 1 && pend[-1] == '/'
-#if defined DOSISH
- && pend[-2] != ':'
-#endif
- ) {
- alloc[len-1] = 0;
- }
- else {
- alloc[len] = 0;
- }
-
- return alloc;
-}
-
-static char*
-extract_elem(path)
- char *path;
-{
- char *pend;
-
- pend = strchr(path, '/');
- if (!pend) pend = path + strlen(path);
-
- return extract_path(path, pend);
-}
-
-static void
-remove_backslashes(p)
- char *p;
-{
-#if defined DOSISH
- char *pend = p + strlen(p);
- char *t = p;
-
- while (p < pend) {
- if (*p == '\\') {
- if (++p == pend) break;
- }
- *t++ = *p++;
- }
- *t = '\0';
-#endif
-}
-
-#ifndef S_ISDIR
-# define S_ISDIR(m) ((m & S_IFMT) == S_IFDIR)
-#endif
-
-static void
-glob_helper(path, sub, flags, func, arg)
- char *path;
- char *sub;
- int flags;
- void (*func) _((const char*, VALUE));
- VALUE arg;
-{
- struct stat st;
- char *p, *m;
-
- p = sub ? sub : path;
- if (!has_magic(p, 0, flags)) {
- remove_backslashes(path);
- if (stat(path, &st) == 0) {
- (*func)(path, arg);
- }
- else if (errno != ENOENT) {
- /* In case stat error is other than ENOENT and
- we may want to know what is wrong. */
- rb_sys_warning(path);
- }
- return;
- }
-
- while (p) {
- if (*p == '/') p++;
- m = strchr(p, '/');
- if (has_magic(p, m, flags)) {
- char *dir, *base, *magic, *buf;
- DIR *dirp;
- struct dirent *dp;
- int recursive = 0;
-
- struct d_link {
- char *path;
- struct d_link *next;
- } *tmp, *link = 0;
-
- base = extract_path(path, p);
- if (path == p) dir = ".";
- else dir = base;
-
- magic = extract_elem(p);
- if (stat(dir, &st) < 0) {
- if (errno != ENOENT) rb_sys_warning(dir);
- free(base);
- break;
- }
- if (S_ISDIR(st.st_mode)) {
- if (m && strcmp(magic, "**") == 0) {
- int n = strlen(base);
- recursive = 1;
- buf = ALLOC_N(char, n+strlen(m)+3);
- sprintf(buf, "%s%s", base, *base ? m : m+1);
- glob_helper(buf, buf+n, flags, func, arg);
- free(buf);
- }
- dirp = opendir(dir);
- if (dirp == NULL) {
- rb_sys_warning(dir);
- free(base);
- break;
- }
- }
- else {
- free(base);
- break;
- }
-
-#if defined DOSISH
-#define BASE (*base && !((isdirsep(*base) && !base[1]) || (base[1] == ':' && isdirsep(base[2]) && !base[3])))
-#else
-#define BASE (*base && !(*base == '/' && !base[1]))
-#endif
-
- for (dp = readdir(dirp); dp != NULL; dp = readdir(dirp)) {
- if (recursive) {
- if (strcmp(".", dp->d_name) == 0 || strcmp("..", dp->d_name) == 0)
- continue;
- buf = ALLOC_N(char, strlen(base)+NAMLEN(dp)+strlen(m)+6);
- sprintf(buf, "%s%s%s", base, (BASE) ? "/" : "", dp->d_name);
- if (lstat(buf, &st) < 0) {
- if (errno != ENOENT) rb_sys_warning(buf);
- continue;
- }
- if (S_ISDIR(st.st_mode)) {
- char *t = buf+strlen(buf);
- strcpy(t, "/**");
- strcpy(t+3, m);
- glob_helper(buf, t, flags, func, arg);
- }
- free(buf);
- continue;
- }
- if (fnmatch(magic, dp->d_name, flags) == 0) {
- buf = ALLOC_N(char, strlen(base)+NAMLEN(dp)+2);
- sprintf(buf, "%s%s%s", base, (BASE) ? "/" : "", dp->d_name);
- if (!m) {
- (*func)(buf, arg);
- free(buf);
- continue;
- }
- tmp = ALLOC(struct d_link);
- tmp->path = buf;
- tmp->next = link;
- link = tmp;
- }
- }
- closedir(dirp);
- free(base);
- free(magic);
- if (link) {
- while (link) {
- if (stat(link->path, &st) == 0) {
- if (S_ISDIR(st.st_mode)) {
- int len = strlen(link->path);
- int mlen = strlen(m);
- char *t = ALLOC_N(char, len+mlen+1);
-
- sprintf(t, "%s%s", link->path, m);
- glob_helper(t, t+len, flags, func, arg);
- free(t);
- }
- tmp = link;
- link = link->next;
- free(tmp->path);
- free(tmp);
- }
- else {
- rb_sys_warning(link->path);
- }
- }
- break;
- }
- }
- p = m;
- }
-}
-
-static void
-rb_glob2(path, flags, func, arg)
- char *path;
- int flags;
- void (*func) _((const char*, VALUE));
- VALUE arg;
-{
- glob_helper(path, 0, flags, func, arg);
-}
-
-void
-rb_glob(path, func, arg)
- char *path;
- void (*func) _((const char*, VALUE));
- VALUE arg;
-{
- rb_glob2(path, 0, func, arg);
-}
-
-void
-rb_globi(path, func, arg)
- char *path;
- void (*func) _((const char*, VALUE));
- VALUE arg;
-{
- rb_glob2(path, FNM_CASEFOLD, func, arg);
-}
-
-static void
-push_pattern(path, ary)
- const char *path;
- VALUE ary;
-{
- VALUE str = rb_tainted_str_new2(path);
-
- if (ary) {
- rb_ary_push(ary, str);
- }
- else {
- rb_yield(str);
- }
-}
-
-static void
-push_globs(ary, s, flags)
- VALUE ary;
- char *s;
- int flags;
-{
- rb_glob2(s, flags, push_pattern, ary);
-}
-
-static void
-push_braces(ary, s, flags)
- VALUE ary;
- char *s;
- int flags;
-{
- char *buf;
- char *p, *t, *b;
- char *lbrace, *rbrace;
- int nest = 0;
-
- p = s;
- lbrace = rbrace = 0;
- while (*p) {
- if (*p == '{') {
- lbrace = p;
- break;
- }
- p++;
- }
- while (*p) {
- if (*p == '{') nest++;
- if (*p == '}' && --nest == 0) {
- rbrace = p;
- break;
- }
- p++;
- }
-
- if (lbrace) {
- int len = strlen(s);
- buf = xmalloc(len + 1);
- memcpy(buf, s, lbrace-s);
- b = buf + (lbrace-s);
- p = lbrace;
- while (*p != '}') {
- t = p + 1;
- for (p = t; *p!='}' && *p!=','; p++) {
- /* skip inner braces */
- if (*p == '{') while (*p!='}') p++;
- }
- memcpy(b, t, p-t);
- strcpy(b+(p-t), rbrace+1);
- push_braces(ary, buf, flags);
- }
- free(buf);
- }
- else {
- push_globs(ary, s, flags);
- }
-}
-
-#define isdelim(c) ((c)=='\0')
-
-static VALUE
-rb_push_glob(str, flags)
- VALUE str;
- int flags;
-{
- char *p, *pend;
- char *buf;
- char *t;
- int nest, maxnest;
- int noescape = flags & FNM_NOESCAPE;
- VALUE ary;
-
- if (rb_block_given_p())
- ary = 0;
- else
- ary = rb_ary_new();
-
- SafeStringValue(str);
- buf = xmalloc(RSTRING(str)->len + 1);
-
- p = RSTRING(str)->ptr;
- pend = p + RSTRING(str)->len;
-
- while (p < pend) {
- t = buf;
- nest = 0;
- while (p < pend && isdelim(*p)) p++;
- while (p < pend && !isdelim(*p)) {
- if (*p == '{') nest++, maxnest++;
- if (*p == '}') nest--;
- if (!noescape && *p == '\\') {
- *t++ = *p++;
- if (p == pend) break;
- }
- *t++ = *p++;
- }
- *t = '\0';
- if (maxnest == 0) {
- push_globs(ary, buf, flags);
- }
- else if (nest == 0) {
- push_braces(ary, buf, flags);
- }
- /* else unmatched braces */
- }
- free(buf);
-
- return ary;
-}
-
-static VALUE
-dir_s_aref(obj, str)
- VALUE obj, str;
-{
- return rb_push_glob(str, 0);
-}
-
-static VALUE
-dir_s_glob(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- VALUE str, rflags;
- int flags;
-
- if (rb_scan_args(argc, argv, "11", &str, &rflags) == 2)
- flags = NUM2INT(rflags);
- else
- flags = 0;
-
- return rb_push_glob(str, flags);
-}
-
-static VALUE
-dir_foreach(io, dirname)
- VALUE io, dirname;
-{
- VALUE dir;
-
- dir = rb_funcall(rb_cDir, rb_intern("open"), 1, dirname);
- rb_ensure(dir_each, dir, dir_close, dir);
- return Qnil;
-}
-
-static VALUE
-dir_entries(io, dirname)
- VALUE io, dirname;
-{
- VALUE dir;
-
- dir = rb_funcall(rb_cDir, rb_intern("open"), 1, dirname);
- return rb_ensure(rb_Array, dir, dir_close, dir);
-}
-
-static VALUE
-file_s_fnmatch(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- VALUE pattern, path;
- VALUE rflags;
- int flags;
-
- if (rb_scan_args(argc, argv, "21", &pattern, &path, &rflags) == 3)
- flags = NUM2INT(rflags);
- else
- flags = 0;
-
- StringValue(pattern);
- StringValue(path);
-
- if (fnmatch(RSTRING(pattern)->ptr, RSTRING(path)->ptr, flags) == 0)
- return Qtrue;
-
- return Qfalse;
-}
-
-void
-Init_Dir()
-{
- rb_cDir = rb_define_class("Dir", rb_cObject);
-
- rb_include_module(rb_cDir, rb_mEnumerable);
-
- rb_define_singleton_method(rb_cDir, "allocate", dir_s_alloc, 0);
- rb_define_singleton_method(rb_cDir, "open", dir_s_open, 1);
- rb_define_singleton_method(rb_cDir, "foreach", dir_foreach, 1);
- rb_define_singleton_method(rb_cDir, "entries", dir_entries, 1);
-
- rb_define_method(rb_cDir,"initialize", dir_initialize, 1);
- rb_define_method(rb_cDir,"path", dir_path, 0);
- rb_define_method(rb_cDir,"read", dir_read, 0);
- rb_define_method(rb_cDir,"each", dir_each, 0);
- rb_define_method(rb_cDir,"rewind", dir_rewind, 0);
- rb_define_method(rb_cDir,"tell", dir_tell, 0);
- rb_define_method(rb_cDir,"seek", dir_seek, 1);
- rb_define_method(rb_cDir,"pos", dir_tell, 0);
- rb_define_method(rb_cDir,"pos=", dir_set_pos, 1);
- rb_define_method(rb_cDir,"close", dir_close, 0);
-
- rb_define_singleton_method(rb_cDir,"chdir", dir_s_chdir, -1);
- rb_define_singleton_method(rb_cDir,"getwd", dir_s_getwd, 0);
- rb_define_singleton_method(rb_cDir,"pwd", dir_s_getwd, 0);
- rb_define_singleton_method(rb_cDir,"chroot", dir_s_chroot, 1);
- rb_define_singleton_method(rb_cDir,"mkdir", dir_s_mkdir, -1);
- rb_define_singleton_method(rb_cDir,"rmdir", dir_s_rmdir, 1);
- rb_define_singleton_method(rb_cDir,"delete", dir_s_rmdir, 1);
- rb_define_singleton_method(rb_cDir,"unlink", dir_s_rmdir, 1);
-
- rb_define_singleton_method(rb_cDir,"glob", dir_s_glob, -1);
- rb_define_singleton_method(rb_cDir,"[]", dir_s_aref, 1);
-
- rb_define_singleton_method(rb_cFile,"fnmatch", file_s_fnmatch, -1);
- rb_define_singleton_method(rb_cFile,"fnmatch?", file_s_fnmatch, -1);
-
- rb_file_const("FNM_NOESCAPE", INT2FIX(FNM_NOESCAPE));
- rb_file_const("FNM_PATHNAME", INT2FIX(FNM_PATHNAME));
- rb_file_const("FNM_DOTMATCH", INT2FIX(FNM_DOTMATCH));
- rb_file_const("FNM_CASEFOLD", INT2FIX(FNM_CASEFOLD));
-}
diff --git a/djgpp/README.djgpp b/djgpp/README.djgpp
deleted file mode 100644
index d81259ccac..0000000000
--- a/djgpp/README.djgpp
+++ /dev/null
@@ -1,21 +0,0 @@
-* How to compile and install on djgpp
-
-This is what you need to do to compile and install Ruby:
-
- 1. Run configure.bat, which will generate config.h and Makefile
- and ext/extmk.rb(GNU sed required).
- Message like this is normal:
- sed.exe: can't read 123456789: No such file or directory (ENOENT)
-
- 2. Edit defines.h if you need. Probably this step will not need.
-
- 3. Remove comment mark(#) before the module names from ext/Setup.dj (or
- add module names if not present).
-
- 4. Run make.
-
- 5. Optionally, run 'make test' to check whether the compiled Ruby
- interpreter works well. If you see the message "test succeeded",
- your ruby works as it should (hopefully).
-
- 6. Run 'make install'
diff --git a/djgpp/config.hin b/djgpp/config.hin
deleted file mode 100644
index 81941d79fa..0000000000
--- a/djgpp/config.hin
+++ /dev/null
@@ -1,73 +0,0 @@
-#define SIZEOF_INT 4
-#define SIZEOF_SHORT 2
-#define SIZEOF_LONG 4
-#define SIZEOF___INT64 0
-#define SIZEOF_VOIDP 4
-#define SIZEOF_FLOAT 4
-#define SIZEOF_DOUBLE 8
-#define HAVE_PROTOTYPES 1
-#define TOKEN_PASTE(x,y) x##y
-#define HAVE_STDARG_PROTOTYPES 1
-#define NORETURN(x) x __attribute__ ((noreturn))
-#define HAVE_DIRENT_H 1
-#define STDC_HEADERS 1
-#define HAVE_STDLIB_H 1
-#define HAVE_UNISTD_H 1
-#define HAVE_LIMITS_H 1
-#define HAVE_SYS_FILE_H 1
-#define HAVE_SYS_IOCTL_H 1
-#define HAVE_PWD_H 1
-#define HAVE_SYS_TIME_H 1
-#define HAVE_SYS_TIMES_H 1
-#define HAVE_SYS_PARAM_H 1
-#define HAVE_SYS_WAIT_H 1
-#define HAVE_STRING_H 1
-#define HAVE_UTIME_H 1
-#define HAVE_MEMORY_H 1
-#define HAVE_DIRECT_H 1
-#define HAVE_ST_BLKSIZE 1
-#define HAVE_ST_RDEV 1
-#define GETGROUPS_T gid_t
-#define RETSIGTYPE void
-#define HAVE_ALLOCA 1
-#define vfork fork
-#define HAVE_DUP2 1
-#define HAVE_SETENV 1
-#define HAVE_MEMMOVE 1
-#define HAVE_MKDIR 1
-#define HAVE_STRCASECMP 1
-#define HAVE_STRERROR 1
-#define HAVE_STRFTIME 1
-#define HAVE_STRCHR 1
-#define HAVE_STRSTR 1
-#define HAVE_STRTOUL 1
-#define HAVE_STRDUP 1
-#define HAVE_ISINF 1
-#define HAVE_ISNAN 1
-#define HAVE_FINITE 1
-#define HAVE_FMOD 1
-#define HAVE_RANDOM 1
-#define HAVE_WAITPID 1
-#define HAVE_GETCWD 1
-#define HAVE_TRUNCATE 1
-#define HAVE_CHSIZE 1
-#define HAVE_TIMES 1
-#define HAVE_UTIMES 1
-#define HAVE_FCNTL_H 1
-/*#define HAVE_SETITIMER 1*/
-#define HAVE_GETGROUPS 1
-#define HAVE_SIGPROCMASK 1
-#define HAVE_SIGACTION 1
-#define HAVE_SETSID 1
-#define POSIX_SIGNAL 1
-#define BSD_SETPGRP setpgrp
-#define RSHIFT(x,y) ((x)>>(int)y)
-#define DEFAULT_KCODE KCODE_NONE
-#define FILE_COUNT _cnt
-#define DLEXT ".o"
-#define RUBY_LIB "/lib/ruby/@MAJOR@.@MINOR@"
-#define RUBY_SITE_LIB "/lib/ruby/site_ruby"
-#define RUBY_SITE_LIB2 "/lib/ruby/site_ruby/@MAJOR@.@MINOR@"
-#define RUBY_PLATFORM "i386-msdosdjgpp"
-#define RUBY_ARCHLIB "/lib/ruby/@MAJOR@.@MINOR@/i386-msdosdjgpp"
-#define RUBY_SITE_ARCHLIB "/lib/ruby/site_ruby/@MAJOR@.@MINOR@/i386-msdosdjgpp"
diff --git a/djgpp/config.sed b/djgpp/config.sed
deleted file mode 100644
index 0713759f16..0000000000
--- a/djgpp/config.sed
+++ /dev/null
@@ -1,80 +0,0 @@
-/^SHELL/s,/bin/sh,$(COMSPEC),
-s%@srcdir@%.%g
-s%@top_srcdir@%..%
-s%@CFLAGS@%-O2%g
-s%@CPPFLAGS@%%g
-s%@CXXFLAGS@%%g
-s%@LDFLAGS@%%g
-s%@LIBS@%-lm %g
-s%@exec_prefix@%${prefix}%g
-s%@prefix@%/usr/local%g
-s%@program_transform_name@%s,x,x,%g
-s%@bindir@%${exec_prefix}/bin%g
-s%@sbindir@%${exec_prefix}/sbin%g
-s%@libexecdir@%${exec_prefix}/libexec%g
-s%@datadir@%${prefix}/share%g
-s%@sysconfdir@%${prefix}/etc%g
-s%@sharedstatedir@%${prefix}/com%g
-s%@localstatedir@%${prefix}/var%g
-s%@libdir@%${exec_prefix}/lib%g
-s%@includedir@%${prefix}/include%g
-s%@oldincludedir@%/usr/include%g
-s%@infodir@%${prefix}/info%g
-s%@mandir@%${prefix}/man%g
-s%@host@%i386-pc-msdosdjgpp%g
-s%@host_alias@%i386-msdosdjgpp%g
-s%@host_cpu@%i386%g
-s%@host_vendor@%pc%g
-s%@host_os@%msdosdjgpp%g
-s%@CC@%gcc%g
-s%@CPP@%gcc -E%g
-s%@YACC@%bison -y%g
-s%@RANLIB@%ranlib%g
-s%@AR@%ar%g
-s%@INSTALL_PROGRAM@%${INSTALL}%g
-s%@INSTALL_DATA@%${INSTALL} -m 644%g
-s%@SET_MAKE@%%g
-s%@LIBOBJS@% crypt.o flock.o vsnprintf.o%g
-s%@ALLOCA@%%g
-s%@DEFAULT_KCODE@%%g
-s%@EXEEXT@%.exe%g
-s%@OBJEXT@%o%g
-s%@XLDFLAGS@%%g
-s%@DLDFLAGS@%%g
-s%@STATIC@%%g
-s%@CCDLFLAGS@%%g
-s%@LDSHARED@%ld%g
-s%@DLEXT@%o%g
-s%@STRIP@%strip%g
-s%@EXTSTATIC@%%g
-s%@binsuffix@%.exe%g
-s%@setup@%Setup.dj%g
-s%@LIBRUBY@%libruby.a%g
-s%@LIBRUBY_A@%libruby.a%g
-s%@LIBRUBYARG@%libruby.a%g
-s%@LIBRUBY_SO@%%g
-s%@SOLIBS@%%g
-s%@arch@%i386-msdosdjgpp%g
-;s%/bin/rm%rm%
-s%@DLDLIBS@%-lc%g
-s%@PREP@%%
-s%@RUBY_INSTALL_NAME@%ruby%g
-s%@RUBY_SO_NAME@%%g
-s%@arch@%i386-msdosdjgpp%g
-s%@sitedir@%${prefix}/lib/ruby/site_ruby%g
-s%@configure_args@%%g
-s%@MINIRUBY@%./miniruby%
-s%@archlib@%/lib/ruby/i386-msdosdjgpp%
-;s%|| true%%
-;/\/dev\/null/ {
-;s,/dev/null 2>&1, nul,
-;s,2> /dev/null,,
-;}
-;/^config.status/ {
-; N;N;N;N;N;d
-;}
-;s%mv -f y\.tab\.c%if exist parse.c del parse.c\
- ren y_tab.c%
-;s%y\.tab\.c%y_tab.c%
-/^,THIS_IS_DUMMY_PATTERN_/i\
-ac_given_srcdir=.
diff --git a/djgpp/config.status b/djgpp/config.status
deleted file mode 100644
index 7a10754d1d..0000000000
--- a/djgpp/config.status
+++ /dev/null
@@ -1,77 +0,0 @@
-/^SHELL/s,/bin/sh,$(COMPSEC),
-s%@srcdir@%.%g
-s%@top_srcdir@%..%
-s%@CFLAGS@%-O2%g
-s%@CPPFLAGS@%%g
-s%@CXXFLAGS@%%g
-s%@LDFLAGS@%%g
-s%@LIBS@%-lm %g
-s%@exec_prefix@%${prefix}%g
-s%@prefix@%/usr/local%g
-s%@program_transform_name@%s,x,x,%g
-s%@bindir@%${exec_prefix}/bin%g
-s%@sbindir@%${exec_prefix}/sbin%g
-s%@libexecdir@%${exec_prefix}/libexec%g
-s%@datadir@%${prefix}/share%g
-s%@sysconfdir@%${prefix}/etc%g
-s%@sharedstatedir@%${prefix}/com%g
-s%@localstatedir@%${prefix}/var%g
-s%@libdir@%${exec_prefix}/lib%g
-s%@includedir@%${prefix}/include%g
-s%@oldincludedir@%/usr/include%g
-s%@infodir@%${prefix}/info%g
-s%@mandir@%${prefix}/man%g
-s%@host@%i386-pc-msdosdjgpp%g
-s%@host_alias@%i386-msdosdjgpp%g
-s%@host_cpu@%i386%g
-s%@host_vendor@%pc%g
-s%@host_os@%msdosdjgpp%g
-s%@CC@%gcc%g
-s%@CPP@%gcc -E%g
-s%@YACC@%bison -y%g
-s%@RANLIB@%ranlib%g
-s%@AR@%ar%g
-s%@INSTALL_PROGRAM@%${INSTALL}%g
-s%@INSTALL_DATA@%${INSTALL} -m 644%g
-s%@SET_MAKE@%%g
-s%@LIBOBJS@% crypt.o flock.o vsnprintf.o%g
-s%@ALLOCA@%%g
-s%@DEFAULT_KCODE@%%g
-s%@EXEEXT@%.exe%g
-s%@OBJEXT@%o%g
-s%@XLDFLAGS@%%g
-s%@DLDFLAGS@%%g
-s%@STATIC@%%g
-s%@CCDLFLAGS@%%g
-s%@LDSHARED@%ld%g
-s%@DLEXT@%o%g
-s%@STRIP@%strip%g
-s%@EXTSTATIC@%%g
-s%@binsuffix@%.exe%g
-s%@setup@%Setup.dj%g
-s%@LIBRUBY@%libruby.a%g
-s%@LIBRUBY_A@%libruby.a%g
-s%@LIBRUBYARG@%libruby.a%g
-s%@LIBRUBY_SO@%%g
-s%@SOLIBS@%%g
-s%@arch@%i386-msdosdjgpp%g
-;s%/bin/rm%rm%
-s%@DLDLIBS@%-lc%g
-s%@PREP@%%
-s%@RUBY_INSTALL_NAME@%ruby%g
-s%@RUBY_SO_NAME@%%g
-s%@arch@%i386-msdosdjgpp%g
-s%@sitedir@%${prefix}/lib/ruby/site_ruby%g
-s%@MINIRUBY@%./miniruby%
-s%@archlib@%/usr/local/lib/ruby/i386-msdosdjgpp%
-;s%|| true%%
-;/\/dev\/null/ {
-;s,/dev/null 2>&1, nul,
-;s,2> /dev/null,,
-;}
-;/^config.status/ {
-; N;N;N;N;N;d
-;}
-;s%y\.tab\.c%y_tab.c%
-/^,THIS_IS_DUMMY_PATTERN_/i\
-ac_given_srcdir=.
diff --git a/djgpp/configure.bat b/djgpp/configure.bat
deleted file mode 100644
index dbb4a08528..0000000000
--- a/djgpp/configure.bat
+++ /dev/null
@@ -1,21 +0,0 @@
-@echo off
-if exist configure.bat cd ..
-if exist djgpp\version.sed goto exist
- sed -n -f djgpp\mkver.sed < version.h > djgpp\version.sed
-:exist
-set _conv_=-f djgpp\config.sed -f djgpp\version.sed
-sed %_conv_% < Makefile.in > Makefile
-sed %_conv_% < ext\extmk.rb.in > ext\extmk.rb
-sed %_conv_% < djgpp\config.hin > config.h
-echo LFN check > 12345678
-sed -n /LFN/d 123456789 > nul
-if errorlevel 2 goto LFN
- copy missing\vsnprintf.c missing\vsnprint.c > nul
- copy djgpp\config.sed config.sta > nul
-goto end
-:LFN
- copy djgpp\config.sed config.status > nul
-:end
-set _conv_=
-del 12345678
-echo Now you must run a make.
diff --git a/djgpp/mkver.sed b/djgpp/mkver.sed
deleted file mode 100644
index f29b9ddd3e..0000000000
--- a/djgpp/mkver.sed
+++ /dev/null
@@ -1 +0,0 @@
-/RUBY_VERSION /s/^.*\([0-9][0-9]*\)\.\([0-9][0-9]*\)\.\([0-9][0-9]*\).*$/s,@MAJOR@,\1,;s,@MINOR@,\2,;s,@TEENY@,\3,/p
diff --git a/dln.c b/dln.c
deleted file mode 100644
index 100fa08a10..0000000000
--- a/dln.c
+++ /dev/null
@@ -1,1754 +0,0 @@
-/**********************************************************************
-
- dln.c -
-
- $Author$
- $Date$
- created at: Tue Jan 18 17:05:06 JST 1994
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
-
-**********************************************************************/
-
-#include "config.h"
-#include "defines.h"
-#include "dln.h"
-
-#ifdef HAVE_STDLIB_H
-# include <stdlib.h>
-#endif
-
-#ifdef __CHECKER__
-#undef HAVE_DLOPEN
-#undef USE_DLN_A_OUT
-#undef USE_DLN_DLOPEN
-#endif
-
-char *dln_argv0;
-void rb_loaderror();
-
-#ifdef _AIX
-#pragma alloca
-#endif
-
-#if defined(HAVE_ALLOCA_H) && !defined(__GNUC__)
-#include <alloca.h>
-#endif
-
-#ifdef HAVE_STRING_H
-# include <string.h>
-#else
-# include <strings.h>
-#endif
-
-#ifndef xmalloc
-void *xmalloc();
-void *xcalloc();
-void *xrealloc();
-#endif
-
-#include <stdio.h>
-#ifdef NT
-#include "missing/file.h"
-#endif
-#include <sys/types.h>
-#include <sys/stat.h>
-
-#ifndef S_ISDIR
-# define S_ISDIR(m) ((m & S_IFMT) == S_IFDIR)
-#endif
-
-#ifdef HAVE_SYS_PARAM_H
-# include <sys/param.h>
-#else
-# define MAXPATHLEN 1024
-#endif
-
-#ifdef HAVE_UNISTD_H
-# include <unistd.h>
-#endif
-
-#ifndef NT
-char *getenv();
-#endif
-
-#ifdef __MACOS__
-# include <TextUtils.h>
-# include <CodeFragments.h>
-# include <Aliases.h>
-# include "macruby_private.h"
-#endif
-
-#ifdef __BEOS__
-# include <image.h>
-#endif
-
-int eaccess();
-
-#if defined(HAVE_DLOPEN) && !defined(USE_DLN_A_OUT) && !defined(_AIX)
-/* dynamic load with dlopen() */
-# define USE_DLN_DLOPEN
-#endif
-
-#ifndef FUNCNAME_PATTERN
-# if defined(__hp9000s300) || (defined(__NetBSD__) && !defined(__ELF__)) || defined(__BORLANDC__) || (defined(__FreeBSD__) && !defined(__ELF__)) || defined(__OpenBSD__) || defined(NeXT) || defined(__WATCOMC__) || defined(__APPLE__)
-# define FUNCNAME_PATTERN "_Init_%s"
-# else
-# define FUNCNAME_PATTERN "Init_%s"
-# endif
-#endif
-
-static void
-init_funcname(buf, file)
- char **buf;
- char *file;
-{
- char *p, *slash;
-
- /* Load the file as an object one */
- for (p = file, slash = p-1; *p; p++) /* Find position of last '/' */
-#ifdef __MACOS__
- if (*p == ':') slash = p;
-#else
- if (*p == '/') slash = p;
-#endif
-
-/* This assumes that systems without length limitation for file names
- provide asprintf(). This shouldn't be too unlikely. */
-#ifdef MAXPATHLEN
- *buf = xmalloc(MAXPATHLEN);
- snprintf(*buf, MAXPATHLEN, FUNCNAME_PATTERN, slash + 1);
-#else
- asprintf(buf, FUNCNAME_PATTERN, slash + 1);
-#endif
- for (p = *buf; *p; p++) { /* Delete suffix if it exists */
- if (*p == '.') {
- *p = '\0'; break;
- }
- }
-}
-
-#ifdef USE_DLN_A_OUT
-
-#ifndef LIBC_NAME
-# define LIBC_NAME "libc.a"
-#endif
-
-#ifndef DLN_DEFAULT_LIB_PATH
-# define DLN_DEFAULT_LIB_PATH "/lib:/usr/lib:/usr/local/lib:."
-#endif
-
-#include <errno.h>
-
-static int dln_errno;
-
-#define DLN_ENOEXEC ENOEXEC /* Exec format error */
-#define DLN_ECONFL 1201 /* Symbol name conflict */
-#define DLN_ENOINIT 1202 /* No inititalizer given */
-#define DLN_EUNDEF 1203 /* Undefine symbol remains */
-#define DLN_ENOTLIB 1204 /* Not a library file */
-#define DLN_EBADLIB 1205 /* Malformed library file */
-#define DLN_EINIT 1206 /* Not initialized */
-
-static int dln_init_p = 0;
-
-#include <ar.h>
-#include <a.out.h>
-#ifndef N_COMM
-# define N_COMM 0x12
-#endif
-#ifndef N_MAGIC
-# define N_MAGIC(x) (x).a_magic
-#endif
-
-#define INVALID_OBJECT(h) (N_MAGIC(h) != OMAGIC)
-
-#include "util.h"
-#include "st.h"
-
-static st_table *sym_tbl;
-static st_table *undef_tbl;
-
-static int load_lib();
-
-static int
-load_header(fd, hdrp, disp)
- int fd;
- struct exec *hdrp;
- long disp;
-{
- int size;
-
- lseek(fd, disp, 0);
- size = read(fd, hdrp, sizeof(struct exec));
- if (size == -1) {
- dln_errno = errno;
- return -1;
- }
- if (size != sizeof(struct exec) || N_BADMAG(*hdrp)) {
- dln_errno = DLN_ENOEXEC;
- return -1;
- }
- return 0;
-}
-
-#if defined(sequent)
-#define RELOC_SYMBOL(r) ((r)->r_symbolnum)
-#define RELOC_MEMORY_SUB_P(r) ((r)->r_bsr)
-#define RELOC_PCREL_P(r) ((r)->r_pcrel || (r)->r_bsr)
-#define RELOC_TARGET_SIZE(r) ((r)->r_length)
-#endif
-
-/* Default macros */
-#ifndef RELOC_ADDRESS
-#define RELOC_ADDRESS(r) ((r)->r_address)
-#define RELOC_EXTERN_P(r) ((r)->r_extern)
-#define RELOC_SYMBOL(r) ((r)->r_symbolnum)
-#define RELOC_MEMORY_SUB_P(r) 0
-#define RELOC_PCREL_P(r) ((r)->r_pcrel)
-#define RELOC_TARGET_SIZE(r) ((r)->r_length)
-#endif
-
-#if defined(sun) && defined(sparc)
-/* Sparc (Sun 4) macros */
-# undef relocation_info
-# define relocation_info reloc_info_sparc
-# define R_RIGHTSHIFT(r) (reloc_r_rightshift[(r)->r_type])
-# define R_BITSIZE(r) (reloc_r_bitsize[(r)->r_type])
-# define R_LENGTH(r) (reloc_r_length[(r)->r_type])
-static int reloc_r_rightshift[] = {
- 0, 0, 0, 0, 0, 0, 2, 2, 10, 0, 0, 0, 0, 0, 0,
-};
-static int reloc_r_bitsize[] = {
- 8, 16, 32, 8, 16, 32, 30, 22, 22, 22, 13, 10, 32, 32, 16,
-};
-static int reloc_r_length[] = {
- 0, 1, 2, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
-};
-# define R_PCREL(r) \
- ((r)->r_type >= RELOC_DISP8 && (r)->r_type <= RELOC_WDISP22)
-# define R_SYMBOL(r) ((r)->r_index)
-#endif
-
-#if defined(sequent)
-#define R_SYMBOL(r) ((r)->r_symbolnum)
-#define R_MEMORY_SUB(r) ((r)->r_bsr)
-#define R_PCREL(r) ((r)->r_pcrel || (r)->r_bsr)
-#define R_LENGTH(r) ((r)->r_length)
-#endif
-
-#ifndef R_SYMBOL
-# define R_SYMBOL(r) ((r)->r_symbolnum)
-# define R_MEMORY_SUB(r) 0
-# define R_PCREL(r) ((r)->r_pcrel)
-# define R_LENGTH(r) ((r)->r_length)
-#endif
-
-static struct relocation_info *
-load_reloc(fd, hdrp, disp)
- int fd;
- struct exec *hdrp;
- long disp;
-{
- struct relocation_info *reloc;
- int size;
-
- lseek(fd, disp + N_TXTOFF(*hdrp) + hdrp->a_text + hdrp->a_data, 0);
- size = hdrp->a_trsize + hdrp->a_drsize;
- reloc = (struct relocation_info*)xmalloc(size);
- if (reloc == NULL) {
- dln_errno = errno;
- return NULL;
- }
-
- if (read(fd, reloc, size) != size) {
- dln_errno = errno;
- free(reloc);
- return NULL;
- }
-
- return reloc;
-}
-
-static struct nlist *
-load_sym(fd, hdrp, disp)
- int fd;
- struct exec *hdrp;
- long disp;
-{
- struct nlist * buffer;
- struct nlist * sym;
- struct nlist * end;
- long displ;
- int size;
-
- lseek(fd, N_SYMOFF(*hdrp) + hdrp->a_syms + disp, 0);
- if (read(fd, &size, sizeof(int)) != sizeof(int)) {
- goto err_noexec;
- }
-
- buffer = (struct nlist*)xmalloc(hdrp->a_syms + size);
- if (buffer == NULL) {
- dln_errno = errno;
- return NULL;
- }
-
- lseek(fd, disp + N_SYMOFF(*hdrp), 0);
- if (read(fd, buffer, hdrp->a_syms + size) != hdrp->a_syms + size) {
- free(buffer);
- goto err_noexec;
- }
-
- sym = buffer;
- end = sym + hdrp->a_syms / sizeof(struct nlist);
- displ = (long)buffer + (long)(hdrp->a_syms);
-
- while (sym < end) {
- sym->n_un.n_name = (char*)sym->n_un.n_strx + displ;
- sym++;
- }
- return buffer;
-
- err_noexec:
- dln_errno = DLN_ENOEXEC;
- return NULL;
-}
-
-static st_table *
-sym_hash(hdrp, syms)
- struct exec *hdrp;
- struct nlist *syms;
-{
- st_table *tbl;
- struct nlist *sym = syms;
- struct nlist *end = syms + (hdrp->a_syms / sizeof(struct nlist));
-
- tbl = st_init_strtable();
- if (tbl == NULL) {
- dln_errno = errno;
- return NULL;
- }
-
- while (sym < end) {
- st_insert(tbl, sym->n_un.n_name, sym);
- sym++;
- }
- return tbl;
-}
-
-static int
-dln_init(prog)
- const char *prog;
-{
- char *file;
- int fd;
- struct exec hdr;
- struct nlist *syms;
-
- if (dln_init_p == 1) return 0;
-
- file = dln_find_exe(prog, NULL);
- if (file == NULL || (fd = open(file, O_RDONLY)) < 0) {
- dln_errno = errno;
- return -1;
- }
-
- if (load_header(fd, &hdr, 0) == -1) return -1;
- syms = load_sym(fd, &hdr, 0);
- if (syms == NULL) {
- close(fd);
- return -1;
- }
- sym_tbl = sym_hash(&hdr, syms);
- if (sym_tbl == NULL) { /* file may be start with #! */
- char c = '\0';
- char buf[MAXPATHLEN];
- char *p;
-
- free(syms);
- lseek(fd, 0L, 0);
- if (read(fd, &c, 1) == -1) {
- dln_errno = errno;
- return -1;
- }
- if (c != '#') goto err_noexec;
- if (read(fd, &c, 1) == -1) {
- dln_errno = errno;
- return -1;
- }
- if (c != '!') goto err_noexec;
-
- p = buf;
- /* skip forwading spaces */
- while (read(fd, &c, 1) == 1) {
- if (c == '\n') goto err_noexec;
- if (c != '\t' && c != ' ') {
- *p++ = c;
- break;
- }
- }
- /* read in command name */
- while (read(fd, p, 1) == 1) {
- if (*p == '\n' || *p == '\t' || *p == ' ') break;
- p++;
- if (p-buf >= MAXPATHLEN) {
- dln_errno = ENAMETOOLONG;
- return -1;
- }
- }
- *p = '\0';
-
- return dln_init(buf);
- }
- dln_init_p = 1;
- undef_tbl = st_init_strtable();
- close(fd);
- return 0;
-
- err_noexec:
- close(fd);
- dln_errno = DLN_ENOEXEC;
- return -1;
-}
-
-static long
-load_text_data(fd, hdrp, bss, disp)
- int fd;
- struct exec *hdrp;
- int bss;
- long disp;
-{
- int size;
- unsigned char* addr;
-
- lseek(fd, disp + N_TXTOFF(*hdrp), 0);
- size = hdrp->a_text + hdrp->a_data;
-
- if (bss == -1) size += hdrp->a_bss;
- else if (bss > 1) size += bss;
-
- addr = (unsigned char*)xmalloc(size);
- if (addr == NULL) {
- dln_errno = errno;
- return 0;
- }
-
- if (read(fd, addr, size) != size) {
- dln_errno = errno;
- free(addr);
- return 0;
- }
-
- if (bss == -1) {
- memset(addr + hdrp->a_text + hdrp->a_data, 0, hdrp->a_bss);
- }
- else if (bss > 0) {
- memset(addr + hdrp->a_text + hdrp->a_data, 0, bss);
- }
-
- return (long)addr;
-}
-
-static int
-undef_print(key, value)
- char *key, *value;
-{
- fprintf(stderr, " %s\n", key);
- return ST_CONTINUE;
-}
-
-static void
-dln_print_undef()
-{
- fprintf(stderr, " Undefined symbols:\n");
- st_foreach(undef_tbl, undef_print, NULL);
-}
-
-static void
-dln_undefined()
-{
- if (undef_tbl->num_entries > 0) {
- fprintf(stderr, "dln: Calling undefined function\n");
- dln_print_undef();
- rb_exit(1);
- }
-}
-
-struct undef {
- char *name;
- struct relocation_info reloc;
- long base;
- char *addr;
- union {
- char c;
- short s;
- long l;
- } u;
-};
-
-static st_table *reloc_tbl = NULL;
-static void
-link_undef(name, base, reloc)
- const char *name;
- long base;
- struct relocation_info *reloc;
-{
- static int u_no = 0;
- struct undef *obj;
- char *addr = (char*)(reloc->r_address + base);
-
- obj = (struct undef*)xmalloc(sizeof(struct undef));
- obj->name = strdup(name);
- obj->reloc = *reloc;
- obj->base = base;
- switch (R_LENGTH(reloc)) {
- case 0: /* byte */
- obj->u.c = *addr;
- break;
- case 1: /* word */
- obj->u.s = *(short*)addr;
- break;
- case 2: /* long */
- obj->u.l = *(long*)addr;
- break;
- }
- if (reloc_tbl == NULL) {
- reloc_tbl = st_init_numtable();
- }
- st_insert(reloc_tbl, u_no++, obj);
-}
-
-struct reloc_arg {
- const char *name;
- long value;
-};
-
-static int
-reloc_undef(no, undef, arg)
- int no;
- struct undef *undef;
- struct reloc_arg *arg;
-{
- int datum;
- char *address;
-#if defined(sun) && defined(sparc)
- unsigned int mask = 0;
-#endif
-
- if (strcmp(arg->name, undef->name) != 0) return ST_CONTINUE;
- address = (char*)(undef->base + undef->reloc.r_address);
- datum = arg->value;
-
- if (R_PCREL(&(undef->reloc))) datum -= undef->base;
-#if defined(sun) && defined(sparc)
- datum += undef->reloc.r_addend;
- datum >>= R_RIGHTSHIFT(&(undef->reloc));
- mask = (1 << R_BITSIZE(&(undef->reloc))) - 1;
- mask |= mask -1;
- datum &= mask;
- switch (R_LENGTH(&(undef->reloc))) {
- case 0:
- *address = undef->u.c;
- *address &= ~mask;
- *address |= datum;
- break;
- case 1:
- *(short *)address = undef->u.s;
- *(short *)address &= ~mask;
- *(short *)address |= datum;
- break;
- case 2:
- *(long *)address = undef->u.l;
- *(long *)address &= ~mask;
- *(long *)address |= datum;
- break;
- }
-#else
- switch (R_LENGTH(&(undef->reloc))) {
- case 0: /* byte */
- if (R_MEMORY_SUB(&(undef->reloc)))
- *address = datum - *address;
- else *address = undef->u.c + datum;
- break;
- case 1: /* word */
- if (R_MEMORY_SUB(&(undef->reloc)))
- *(short*)address = datum - *(short*)address;
- else *(short*)address = undef->u.s + datum;
- break;
- case 2: /* long */
- if (R_MEMORY_SUB(&(undef->reloc)))
- *(long*)address = datum - *(long*)address;
- else *(long*)address = undef->u.l + datum;
- break;
- }
-#endif
- free(undef->name);
- free(undef);
- return ST_DELETE;
-}
-
-static void
-unlink_undef(name, value)
- const char *name;
- long value;
-{
- struct reloc_arg arg;
-
- arg.name = name;
- arg.value = value;
- st_foreach(reloc_tbl, reloc_undef, &arg);
-}
-
-#ifdef N_INDR
-struct indr_data {
- char *name0, *name1;
-};
-
-static int
-reloc_repl(no, undef, data)
- int no;
- struct undef *undef;
- struct indr_data *data;
-{
- if (strcmp(data->name0, undef->name) == 0) {
- free(undef->name);
- undef->name = strdup(data->name1);
- }
- return ST_CONTINUE;
-}
-#endif
-
-static int
-load_1(fd, disp, need_init)
- int fd;
- long disp;
- const char *need_init;
-{
- static char *libc = LIBC_NAME;
- struct exec hdr;
- struct relocation_info *reloc = NULL;
- long block = 0;
- long new_common = 0; /* Length of new common */
- struct nlist *syms = NULL;
- struct nlist *sym;
- struct nlist *end;
- int init_p = 0;
-
- if (load_header(fd, &hdr, disp) == -1) return -1;
- if (INVALID_OBJECT(hdr)) {
- dln_errno = DLN_ENOEXEC;
- return -1;
- }
- reloc = load_reloc(fd, &hdr, disp);
- if (reloc == NULL) return -1;
- syms = load_sym(fd, &hdr, disp);
- if (syms == NULL) return -1;
-
- sym = syms;
- end = syms + (hdr.a_syms / sizeof(struct nlist));
- while (sym < end) {
- struct nlist *old_sym;
- int value = sym->n_value;
-
-#ifdef N_INDR
- if (sym->n_type == (N_INDR | N_EXT)) {
- char *key = sym->n_un.n_name;
-
- if (st_lookup(sym_tbl, sym[1].n_un.n_name, &old_sym)) {
- if (st_delete(undef_tbl, &key, NULL)) {
- unlink_undef(key, old_sym->n_value);
- free(key);
- }
- }
- else {
- struct indr_data data;
-
- data.name0 = sym->n_un.n_name;
- data.name1 = sym[1].n_un.n_name;
- st_foreach(reloc_tbl, reloc_repl, &data);
-
- st_insert(undef_tbl, strdup(sym[1].n_un.n_name), NULL);
- if (st_delete(undef_tbl, &key, NULL)) {
- free(key);
- }
- }
- sym += 2;
- continue;
- }
-#endif
- if (sym->n_type == (N_UNDF | N_EXT)) {
- if (st_lookup(sym_tbl, sym->n_un.n_name, &old_sym) == 0) {
- old_sym = NULL;
- }
-
- if (value) {
- if (old_sym) {
- sym->n_type = N_EXT | N_COMM;
- sym->n_value = old_sym->n_value;
- }
- else {
- int rnd =
- value >= sizeof(double) ? sizeof(double) - 1
- : value >= sizeof(long) ? sizeof(long) - 1
- : sizeof(short) - 1;
-
- sym->n_type = N_COMM;
- new_common += rnd;
- new_common &= ~(long)rnd;
- sym->n_value = new_common;
- new_common += value;
- }
- }
- else {
- if (old_sym) {
- sym->n_type = N_EXT | N_COMM;
- sym->n_value = old_sym->n_value;
- }
- else {
- sym->n_value = (long)dln_undefined;
- st_insert(undef_tbl, strdup(sym->n_un.n_name), NULL);
- }
- }
- }
- sym++;
- }
-
- block = load_text_data(fd, &hdr, hdr.a_bss + new_common, disp);
- if (block == 0) goto err_exit;
-
- sym = syms;
- while (sym < end) {
- struct nlist *new_sym;
- char *key;
-
- switch (sym->n_type) {
- case N_COMM:
- sym->n_value += hdr.a_text + hdr.a_data;
- case N_TEXT|N_EXT:
- case N_DATA|N_EXT:
-
- sym->n_value += block;
-
- if (st_lookup(sym_tbl, sym->n_un.n_name, &new_sym) != 0
- && new_sym->n_value != (long)dln_undefined) {
- dln_errno = DLN_ECONFL;
- goto err_exit;
- }
-
- key = sym->n_un.n_name;
- if (st_delete(undef_tbl, &key, NULL) != 0) {
- unlink_undef(key, sym->n_value);
- free(key);
- }
-
- new_sym = (struct nlist*)xmalloc(sizeof(struct nlist));
- *new_sym = *sym;
- new_sym->n_un.n_name = strdup(sym->n_un.n_name);
- st_insert(sym_tbl, new_sym->n_un.n_name, new_sym);
- break;
-
- case N_TEXT:
- case N_DATA:
- sym->n_value += block;
- break;
- }
- sym++;
- }
-
- /*
- * First comes the text-relocation
- */
- {
- struct relocation_info * rel = reloc;
- struct relocation_info * rel_beg = reloc +
- (hdr.a_trsize/sizeof(struct relocation_info));
- struct relocation_info * rel_end = reloc +
- (hdr.a_trsize+hdr.a_drsize)/sizeof(struct relocation_info);
-
- while (rel < rel_end) {
- char *address = (char*)(rel->r_address + block);
- long datum = 0;
-#if defined(sun) && defined(sparc)
- unsigned int mask = 0;
-#endif
-
- if(rel >= rel_beg)
- address += hdr.a_text;
-
- if (rel->r_extern) { /* Look it up in symbol-table */
- sym = &(syms[R_SYMBOL(rel)]);
- switch (sym->n_type) {
- case N_EXT|N_UNDF:
- link_undef(sym->n_un.n_name, block, rel);
- case N_EXT|N_COMM:
- case N_COMM:
- datum = sym->n_value;
- break;
- default:
- goto err_exit;
- }
- } /* end.. look it up */
- else { /* is static */
- switch (R_SYMBOL(rel)) {
- case N_TEXT:
- case N_DATA:
- datum = block;
- break;
- case N_BSS:
- datum = block + new_common;
- break;
- case N_ABS:
- break;
- }
- } /* end .. is static */
- if (R_PCREL(rel)) datum -= block;
-
-#if defined(sun) && defined(sparc)
- datum += rel->r_addend;
- datum >>= R_RIGHTSHIFT(rel);
- mask = (1 << R_BITSIZE(rel)) - 1;
- mask |= mask -1;
- datum &= mask;
-
- switch (R_LENGTH(rel)) {
- case 0:
- *address &= ~mask;
- *address |= datum;
- break;
- case 1:
- *(short *)address &= ~mask;
- *(short *)address |= datum;
- break;
- case 2:
- *(long *)address &= ~mask;
- *(long *)address |= datum;
- break;
- }
-#else
- switch (R_LENGTH(rel)) {
- case 0: /* byte */
- if (datum < -128 || datum > 127) goto err_exit;
- *address += datum;
- break;
- case 1: /* word */
- *(short *)address += datum;
- break;
- case 2: /* long */
- *(long *)address += datum;
- break;
- }
-#endif
- rel++;
- }
- }
-
- if (need_init) {
- int len;
- char **libs_to_be_linked = 0;
- char *buf;
-
- if (undef_tbl->num_entries > 0) {
- if (load_lib(libc) == -1) goto err_exit;
- }
-
- init_funcname(&buf, need_init);
- len = strlen(buf);
-
- for (sym = syms; sym<end; sym++) {
- char *name = sym->n_un.n_name;
- if (name[0] == '_' && sym->n_value >= block) {
- if (strcmp(name+1, "dln_libs_to_be_linked") == 0) {
- libs_to_be_linked = (char**)sym->n_value;
- }
- else if (strcmp(name+1, buf) == 0) {
- init_p = 1;
- ((int (*)())sym->n_value)();
- }
- }
- }
- free (buf);
- if (libs_to_be_linked && undef_tbl->num_entries > 0) {
- while (*libs_to_be_linked) {
- load_lib(*libs_to_be_linked);
- libs_to_be_linked++;
- }
- }
- }
- free(reloc);
- free(syms);
- if (need_init) {
- if (init_p == 0) {
- dln_errno = DLN_ENOINIT;
- return -1;
- }
- if (undef_tbl->num_entries > 0) {
- if (load_lib(libc) == -1) goto err_exit;
- if (undef_tbl->num_entries > 0) {
- dln_errno = DLN_EUNDEF;
- return -1;
- }
- }
- }
- return 0;
-
- err_exit:
- if (syms) free(syms);
- if (reloc) free(reloc);
- if (block) free((char*)block);
- return -1;
-}
-
-static int target_offset;
-static int
-search_undef(key, value, lib_tbl)
- const char *key;
- int value;
- st_table *lib_tbl;
-{
- long offset;
-
- if (st_lookup(lib_tbl, key, &offset) == 0) return ST_CONTINUE;
- target_offset = offset;
- return ST_STOP;
-}
-
-struct symdef {
- int rb_str_index;
- int lib_offset;
-};
-
-char *dln_librrb_ary_path = DLN_DEFAULT_LIB_PATH;
-
-static int
-load_lib(lib)
- const char *lib;
-{
- char *path, *file;
- char armagic[SARMAG];
- int fd, size;
- struct ar_hdr ahdr;
- st_table *lib_tbl = NULL;
- int *data, nsym;
- struct symdef *base;
- char *name_base;
-
- if (dln_init_p == 0) {
- dln_errno = DLN_ENOINIT;
- return -1;
- }
-
- if (undef_tbl->num_entries == 0) return 0;
- dln_errno = DLN_EBADLIB;
-
- if (lib[0] == '-' && lib[1] == 'l') {
- char *p = alloca(strlen(lib) + 4);
- sprintf(p, "lib%s.a", lib+2);
- lib = p;
- }
-
- /* library search path: */
- /* look for environment variable DLN_LIBRARY_PATH first. */
- /* then variable dln_librrb_ary_path. */
- /* if path is still NULL, use "." for path. */
- path = getenv("DLN_LIBRARY_PATH");
- if (path == NULL) path = dln_librrb_ary_path;
-
- file = dln_find_file(lib, path);
- fd = open(file, O_RDONLY);
- if (fd == -1) goto syserr;
- size = read(fd, armagic, SARMAG);
- if (size == -1) goto syserr;
-
- if (size != SARMAG) {
- dln_errno = DLN_ENOTLIB;
- goto badlib;
- }
- size = read(fd, &ahdr, sizeof(ahdr));
- if (size == -1) goto syserr;
- if (size != sizeof(ahdr) || sscanf(ahdr.ar_size, "%d", &size) != 1) {
- goto badlib;
- }
-
- if (strncmp(ahdr.ar_name, "__.SYMDEF", 9) == 0) {
- /* make hash table from __.SYMDEF */
-
- lib_tbl = st_init_strtable();
- data = (int*)xmalloc(size);
- if (data == NULL) goto syserr;
- size = read(fd, data, size);
- nsym = *data / sizeof(struct symdef);
- base = (struct symdef*)(data + 1);
- name_base = (char*)(base + nsym) + sizeof(int);
- while (nsym > 0) {
- char *name = name_base + base->rb_str_index;
-
- st_insert(lib_tbl, name, base->lib_offset + sizeof(ahdr));
- nsym--;
- base++;
- }
- for (;;) {
- target_offset = -1;
- st_foreach(undef_tbl, search_undef, lib_tbl);
- if (target_offset == -1) break;
- if (load_1(fd, target_offset, 0) == -1) {
- st_free_table(lib_tbl);
- free(data);
- goto badlib;
- }
- if (undef_tbl->num_entries == 0) break;
- }
- free(data);
- st_free_table(lib_tbl);
- }
- else {
- /* linear library, need to scan (FUTURE) */
-
- for (;;) {
- int offset = SARMAG;
- int found = 0;
- struct exec hdr;
- struct nlist *syms, *sym, *end;
-
- while (undef_tbl->num_entries > 0) {
- found = 0;
- lseek(fd, offset, 0);
- size = read(fd, &ahdr, sizeof(ahdr));
- if (size == -1) goto syserr;
- if (size == 0) break;
- if (size != sizeof(ahdr)
- || sscanf(ahdr.ar_size, "%d", &size) != 1) {
- goto badlib;
- }
- offset += sizeof(ahdr);
- if (load_header(fd, &hdr, offset) == -1)
- goto badlib;
- syms = load_sym(fd, &hdr, offset);
- if (syms == NULL) goto badlib;
- sym = syms;
- end = syms + (hdr.a_syms / sizeof(struct nlist));
- while (sym < end) {
- if (sym->n_type == N_EXT|N_TEXT
- && st_lookup(undef_tbl, sym->n_un.n_name, NULL)) {
- break;
- }
- sym++;
- }
- if (sym < end) {
- found++;
- free(syms);
- if (load_1(fd, offset, 0) == -1) {
- goto badlib;
- }
- }
- offset += size;
- if (offset & 1) offset++;
- }
- if (found) break;
- }
- }
- close(fd);
- return 0;
-
- syserr:
- dln_errno = errno;
- badlib:
- if (fd >= 0) close(fd);
- return -1;
-}
-
-static int
-load(file)
- const char *file;
-{
- int fd;
- int result;
-
- if (dln_init_p == 0) {
- if (dln_init(dln_argv0) == -1) return -1;
- }
- result = strlen(file);
- if (file[result-1] == 'a') {
- return load_lib(file);
- }
-
- fd = open(file, O_RDONLY);
- if (fd == -1) {
- dln_errno = errno;
- return -1;
- }
- result = load_1(fd, 0, file);
- close(fd);
-
- return result;
-}
-
-void*
-dln_sym(name)
- const char *name;
-{
- struct nlist *sym;
-
- if (st_lookup(sym_tbl, name, &sym))
- return (void*)sym->n_value;
- return NULL;
-}
-
-#endif /* USE_DLN_A_OUT */
-
-#ifdef USE_DLN_DLOPEN
-# ifdef __NetBSD__
-# include <nlist.h>
-# include <link.h>
-# else
-# include <dlfcn.h>
-# endif
-#endif
-
-#ifdef __hpux
-#include <errno.h>
-#include "dl.h"
-#endif
-
-#if defined(_AIX)
-#include <ctype.h> /* for isdigit() */
-#include <errno.h> /* for global errno */
-#include <sys/ldr.h>
-#endif
-
-#ifdef NeXT
-#if NS_TARGET_MAJOR < 4
-#include <mach-o/rld.h>
-#else
-#include <mach-o/dyld.h>
-#endif
-#endif
-#ifdef __APPLE__
-#include <mach-o/dyld.h>
-#endif
-
-
-#if defined _WIN32 && !defined __CYGWIN__
-#include <windows.h>
-#endif
-
-static const char *
-dln_strerror()
-{
-#ifdef USE_DLN_A_OUT
- char *strerror();
-
- switch (dln_errno) {
- case DLN_ECONFL:
- return "Symbol name conflict";
- case DLN_ENOINIT:
- return "No inititalizer given";
- case DLN_EUNDEF:
- return "Unresolved symbols";
- case DLN_ENOTLIB:
- return "Not a library file";
- case DLN_EBADLIB:
- return "Malformed library file";
- case DLN_EINIT:
- return "Not initialized";
- default:
- return strerror(dln_errno);
- }
-#endif
-
-#ifdef USE_DLN_DLOPEN
- return (char*)dlerror();
-#endif
-
-#if defined _WIN32 && !defined __CYGWIN__
- static char message[1024];
- int error = GetLastError();
- char *p = message;
- p += sprintf(message, "%d: ", error);
- FormatMessage(
- FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
- NULL,
- error,
- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
- p,
- sizeof message - strlen(message),
- NULL);
-
- for (p = message; *p; p++) {
- if (*p == '\n' || *p == '\r')
- *p = ' ';
- }
- return message;
-#endif
-}
-
-
-#if defined(_AIX) && ! defined(_IA64)
-static void
-aix_loaderror(const char *pathname)
-{
- char *message[8], errbuf[1024];
- int i,j;
-
- struct errtab {
- int errno;
- char *errstr;
- } load_errtab[] = {
- {L_ERROR_TOOMANY, "too many errors, rest skipped."},
- {L_ERROR_NOLIB, "can't load library:"},
- {L_ERROR_UNDEF, "can't find symbol in library:"},
- {L_ERROR_RLDBAD,
- "RLD index out of range or bad relocation type:"},
- {L_ERROR_FORMAT, "not a valid, executable xcoff file:"},
- {L_ERROR_MEMBER,
- "file not an archive or does not contain requested member:"},
- {L_ERROR_TYPE, "symbol table mismatch:"},
- {L_ERROR_ALIGN, "text allignment in file is wrong."},
- {L_ERROR_SYSTEM, "System error:"},
- {L_ERROR_ERRNO, NULL}
- };
-
-#define LOAD_ERRTAB_LEN (sizeof(load_errtab)/sizeof(load_errtab[0]))
-#define ERRBUF_APPEND(s) strncat(errbuf, s, sizeof(errbuf)-strlen(errbuf)-1)
-
- snprintf(errbuf, 1024, "load failed - %s ", pathname);
-
- if (!loadquery(1, &message[0], sizeof(message)))
- ERRBUF_APPEND(strerror(errno));
- for(i = 0; message[i] && *message[i]; i++) {
- int nerr = atoi(message[i]);
- for (j=0; j<LOAD_ERRTAB_LEN; j++) {
- if (nerr == load_errtab[i].errno && load_errtab[i].errstr)
- ERRBUF_APPEND(load_errtab[i].errstr);
- }
- while (isdigit(*message[i])) message[i]++;
- ERRBUF_APPEND(message[i]);
- ERRBUF_APPEND("\n");
- }
- errbuf[strlen(errbuf)-1] = '\0'; /* trim off last newline */
- rb_loaderror(errbuf);
- return;
-}
-#endif
-
-void*
-dln_load(file)
- const char *file;
-{
-#if defined _WIN32 && !defined __CYGWIN__
- HINSTANCE handle;
- char winfile[MAXPATHLEN];
- void (*init_fct)();
- char *buf;
-
- if (strlen(file) >= MAXPATHLEN) rb_loaderror("filename too long");
-
- /* Load the file as an object one */
- init_funcname(&buf, file);
-
- strcpy(winfile, file);
-
- /* Load file */
- if ((handle = LoadLibrary(winfile)) == NULL) {
- goto failed;
- }
-
- if ((init_fct = (void(*)())GetProcAddress(handle, buf)) == NULL) {
- rb_loaderror("%s - %s\n%s", dln_strerror(), buf, file);
- }
- free(buf);
-
- /* Call the init code */
- (*init_fct)();
- return handle;
-#else
-#ifdef USE_DLN_A_OUT
- if (load(file) == -1) {
- goto failed;
- }
- return 0;
-#else
-
- char *buf;
- /* Load the file as an object one */
- init_funcname(&buf, file);
-
-#ifdef USE_DLN_DLOPEN
-#define DLN_DEFINED
- {
- void *handle;
- void (*init_fct)();
-
-#ifndef RTLD_LAZY
-# define RTLD_LAZY 1
-#endif
-#ifndef RTLD_GLOBAL
-# define RTLD_GLOBAL 0
-#endif
-
- /* Load file */
- if ((handle = (void*)dlopen(file, RTLD_LAZY|RTLD_GLOBAL)) == NULL) {
- goto failed;
- }
-
- init_fct = (void(*)())dlsym(handle, buf);
- free(buf);
- if (init_fct == NULL) {
- dlclose(handle);
- goto failed;
- }
- /* Call the init code */
- (*init_fct)();
-
- return handle;
- }
-#endif /* USE_DLN_DLOPEN */
-
-#ifdef __hpux
-#define DLN_DEFINED
- {
- shl_t lib = NULL;
- int flags;
- void (*init_fct)();
-
- flags = BIND_DEFERRED;
- lib = shl_load(file, flags, 0);
- if (lib == NULL) {
- extern int errno;
- rb_loaderror("%s - %s", strerror(errno), file);
- }
- shl_findsym(&lib, buf, TYPE_PROCEDURE, (void*)&init_fct);
- free(buf);
- if (init_fct == NULL) {
- shl_findsym(&lib, buf, TYPE_UNDEFINED, (void*)&init_fct);
- if (init_fct == NULL) {
- errno = ENOSYM;
- rb_loaderror("%s - %s", strerror(ENOSYM), file);
- }
- }
- (*init_fct)();
- return (void*)lib;
- }
-#endif /* hpux */
-
-#if defined(_AIX) && ! defined(_IA64)
-#define DLN_DEFINED
- {
- void (*init_fct)();
-
- init_fct = (void(*)())load((char*)file, 1, 0);
- if (init_fct == NULL) {
- aix_loaderror(file);
- }
- if (loadbind(0, (void*)dln_load, (void*)init_fct) == -1) {
- aix_loaderror(file);
- }
- (*init_fct)();
- return (void*)init_fct;
- }
-#endif /* _AIX */
-
-#if defined(NeXT) || defined(__APPLE__)
-#define DLN_DEFINED
-/*----------------------------------------------------
- By SHIROYAMA Takayuki Psi@fortune.nest.or.jp
-
- Special Thanks...
- Yu tomoak-i@is.aist-nara.ac.jp,
- Mi hisho@tasihara.nest.or.jp,
- and... Miss ARAI Akino(^^;)
- ----------------------------------------------------*/
-#if defined(NeXT) && (NS_TARGET_MAJOR < 4)/* NeXTSTEP rld functions */
-
- {
- unsigned long init_address;
- char *object_files[2] = {NULL, NULL};
-
- void (*init_fct)();
-
- object_files[0] = file;
-
- /* Load object file, if return value ==0 , load failed*/
- if(rld_load(NULL, NULL, object_files, NULL) == 0) {
- rb_loaderror("Failed to load %.200s", file);
- }
-
- /* lookup the initial function */
- if(rld_lookup(NULL, buf, &init_address) == 0) {
- rb_loaderror("Failed to lookup Init function %.200s", file);
- }
- free(buf);
-
- /* Cannot call *init_address directory, so copy this value to
- funtion pointer */
-
- init_fct = (void(*)())init_address;
- (*init_fct)();
- return (void*)init_address;
- }
-#else/* OPENSTEP dyld functions */
- {
- int dyld_result;
- NSObjectFileImage obj_file; /* handle, but not use it */
- /* "file" is module file name .
- "buf" is pointer to initial function name with "_" . */
-
- void (*init_fct)();
-
-
- dyld_result = NSCreateObjectFileImageFromFile(file, &obj_file);
-
- if (dyld_result != NSObjectFileImageSuccess) {
- rb_loaderror("Failed to load %.200s", file);
- }
-
- NSLinkModule(obj_file, file, NSLINKMODULE_OPTION_BINDNOW);
-
- /* lookup the initial function */
- /*NSIsSymbolNameDefined require function name without "_" */
- if(NSIsSymbolNameDefined(buf + 1)) {
- rb_loaderror("Failed to lookup Init function %.200s",file);
- }
-
- /* NSLookupAndBindSymbol require function name with "_" !! */
- init_fct = NSAddressOfSymbol(NSLookupAndBindSymbol(buf));
- free(buf);
- (*init_fct)();
-
- return (void*)init_fct;
- }
-#endif /* rld or dyld */
-#endif
-
-#ifdef __BEOS__
-# define DLN_DEFINED
- {
- status_t err_stat; /* BeOS error status code */
- image_id img_id; /* extention module unique id */
- void (*init_fct)(); /* initialize function for extention module */
-
- /* load extention module */
- img_id = load_add_on(file);
- if (img_id <= 0) {
- rb_loaderror("Failed to load %.200s", file);
- }
-
- /* find symbol for module initialize function. */
- /* The Be Book KernelKit Images section described to use
- B_SYMBOL_TYPE_TEXT for symbol of function, not
- B_SYMBOL_TYPE_CODE. Why ? */
- /* strcat(init_fct_symname, "__Fv"); */ /* parameter nothing. */
- /* "__Fv" dont need! The Be Book Bug ? */
- err_stat = get_image_symbol(img_id, buf,
- B_SYMBOL_TYPE_TEXT, (void **)&init_fct);
-
- if (err_stat != B_NO_ERROR) {
- char real_name[MAXPATHLEN];
-
- strcpy(real_name, buf);
- strcat(real_name, "__Fv");
- err_stat = get_image_symbol(img_id, real_name,
- B_SYMBOL_TYPE_TEXT, (void **)&init_fct);
- }
-
- if ((B_BAD_IMAGE_ID == err_stat) || (B_BAD_INDEX == err_stat)) {
- unload_add_on(img_id);
- free(buf);
- rb_loaderror("Failed to lookup Init function %.200s", file);
- }
- else if (B_NO_ERROR != err_stat) {
- char errmsg[] = "Internal of BeOS version. %.200s (symbol_name = %s)";
- unload_add_on(img_id);
- free(buf);
- rb_loaderror(errmsg, strerror(err_stat), buf);
- }
-
- free(buf);
- /* call module initialize function. */
- (*init_fct)();
- return (void*)img_id;
- }
-#endif /* __BEOS__*/
-
-#ifdef __MACOS__
-# define DLN_DEFINED
- {
- OSErr err;
- FSSpec libspec;
- CFragConnectionID connID;
- Ptr mainAddr;
- char errMessage[1024];
- Boolean isfolder, didsomething;
- Str63 fragname;
- Ptr symAddr;
- CFragSymbolClass class;
- void (*init_fct)();
- char fullpath[MAXPATHLEN];
-
- strcpy(fullpath, file);
-
- /* resolve any aliases to find the real file */
- c2pstr(fullpath);
- (void)FSMakeFSSpec(0, 0, fullpath, &libspec);
- err = ResolveAliasFile(&libspec, 1, &isfolder, &didsomething);
- if (err) {
- rb_loaderror("Unresolved Alias - %s", file);
- }
-
- /* Load the fragment (or return the connID if it is already loaded */
- fragname[0] = 0;
- err = GetDiskFragment(&libspec, 0, 0, fragname,
- kLoadCFrag, &connID, &mainAddr,
- errMessage);
- if (err) {
- p2cstr(errMessage);
- rb_loaderror("%s - %s",errMessage , file);
- }
-
- /* Locate the address of the correct init function */
- c2pstr(buf);
- err = FindSymbol(connID, buf, &symAddr, &class);
- free(buf);
- if (err) {
- rb_loaderror("Unresolved symbols - %s" , file);
- }
- init_fct = (void (*)())symAddr;
- (*init_fct)();
- return (void*)init_fct;
- }
-#endif /* __MACOS__ */
-
-#ifndef DLN_DEFINED
- rb_notimplement("dynamic link not supported");
-#endif
-
-#endif /* USE_DLN_A_OUT */
-#endif
-#if !defined(_AIX) && !defined(NeXT)
- failed:
- rb_loaderror("%s - %s", dln_strerror(), file);
-#endif
- return 0; /* dummy return */
-}
-
-static char *dln_find_1();
-
-char *
-dln_find_exe(fname, path)
- const char *fname;
- const char *path;
-{
- if (!path) {
-#if defined(__human68k__)
- path = getenv("path");
-#else
- path = getenv("PATH");
-#endif
- }
-
- if (!path) {
-#if defined(MSDOS) || defined(NT) || defined(__human68k__) || defined(__MACOS__)
- path = "/usr/local/bin;/usr/ucb;/usr/bin;/bin;.";
-#else
- path = "/usr/local/bin:/usr/ucb:/usr/bin:/bin:.";
-#endif
- }
- return dln_find_1(fname, path, 1);
-}
-
-char *
-dln_find_file(fname, path)
- const char *fname;
- const char *path;
-{
-#ifndef __MACOS__
- if (!path) path = ".";
- return dln_find_1(fname, path, 0);
-#else
- if (!path) path = ".";
- return _macruby_path_conv_posix_to_macos(dln_find_1(fname, path, 0));
-#endif
-}
-
-#if defined(__CYGWIN32__)
-const char *
-conv_to_posix_path(win32, posix, len)
- char *win32;
- char *posix;
- int len;
-{
- char *first = win32;
- char *p = win32;
- char *dst = posix;
-
- for (p = win32; *p; p++)
- if (*p == ';') {
- *p = 0;
- cygwin32_conv_to_posix_path(first, posix);
- posix += strlen(posix);
- *posix++ = ':';
- first = p + 1;
- *p = ';';
- }
- if (len < strlen(first))
- fprintf(stderr, "PATH length too long: %s\n", first);
- else
- cygwin32_conv_to_posix_path(first, posix);
- return dst;
-}
-#endif
-
-static char fbuf[MAXPATHLEN];
-
-static char *
-dln_find_1(fname, path, exe_flag)
- char *fname;
- char *path;
- int exe_flag; /* non 0 if looking for executable. */
-{
- register char *dp;
- register char *ep;
- register char *bp;
- struct stat st;
-#ifdef __MACOS__
- const char* mac_fullpath;
-#endif
-
- if (fname[0] == '/') return fname;
- if (strncmp("./", fname, 2) == 0 || strncmp("../", fname, 3) == 0)
- return fname;
- if (exe_flag && strchr(fname, '/')) return fname;
-#if defined(MSDOS) || defined(NT) || defined(__human68k__) || defined(__EMX__)
- if (fname[0] == '\\') return fname;
- if (strlen(fname) > 2 && fname[1] == ':') return fname;
- if (strncmp(".\\", fname, 2) == 0 || strncmp("..\\", fname, 3) == 0)
- return fname;
- if (exe_flag && strchr(fname, '\\')) return fname;
-#endif
-
- for (dp = path;; dp = ++ep) {
- register int l;
- int i;
- int fspace;
-
- /* extract a component */
- ep = strchr(dp, PATH_SEP[0]);
- if (ep == NULL)
- ep = dp+strlen(dp);
-
- /* find the length of that component */
- l = ep - dp;
- bp = fbuf;
- fspace = sizeof fbuf - 2;
- if (l > 0) {
- /*
- ** If the length of the component is zero length,
- ** start from the current directory. If the
- ** component begins with "~", start from the
- ** user's $HOME environment variable. Otherwise
- ** take the path literally.
- */
-
- if (*dp == '~' && (l == 1 ||
-#if defined(MSDOS) || defined(NT) || defined(__human68k__) || defined(__EMX__)
- dp[1] == '\\' ||
-#endif
- dp[1] == '/')) {
- char *home;
-
- home = getenv("HOME");
- if (home != NULL) {
- i = strlen(home);
- if ((fspace -= i) < 0)
- goto toolong;
- memcpy(bp, home, i);
- bp += i;
- }
- dp++;
- l--;
- }
- if (l > 0) {
- if ((fspace -= l) < 0)
- goto toolong;
- memcpy(bp, dp, l);
- bp += l;
- }
-
- /* add a "/" between directory and filename */
- if (ep[-1] != '/')
- *bp++ = '/';
- }
-
- /* now append the file name */
- i = strlen(fname);
- if ((fspace -= i) < 0) {
- toolong:
- fprintf(stderr, "openpath: pathname too long (ignored)\n");
- *bp = '\0';
- fprintf(stderr, "\tDirectory \"%s\"\n", fbuf);
- fprintf(stderr, "\tFile \"%s\"\n", fname);
- continue;
- }
- memcpy(bp, fname, i + 1);
-
-#ifndef __MACOS__
- if (stat(fbuf, &st) == 0) {
- if (exe_flag == 0) return fbuf;
- /* looking for executable */
- if (!S_ISDIR(st.st_mode) && eaccess(fbuf, X_OK) == 0)
- return fbuf;
- }
-#else
- if (mac_fullpath = _macruby_exist_file_in_libdir_as_posix_name(fbuf)) {
- if (exe_flag == 0) return mac_fullpath;
- /* looking for executable */
- if (stat(mac_fullpath, &st) == 0) {
- if (!S_ISDIR(st.st_mode) && eaccess(mac_fullpath, X_OK) == 0)
- return mac_fullpath;
- }
- }
-#endif
-#if defined(MSDOS) || defined(NT) || defined(__human68k__) || defined(__EMX__)
- if (exe_flag) {
- static const char *extension[] = {
-#if defined(MSDOS)
- ".com", ".exe", ".bat",
-#if defined(DJGPP)
- ".btm", ".sh", ".ksh", ".pl", ".sed",
-#endif
-#elif defined(__EMX__) || defined(NT)
- ".exe", ".com", ".cmd", ".bat",
-/* end of __EMX__ or NT*/
-#else
- ".r", ".R", ".x", ".X", ".bat", ".BAT",
-/* __human68k__ */
-#endif
- (char *) NULL
- };
- int j;
-
- for (j = 0; extension[j]; j++) {
- if (fspace < strlen(extension[j])) {
- fprintf(stderr, "openpath: pathname too long (ignored)\n");
- fprintf(stderr, "\tDirectory \"%.*s\"\n", (int) (bp - fbuf), fbuf);
- fprintf(stderr, "\tFile \"%s%s\"\n", fname, extension[j]);
- continue;
- }
- strcpy(bp + i, extension[j]);
-#ifndef __MACOS__
- if (stat(fbuf, &st) == 0)
- return fbuf;
-#else
- if (mac_fullpath = _macruby_exist_file_in_libdir_as_posix_name(fbuf))
- return mac_fullpath;
-#endif
- }
- }
-#endif /* MSDOS or NT or __human68k__ or __EMX__ */
- /* if not, and no other alternatives, life is bleak */
- if (*ep == '\0') {
- return NULL;
- }
-
- /* otherwise try the next component in the search path */
- }
-}
diff --git a/dln.h b/dln.h
deleted file mode 100644
index c6f9654eb6..0000000000
--- a/dln.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/**********************************************************************
-
- dln.h -
-
- $Author$
- $Date$
- created at: Wed Jan 19 16:53:09 JST 1994
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
-
-**********************************************************************/
-
-#ifndef DLN_H
-#define DLN_H
-
-#ifdef __cplusplus
-# ifndef HAVE_PROTOTYPES
-# define HAVE_PROTOTYPES 1
-# endif
-# ifndef HAVE_STDARG_PROTOTYPES
-# define HAVE_STDARG_PROTOTYPES 1
-# endif
-#endif
-
-#undef _
-#ifdef HAVE_PROTOTYPES
-# define _(args) args
-#else
-# define _(args) ()
-#endif
-
-char *dln_find_exe _((const char*,const char*));
-char *dln_find_file _((const char*,const char*));
-
-#ifdef USE_DLN_A_OUT
-extern char *dln_argv0;
-#endif
-
-void *dln_load _((const char*));
-#endif
diff --git a/dmyext.c b/dmyext.c
deleted file mode 100644
index 4120d493c3..0000000000
--- a/dmyext.c
+++ /dev/null
@@ -1,4 +0,0 @@
-void
-Init_ext()
-{
-}
diff --git a/doc/NEWS b/doc/NEWS
deleted file mode 100644
index ca0b2c29d6..0000000000
--- a/doc/NEWS
+++ /dev/null
@@ -1,465 +0,0 @@
-: IO
-
- 64bit off_t support by Janathan Baker.
-
-: abort()
-
- optional terminate message argument.
-
-: iconv module
-
- Imported. Wrapper library of (({iconv})).
-
-: Dir::glob
-
- Now accepts optional FNM_* flags via the second argument, whereas
- Dir::[] doesn't.
-
- Dir.glob("makefile", File::FNM_CASEFOLD) #=> ['Makefile', 'makefile']
-
-: tsort module
-
- Imported. Topological sorting library.
-
-: stringio module
-
- Imported. Pseudo (({IO})) class from/to (({String})).
-
-: Array#pack, String#unpack
-
- allows comment in template strings.
-
-: Array#pack, String#unpack
-
- new templates 'q' and 'Q' for 64bit integer (signed and unsigned respectively).
-
-: Array#fill
-
- takes block to get the values to fill.
-
-: Array#new
-
- takes block to get the values to fill.
-
-: Array#fetch
-
- takes block to get the default value.
-
-: Hash#update
-
- takes block to resolve key conflict.
-
-: IO#fsync
-
- Added.
-
-: Array expansion
-
- Fixed with the following behavior:
-
- a = *[1]
- p a #=> [1]
-
- Now 1-element array in rhs is expanded properly.
-
- a = *[1]
- p a #=> 1
-
-: allocation framework
-
- any instance of class can be allocated by class.allocate,
- (except a few classes).
-
-: break and next
-
- Extended to take an optional expression, which is used as a value
- for termination. [experimental]
-
-: comparison of exception classes in a rescue clause
-
- Changed to use Module#=== for comparing $! with the exception
- class specified in each rescue clause.
-
- As the previous behavior was to use kind_of?, the effect is limited
- to the SystemCallError case. SystemCallError.=== has been newly
- defined to return true when the two have the same errno. With this
- change, SystemCallError's with the same errno, such as Errno::EAGAIN
- and Errno::EWOULDBLOCK, can both be rescued by listing just one of
- them.
-
-: constants lookup
-
- Improved at the performance of searching by using an internal hash
- table.
-
-: expression parenthesis in the first argument
-
- Experimentally altered to get the following code (note the space
- after p):
-
- p ("xx"*2).to_i
-
- Interpreted as:
-
- p (("xx"*2).to_i)
-
- Instead of:
-
- (p("xx"*2)).to_i
-
-: implicit comparison in conditional expressions
-
- is obsoleted except when it is used in -e.
-
- : between Range and $.
- Use explicit comparison instead.
-
- : between Regexp and $_
- Use the unary method ~/re/ instead.
-
-: to_str
-
- Added to get objects which define to_str() treated as String's.
-
- Now almost all the built-in methods try each argument with to_str()
- when they expect it to be a String.
-
- foo = Object.new
- class <<foo
- def to_str
- "foo"
- end
- end
- p File.open(foo)
- => -:7:in `open': wrong argument type Object (expected String) (TypeError)
- ruby 1.6.4 (2001-04-19) [i586-linux]
- => -:7:in `open': No such file or directory - "foo" (Errno::ENOENT)
- ruby 1.7.0 (2001-05-02) [i586-linux]
-
-: pp module
-
- Imported. Prity Printing library.
-
-: open
-
- Extended so that when the third argument is permission flags it
- calls open(2) instead of fopen(3).
-
-: Array#fetch
-
- Added.
-
-: Array#insert(n, other, ...)
-
- Added. [ruby-talk:14289]
-
- This is much the same as (({ary[n,0] = [other,...]})) except
- returing self.
-
- ary = [0,1,2,3]
- ary[2, 0] = [4, 5, 6]
- p ary
-
- ary = [0,1,2,3]
- ary.insert(2, 4, 5, 6)
- p ary
-
-: Array#sort!
-
- Changed to always return self without checking whether the sequence
- of the elements was modified or not.
-
- Beware that this behavior is not guaranteed to continue in the
- future. Do not rely on its return value. [ruby-dev:12506]
-
-: Curses
-
- Updated. New methods and constants for using the mouse, character
- attributes, colors and key codes have been added.
-
-: Dir#path
-
- Added.
-
-: Dir.chdir
-
- Extended to take a block.
-
-: Dir.glob
-
- Made to support meta-character escaping by a backslash. Wildcards
- and spaces may now be escaped using a backslash.
-
-: Dir.open
-
- Changed to return what the block returns when a block is given, just
- as File.open does. (It always returned (({nil})) in 1.6 and
- prior)
-
-: Dir.chdir
-
- Changed to warn only when invoked from multiple threads or no block
- is given. [ruby-dev:13823]
-
- Dir.chdir('foo') {
- Dir.chdir('bar') { # previously warned
- puts Dir.pwd
- }
- }
-
-: Enumerable#all?
-: Enumerable#any?
-: Enumerable#inject
-: Enumerable#sort_by
-
- Added.
-
-: File#fnmatch, File::Constants::FNM_*
-
- Added. Refer to the fnmatch(3) manpage for details.
-
- Localism is FNM_DOTMATCH which has the opposite meaning of the
- commonly known FNM_PERIOD, which does not exist in Ruby.
-
- e.g.
-
- # exclude files matching "*.bak" case-insensitively.
- files.reject! {|fn| File.fnmatch?("*.bak", fn, File::FNM_CASEFOLD) }
-
-: File.lchmod
-: File.lchown
-
- Added.
-
-: IO#puts
-
- do not treat Array specially.
-
-: IO.for_fd
-
- Added.
-
-: IO.read
-
- Added. [ruby-talk:9460]
-
-: Interrupt
-
- Made a subclass of SignalException. (It was a subclass of
- Exception in 1.6 and prior)
-
-: Marshal
-
- Fixed not to dump anonymous classes/modules.
-
- Fixed with loading modules.
-
-: MatchData#to_ary
-
- Added for convenience of Regexp#match. [ruby-dev:12766]
-
- Previously we had to do:
-
- foo, bar, baz = /(\w+?)\s+(\w+?)\s+(\w+)/.match("foo bar baz").to_a[1..-1]
- p [foo, bar, baz]
-
- But now can do:
-
- _, foo, bar, baz = /(\w+?)\s+(\w+?)\s+(\w+)/.match("foo bar baz")
- p [foo, bar, baz]
-
-: Math.acos(x)
-: Math.asin(x)
-: Math.atan(x)
-: Math.cosh(x)
-: Math.hypot(x,y)
-: Math.sinh(x)
-: Math.tanh(x)
-
- Added.
-
-: Method#==
-
- Added.
-
-: Module#include?
-
- Added. [ruby-dev:13941]
-
-: Module#included
-
- Added. This is a hook called after Module#append_feature.
-
-: Module#method_removed
-: Module#method_undefined
-
- Added.
-
-: Module.new, Class.new
-
- Extended to take block.
-
-: Multiple assignment behavior
-
- Fixed so that "*a = nil" results in "a == []".
-
-: NameError and NoMethodError
-
- Moved and now NoMethodError < NameError < StandardError.
-
-: NoMethodError
-
- Added. [ruby-dev:12763]
-
-: NotImplementError
-
- Finally obsoleted. Use NotImplementedError.
-
-: Object#singleton_method_removed
-: Object#singleton_method_undefined
-
- Added.
-
-: Proc#==
-
- Added.
-
-: Proc#yield
-
- Added. This is equivalent to Proc#call except it does not check the
- number of given arguments, which are thus passed to the proc as-is.
-
-: Process.times
-
- Moved from Time.times. (Time.times still remains but emits a
- warning)
-
-: Process.waitall
-
- Added.
-
-: Process::Status
-
- Added. (({$?})) is now an instance of this class.
-
-: Range#step([step=1])
-
- Added.
-
-: Range#to_ary
-
- Added. You can now do something like this:
-
- a, b, c = 1..3
-
-: Regexp#options
-
- Added.
-
-: Regexp.last_match(n)
-
- Extended to take an optional argument.
-
-: Signal
-
- Added. This module has module functions Signal.trap and Signal.list.
-
-: Socket.pack_sockaddr_in, Socket.unpack_sockaddr_in
-
- Added. Utility for direct Socket access.
-
-: Socket.pack_sockaddr_un, Socket.unpack_sockaddr_un
-
- Added. Utility for direct Socket access.
-
-: String#[regexp, nth]
-
- Extended to accepts optional second argument.
-
- tries match between self and REGEXP, then returns the
- content of the NTH regexp register.
-
-: String#casecmp
-
- Added. This is a case insensitive version of String#<=>.
-
-: String#chomp
-
- if $/ == '\n', chops off last newlines (any of \n, \r, \r\n).
-
-: String#eql?
-
- Changed to be always case sensitive.
-
-: String#insert(n, other)
-
- Added.
-
- This is much the same as (({str[n, 0] = other})) except returing
- self.
-
-: String#lstrip, rstrip, lstrip!, rstrip!
-
- Added. These strip only left or right part of a string.
-
-: String#match
-
- Added.
-
-: String/Array methods
-
- returns an instance of receivers class.
-
-: String.new
-
- The first argument becomes optional.
-
-: Symbol#intern
-
- Added.
-
-: Symbol.all_symbols
-
- Added. [ruby-dev:12921]
-
-: SystemCallError.===
-
- Added. (See the "Comparison of exception classes in a rescue clause"
- paragraph above) [ruby-dev:12670]
-
-: SystemExit#status
-
- Added.
-
-: TCPServer#listen, UNIXServer#listen
-
- Added.
-
-: TCPSocket.new
-: TCPSocket.open
-
- Extended to take an address and a port number for the local side in
- optional 3rd and 4th arguments.
-
-: Time
-
- Extended to accept a negative time_t. (Only when the platform
- supports it)
-
- p Time.at(-1)
- => Thu Jan 01 08:59:59 JST 1970
-
-: Time#to_a
-: Time#zone
-
- Made to return "UTC" under gmtime. It used to return a platform
- dependent value, typically "GMT", in 1.6 and prior.
-
-To be investigated:
-
- Sat Feb 24 03:15:49 2001 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (set_stdin): preserve original stdin.
-
- * io.c (set_outfile): preserve original stdout/stderr.
-
diff --git a/doc/forwardable.rd b/doc/forwardable.rd
deleted file mode 100644
index 7272c374b6..0000000000
--- a/doc/forwardable.rd
+++ /dev/null
@@ -1,84 +0,0 @@
- -- forwardable.rb
-
- $Release Version: 1.1 $
- $Revision$
- $Date$
- Original version by Tosh
-
-=begin
-
-= Forwardable
-
-A Module to define delegations for selected methods to a class.
-
-== Usage
-
-Using through extending the class.
-
- class Foo
- extend Forwardable
-
- def_delegators("@out", "printf", "print")
- def_delegators(:@in, :gets)
- def_delegator(:@contents, :[], "content_at")
- end
- f = Foo.new
- f.printf ...
- f.gets
- f.content_at(1)
-
-== Methods
-
---- Forwardable#def_instance_delegators(accessor, *methods)
-
- adding the delegations for each method of ((|methods|)) to
- ((|accessor|)).
-
---- Forwardable#def_instance_delegator(accessor, method, ali = method)
-
- adding the delegation for ((|method|)) to ((|accessor|)). When
- you give optional argument ((|ali|)), ((|ali|)) is used as the
- name of the delegation method, instead of ((|method|)).
-
---- Forwardable#def_delegators(accessor, *methods)
-
- the alias of ((|Forwardable#def_instance_delegators|)).
-
---- Forwardable#def_delegator(accessor, method, ali = method)
-
- the alias of ((|Forwardable#def_instance_delegator|)).
-
-= SingleForwardable
-
-a Module to define delegations for selected methods to an object.
-
-== Usage
-
-Using through extending the object.
-
- g = Goo.new
- g.extend SingleForwardable
- g.def_delegator("@out", :puts)
- g.puts ...
-
-== Methods
-
---- SingleForwardable#def_singleton_delegators(accessor, *methods)
-
- adding the delegations for each method of ((|methods|)) to
- ((|accessor|)).
-
---- SingleForwardable#def_singleton_delegator(accessor, method, ali = method)
-
- adding the delegation for ((|method|)) to ((|accessor|)). When
- you give optional argument ((|ali|)), ((|ali|)) is used as the
- name of the delegation method, instead of ((|method|)).
-
---- SingleForwardable#def_delegators(accessor, *methods)
-
- the alias of ((|SingleForwardable#def_instance_delegators|)).
-
---- SingleForwardable#def_delegator(accessor, method, ali = method)
-
- the alias of ((|SingleForwardable#def_instance_delegator|)).
-=end
diff --git a/doc/forwardable.rd.ja b/doc/forwardable.rd.ja
deleted file mode 100644
index d928fddc5e..0000000000
--- a/doc/forwardable.rd.ja
+++ /dev/null
@@ -1,81 +0,0 @@
- -- forwatable.rb
- $Release Version: 1.1 $
- $Revision$
- $Date$
-
-=begin
-= Forwardable
-
-クラスに対しメソッドの委譲機能を定義します.
-
-== 使い方
-
-クラスに対してextendして使います.
-
- class Foo
- extend Forwardable
-
- def_delegators("@out", "printf", "print")
- def_delegators(:@in, :gets)
- def_delegator(:@contents, :[], "content_at")
- end
- f = Foo.new
- f.printf ...
- f.gets
- f.content_at(1)
-
-== メソッド
-
---- Forwardable#def_instance_delegators(accessor, *methods)
-
- ((|methods|))で渡されたメソッドのリストを((|accessorに|))委譲する
- ようにします.
-
---- Forwardable#def_instance_delegator(accessor, method, ali = method)
-
- ((||method|))で渡されたメソッドを((|accessor|))に委譲するようにし
- ます. ((|ali|))が引数として渡されたときは, メソッド((|ali|))が呼ば
- れたときには, ((|accessor|))に対し((|method|))を呼び出します.
-
---- Forwardable#def_delegators(accessor, *methods)
-
- ((|Forwardable#def_instance_delegators|))の別名です.
-
---- Forwardable#def_delegator(accessor, method, ali = method)
-
- ((|Forwardable#def_instance_delegator|))の別名です.
-
-= SingleForwardable
-
-オブジェクトに対し, メソッドの委譲機能を定義します.
-
-== 使い方
-
-オブジェクトに対して((|extend|))して使います.
-
- g = Goo.new
- g.extend SingleForwardable
- g.def_delegator("@out", :puts)
- g.puts ...
-
-== メソッド
-
---- SingleForwardable#def_singleton_delegators(accessor, *methods)
-
- ((|methods|))で渡されたメソッドのリストを((|accessor|))に委譲する
- ようにします.
-
---- SingleForwardable#def_singleton_delegator(accessor, method, ali = method)
-
- ((|method|))で渡されたメソッドを((|accessor|))に委譲するようにしま
- す. ((|ali|))が引数として渡されたときは, メソッド((|ali|))が呼ばれ
- たときには, ((|accessor|))に対し((|method|))を呼び出します.
-
---- SingleForwardable#def_delegators(accessor, *methods)
-
- ((|SingleForwardable#def_singleton_delegators|))の別名です.
-
---- SingleForwardable#def_delegator(accessor, method, ali = method)
-
- ((|SingleForwardable#def_singleton_delegator|))の別名です.
-=end
diff --git a/doc/irb/irb-tools.rd.ja b/doc/irb/irb-tools.rd.ja
deleted file mode 100644
index 64d9ab29c8..0000000000
--- a/doc/irb/irb-tools.rd.ja
+++ /dev/null
@@ -1,185 +0,0 @@
-irb関連おまけコマンドとライブラリ
- $Release Version: 0.7.1 $
- $Revision$
- $Date$
- by Keiju ISHITSUKA(Nihon Rational Co.,Ltd.)
-
-=begin
-
-:コマンド:
-* rtags -- ruby tags command
-
-:関数ライブラリ:
-* xmp -- irb version of gotoken xmp-function
-
-:クラスライブラリ:
-* frame.rb -- frame tracer
-* completion.rb -- irb completor
-
-= rtags
-
-rtagsはemacs及びvi用の, TAGファイルをつくるコマンドです.
-
-== 使い方
-
- rtags [-vi] file....
-
-カレントディレクトリにemacs用のTAGSファイルができます. -viオプションを
-つけた時にはvi用のtagsファイルを作成します.
-
-emacsの場合, 通常のetags.elがそのまま使えます. 検索可能なのは,
-
-* クラス
-* メソッド
-* 特異メソッド
-* alias
-* attrで宣言されたアクセサ(パラメータがシンボルか文字列リテラルに限る)
-* attr_XXXで宣言されたアクセサ(パラメータがシンボルか文字列リテラルに限る)
-
-です.
-
-Cなどで使っているのと違うのは, コンプリーションに関する部分で,
-
-関数名は,
-
- 関数名(
-
-クラスは,
-
- ::クラス名::....::クラス名
-
-メソッドは,
-
- ::クラス名::....::クラス名#メソッド名
-
-特異メソッド(クラスメソッド)は
-
- ::クラス名::....::クラス名.メソッド名
-
-でコンプリーションを行なうところです.
-
-= xmp.rb
-
-ごとけんxmpの上位互換バージョンです. ただ, 非常に重いのでごとけんxmpで
-は対応できない時に, 使用すると良いでしょう.
-
-== 使い方
-
-=== 関数として使う.
-
- require "irb/xmp"
- xmp <<END
- foo = 1
- foo
- END
- ---
- foo = 1
- ==>1
- foo
- ==>1
-
-=== XMPインスタンスを用いる.
-
-この場合は, XMPがコンテキスト情報を持つので, 変数の値などを保持してい
-ます.
-
- require "irb/xmp"
- xmp = XMP.new
- xmp.puts <<END
- foo = 1
- foo
- END
- xmp.puts <<END
- foo
- END
- ===
- foo = 1
- ==>1
- foo
- ==>1
- foo
- ==>1
-
-== コンテキストに関して
-
-XMPメソッド群のコンテキストは, 呼び出す前のコンテキストで評価されます.
-明示的にコンテキストを指定するとそのコンテキストで評価します.
-
-例:
-
- xmp "foo", an_binding
-
-:注:
-マルチスレッドには対応していません.
-
-= frame.rb
-現在実行中のフレーム情報を取り扱うためのクラスです.
-
-* IRB::Frame.top(n = 0)
- 上からn番目のコンテキストを取り出します. nは0が最上位になります.
-* IRB::Frame.bottom(n = 0)
- 下からn番目のコンテキストを取り出します. nは0が最下位になります.
-* IRB::Frame.sender
- センダになっているオブジェクトを取り出します. センダとは, そのメソッ
- ドを呼び出した側のselfのことです.
-
-:注:
-set_trace_funcを用いてRubyの実行をトレースしています. マルチスレッドに
-は対応していません.
-
-= completion.rb
-irbのcompletion機能を提供するものです.
-
-== 使い方
-
- % irb -r irb/completion
-
-とするか, ~/.irbrc 中に
-
- require "irb/completion"
-
-を入れてください. irb実行中に require "irb/completion" してもよいです.
-
-irb実行中に (TAB) を押すとコンプレーションします.
-
-トップレベルで(TAB)を押すとすべての構文要素, クラス, メソッドの候補がで
-ます. 候補が唯一ならば完全に補完します.
-
- irb(main):001:0> in
- in inspect instance_eval
- include install_alias_method instance_of?
- initialize install_aliases instance_variables
- irb(main):001:0> inspect
- "main"
- irb(main):002:0> foo = Object.new
- #<Object:0x4027146c>
-
- ((|変数名.|))の後に(TAB)を押すと, そのオブジェクトのメソッド一覧がでま
- す.
-
- irb(main):003:0> foo.
- foo.== foo.frozen? foo.protected_methods
- foo.=== foo.hash foo.public_methods
- foo.=~ foo.id foo.respond_to?
- foo.__id__ foo.inspect foo.send
- foo.__send__ foo.instance_eval foo.singleton_methods
- foo.class foo.instance_of? foo.taint
- foo.clone foo.instance_variables foo.tainted?
- foo.display foo.is_a? foo.to_a
- foo.dup foo.kind_of? foo.to_s
- foo.eql? foo.method foo.type
- foo.equal? foo.methods foo.untaint
- foo.extend foo.nil?
- foo.freeze foo.private_methods
-
-=end
-
-% Begin Emacs Environment
-% Local Variables:
-% mode: text
-% comment-column: 0
-% comment-start: "%"
-% comment-end: "\n"
-% End:
-%
-
diff --git a/doc/irb/irb.rd b/doc/irb/irb.rd
deleted file mode 100644
index 522bbef555..0000000000
--- a/doc/irb/irb.rd
+++ /dev/null
@@ -1,377 +0,0 @@
-irb -- interactive ruby
- $Release Version: 0.5 $
- $Revision$
- $Date$
- by Keiju ISHITSUKA(keiju@ishitsuka.com)
- translate from japanese by gotoken-san
-
-=begin
-= What is irb?
-
-irb stands for `interactive ruby'. irb is a tool to execute interactively
-ruby expressions read from stdin.
-
-= Invoking
-
- % ruby -r irb -e0
- % irb
-
-Either of the aboves. In the former style, options can be specified
-as follows:
-
- % ruby -r irb -e0 -- -v
-
-= Usage
-
-Use of irb is easy if you know ruby. Executing irb, prompts are
-displayed as follows. Then, enter expression of ruby. A input is
-executed when it is syntacticaly completed.
-
- dim% irb
- irb(main):001:0> 1+2
- 3
- irb(main):002:0> class Foo
- irb(main):003:1> def foo
- irb(main):004:2> print 1
- irb(main):005:2> end
- irb(main):006:1> end
- nil
- irb(main):007:0>
-
-And, Readline extesion module can be used with irb. Using Readline
-is the standard default action if Readline is installed.
-
-= Command line option
-
- irb.rb [options] file_name opts
- options:
- -f suppress read ~/.irbrc
- -m bc mode (fraction or matrix are available)
- -d set $DEBUG to true (same as `ruby -d')
- -r load-module same as `ruby -r'
- --inspect uses `inspect' for output (the default except bc mode)
- --noinspect doesn't uses inspect for output
- --readline uses Readline extension module
- --noreadline doesn't use Readline extension module
- --prompt prompt-mode
- --prompt-mode prompt-mode
- switches prompt mode. Pre-defined prompt modes are
- `deflaut', `simple', `xmp' and `inf-ruby'
-
- --inf-ruby-mode uses prompt appreciate for inf-ruby-mode on emacs.
- Suppresses --readline.
- --simple-prompt simple prompt mode
- --noprompt no prompt
- --tracer display trace for each execution of commands.
- --back-trace-limit n
- displayes backtrace top n and tail n. The default
- value is 16.
- --irb_debug n sets internal debug level to n (It shouldn't be used)
- -v, --version prints the version of irb
-
-
-
-= Configurations
-
-irb reads `~/.irbrc' when it is invoked. If `~/.irbrb' doesn't exist
-irb try to read in the order `.irbrc', `irb.rc', `_irbrc' then `$irbrc'.
-
-The following is altanative to the command line option. To use them
-type as follows in an irb session.
-
- IRB.conf[:IRB_NAME]="irb"
- IRB.conf[:MATH_MODE]=false
- IRB.conf[:USE_TRACER]=false
- IRB.conf[:USE_LOADER]=false
- IRB.conf[:IGNORE_SIGINT]=true
- IRB.conf[:IGNORE_EOF]=false
- IRB.conf[:INSPECT_MODE]=nil
- IRB.conf[:IRB_RC] = nil
- IRB.conf[:BACK_TRACE_LIMIT]=16
- IRB.conf[:USE_LOADER] = false
- IRB.conf[:USE_READLINE] = nil
- IRB.conf[:USE_TRACER] = false
- IRB.conf[:IGNORE_SIGINT] = true
- IRB.conf[:IGNORE_EOF] = false
- IRB.conf[:PROMPT_MODE] = :DEFALUT
- IRB.conf[:PROMPT] = {...}
- IRB.conf[:DEBUG_LEVEL]=0
- IRB.conf[:VERBOSE]=true
-
-== Customizing prompt
-
-To costomize the prompt you set a variable
-
- IRB.conf[:PROMPT]
-
-For example, describe as follows in `.irbrc'.
-
- IRB.conf[:PROMPT][:MY_PROMPT] = { # name of prompt mode
- :PROMPT_I => nil, # normal prompt
- :PROMPT_S => nil, # prompt for continuated strings
- :PROMPT_C => nil, # prompt for continuated statement
- :RETURN => " ==>%s\n" # format to return value
- }
-
-Then, invoke irb with the above prompt mode by
-
- % irb --prompt my-prompt
-
-Or add the following in `.irbrc'.
-
- IRB.conf[:PROMPT_MODE] = :MY_PROMPT
-
-Constants PROMPT_I, PROMPT_S and PROMPT_C specifies the format.
-In the prompt specification, some special strings are available.
-
- %N command name which is running
- %m to_s of main object (self)
- %M inspect of main object (self)
- %l type of string(", ', /, ]), `]' is inner %w[...]
- %NNi indent level. NN is degits and means as same as printf("%NNd").
- It can be ommited
- %NNn line number.
- %% %
-
-For instance, the default prompt mode is defined as follows:
-
-IRB.conf[:PROMPT_MODE][:DEFAULT] = {
- :PROMPT_I => "%N(%m):%03n:%i> ",
- :PROMPT_S => "%N(%m):%03n:%i%l ",
- :PROMPT_C => "%N(%m):%03n:%i* ",
- :RETURN => "%s\n"
-}
-
-RETURN is used to printf.
-
-== Configurating subirb
-
-The command line option or IRB.conf specify the default behavior of
-(sub)irb. On the other hand, each conf of in the next sction `6. Command'
-is used to individually configurate (sub)irb.
-
-If proc is set to IRB.conf[:IRB_RC], its subirb will be invoked after
-execution of that proc under giving the context of irb as its
-aregument. By this mechanism each subirb can be configurated.
-
-= Command
-
-For irb commands, both simple name and `irb_'-prefixed name are prepared.
-
---- exit, quit, irb_exit
- Quits (sub)irb.
- if you've done cb (see below), exit from the binding mode.
-
---- conf, irb_context
- Displays current configuration. Modifing the configuration is
- achieved by sending message to `conf'.
-
---- conf.back_trace_limit
- Sets display lines of backtrace as top n and tail n.
- The default value is 16.
-
---- conf.debug_level = N
- Sets debug level of irb.
-
---- conf.ignore_eof = true/false
- Whether ^D (control-d) will be ignored or not.
- If false is set, ^D means quit.
-
---- conf.ignore_sigint= true/false
- Whether ^C (control-c) will be ignored or not.
- If false is set, ^D means quit. If true,
- during input: cancel inputing then return to top level.
- during execute: abondon current execution.
-
---- conf.inf_ruby_mode = true/false
- Whether inf-ruby-mode or not. The default value is false.
-
---- conf.inspect_mode = true/false/nil
- Specifies inspect mode.
- true: display inspect
- false: display to_s
- nil: inspect mode in non math mode,
- non inspect mode in math mode.
-
---- conf.irb_level
- The level of cb.
-
---- conf.math_mode
- Whether bc mode or not.
-
---- conf.use_loader = true/false
- Whether irb's own file reader method is used when load/require or not.
- This mode is globaly affected (irb wide).
-
---- conf.prompt_c
- prompt for a continuating statement (e.g, immediately after of `if')
-
---- conf.prompt_i
- standard prompt
-
---- conf.prompt_s
- prompt for a continuating string
-
---- conf.rc
- Whether ~/.irbrc is read or not.
-
---- conf.use_prompt = true/false
- Prompting or not.
-
---- conf.use_readline = true/false/nil
- Whether readline is used or not.
- true: uses
- false: doen't use
- nil: intends to use readline except for inf-reuby-mode (default)
-
---- conf.verbose=T/F
- Whether verbose messages are display or not.
-
---- cb, irb_change_binding [obj]
- Enter new binding which has a distinct scope of local variables.
- If obj is given, obj will be self.
-
---- irb [obj]
- Invoke subirb. If obj is given, obj will be self.
-
---- jobs, irb_jobs
- List of subirb
-
---- fg n, irb_fg n
- Switch into specified subirb. The following is candidates of n:
-
- irb number
- thhread
- irb object
- self(obj which is specified of irb obj)
-
---- kill n, irb_kill n
- Kill subirb. The means of n is as same as the case of irb_fg.
-
-= System variable
-
- _ The latest value of evaluation (it is local)
-
-
-= Session Example
-
- dim% ruby irb.rb
- irb(main):001:0> irb # invoke subirb
- irb#1(main):001:0> jobs # list of subirbs
- #0->irb on main (#<Thread:0x400fb7e4> : stop)
- #1->irb#1 on main (#<Thread:0x40125d64> : running)
- nil
- irb#1(main):002:0> fg 0 # switch job
- nil
- irb(main):002:0> class Foo;end
- nil
- irb(main):003:0> irb Foo # invoke subirb which has the
- # context of Foo
- irb#2(Foo):001:0> def foo # define Foo#foo
- irb#2(Foo):002:1> print 1
- irb#2(Foo):003:1> end
- nil
- irb#2(Foo):004:0> fg 0 # switch job
- nil
- irb(main):004:0> jobs # list of job
- #0->irb on main (#<Thread:0x400fb7e4> : running)
- #1->irb#1 on main (#<Thread:0x40125d64> : stop)
- #2->irb#2 on Foo (#<Thread:0x4011d54c> : stop)
- nil
- irb(main):005:0> Foo.instance_methods # Foo#foo is defined asurely
- ["foo"]
- irb(main):006:0> fg 2 # switch job
- nil
- irb#2(Foo):005:0> def bar # define Foo#bar
- irb#2(Foo):006:1> print "bar"
- irb#2(Foo):007:1> end
- nil
- irb#2(Foo):010:0> Foo.instance_methods
- ["bar", "foo"]
- irb#2(Foo):011:0> fg 0
- nil
- irb(main):007:0> f = Foo.new
- #<Foo:0x4010af3c>
- irb(main):008:0> irb f # invoke subirb which has the
- # context of f (instance of Foo)
- irb#3(#<Foo:0x4010af3c>):001:0> jobs
- #0->irb on main (#<Thread:0x400fb7e4> : stop)
- #1->irb#1 on main (#<Thread:0x40125d64> : stop)
- #2->irb#2 on Foo (#<Thread:0x4011d54c> : stop)
- #3->irb#3 on #<Foo:0x4010af3c> (#<Thread:0x4010a1e0> : running)
- nil
- irb#3(#<Foo:0x4010af3c>):002:0> foo # evaluate f.foo
- 1nil
- irb#3(#<Foo:0x4010af3c>):003:0> bar # evaluate f.bar
- barnil
- irb#3(#<Foo:0x4010af3c>):004:0> kill 1, 2, 3# kill job
- nil
- irb(main):009:0> jobs
- #0->irb on main (#<Thread:0x400fb7e4> : running)
- nil
- irb(main):010:0> exit # exit
- dim%
-
-= Restrictions
-
-Because irb evaluates the inputs immediately after the imput is
-syntactically completed, irb gives slight different result than
-directly use ruby. Known difference is pointed out here.
-
-
-== Declaration of the local variable
-
-The following causes an error in ruby:
-
- eval "foo = 0"
- foo
- --
- -:2: undefined local variable or method `foo' for #<Object:0x40283118> (NameError)
- ---
- NameError
-
-Though, the above will successfully done by irb.
-
- >> eval "foo = 0"
- => 0
- >> foo
- => 0
-
-Ruby evaluates a code after reading entire of code and determination
-of the scope of local variables. On the other hand, irb do
-immediately. More precisely, irb evaluate at first
-
- evel "foo = 0"
-
-then foo is defined on this timing. It is because of this
-incompatibility.
-
-If you'd like to detect those differences, begin...end can be used:
-
- >> begin
- ?> eval "foo = 0"
- >> foo
- >> end
- NameError: undefined local variable or method `foo' for #<Object:0x4013d0f0>
- (irb):3
- (irb_local_binding):1:in `eval'
-
-== Here-document
-
-Implementation of Here-document is incomplete.
-
-== Symbol
-
-Irb can not always recognize a symbol as to be Symbol. Concretely, an
-expression have completed, however Irb regard it as continuation line.
-
-=end
-
-% Begin Emacs Environment
-% Local Variables:
-% mode: text
-% comment-column: 0
-% comment-start: "%"
-% comment-end: "\n"
-% End:
-%
diff --git a/doc/irb/irb.rd.ja b/doc/irb/irb.rd.ja
deleted file mode 100644
index 5068f4536f..0000000000
--- a/doc/irb/irb.rd.ja
+++ /dev/null
@@ -1,391 +0,0 @@
-irb -- interactive ruby
- $Release Version: 0.6 $
- $Revision$
- $Date$
- by Keiju ISHITSUKA(keiju@ishitsuka.com)
-=begin
-= irbとは?
-
-irbはinteractive rubyの略です. rubyの式を標準入力から簡単に入力/実行す
-るためのツールです.
-
-= 起動
-
- % ruby -r irb -e0
- % irb
-
-のいずれかで行ないます. 前者の場合irbへのオプション指定は, 以下のように
-なります.
-
- % ruby -r irb -e0 -- -v
-
-= 使い方
-
-irbの使い方は, Rubyさえ知っていればいたって簡単です. 基本的には irb と
-いうコマンドを実行するだけです. irbを実行すると, 以下のようなプロンプ
-トが表れてきます. 後は, rubyの式を入れて下さい. 式が完結した時点で実行
-されます.
-
- dim% irb
- irb(main):001:0> 1+2
- 3
- irb(main):002:0> class Foo
- irb(main):003:1> def foo
- irb(main):004:2> print 1
- irb(main):005:2> end
- irb(main):006:1> end
- nil
- irb(main):007:0>
-
-また, irbはReadlineモジュールにも対応しています. Readlineモジュールが
-インストールされている時には, それを使うのが標準の動作になります.
-
-= コマンドオプション
-
- irb.rb [options] file_name opts
- options:
- -f ~/.irbrc を読み込まない.
- -m bcモード(分数, 行列の計算ができる)
- -d $DEBUG をtrueにする(ruby -d と同じ)
- -r load-module ruby -r と同じ.
- --inspect 結果出力にinspectを用いる(bcモード以外はデフォルト).
- --noinspect 結果出力にinspectを用いない.
- --readline readlineライブラリを利用する.
- --noreadline readlineライブラリを利用しない. デフォルトの動作は,
- inf-reuby-mode以外でreadlineライブラリを利用しよう
- とする.
- --prompt prompt-mode
- --prompt-mode prompt-mode
- プロンプトモードを切替えます. 現在定義されているプ
- ロンプトモードは, default, simple, xmp, inf-rubyが
- 用意されています. デフォルトはdefaultプロンプトモー
- ドになっています.
-
- --inf-ruby-mode emacsのinf-ruby-mode用のプロンプト表示を行なう. 特
- に指定がない限り, readlineライブラリは使わなくなる.
- --simple-prompt
- 非常にシンプルなプロンプトを用いるモードです.
- --noprompt プロンプト表示を行なわない.
- --tracer コマンド実行時にトレースを行なう.
- --back-trace-limit n
- バックトレース表示をバックトレースの頭から n, 後ろ
- からnだけ行なう. デフォルトは16
- --irb_debug n irbのデバッグデバッグレベルをnに設定する(利用しな
- い方が無難でしょう).
- -v, --version irbのバージョンを表示する
-
-= コンフィギュレーション
-
-irb起動時に``~/.irbrc''を読み込みます. もし存在しない場合は,
-``.irbrc'', ``irb.rc'', ``_irbrc'', ``$irbrc''の順にloadを試みます.
-
-オプションを設定する代わりに, 以下のコマンドでもデフォルトの動作を設定
-できます.
-
- IRB.conf[:IRB_NAME]="irb"
- IRB.conf[:MATH_MODE]=false
- IRB.conf[:USE_TRACER]=false
- IRB.conf[:USE_LOADER]=false
- IRB.conf[:IGNORE_SIGINT]=true
- IRB.conf[:IGNORE_EOF]=false
- IRB.conf[:INSPECT_MODE]=nil
- IRB.conf[:IRB_RC] = nil
- IRB.conf[:BACK_TRACE_LIMIT]=16
- IRB.conf[:USE_LOADER] = false
- IRB.conf[:USE_READLINE] = nil
- IRB.conf[:USE_TRACER] = false
- IRB.conf[:IGNORE_SIGINT] = true
- IRB.conf[:IGNORE_EOF] = false
- IRB.conf[:PROMPT_MODE] = :DEFALUT
- IRB.conf[:PROMPT] = {...}
- IRB.conf[:DEBUG_LEVEL]=0
- IRB.conf[:VERBOSE]=true
-
-== プロンプトの設定
-
-プロンプトをカスタマイズしたい時には,
-
- IRB.conf[:PROMPT]
-
-を用います. 例えば, .irbrcの中で下のような式を記述します:
-
- IRB.conf[:PROMPT][:MY_PROMPT] = { # プロンプトモードの名前
- :PROMPT_I => nil, # 通常のプロンプト
- :PROMPT_S => nil, # 文字列などの継続行のプロンプト
- :PROMPT_C => nil, # 式が継続している時のプロンプト
- :RETURN => " ==>%s\n" # リターン時のプロンプト
- }
-
-プロンプトモードを指定したい時には,
-
- irb --prompt my-prompt
-
-でそのプロンプトモードで起動されます. または, .irbrcに下式を記述しても
-OKです.
-
- IRB.conf[:PROMPT_MODE] = :MY_PROMPT
-
-PROMPT_I, PROMPT_S, PROMPT_Cは, フォーマットを指定します.
-
- %N 起動しているコマンド名が出力される.
- %m mainオブジェクト(self)がto_sで出力される.
- %M mainオブジェクト(self)がinspectされて出力される.
- %l 文字列中のタイプを表す(", ', /, ], `]'は%wの中の時)
- %NNi インデントのレベルを表す. NNは数字が入りprintfの%NNdと同じ. 省
- 略可能
- %NNn 行番号を表します.
- %% %
-
-例えば, デフォルトのプロンプトモードは:
-
- IRB.conf[:PROMPT_MODE][:DEFAULT] = {
- :PROMPT_I => "%N(%m):%03n:%i> ",
- :PROMPT_S => "%N(%m):%03n:%i%l ",
- :PROMPT_C => "%N(%m):%03n:%i* ",
- :RETURN => "%s\n"
- }
-
-となっています.
-
-RETURNは, 現在のところprintf形式です. 将来仕様が変わるかも知れません.
-
-== サブirbの設定
-
-コマンドラインオプションおよびIRB.confは(サブ)irb起動時のデフォルトの
-設定を決めるもので, `5. コマンド'にあるconfで個別の(サブ)irbの設定がで
-きるようになっています.
-
-IRB.conf[:IRB_RC]にprocが設定されていると, サブirbを起動する時にその
-procをirbのコンテキストを引数として呼び出します. これによって個別のサ
-ブirbごとに設定を変えることができるようになります.
-
-
-= コマンド
-
-irb拡張コマンドは, 簡単な名前と頭に`irb_'をつけた名前と両方定義されて
-います. これは, 簡単な名前がoverrideされた時のためです.
-
---- exit, quit, irb_exit
- 終了する.
- サブirbの場合, そのサブirbを終了する.
- cbしている場合, そのバインディングのモードを終了する.
-
---- conf, irb_context
- irbの現在の設定を表示する. 設定の変更は, confにメッセージを送るこ
- とによって行なえる.
-
---- conf.back_trace_limit
- バックトレース表示をバックトレースの頭からn, 後ろからnだけ行なう.
- デフォルトは16
-
---- conf.debug_level = N
- irb用のデバッグレベルの設定
-
---- conf.ignore_eof = true/false
- ^Dが入力された時の動作を設定する. trueの時は^Dを無視する, falseの
- 時はirbを終了する.
-
---- conf.ignore_sigint= true/false
- ^Cが入力された時の動作を設定する. false時は, irbを終了する. trueの
- 時の動作は以下のようになる:
- 入力中: これまで入力したものをキャンセルしトップレベルに戻る.
- 実行中: 実行を中止する.
-
---- conf.inf_ruby_mode = true/false
- inf-ruby-mode用のプロンプト表示を行なう. デフォルトはfalse.
-
---- conf.inspect_mode = true/false/nil
- インスペクトモードを設定する.
- true: インスペクトして表示する.
- false: 通常のprintで表示する.
- nil: 通常モードであれば, inspect modeとなり, mathモードの時は, non
- inspect modeとなる.
-
---- conf.irb_level
- 参照のみ. irbが何段cbしているか?
-
---- conf.math_mode
- 参照のみ. bcモード(分数, 行列の計算ができます)かどうか?
-
---- conf.use_loader = true/false
- load/require時にirbのfile読み込み機能を用いるモードのスイッチ(デフォ
- ルトは用いない). このモードはIRB全体に反映される.
-
---- conf.prompt_c
- ifの直後など, 行が継続している時のプロンプト.
-
---- conf.prompt_i
- 通常のプロンプト.
-
---- conf.prompt_s
- 文字列中などを表すプロンプト.
-
---- conf.rc
- ~/.irbrcを読み込んだかどうか?
-
---- conf.use_prompt = true/false
- プロンプト表示するかどうか? デフォルトではプロンプトを表示する.
-
---- conf.use_readline = true/false/nil
- readlineを使うかどうか?
- true: readlineを使う.
- false: readlineを使わない.
- nil: (デフォルト)inf-reuby-mode以外でreadlineライブラリを利用しよ
- うとする.
-
---- conf.verbose=T/F
- irbからいろいろなメッセージを出力するか?
-
---- cb, irb_change_binding [obj]
- ローカル変数のスコープが違う新たなbindingに移る. objが指定された
- 時は, そのobjをselfとする.
-
---- irb [obj]
- サブirbを立ちあげる. objが指定された時は, そのobjをselfとする.
-
---- jobs, irb_jobs
- サブirbのリスト
-
---- fg n, irb_fg n
- 指定したサブirbにスイッチする. nは, 次のものを指定する.
-
- irb番号
- スレッド
- irbオブジェクト
- self(irb objで起動した時のobj)
-
---- kill n, irb_kill n
- サブirbをkillする. nはfgと同じ.
-
-
-= システム変数
-
- _ 前の計算の実行結果を覚えている(ローカル変数).
-
-= 使用例
-
-以下のような感じです.
-
- dim% ruby irb.rb
- irb(main):001:0> irb # サブirbの立ちあげ
- irb#1(main):001:0> jobs # サブirbのリスト
- #0->irb on main (#<Thread:0x400fb7e4> : stop)
- #1->irb#1 on main (#<Thread:0x40125d64> : running)
- nil
- irb#1(main):002:0> fg 0 # jobのスイッチ
- nil
- irb(main):002:0> class Foo;end
- nil
- irb(main):003:0> irb Foo # Fooをコンテキストしてirb
- # 立ちあげ
- irb#2(Foo):001:0> def foo # Foo#fooの定義
- irb#2(Foo):002:1> print 1
- irb#2(Foo):003:1> end
- nil
- irb#2(Foo):004:0> fg 0 # jobをスイッチ
- nil
- irb(main):004:0> jobs # jobのリスト
- #0->irb on main (#<Thread:0x400fb7e4> : running)
- #1->irb#1 on main (#<Thread:0x40125d64> : stop)
- #2->irb#2 on Foo (#<Thread:0x4011d54c> : stop)
- nil
- irb(main):005:0> Foo.instance_methods # Foo#fooがちゃんと定義さ
- # れている
- ["foo"]
- irb(main):006:0> fg 2 # jobをスイッチ
- nil
- irb#2(Foo):005:0> def bar # Foo#barを定義
- irb#2(Foo):006:1> print "bar"
- irb#2(Foo):007:1> end
- nil
- irb#2(Foo):010:0> Foo.instance_methods
- ["bar", "foo"]
- irb#2(Foo):011:0> fg 0
- nil
- irb(main):007:0> f = Foo.new
- #<Foo:0x4010af3c>
- irb(main):008:0> irb f # Fooのインスタンスでirbを
- # 立ちあげる.
- irb#3(#<Foo:0x4010af3c>):001:0> jobs
- #0->irb on main (#<Thread:0x400fb7e4> : stop)
- #1->irb#1 on main (#<Thread:0x40125d64> : stop)
- #2->irb#2 on Foo (#<Thread:0x4011d54c> : stop)
- #3->irb#3 on #<Foo:0x4010af3c> (#<Thread:0x4010a1e0> : running)
- nil
- irb#3(#<Foo:0x4010af3c>):002:0> foo # f.fooの実行
- nil
- irb#3(#<Foo:0x4010af3c>):003:0> bar # f.barの実行
- barnil
- irb#3(#<Foo:0x4010af3c>):004:0> kill 1, 2, 3# jobのkill
- nil
- irb(main):009:0> jobs
- #0->irb on main (#<Thread:0x400fb7e4> : running)
- nil
- irb(main):010:0> exit # 終了
- dim%
-
-= 使用上の制限
-
-irbは, 評価できる時点(式が閉じた時点)での逐次実行を行ないます. したがっ
-て, rubyを直接使った時と, 若干異なる動作を行なう場合があります.
-
-現在明らかになっている問題点を説明します.
-
-== ローカル変数の宣言
-
-rubyでは, 以下のプログラムはエラーになります.
-
- eval "foo = 0"
- foo
- --
- -:2: undefined local variable or method `foo' for #<Object:0x40283118> (NameError)
- ---
- NameError
-
-ところが, irbを用いると
-
- >> eval "foo = 0"
- => 0
- >> foo
- => 0
-
-となり, エラーを起こしません. これは, rubyが最初にスクリプト全体をコン
-パイルしてローカル変数を決定するからです. それに対し, irbは実行可能に
-なる(式が閉じる)と自動的に評価しているからです. 上記の例では,
-
- evel "foo = 0"
-
-を行なった時点で評価を行ない, その時点で変数が定義されるため, 次式で
-変数fooは定義されているからです.
-
-このようなrubyとirbの動作の違いを解決したい場合は, begin...endで括って
-バッチ的に実行して下さい:
-
- >> begin
- ?> eval "foo = 0"
- >> foo
- >> end
- NameError: undefined local variable or method `foo' for #<Object:0x4013d0f0>
- (irb):3
- (irb_local_binding):1:in `eval'
-
-== ヒアドキュメント
-
-現在のところヒアドキュメントの実装は不完全です.
-
-== シンボル
-
-シンボルであるかどうかの判断を間違えることがあります. 具体的には式が完了
-しているのに継続行と見なすことがあります.
-
-=end
-
-% Begin Emacs Environment
-% Local Variables:
-% mode: text
-% comment-column: 0
-% comment-start: "%"
-% comment-end: "\n"
-% End:
-%
-
diff --git a/doc/net/http.rd.ja b/doc/net/http.rd.ja
deleted file mode 100644
index 1bdb898b80..0000000000
--- a/doc/net/http.rd.ja
+++ /dev/null
@@ -1,433 +0,0 @@
-=begin
-
-= net/http.rb
-
-== このライブラリについて
-
-汎用データ転送プロトコル HTTP を扱うライブラリです。
-実装は [RFC2616] ((<URL:http://www.ietf.org/rfc/rfc2616.txt>)) に
-基いています。
-
-== 使用例
-
-=== ウェブサーバからドキュメントを得る (GET)
-
- require 'net/http'
- Net::HTTP.start( 'some.www.server', 80 ) {|http|
- response , = http.get('/index.html')
- puts response.body
- }
-
-また以下は同じ意味で短く書いたものです。
-
- require 'net/http'
- Net::HTTP.get_print 'some.www.server', '/index.html'
-
-=== フォームの情報を送信する (POST)
-
- require 'net/http'
- Net::HTTP.start( 'some.www.server', 80 ) {|http|
- response , = http.post( '/cgi-bin/any.rhtml',
- 'querytype=subject&target=ruby' )
- }
-
-=== プロクシ経由のアクセス
-
-Net::HTTP のクラスメソッド Net::HTTP.Proxy は、常にプロクシ経由で
-接続するような動作をする、新しいクラスを作成して返します。このクラスは
-Net::HTTP を継承しているので Net::HTTP と全く同じように使えます。
-
- require 'net/http'
-
- $proxy_addr = 'your.proxy.addr'
- $proxy_port = 8080
- :
- Net::HTTP::Proxy($proxy_addr, $proxy_port).start( 'some.www.server' ) {|http|
- # always connect to your.proxy.addr:8080
- :
- }
-
-また Net::HTTP.Proxy は第一引数が nil だと Net::HTTP 自身を返すので
-上のコードのように書いておけばプロクシなしの場合にも対応できます。
-
-=== リダイレクトに対応する
-
- require 'net/http'
- Net::HTTP.version_1_1
-
- host = 'www.ruby-lang.org'
- path = '/'
- begin
- Net::HTTP.start( host, 80 ) {|http|
- response , = http.get(path)
- print response.body
- }
- rescue Net::ProtoRetriableError => err
- if m = %r<http://([^/]+)>.match( err.response['location'] ) then
- host = m[1].strip
- path = m.post_match
- retry
- end
- end
-
-この例では URL からホスト名を得るのにいいかげんな方法を使っていますが、
-将来 URI クラスが標準添付になればもっと簡単になるはずです。
-
-=== Basic 認証
-
- require 'net/http'
-
- Net::HTTP.start( 'auth.some.domain' ) {|http|
- response , = http.get( '/need-auth.cgi',
- 'Authorization' => 'Basic ' + ["#{account}:#{password}"].pack('m').strip )
- print response.body
- }
-
-バージョン 1.2 (Ruby 1.7 以降に添付) では次のように書けます。
-
- require 'net/http'
-
- req = Net::HTTP::Get.new('/need-auth.cgi')
- req.basic_auth 'account', 'password'
- Net::HTTP.start( 'auth.some.domain' ) {|http|
- response = http.request(req)
- print response.body
- }
-
-== 新しい仕様への変更と移行措置について
-
-Ruby 1.6 に入っているのが http.rb 1.1 で 1.7 以降が 1.2 ですが、
-この間ではかなり大きく仕様が変わります。そこで突然に仕様を変更
-するのでなく、両方の実装を並存させる時期を設けることにしました。
-
-メソッド HTTP.version_1_2、HTTP.version_1_1 を呼ぶと
-そのあとに生成される Net::HTTP オブジェクトはそれぞれの
-バージョンの仕様で動作するようになります。以下は使用例です。
-
- # example
- Net::HTTP.start {|http1| ...(http1 has 1.2 features)... }
-
- Net::HTTP.version_1_1
- Net::HTTP.start {|http2| ...(http2 has 1.1 features)... }
-
- Net::HTTP.version_1_2
- Net::HTTP.start {|http3| ...(http3 has 1.2 features)... }
-
-この機能はスレッドセーフではありません。
-
-== class Net::HTTP
-
-=== クラスメソッド
-
-: new( address, port = 80, proxy_addr = nil, proxy_port = nil )
- 新しい HTTP オブジェクトを生成します。address は HTTP サーバーの FQDN で、
- port は接続するポート番号です。このメソッドではまだ接続はしません。
-
- proxy_addr を与えるとプロクシを介して接続するオブジェクトを生成します。
-
-: start( address, port = 80, proxy_addr = nil, proxy_port = nil )
-: start( address, port = 80, proxy_addr = nil, proxy_port = nil ) {|http| .... }
- 以下と同じです。
-
- Net::HTTP.new(address, port, proxy_addr, proxy_port).start(&block)
-
-: get( address, path, port = 80 )
- ホスト address の port 番ポートに接続して path の表現する
- エンティティを取得、文字列で返します。
-
-: get_print( address, path, port = 80 )
- ホスト address の port 番ポートに接続して path の表現する
- エンティティを取得したうえ、$stdout に << で出力します。
-
-: Proxy( address, port = 80 )
- 常に指定されたプロクシに接続するクラスを作成し返します。
- このクラスは Net::HTTP を継承しているので Net::HTTP と全く
- 同じように使えます。
-
- address が nil のときは Net::HTTP クラスをそのまま返します。
-
- # example
- proxy_class = Net::HTTP::Proxy( 'proxy.foo.org', 8080 )
- :
- proxy_class.start( 'www.ruby-lang.org' ) {|http|
- # connecting proxy.foo.org:8080
- :
- }
-
-: proxy_class?
- 自身が (Proxy メソッドによって作成された) プロクシ用のクラスならば真。
-
-: port
- HTTP のデフォルトポート (80)。
-
-=== メソッド
-
-: start
-: start {|http| .... }
- TCP コネクションを張り、HTTP セッションを開始します。
- すでにセッションが開始していたら例外 IOError を発生します。
-
- イテレータとして呼ばれた時はブロックの間だけセッションを接続し、
- ブロック終了とともに自動的にセッションを閉じます。
-
-: active?
- HTTP セッションが開始されていたら真。
-
-: address
- 接続するアドレス
-
-: port
- 接続するポート番号
-
-: open_timeout
-: open_timeout=(n)
- 接続時に待つ最大秒数。この秒数たってもコネクションが
- 開かなければ例外 TimeoutError を発生します。
-
-: read_timeout
-: read_timeout=(n)
- 読みこみ (read(1) 一回) でブロックしてよい最大秒数。
- この秒数たっても読みこめなければ例外 TimeoutError を発生します。
-
-: finish
- HTTP セッションを終了します。セッション開始前にこのメソッドが
- 呼ばれた場合は例外 IOError を発生します。
-
-: proxy?
- プロクシを介して接続するなら真。
-
-: proxy_address
- プロクシ経由で接続する HTTP オブジェクトならプロクシのアドレス。
- そうでないなら nil。
-
-: proxy_port
- プロクシ経由で接続する HTTP オブジェクトならプロクシのポート。
- そうでないなら nil。
-
-: get( path, header = nil )
-: get( path, header = nil ) {|str| .... }
- サーバ上の path にあるエンティティを取得します。また header が nil
- でなければ、リクエストを送るときにその内容を HTTP ヘッダとして書き
- こみます。header はハッシュで、「ヘッダ名 => 内容」のような形式で
- なければいけません。
-
- 返り値は、バージョン 1.1 では HTTPResponse とエンティティボディ文字列の
- 二要素の配列です。1.2 では HTTPResponse ただひとつのみです。この場合、
- エンティティボディは response.body で得られます。
-
- ブロックとともに呼ばれた時はエンティティボディを少しづつブロックに
- 与えます。
-
- 1.1 では 3xx (再試行可能なエラー)に対しても例外を発生します。この場合
- HTTPResponse は例外オブジェクトから err.response で得ることができます。
- 一方 1.2 では全く例外を発生しません。
-
- # version 1.1 (bundled with Ruby 1.6)
- response, body = http.get( '/index.html' )
-
- # version 1.2 (bundled with Ruby 1.7 or later)
- response = http.get( '/index.html' )
-
- # compatible in both version
- response , = http.get( '/index.html' )
- response.body
-
- # using block
- File.open( 'save.txt', 'w' ) {|f|
- http.get( '/~foo/', nil ) do |str|
- f.write str
- end
- }
-
-: head( path, header = nil )
- サーバ上の path にあるエンティティのヘッダのみを取得します。
- また header が nil でなければリクエストを送るときにその内容を
- HTTP ヘッダとして書きこみます。header はハッシュで、
- 「ヘッダ名 => 内容」のような形式でなければいけません。
-
- HTTPResponse オブジェクトを返します。
-
- 1.1 では 3xx (再試行可能なエラー)に対しても例外を発生します。この場合
- HTTPResponse は例外オブジェクトから err.response で得ることができます。
- 一方 1.2 では全く例外を発生しません。
-
- response = nil
- Net::HTTP.start( 'some.www.server', 80 ) {|http|
- response = http.head( '/index.html' )
- }
- p response['content-type']
-
-: post( path, data, header = nil )
-: post( path, data, header = nil ) {|str| .... }
- サーバ上の path にあるエンティティに対し文字列 data を
- 送ります。レスポンスは << メソッドを使って dest に書き
- こまれます。header は get メソッドと同じです。
- HTTPResponse オブジェクトと dest の配列を返します。
-
- イテレータとして呼びだされたときはエンティティボディを少しづつ
- ブロックに与えます。
-
- 1.1 では 3xx (再試行可能なエラー)に対しても例外を発生します。この場合
- HTTPResponse は例外オブジェクトから err.response で得ることができます。
- 一方 1.2 では全く例外を発生しません。
-
- # version 1.1
- response, body = http.post( '/cgi-bin/search.rb', 'query=subject&target=ruby' )
-
- # version 1.2
- response = http.post( '/cgi-bin/search.rb', 'query=subject&target=ruby' )
-
- # compatible in both version
- response , = http.post( '/cgi-bin/search.rb', 'query=subject&target=ruby' )
-
- # using block
- File.open( 'save.html', 'w' ) {|f|
- http.post( '/cgi-bin/search.rb',
- 'query=subject&target=ruby' ) do |str|
- f.write str
- end
- }
-
-: request_get( path, header = nil )
-: request_get( path, header = nil ) {|response| .... }
- path にあるエンティティを取得します。HTTPResponse
- オブジェクトを返します。
-
- ブロックとともに呼び出されたときは、ブロック実行中は接続を
- 維持したまま HTTPResponse オブジェクトをブロックに渡します。
-
- このメソッドは HTTP プロトコルに関連した例外は発生させません。
-
- # example
- response = http.request_get( '/index.html' )
- p response['content-type']
- puts response.body # body is already read
-
- # using block
- http.request_get( '/index.html' ) {|response|
- p response['content-type']
- response.read_body do |str| # read body now
- print str
- end
- }
-
-: request_post( path, data, header = nil )
-: request_post( path, data, header = nil ) {|response| .... }
- path にあるエンティティを取得します。HTTPResponse
- オブジェクトを返します。
-
- ブロックとともに呼び出されたときは、ボディを読みこむ前に
- HTTPResponse オブジェクトをブロックに渡します。
-
- このメソッドは HTTP プロトコルに関連した例外は発生させません。
-
- # example
- response = http.post2( '/cgi-bin/nice.rb', 'datadatadata...' )
- p response.status
- puts response.body # body is already read
-
- # using block
- http.post2( '/cgi-bin/nice.rb', 'datadatadata...' ) {|response|
- p response.status
- p response['content-type']
- response.read_body do |str| # read body now
- print str
- end
- }
-
-: request( request [, data] )
-: request( request [, data] ) {|response| .... }
- HTTPResquest オブジェクト request を送信します。POST/PUT の時は data も
- 与えられます (POST/PUT 以外で data を与えると ArgumentError を発生します)。
-
- ブロックとともに呼びだされたときはボディを読みこまずに HTTPResponse
- オブジェクトをブロックに与えます。
-
- このメソッドは HTTP プロトコルに関連した例外は発生させません。
-
-== class Net::HTTP::Get, Head, Post
-
-HTTP リクエストを抽象化するクラス。key はすべて大文字小文字を
-区別しません。
-
-=== クラスメソッド
-
-: new
- HTTP リクエストオブジェクトを生成します。
-
-=== メソッド
-
-: self[ key ]
- key ヘッダフィールドの文字列。
- key は大文字小文字を区別しません。
-
-: self[ key ] = val
- key ヘッダフィールドに val をセットします。
- key は大文字小文字を区別しません。
-
-: each {|name, val| .... }
- ヘッダ名とその値に対するくりかえし。ヘッダ名は小文字で統一されます。
-
-: basic_auth( account, password )
- Authrization: ヘッダを basic auth 用にセットします。
-
-: range
- Range: ヘッダの示す範囲を Range オブジェクトで返します。
-
-: range = r
-: set_range( i, len )
- 範囲を指定してエンティティを取得するためのヘッダ Range: をセットします。
- r は Range オブジェクト、i, len は始点と長さです。
-
-: content_length
- Content-Length: ヘッダの値 (整数)。
-
-: content_range
- Content-Range: ヘッダの値 (Range)。
-
-== class Net::HTTPResponse
-
-HTTP レスポンスのクラスです。
-引数がヘッダフィールド名である場合、大文字小文字を区別しません。
-
-=== メソッド
-
-: self[ key ]
- key ヘッダフィールド(文字列)です。たとえばキー 'content-length'
- に対しては '2048' のような文字列が得られます。
- key は大文字小文字を区別しません。
-
-: self[ key ] = val
- key ヘッダフィールドを value に設定します。
- key は大文字小文字を区別しません。
-
-: key?( key )
- key というヘッダフィールドがあれば真。
- key は大文字小文字を区別しません。
-
-: each {|name,value| .... }
- すべてのヘッダフィールド名とその値のペアに対するくりかえし。
-
-: canonical_each {|name,value| .... }
- ヘッダフィールドの正式名とその値のペアに対して繰り返します。
-
-: code
- HTTP のリザルトコードです。例えば '302' などです。
-
-: message
- HTTP サーバがリザルトコードに付加して返すメッセージです。
- 例えば 'Not Found' などです。
-
-: read_body( dest = '' )
- エンティティボディを取得し dest に << メソッドを使って書きこみます。
- 同じ HTTPResponse オブジェクトに対して二回以上呼ばれた場合、
- 二回目からはなにもせずに一回目の返り値をそのまま返します。
-
-: read_body {|str| .... }
- エンティティボディを少しづつ取得して順次ブロックに与えます。
-
-: body
- エンティティボディです。read_body を呼んでいればその引数 dest、
- 呼んでいなければエンティティボディを文字列として読みこんで返します。
-
-=end
diff --git a/doc/net/pop.rd.ja b/doc/net/pop.rd.ja
deleted file mode 100644
index 2c7e22f29f..0000000000
--- a/doc/net/pop.rd.ja
+++ /dev/null
@@ -1,326 +0,0 @@
-=begin
-
-= net/pop.rb
-
-== このライブラリについて
-
-メールを受信するためのプロトコル POP3 (Post Office Protocol version 3) を
-を扱うライブラリです。POP3 の実装は [RFC1939]
-((<URL:http://www.ietf.org/rfc/rfc1939.txt>)) に基いています。
-
-== 使用例
-
-=== メールの受信
-
-以下のコードは、メールを受信してファイル 'inbox/1' 'inbox/2'... に
-書きこみ、サーバ上からメールを消します。pop3.server.address は適宜
-読みかえてください。
-
- require 'net/pop'
-
- pop = Net::POP3.new( 'pop3.server.address', 110 )
- pop.start( 'YourAccount', 'YourPassword' ) ###
- if pop.mails.empty? then
- puts 'no mail.'
- else
- i = 0
- pop.each_mail do |m| # or "pop.mails.each ..."
- File.open( 'inbox/' + i.to_s, 'w' ) {|f|
- f.write m.pop
- }
- m.delete
- i += 1
- end
- puts "#{pop.mails.size} mails popped."
- end
- pop.finish ###
-
-POP サーバはネットワークのむこうに存在するので、なにか仕事をさせる
-にはその前に開始手続きを、終わったら終了手続きを、行わなければいけ
-ません。それを行うのが Net::POP3#start と #finish で、POP3 オブジェクト
-はその二つのメソッドの間でだけ有効になります。
-
-サーバ上のメールは POPMail オブジェクトとして表現されており、この
-オブジェクトのメソッドを呼ぶことでメールを取ってきたり消したりする
-ことができます。POP3#mails はこの POPMail オブジェクトの配列であり、
-POP3#each_mail はさらに mails.each のショートカットです。
-
-=== 短くする
-
-上の例はあえて省略や短縮用メソッドを避けたためにかなり冗長です。
-まず、ブロック付きの Net::POP3.start を使うことで POP3.new #start
-#finish を併合できます。
-
- require 'net/pop'
-
- Net::POP3.start( 'pop3.server.address', 110 )
- 'YourAccount', 'YourPassword' )
- if pop.mails.empty? then
- puts 'no mail.'
- else
- i = 0
- pop.each_mail do |m| # or "pop.mails.each ..."
- File.open( 'inbox/' + i.to_s, 'w' ) {|f|
- f.write m.pop
- }
- m.delete
- i += 1
- end
- puts "#{pop.mails.size} mails popped."
- end
- }
-
-POP3#delete_all を使うとさらに #each_mail と m.delete を
-併合できます。
-
- require 'net/pop'
-
- Net::POP3.start( 'pop3.server.address', 110,
- 'YourAccount', 'YourPassword' ) {|pop|
- if pop.mails.empty? then
- puts 'no mail.'
- else
- i = 0
- pop.delete_all do |m|
- File.open( 'inbox/' + i.to_s, 'w' ) {|f|
- f.write m.pop
- }
- i += 1
- end
- end
- }
-
-クラスメソッドの POP3.delete_all を使うとさらに短くなります。
-
- require 'net/pop'
-
- i = 0
- Net::POP3.delete_all( 'pop3.server.address', 110,
- 'YourAccount', 'YourPassword' ) do |m|
- File.open( 'inbox/' + i.to_s, 'w' ) {|f|
- f.write m.pop
- }
- i += 1
- end
-
-=== ファイルに直接書く
-
-これまでの例では m.pop の部分でメールをひとつの文字列として
-うけとっていましたが、たとえば 3MB くらいある巨大なメールの場合は
-これではまずい場合があります。そのような場合は以下のように m.pop
-に File オブジェクトを与える手が使えます。
-
- require 'net/pop'
- Net::POP3.delete_all( 'pop3.server.address', 110,
- 'YourAccount', 'YourPassword' ) do |m|
- File.open( 'inbox', 'w' ) {|f|
- m.pop f ####
- }
- end
-
-=== APOP
-
-Net::POP3 クラスのかわりに Net::APOP クラスを使うと、認証時に APOP を
-使うようになります。また動的にノーマル POP と APOP を選択するには、
-以下のように Net::POP3.APOP() メソッドを使うのが便利です。
-
- require 'net/pop'
-
- # use APOP authentication if $isapop == true
- pop = Net::POP3.APOP($isapop).new( 'apop.server.address', 110 )
- pop.start( YourAccount', 'YourPassword' ) {|pop|
- # Rest code is same.
- }
-
-この方法はクラス自体を変えるので、クラスメソッドの start や foreach、
-delete_all、auth_only なども APOP とともに使えます。
-
-== Net::POP3 class
-
-=== クラスメソッド
-
-: new( address, port = 110, apop = false )
- Net::POP3 オブジェクトを生成します。まだ接続はしません。
- apop が真のときは APOP 認証を行うオブジェクトを生成します。
-
-: start( address, port = 110, account, password )
-: start( address, port = 110, account, password ) {|pop| .... }
- address の port 番ポートに接続し、アカウント account パスワード
- password で POP ログインします。第二引数 port に nil を渡すと
- POP3 のデフォルトポート(110)を使います。
-
- Net::POP3.start( addr, port, account, password ) {|pop|
- pop.each_mail do |m|
- file.write m.pop
- m.delete
- end
- }
-
-: APOP( is_apop )
- bool が真なら Net::APOP クラス、偽なら Net::POP3 クラスを返します。
- 以下の例のように使ってください。
-
- # example 1
- pop = Net::POP3::APOP($isapop).new( addr, port )
-
- # example 2
- Net::POP3::APOP($isapop).start( addr, port ) {|pop|
- ....
- }
-
-: foreach( address, port = 110, account, password ) {|mail| .... }
- POP セッションを開き、サーバ上のすべてのメールに対して繰り返します。
- 以下と同じです。
-
- Net::POP3.start( address, port, account, password ) {|pop|
- pop.each_mail do |m|
- yield m
- end
- }
-
- # example
- Net::POP3.foreach( 'your.pop.server', 110,
- 'YourAccount', 'YourPassword' ) do |m|
- file.write m.pop
- m.delete if $DELETE
- end
-
-: delete_all( address, port = 110, account, password )
-: delete_all( address, port = 110, account, password ) {|mail| .... }
- POP セッションを開き、サーバ上のメールをすべて削除します。
- ブロックが与えられた時は削除する前にブロックにそのメールを
- 渡します。以下と同じです。
-
- # example
- Net::POP3.delete_all( addr, nil, 'YourAccount', 'YourPassword' ) do |m|
- m.pop file
- end
-
-: auth_only( address, port = 110, account, password )
- POP セッションを開き認証だけを行って接続を切ります。
- POP before SMTP 専用です。
-
- # example
- Net::POP3.auth_only( 'your.pop3.server',
- nil, # using default (110)
- 'YourAccount',
- 'YourPassword' )
-
-=== メソッド
-
-: start( account, password )
-: start( account, password ) {|pop| .... }
- リモートホストとの接続を開始し、アカウントに account、
- パスワードに password を使って POP ログインします。
-
-: active?
- POP3 セッションが開始されていたら真。
-
-: address
- 接続するアドレス
-
-: port
- 接続するポート番号
-
-: open_timeout
-: open_timeout=(n)
- 接続時に待つ最大秒数。この秒数たってもコネクションが
- 開かなければ例外 TimeoutError を発生します。
-
-: read_timeout
-: read_timeout=(n)
- 読みこみ (read(1) 一回) でブロックしてよい最大秒数。
- この秒数たっても読みこめなければ例外 TimeoutError を発生します。
-
-: finish
- POP3 セッションを終了します。セッション開始前にこのメソッドが
- 呼ばれた場合は例外 IOError を発生します。
-
-: mails
- Net::POPMail オブジェクトの配列をかえします。
- この配列はセッションを開始したときに自動的に更新されます。
-
-: each_mail {|popmail| .... }
-: each {|popmail| .... }
- pop3.mails.each と同じです。
-
-: delete_all
-: delete_all {|popmail| .... }
- サーバ上のメールを全て消去します。
- ブロックを与えられたときは消去する前にその POPMail オブジェクトを
- ブロックに渡します。
-
- # example
- n = 1
- pop.delete_all do |m|
- File.open("inbox/#{n}") {|f| f.write m.pop }
- n += 1
- end
-
-: auth_only( account, password )
- POP セッションを開き認証だけを行って接続を切ります。
- POP before SMTP 専用です。
- # example
- pop = Net::POP3.new( 'your.pop3.server' )
- pop.auth_only 'YourAccount', 'YourPassword'
-
-: reset
- セッションをリセットします。
- 具体的には POPMail#delete で消したメールが全て復活します。
- (POP3 ではメール一個だけを復活する方法はありません)
-
-== Net::APOP
-
-このクラスでは新しいメソッドは導入していません。
-認証方式が APOP に変わるだけです。
-
-=== スーパークラス
-Net::POP3
-
-== Net::POPMail
-
-POP サーバー上のメール一通を抽象的に表現するクラス。
-メールの取得や消去といった操作をカプセル化します。
-
-=== メソッド
-
-: pop( dest = '' )
- メールを受信して dest に << メソッドを使って書きこみます。
- dest を返します。
-
- # example
- allmails = nil
- POP3.start( 'your.pop3.server', 110,
- 'YourAccount, 'YourPassword' ) {|pop|
- allmails = pop.mails.collect {|popmail| popmail.pop }
- }
-
-: pop {|str| .... }
- メールの文字列を少しづつ読みこみ、順次ブロックに与えます。
-
- # example
- POP3.start( 'localhost', 110 ) {|pop3|
- pop3.each_mail do |m|
- m.pop do |str|
- # do anything
- end
- end
- }
-
-: header
- ヘッダだけを受信して文字列で返します。
-
-: top( lines )
- メールヘッダと lines 行ぶんの本文を取得し文字列で返します。
-
-: delete
- サーバ上からメールを削除します。
-
-: size
- メールのサイズ (単位はバイト) をかえします。
-
-: deleted?
- メールがサーバ上で消去されているとき真。消去してしまったら
- POP3#reset を使う以外に復活する方法はありません。
-
-=end
diff --git a/doc/net/smtp.rd.ja b/doc/net/smtp.rd.ja
deleted file mode 100644
index cc87865dc7..0000000000
--- a/doc/net/smtp.rd.ja
+++ /dev/null
@@ -1,194 +0,0 @@
-=begin
-
-= net/smtp.rb
-
-== このライブラリについて
-
-メールを送信するためのプロトコル SMTP (Simple Mail Transfer Protocol)
-を扱うライブラリです。ヘッダなどメールのデータを扱うことはできません。
-SMTP の実装は [RFC2821] ((<URL:http://www.ietf.org/rfc/rfc2821.txt>))
-に基いています。
-
-== 使用例
-
-=== とにかくメールを送る
-
-SMTP を使ってメールを送るにはまず SMTP.start でセッションを開きます。
-第一引数がサーバのアドレスで第二引数がポート番号です。
-ブロックを使うと File.open と同じように終端処理を自動的にやってくれる
-のでおすすめです。
-
- require 'net/smtp'
- Net::SMTP.start( 'your.smtp.server', 25 ) {|smtp|
- # use smtp object only in this block
- }
-
-your.smtp.server は適切な SMTP サーバのアドレスに読みかえてください。
-通常は LAN の管理者やプロバイダが SMTP サーバを用意してくれているはずです。
-
-セッションが開いたらあとは send_mail でメールを流しこむだけです。
-
- require 'net/smtp'
-
- Net::SMTP.start( 'your.smtp.server', 25 ) {|smtp|
- smtp.send_mail <<EndOfMail, 'your@mail.address', 'to@some.domain'
- From: Your Name <your@mail.address>
- To: Dest Address <to@some.domain>
- Subject: test mail
- Date: Sat, 23 Jun 2001 16:26:43 +0900
- Message-Id: <unique.message.id.string@some.domain>
-
- This is test mail.
- EndOfMail
- }
-
-=== セッションを終了する
-
-メールを送ったら SMTP#finish を呼んでセッションを終了しなければいけ
-ません。File のように GC 時に勝手に close されることもありません。
-いろいろなところで finish がないソースコードの例を見掛けますが、
-すべて誤りです。finish は必ず呼んでください。
-
-またブロック付きの SMTP.start/SMTP#start を使うと勝手に finish を
-呼んでくれるので便利です。可能な限りブロック付きの start を使うのが
-よいでしょう。
-
- # using SMTP#finish
- smtp = Net::SMTP.start( 'your.smtp.server', 25 )
- smtp.send_mail mail_string, 'from@address', 'to@address'
- smtp.finish
-
- # using block form of SMTP.start
- Net::SMTP.start( 'your.smtp.server', 25 ) {|smtp|
- smtp.send_mail mail_string, 'from@address', 'to@address'
- }
-
-=== 文字列以外からの送信
-
-ひとつ上の例では文字列リテラル(ヒアドキュメント)を使って送信しましたが、
-each メソッドを持ったオブジェクトからならなんでも送ることができます。
-以下は File オブジェクトから直接送信する例です。
-
- require 'net/smtp'
- Net::SMTP.start( 'your.smtp.server', 25 ) {|smtp|
- File.open( 'Mail/draft/1' ) {|f|
- smtp.send_mail f, 'your@mail.address', 'to@some.domain'
- }
- }
-
-=== HELO ドメイン
-
-SMTP ではメールを送る側のホストの名前 (HELO ドメインと呼ぶ) を要求
-されるのですが、Net::SMTP ではとりあえず localhost.localdomain と
-いう名前を送信しています。たいていの SMTP サーバはこの HELO ドメイン
-による認証はあまり真面目に行わないので (簡単に偽造できるからです)
-問題にならないことが多いのですが、まれにメールセッションを切られる
-こともあります。そういうときはとりあえず HELO ドメインを与えてみて
-ください。もちろんそれ以外の時も HELO ドメインはちゃんと渡すのが
-ベストです。
-
-HELO ドメインは SMTP.start/SMTP#start の第三引数 helo_domain に指定
-します。
-
- Net::SMTP.start( 'your.smtp.server', 25,
- 'mail.from.domain' ) {|smtp|
-
-よくあるダイヤルアップホストの場合、HELO ドメインには ISP のメール
-サーバのドメインを使っておけばたいてい通ります。
-
-== class Net::SMTP
-
-=== クラスメソッド
-
-: new( address, port = 25 )
- 新しい SMTP オブジェクトを生成します。address はSMTPサーバーのFQDNで、
- port は接続するポート番号です。ただし、このメソッドではまだ接続はしません。
-
-: start( address, port = 25, helo_domain = 'localhost.localdomain', account = nil, password = nil, authtype = nil )
-: start( address, port = 25, helo_domain = 'localhost.localdomain', account = nil, password = nil, authtype = nil ) {|smtp| .... }
- 以下と同じです。
- Net::SMTP.new(address,port).start(helo_domain,account,password,authtype)
-
- # example
- Net::SMTP.start( 'your.smtp.server' ) {
- smtp.send_mail mail_string, 'from@mail.address', 'dest@mail.address'
- }
-
-=== メソッド
-
-: start( helo_domain = <local host name>, account = nil, password = nil, authtype = nil )
-: start( helo_domain = <local host name>, account = nil, password = nil, authtype = nil ) {|smtp| .... }
- TCP コネクションを張り、同時に SMTP セッションを開始します。そのとき、
- こちらのホストの FQDN を helo_domain に指定します。
- もしすでにセッションが開始していたら IOError を発生します。
-
- account と password の両方が与えられた場合、AUTH コマンドによって
- 認証を行います。authtype は使用する認証のタイプで、シンボル
- で :plain か :cram_md5 を指定します。
-
-: active?
- SMTP セッションが開始されていたら真。
-
-: address
- 接続するアドレス
-
-: port
- 接続するポート番号
-
-: open_timeout
-: open_timeout=(n)
- 接続時に待つ最大秒数。この秒数たってもコネクションが
- 開かなければ例外 TimeoutError を発生します。
-
-: read_timeout
-: read_timeout=(n)
- 読みこみ (read(1) 一回) でブロックしてよい最大秒数。
- この秒数たっても読みこめなければ例外 TimeoutError を発生します。
-
-: finish
- SMTP セッションを終了します。セッション開始前にこのメソッドが
- 呼ばれた場合は例外 IOError を発生します。
-
-: send_mail( mailsrc, from_addr, *to_addrs )
- mailsrc をメールとして送信します。mailsrc は each イテレータを持つ
- オブジェクトならなんでも構いません (たとえば String や File)。
- from_domain は送り主のメールアドレス ('...@...'のかたちのもの) で、
- to_addrs には送信先メールアドレスを並べます。
-
- # example
- Net::SMTP.start( 'your.smtp.server' ) {|smtp|
- smtp.send_mail mail_string,
- 'from@mail.address',
- 'dest@mail.address' 'dest2@mail.address'
- }
-
-: ready( from_addr, *to_addrs ) {|adapter| .... }
- メール書きこみの準備をしたうえで、write メソッドを持つオブジェクトを
- ブロックにあたえます。from_addr は送信元メールアドレスで to_addrs は
- 宛先のメールボックスです。
-
- # example
- Net::SMTP.start( 'your.smtp.server', 25 ) {|smtp|
- smtp.ready( 'from@mail.addr', 'dest@mail.addr' ) {|f|
- f.puts 'From: aamine@loveruby.net'
- f.puts 'To: someone@somedomain.org'
- f.puts 'Subject: test mail'
- f.puts
- f.puts 'This is test mail.'
- }
- }
-
-== 発生する例外
-
-セッション中に (SMTP レベルの) エラーがおこった場合、
-以下の例外が発生します。
-: Net::ProtoSyntaxError
- SMTP コマンドの構文ミス(500番台)
-: Net::ProtoFatalError
- 恒久的なエラー(550番台)
-: Net::ProtoUnknownError
- 予期しないエラー。おそらくバグ
-: Net::ProtoServerBusy
- 一時的なエラー(420/450番台)
-
-=end
diff --git a/doc/shell.rd b/doc/shell.rd
deleted file mode 100644
index 02ee1b020a..0000000000
--- a/doc/shell.rd
+++ /dev/null
@@ -1,348 +0,0 @@
- -- shell.rb
- $Release Version: 0.6.0 $
- $Revision$
- $Date$
- by Keiju ISHITSUKA(keiju@ishitsuka.com)
-
-=begin
-
-= What's shell.rb?
-
-It realizes a wish to do execution of commands with filters and pipes
-like sh/csh by using just native facilities of ruby.
-
-= Main classes
-
-== Shell
-
-Every shell object has its own current working directory, and executes
-each command as if it stands in the directory.
-
---- Shell#cwd
---- Shell#dir
---- Shell#getwd
---- Shell#pwd
-
- Returns the current directory
-
---- Shell#system_path
-
- Returns the command search path in an array
-
---- Shell#umask
-
- Returns the umask
-
-== Filter
-
-Any result of command exection is a Filter. Filter include
-Enumerable, therefore a Filter object can use all Enumerable
-facilities.
-
-= Main methods
-
-== Command definitions
-
-In order to execute a command on your OS, you need to define it as a
-Shell method.
-
-Alternatively, you can execute any command via Shell#system even if it
-is not defined.
-
---- Shell.def_system_command(command, path = command)
-
- Defines a command. Registers <path> as a Shell method
- <command>.
-
- ex)
- Shell.def_system_command "ls"
- Defines ls.
-
- Shell.def_system_command "sys_sort", "sort"
- Defines sys_sort as sort.
-
---- Shell.undef_system_command(command)
-
- Undefines a commmand
-
---- Shell.alias_command(ali, command, *opts) {...}
-
- Aliases a command.
-
- ex)
- Shell.alias_command "lsC", "ls", "-CBF", "--show-control-chars"
- Shell.alias_command("lsC", "ls"){|*opts| ["-CBF", "--show-control-chars", *opts]}
-
---- Shell.unalias_command(ali)
-
- Unaliases a command.
-
---- Shell.install_system_commands(pre = "sys_")
-
- Defines all commands in the default_system_path as Shell method,
- all with <pre> prefixed to their names.
-
-== Creation
-
---- Shell.new
-
- Creates a Shell object which current directory is set to the
- process current directory.
-
---- Shell.cd(path)
-
- Creates a Shell object which current directory is set to
- <path>.
-
-== Process management
-
---- Shell#jobs
-
- Returns a list of scheduled jobs.
-
---- Shell#kill sig, job
-
- Sends a signal <sig> to <job>.
-
-== Current directory operations
-
---- Shell#cd(path, &block)
---- Shell#chdir
-
- Changes the current directory to <path>. If a block is given,
- it restores the current directory when the block ends.
-
---- Shell#pushd(path = nil, &block)
---- Shell#pushdir
-
- Pushes the current directory to the directory stack, changing
- the current directory to <path>. If <path> is omitted, it
- exchanges its current directory and the top of its directory
- stack. If a block is given, it restores the current directory
- when the block ends.
-
---- Shell#popd
---- Shell#popdir
-
- Pops a directory from the directory stack, and sets the current
- directory to it.
-
-== File and directory operations
-
---- Shell#foreach(path = nil, &block)
-
- Same as:
- File#foreach (when path is a file)
- Dir#foreach (when path is a directory)
-
---- Shell#open(path, mode)
-
- Same as:
- File#open (when path is a file)
- Dir#open (when path is a directory)
-
---- Shell#unlink(path)
-
- Same as:
- Dir#open (when path is a file)
- Dir#unlink (when path is a directory)
-
---- Shell#test(command, file1, file2)
---- Shell#[command, file1, file2]
-
- Same as test().
- ex)
- sh[?e, "foo"]
- sh[:e, "foo"]
- sh["e", "foo"]
- sh[:exists?, "foo"]
- sh["exists?", "foo"]
-
---- Shell#mkdir(*path)
-
- Same as Dir.mkdir (with multiple directories allowed)
-
---- Shell#rmdir(*path)
-
- Same as Dir.rmdir (with multiple directories allowed)
-
-== Command execution
-
---- System#system(command, *opts)
-
- Executes <command> with <opts>.
-
- ex)
- print sh.system("ls", "-l")
- sh.system("ls", "-l") | sh.head > STDOUT
-
---- System#rehash
-
- Does rehash.
-
---- Shell#transact &block
-
- Executes a block as self.
- ex)
- sh.transact{system("ls", "-l") | head > STDOUT}
-
---- Shell#out(dev = STDOUT, &block)
-
- Does transact, with redirecting the result output to <dev>.
-
-== Internal commands
-
---- Shell#echo(*strings)
---- Shell#cat(*files)
---- Shell#glob(patten)
---- Shell#tee(file)
-
- Return Filter objects, which are results of their execution.
-
---- Filter#each &block
-
- Iterates a block for each line of it.
-
---- Filter#<(src)
-
- Inputs from <src>, which is either a string of a file name or an
- IO.
-
---- Filter#>(to)
-
- Outputs to <to>, which is either a string of a file name or an
- IO.
-
---- Filter#>>(to)
-
- Appends the ouput to <to>, which is either a string of a file
- name or an IO.
-
---- Filter#|(filter)
-
- Processes a pipeline.
-
---- Filter#+(filter)
-
- (filter1 + filter2) outputs filter1, and then outputs filter2.
-
---- Filter#to_a
---- Filter#to_s
-
-== Built-in commands
-
---- Shell#atime(file)
---- Shell#basename(file, *opt)
---- Shell#chmod(mode, *files)
---- Shell#chown(owner, group, *file)
---- Shell#ctime(file)
---- Shell#delete(*file)
---- Shell#dirname(file)
---- Shell#ftype(file)
---- Shell#join(*file)
---- Shell#link(file_from, file_to)
---- Shell#lstat(file)
---- Shell#mtime(file)
---- Shell#readlink(file)
---- Shell#rename(file_from, file_to)
---- Shell#split(file)
---- Shell#stat(file)
---- Shell#symlink(file_from, file_to)
---- Shell#truncate(file, length)
---- Shell#utime(atime, mtime, *file)
-
- Equivalent to the class methods of File with the same names.
-
---- Shell#blockdev?(file)
---- Shell#chardev?(file)
---- Shell#directory?(file)
---- Shell#executable?(file)
---- Shell#executable_real?(file)
---- Shell#exist?(file)/Shell#exists?(file)
---- Shell#file?(file)
---- Shell#grpowned?(file)
---- Shell#owned?(file)
---- Shell#pipe?(file)
---- Shell#readable?(file)
---- Shell#readable_real?(file)
---- Shell#setgid?(file)
---- Shell#setuid?(file)
---- Shell#size(file)/Shell#size?(file)
---- Shell#socket?(file)
---- Shell#sticky?(file)
---- Shell#symlink?(file)
---- Shell#writable?(file)
---- Shell#writable_real?(file)
---- Shell#zero?(file)
-
- Equivalent to the class methods of FileTest with the same names.
-
---- Shell#syscopy(filename_from, filename_to)
---- Shell#copy(filename_from, filename_to)
---- Shell#move(filename_from, filename_to)
---- Shell#compare(filename_from, filename_to)
---- Shell#safe_unlink(*filenames)
---- Shell#makedirs(*filenames)
---- Shell#install(filename_from, filename_to, mode)
-
- Equivalent to the class methods of FileTools with the same
- names.
-
- And also, there are some aliases for convenience:
-
---- Shell#cmp <- Shell#compare
---- Shell#mv <- Shell#move
---- Shell#cp <- Shell#copy
---- Shell#rm_f <- Shell#safe_unlink
---- Shell#mkpath <- Shell#makedirs
-
-= Samples
-
-== ex1
-
- sh = Shell.cd("/tmp")
- sh.mkdir "shell-test-1" unless sh.exists?("shell-test-1")
- sh.cd("shell-test-1")
- for dir in ["dir1", "dir3", "dir5"]
- if !sh.exists?(dir)
- sh.mkdir dir
- sh.cd(dir) do
- f = sh.open("tmpFile", "w")
- f.print "TEST\n"
- f.close
- end
- print sh.pwd
- end
- end
-
-== ex2
-
- sh = Shell.cd("/tmp")
- sh.transact do
- mkdir "shell-test-1" unless exists?("shell-test-1")
- cd("shell-test-1")
- for dir in ["dir1", "dir3", "dir5"]
- if !exists?(dir)
- mkdir dir
- cd(dir) do
- f = open("tmpFile", "w")
- f.print "TEST\n"
- f.close
- end
- print pwd
- end
- end
- end
-
-== ex3
-
- sh.cat("/etc/printcap") | sh.tee("tee1") > "tee2"
- (sh.cat < "/etc/printcap") | sh.tee("tee11") > "tee12"
- sh.cat("/etc/printcap") | sh.tee("tee1") >> "tee2"
- (sh.cat < "/etc/printcap") | sh.tee("tee11") >> "tee12"
-
-== ex4
-
- print sh.cat("/etc/passwd").head.collect{|l| l =~ /keiju/}
-
-=end
diff --git a/doc/shell.rd.ja b/doc/shell.rd.ja
deleted file mode 100644
index 073e71ea42..0000000000
--- a/doc/shell.rd.ja
+++ /dev/null
@@ -1,336 +0,0 @@
- -- shell.rb
- $Release Version: 0.6.0 $
- $Revision$
- $Date$
- by Keiju ISHITSUKA(keiju@ishitsuka.com)
-
-=begin
-
-= 目的
-
-ruby上でsh/cshのようにコマンドの実行及びフィルタリングを手軽に行う.
-sh/cshの制御文はrubyの機能を用いて実現する.
-
-= 主なクラス一覧
-
-== Shell
-
-Shellオブジェクトはカレントディレクトリを持ち, コマンド実行はそこからの
-相対パスになります.
-
---- Shell#cwd
---- Shell#dir
---- Shell#getwd
---- Shell#pwd
-
- カレントディレクトリを返す。
-
---- Shell#system_path
-
- コマンドサーチパスの配列を返す。
-
---- Shell#umask
-
- umaskを返す。
-
-== Filter
-
-コマンドの実行結果はすべてFilterとしてかえります. Enumerableをincludeし
-ています.
-
-= 主なメソッド一覧
-
-== コマンド定義
-
-OS上のコマンドを実行するにはまず, Shellのメソッドとして定義します.
-
-注) コマンドを定義しなくとも直接実行できるShell#systemコマンドもあります.
-
---- Shell.def_system_command(command, path = command)
-
- Shellのメソッドとしてcommandを登録します.
-
- 例)
- Shell.def_system_command "ls"
- ls を定義
-
- Shell.def_system_command "sys_sort", "sort"
- sortコマンドをsys_sortとして定義
-
---- Shell.undef_system_command(command)
-
- commandを削除します.
-
---- Shell.alias_command(ali, command, *opts) {...}
-
- commandのaliasをします.
-
- 例)
- Shell.alias_command "lsC", "ls", "-CBF", "--show-control-chars"
- Shell.alias_command("lsC", "ls"){|*opts| ["-CBF", "--show-control-chars", *opts]}
-
---- Shell.unalias_command(ali)
-
- commandのaliasを削除します.
-
---- Shell.install_system_commands(pre = "sys_")
-
- system_path上にある全ての実行可能ファイルをShellに定義する. メソッ
- ド名は元のファイル名の頭にpreをつけたものとなる.
-
-== 生成
-
---- Shell.new
-
- プロセスのカレントディレクトリをカレントディレクトリとするShellオ
- ブジェクトを生成します.
-
---- Shell.cd(path)
-
- pathをカレントディレクトリとするShellオブジェクトを生成します.
-
-== プロセス管理
-
---- Shell#jobs
-
- スケジューリングされているjobの一覧を返す.
-
---- Shell#kill sig, job
-
- jobにシグナルsigを送る
-
-== カレントディレクトリ操作
-
---- Shell#cd(path, &block)
---- Shell#chdir
-
- カレントディレクトリをpathにする. イテレータとして呼ばれたときには
- ブロック実行中のみカレントディレクトリを変更する.
-
---- Shell#pushd(path = nil, &block)
---- Shell#pushdir
-
- カレントディレクトリをディレクトリスタックにつみ, カレントディレク
- トリをpathにする. pathが省略されたときには, カレントディレクトリと
- ディレクトリスタックのトップを交換する. イテレータとして呼ばれたと
- きには, ブロック実行中のみpushdする.
-
---- Shell#popd
---- Shell#popdir
-
- ディレクトリスタックからポップし, それをカレントディレクトリにする.
-
-== ファイル/ディレクトリ操作
-
---- Shell#foreach(path = nil, &block)
-
- pathがファイルなら, File#foreach
- pathがディレクトリなら, Dir#foreach
-
---- Shell#open(path, mode)
-
- pathがファイルなら, File#open
- pathがディレクトリなら, Dir#open
-
---- Shell#unlink(path)
-
- pathがファイルなら, File#unlink
- pathがディレクトリなら, Dir#unlink
-
---- Shell#test(command, file1, file2)
---- Shell#[command, file1, file2]
-
- ファイルテスト関数testと同じ.
- 例)
- sh[?e, "foo"]
- sh[:e, "foo"]
- sh["e", "foo"]
- sh[:exists?, "foo"]
- sh["exists?", "foo"]
-
---- Shell#mkdir(*path)
-
- Dir.mkdirと同じ(複数可)
-
---- Shell#rmdir(*path)
-
- Dir.rmdirと同じ(複数可)
-
-== コマンド実行
-
---- System#system(command, *opts)
-
- commandを実行する.
- 例)
- print sh.system("ls", "-l")
- sh.system("ls", "-l") | sh.head > STDOUT
-
---- System#rehash
-
- リハッシュする
-
---- Shell#transact &block
-
- ブロック中ではshellをselfとして実行する.
- 例)
- sh.transact{system("ls", "-l") | head > STDOUT}
-
---- Shell#out(dev = STDOUT, &block)
-
- transactを呼び出しその結果をdevに出力する.
-
-== 内部コマンド
-
---- Shell#echo(*strings)
---- Shell#cat(*files)
---- Shell#glob(patten)
---- Shell#tee(file)
-
- これらは実行すると, それらを内容とするFilterオブジェクトを返します.
-
---- Filter#each &block
-
- フィルタの一行ずつをblockに渡す.
-
---- Filter#<(src)
-
- srcをフィルタの入力とする. srcが, 文字列ならばファイルを, IOであれ
- ばそれをそのまま入力とする.
-
---- Filter#>(to)
-
- srcをフィルタの出力とする. toが, 文字列ならばファイルに, IOであれ
- ばそれをそのまま出力とする.
-
---- Filter#>>(to)
-
- srcをフィルタに追加する. toが, 文字列ならばファイルに, IOであれば
- それをそのまま出力とする.
-
---- Filter#|(filter)
-
- パイプ結合
-
---- Filter#+(filter)
-
- filter1 + filter2 は filter1の出力の後, filter2の出力を行う.
-
---- Filter#to_a
---- Filter#to_s
-
-== 組込みコマンド
-
---- Shell#atime(file)
---- Shell#basename(file, *opt)
---- Shell#chmod(mode, *files)
---- Shell#chown(owner, group, *file)
---- Shell#ctime(file)
---- Shell#delete(*file)
---- Shell#dirname(file)
---- Shell#ftype(file)
---- Shell#join(*file)
---- Shell#link(file_from, file_to)
---- Shell#lstat(file)
---- Shell#mtime(file)
---- Shell#readlink(file)
---- Shell#rename(file_from, file_to)
---- Shell#split(file)
---- Shell#stat(file)
---- Shell#symlink(file_from, file_to)
---- Shell#truncate(file, length)
---- Shell#utime(atime, mtime, *file)
-
- これらはFileクラスにある同名のクラスメソッドと同じです.
-
---- Shell#blockdev?(file)
---- Shell#chardev?(file)
---- Shell#directory?(file)
---- Shell#executable?(file)
---- Shell#executable_real?(file)
---- Shell#exist?(file)/Shell#exists?(file)
---- Shell#file?(file)
---- Shell#grpowned?(file)
---- Shell#owned?(file)
---- Shell#pipe?(file)
---- Shell#readable?(file)
---- Shell#readable_real?(file)
---- Shell#setgid?(file)
---- Shell#setuid?(file)
---- Shell#size(file)/Shell#size?(file)
---- Shell#socket?(file)
---- Shell#sticky?(file)
---- Shell#symlink?(file)
---- Shell#writable?(file)
---- Shell#writable_real?(file)
---- Shell#zero?(file)
-
- これらはFileTestクラスにある同名のクラスメソッドと同じです.
-
---- Shell#syscopy(filename_from, filename_to)
---- Shell#copy(filename_from, filename_to)
---- Shell#move(filename_from, filename_to)
---- Shell#compare(filename_from, filename_to)
---- Shell#safe_unlink(*filenames)
---- Shell#makedirs(*filenames)
---- Shell#install(filename_from, filename_to, mode)
-
- これらはFileToolsクラスにある同名のクラスメソッドと同じです.
-
- その他, 以下のものがエイリアスされています.
-
---- Shell#cmp <- Shell#compare
---- Shell#mv <- Shell#move
---- Shell#cp <- Shell#copy
---- Shell#rm_f <- Shell#safe_unlink
---- Shell#mkpath <- Shell#makedirs
-
-= サンプル
-
-== ex1
-
- sh = Shell.cd("/tmp")
- sh.mkdir "shell-test-1" unless sh.exists?("shell-test-1")
- sh.cd("shell-test-1")
- for dir in ["dir1", "dir3", "dir5"]
- if !sh.exists?(dir)
- sh.mkdir dir
- sh.cd(dir) do
- f = sh.open("tmpFile", "w")
- f.print "TEST\n"
- f.close
- end
- print sh.pwd
- end
- end
-
-== ex2
-
- sh = Shell.cd("/tmp")
- sh.transact do
- mkdir "shell-test-1" unless exists?("shell-test-1")
- cd("shell-test-1")
- for dir in ["dir1", "dir3", "dir5"]
- if !exists?(dir)
- mkdir dir
- cd(dir) do
- f = open("tmpFile", "w")
- f.print "TEST\n"
- f.close
- end
- print pwd
- end
- end
- end
-
-== ex3
-
- sh.cat("/etc/printcap") | sh.tee("tee1") > "tee2"
- (sh.cat < "/etc/printcap") | sh.tee("tee11") > "tee12"
- sh.cat("/etc/printcap") | sh.tee("tee1") >> "tee2"
- (sh.cat < "/etc/printcap") | sh.tee("tee11") >> "tee12"
-
-== ex4
-
- print sh.cat("/etc/passwd").head.collect{|l| l =~ /keiju/}
-
-=end
diff --git a/enum.c b/enum.c
deleted file mode 100644
index 301dd95166..0000000000
--- a/enum.c
+++ /dev/null
@@ -1,489 +0,0 @@
-/**********************************************************************
-
- enum.c -
-
- $Author$
- $Date$
- created at: Fri Oct 1 15:15:19 JST 1993
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
-
-**********************************************************************/
-
-#include "ruby.h"
-#include "node.h"
-#include "util.h"
-
-VALUE rb_mEnumerable;
-static ID id_each, id_eqq, id_cmp;
-
-VALUE
-rb_each(obj)
- VALUE obj;
-{
- return rb_funcall(obj, id_each, 0, 0);
-}
-
-static VALUE
-grep_i(i, arg)
- VALUE i, *arg;
-{
- if (RTEST(rb_funcall(arg[0], id_eqq, 1, i))) {
- rb_ary_push(arg[1], i);
- }
- return Qnil;
-}
-
-static VALUE
-grep_iter_i(i, arg)
- VALUE i, *arg;
-{
- if (RTEST(rb_funcall(arg[0], id_eqq, 1, i))) {
- rb_ary_push(arg[1], rb_yield(i));
- }
- return Qnil;
-}
-
-static VALUE
-enum_grep(obj, pat)
- VALUE obj, pat;
-{
- VALUE tmp, arg[2];
-
- arg[0] = pat; arg[1] = tmp = rb_ary_new();
- if (rb_block_given_p()) {
- rb_iterate(rb_each, obj, grep_iter_i, (VALUE)arg);
- }
- else {
- rb_iterate(rb_each, obj, grep_i, (VALUE)arg);
- }
- return tmp;
-}
-
-static VALUE
-find_i(i, memo)
- VALUE i;
- NODE *memo;
-{
- if (RTEST(rb_yield(i))) {
- memo->u2.value = Qtrue;
- memo->u1.value = i;
- rb_iter_break();
- }
- return Qnil;
-}
-
-static VALUE
-enum_find(argc, argv, obj)
- int argc;
- VALUE* argv;
- VALUE obj;
-{
- NODE *memo = rb_node_newnode(NODE_MEMO, Qnil, Qfalse, 0);
- VALUE if_none;
-
- rb_scan_args(argc, argv, "01", &if_none);
- rb_iterate(rb_each, obj, find_i, (VALUE)memo);
- if (memo->u2.value) {
- VALUE result = memo->u1.value;
- rb_gc_force_recycle((VALUE)memo);
- return result;
- }
- rb_gc_force_recycle((VALUE)memo);
- if (!NIL_P(if_none)) {
- rb_eval_cmd(if_none, rb_ary_new2(0), 0);
- }
- return Qnil;
-}
-
-static VALUE
-find_all_i(i, tmp)
- VALUE i, tmp;
-{
- if (RTEST(rb_yield(i))) {
- rb_ary_push(tmp, i);
- }
- return Qnil;
-}
-
-static VALUE
-enum_find_all(obj)
- VALUE obj;
-{
- VALUE tmp;
-
- tmp = rb_ary_new();
- rb_iterate(rb_each, obj, find_all_i, tmp);
-
- return tmp;
-}
-
-static VALUE
-reject_i(i, tmp)
- VALUE i, tmp;
-{
- if (!RTEST(rb_yield(i))) {
- rb_ary_push(tmp, i);
- }
- return Qnil;
-}
-
-static VALUE
-enum_reject(obj)
- VALUE obj;
-{
- VALUE tmp;
-
- tmp = rb_ary_new();
- rb_iterate(rb_each, obj, reject_i, tmp);
-
- return tmp;
-}
-
-static VALUE
-collect_i(i, tmp)
- VALUE i, tmp;
-{
- rb_ary_push(tmp, rb_yield(i));
- return Qnil;
-}
-
-static VALUE
-collect_all(i, ary)
- VALUE i, ary;
-{
- rb_ary_push(ary, i);
- return Qnil;
-}
-
-static VALUE
-enum_to_a(obj)
- VALUE obj;
-{
- VALUE ary;
-
- ary = rb_ary_new();
- rb_iterate(rb_each, obj, collect_all, ary);
-
- return ary;
-}
-
-static VALUE
-enum_collect(obj)
- VALUE obj;
-{
- VALUE tmp;
-
- tmp = rb_ary_new();
- rb_iterate(rb_each, obj, rb_block_given_p() ? collect_i : collect_all, tmp);
-
- return tmp;
-}
-
-static VALUE
-inject_i(i, memo)
- VALUE i;
- NODE *memo;
-{
- if (memo->u2.value) {
- memo->u2.value = Qfalse;
- memo->u1.value = i;
- }
- else {
- memo->u1.value = rb_yield(rb_assoc_new(memo->u1.value, i));
- }
-
- return Qnil;
-}
-
-static VALUE
-enum_inject(argc, argv, obj)
- int argc;
- VALUE *argv, obj;
-{
- NODE *memo;
- VALUE n;
-
- if (rb_scan_args(argc, argv, "01", &n) == 1)
- memo = rb_node_newnode(NODE_MEMO, n, Qfalse, 0);
- else
- memo = rb_node_newnode(NODE_MEMO, Qnil, Qtrue, 0);
-
- rb_iterate(rb_each, obj, inject_i, (VALUE)memo);
- n = memo->u1.value;
-
- rb_gc_force_recycle((VALUE)memo);
- return n;
-}
-
-static VALUE
-enum_sort(obj)
- VALUE obj;
-{
- return rb_ary_sort(enum_to_a(obj));
-}
-
-static VALUE
-sort_by_i(i, ary)
- VALUE i, ary;
-{
- VALUE v, e;
-
- v = rb_yield(i);
- e = rb_assoc_new(v, i);
- rb_ary_push(ary, e);
- return Qnil;
-}
-
-static int
-sort_by_cmp(a, b)
- VALUE *a, *b;
-{
- VALUE retval;
-
- retval = rb_funcall(RARRAY(*a)->ptr[0], id_cmp, 1, RARRAY(*b)->ptr[0]);
- return rb_cmpint(retval);
-}
-
-static VALUE
-enum_sort_by(obj)
- VALUE obj;
-{
- VALUE ary;
- long i;
-
- ary = rb_ary_new2((TYPE(obj) == T_ARRAY) ? RARRAY(obj)->len : 2000);
- rb_iterate(rb_each, obj, sort_by_i, ary);
- if (RARRAY(ary)->len <= 1) return ary;
- qsort(RARRAY(ary)->ptr, RARRAY(ary)->len, sizeof(VALUE), sort_by_cmp);
- for (i=0; i<RARRAY(ary)->len; i++) {
- VALUE e = RARRAY(ary)->ptr[i];
- RARRAY(ary)->ptr[i] = RARRAY(e)->ptr[1];
- }
-
- return ary;
-}
-
-static VALUE
-all_i(i, memo)
- VALUE i;
- NODE *memo;
-{
- if (!RTEST(rb_yield(i))) {
- memo->u1.value = Qfalse;
- rb_iter_break();
- }
- return Qnil;
-}
-
-static VALUE
-enum_all(obj)
- VALUE obj;
-{
- VALUE result;
- NODE *memo = rb_node_newnode(NODE_MEMO, Qnil, 0, 0);
-
- memo->u1.value = Qtrue;
- rb_iterate(rb_each, obj, all_i, (VALUE)memo);
- result = memo->u1.value;
- rb_gc_force_recycle((VALUE)memo);
- return result;
-}
-
-static VALUE
-any_i(i, memo)
- VALUE i;
- NODE *memo;
-{
- if (RTEST(rb_yield(i))) {
- memo->u1.value = Qtrue;
- rb_iter_break();
- }
- return Qnil;
-}
-
-static VALUE
-enum_any(obj)
- VALUE obj;
-{
- VALUE result;
- NODE *memo = rb_node_newnode(NODE_MEMO, Qnil, 0, 0);
-
- memo->u1.value = Qfalse;
- rb_iterate(rb_each, obj, any_i, (VALUE)memo);
- result = memo->u1.value;
- rb_gc_force_recycle((VALUE)memo);
- return result;
-}
-
-static VALUE
-min_i(i, memo)
- VALUE i;
- NODE *memo;
-{
- VALUE cmp;
-
- if (NIL_P(memo->u1.value))
- memo->u1.value = i;
- else {
- cmp = rb_funcall(i, id_cmp, 1, memo->u1.value);
- if (rb_cmpint(cmp) < 0)
- memo->u1.value = i;
- }
- return Qnil;
-}
-
-static VALUE
-min_ii(i, memo)
- VALUE i;
- NODE *memo;
-{
- VALUE cmp;
-
- if (NIL_P(memo->u1.value))
- memo->u1.value = i;
- else {
- cmp = rb_yield(rb_assoc_new(i, memo->u1.value));
- if (rb_cmpint(cmp) < 0)
- memo->u1.value = i;
- }
- return Qnil;
-}
-
-static VALUE
-enum_min(obj)
- VALUE obj;
-{
- VALUE result;
- NODE *memo = rb_node_newnode(NODE_MEMO, Qnil, 0, 0);
-
- rb_iterate(rb_each, obj, rb_block_given_p()?min_ii:min_i, (VALUE)memo);
- result = memo->u1.value;
- rb_gc_force_recycle((VALUE)memo);
- return result;
-}
-
-static VALUE
-max_i(i, memo)
- VALUE i;
- NODE *memo;
-{
- VALUE cmp;
-
- if (NIL_P(memo->u1.value))
- memo->u1.value = i;
- else {
- cmp = rb_funcall(i, id_cmp, 1, memo->u1.value);
- if (rb_cmpint(cmp) > 0)
- memo->u1.value = i;
- }
- return Qnil;
-}
-
-static VALUE
-max_ii(i, memo)
- VALUE i;
- NODE *memo;
-{
- VALUE cmp;
-
- if (NIL_P(memo->u1.value))
- memo->u1.value = i;
- else {
- cmp = rb_yield(rb_assoc_new(i, memo->u1.value));
- if (rb_cmpint(cmp) > 0)
- memo->u1.value = i;
- }
- return Qnil;
-}
-
-static VALUE
-enum_max(obj)
- VALUE obj;
-{
- VALUE result;
- NODE *memo = rb_node_newnode(NODE_MEMO, Qnil, 0, 0);
-
- rb_iterate(rb_each, obj, rb_block_given_p()?max_ii:max_i, (VALUE)memo);
- result = memo->u1.value;
- rb_gc_force_recycle((VALUE)memo);
- return result;
-}
-
-static VALUE
-member_i(item, memo)
- VALUE item;
- NODE *memo;
-{
- if (rb_equal(item, memo->u1.value)) {
- memo->u2.value = Qtrue;
- rb_iter_break();
- }
- return Qnil;
-}
-
-static VALUE
-enum_member(obj, val)
- VALUE obj, val;
-{
- VALUE result;
- NODE *memo = rb_node_newnode(NODE_MEMO, val, Qfalse, 0);
-
- rb_iterate(rb_each, obj, member_i, (VALUE)memo);
- result = memo->u2.value;
- rb_gc_force_recycle((VALUE)memo);
- return result;
-}
-
-static VALUE
-each_with_index_i(val, memo)
- VALUE val;
- NODE *memo;
-{
- rb_yield(rb_assoc_new(val, INT2FIX(memo->u3.cnt)));
- memo->u3.cnt++;
- return Qnil;
-}
-
-static VALUE
-enum_each_with_index(obj)
- VALUE obj;
-{
- NODE *memo = rb_node_newnode(NODE_MEMO, 0, 0, 0);
-
- rb_iterate(rb_each, obj, each_with_index_i, (VALUE)memo);
- rb_gc_force_recycle((VALUE)memo);
- return obj;
-}
-
-void
-Init_Enumerable()
-{
- rb_mEnumerable = rb_define_module("Enumerable");
-
- rb_define_method(rb_mEnumerable,"to_a", enum_to_a, 0);
- rb_define_method(rb_mEnumerable,"entries", enum_to_a, 0);
-
- rb_define_method(rb_mEnumerable,"sort", enum_sort, 0);
- rb_define_method(rb_mEnumerable,"sort_by", enum_sort_by, 0);
- rb_define_method(rb_mEnumerable,"grep", enum_grep, 1);
- rb_define_method(rb_mEnumerable,"find", enum_find, -1);
- rb_define_method(rb_mEnumerable,"detect", enum_find, -1);
- rb_define_method(rb_mEnumerable,"find_all", enum_find_all, 0);
- rb_define_method(rb_mEnumerable,"select", enum_find_all, 0);
- rb_define_method(rb_mEnumerable,"reject", enum_reject, 0);
- rb_define_method(rb_mEnumerable,"collect", enum_collect, 0);
- rb_define_method(rb_mEnumerable,"map", enum_collect, 0);
- rb_define_method(rb_mEnumerable,"inject", enum_inject, -1);
- rb_define_method(rb_mEnumerable,"all?", enum_all, 0);
- rb_define_method(rb_mEnumerable,"any?", enum_any, 0);
- rb_define_method(rb_mEnumerable,"min", enum_min, 0);
- rb_define_method(rb_mEnumerable,"max", enum_max, 0);
- rb_define_method(rb_mEnumerable,"member?", enum_member, 1);
- rb_define_method(rb_mEnumerable,"include?", enum_member, 1);
- rb_define_method(rb_mEnumerable,"each_with_index", enum_each_with_index, 0);
-
- id_eqq = rb_intern("===");
- id_each = rb_intern("each");
- id_cmp = rb_intern("<=>");
-}
diff --git a/env.h b/env.h
deleted file mode 100644
index 8e96f1a7f7..0000000000
--- a/env.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/**********************************************************************
-
- env.h -
-
- $Author$
- $Date$
- created at: Mon Jul 11 11:53:03 JST 1994
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
-
-**********************************************************************/
-
-#ifndef ENV_H
-#define ENV_H
-
-extern struct FRAME {
- VALUE self;
- int argc;
- VALUE *argv;
- ID last_func;
- VALUE last_class;
- VALUE cbase;
- struct FRAME *prev;
- struct FRAME *tmp;
- char *file;
- int line;
- int iter;
- int flags;
-} *ruby_frame;
-
-void rb_gc_mark_frame _((struct FRAME *));
-
-#define FRAME_ALLOCA 0
-#define FRAME_MALLOC 1
-
-extern struct SCOPE {
- struct RBasic super;
- ID *local_tbl;
- VALUE *local_vars;
- int flags;
-} *ruby_scope;
-
-#define SCOPE_ALLOCA 0
-#define SCOPE_MALLOC 1
-#define SCOPE_NOSTACK 2
-#define SCOPE_DONT_RECYCLE 4
-
-extern int ruby_in_eval;
-
-extern VALUE ruby_class;
-
-struct RVarmap {
- struct RBasic super;
- ID id;
- VALUE val;
- struct RVarmap *next;
-};
-extern struct RVarmap *ruby_dyna_vars;
-
-#endif /* ENV_H */
diff --git a/error.c b/error.c
deleted file mode 100644
index e52f2e91c7..0000000000
--- a/error.c
+++ /dev/null
@@ -1,1226 +0,0 @@
-/**********************************************************************
-
- error.c -
-
- $Author$
- $Date$
- created at: Mon Aug 9 16:11:34 JST 1993
-
- Copyright (C) 1993-2002 Yukihiro Matsumoto
-
-**********************************************************************/
-
-#include "ruby.h"
-#include "env.h"
-#include "version.h"
-
-#include <stdio.h>
-#ifdef HAVE_STDARG_PROTOTYPES
-#include <stdarg.h>
-#define va_init_list(a,b) va_start(a,b)
-#else
-#include <varargs.h>
-#define va_init_list(a,b) va_start(a)
-#endif
-
-#if defined __CYGWIN__
-# include <cygwin/version.h>
-# if (CYGWIN_VERSION_API_MAJOR > 0) || (CYGWIN_VERSION_API_MINOR >= 8)
-# define sys_nerr _sys_nerr
-# endif
-#endif
-
-int ruby_nerrs;
-
-static void
-err_snprintf(buf, len, fmt, args)
- char *buf, *fmt;
- int len;
- va_list args;
-{
- int n;
-
- if (!ruby_sourcefile) {
- vsnprintf(buf, len, fmt, args);
- return;
- }
- else if (ruby_sourceline == 0) {
- n = snprintf(buf, len, "%s: ", ruby_sourcefile);
- }
- else {
- n = snprintf(buf, len, "%s:%d: ", ruby_sourcefile, ruby_sourceline);
- }
- if (len > n) {
- vsnprintf((char*)buf+n, len-n, fmt, args);
- }
-}
-
-static void err_append _((const char*));
-static void
-err_print(fmt, args)
- const char *fmt;
- va_list args;
-{
- char buf[BUFSIZ];
-
- err_snprintf(buf, BUFSIZ, fmt, args);
- err_append(buf);
-}
-
-void
-#ifdef HAVE_STDARG_PROTOTYPES
-rb_compile_error(const char *fmt, ...)
-#else
-rb_compile_error(fmt, va_alist)
- const char *fmt;
- va_dcl
-#endif
-{
- va_list args;
-
- va_init_list(args, fmt);
- err_print(fmt, args);
- va_end(args);
- ruby_nerrs++;
-}
-
-void
-#ifdef HAVE_STDARG_PROTOTYPES
-rb_compile_error_append(const char *fmt, ...)
-#else
-rb_compile_error_append(fmt, va_alist)
- const char *fmt;
- va_dcl
-#endif
-{
- va_list args;
- char buf[BUFSIZ];
-
- va_init_list(args, fmt);
- vsnprintf(buf, BUFSIZ, fmt, args);
- va_end(args);
- err_append(buf);
-}
-
-static void
-warn_print(fmt, args)
- const char *fmt;
- va_list args;
-{
- char buf[BUFSIZ];
-
- err_snprintf(buf, BUFSIZ, fmt, args);
- fputs(buf, stderr);
- fputs("\n", stderr);
- fflush(stderr);
-}
-
-void
-#ifdef HAVE_STDARG_PROTOTYPES
-rb_warn(const char *fmt, ...)
-#else
-rb_warn(fmt, va_alist)
- const char *fmt;
- va_dcl
-#endif
-{
- char buf[BUFSIZ];
- va_list args;
-
- snprintf(buf, BUFSIZ, "warning: %s", fmt);
-
- va_init_list(args, fmt);
- warn_print(buf, args);
- va_end(args);
-}
-
-/* rb_warning() reports only in verbose mode */
-void
-#ifdef HAVE_STDARG_PROTOTYPES
-rb_warning(const char *fmt, ...)
-#else
-rb_warning(fmt, va_alist)
- const char *fmt;
- va_dcl
-#endif
-{
- char buf[BUFSIZ];
- va_list args;
-
- if (!RTEST(ruby_verbose)) return;
-
- snprintf(buf, BUFSIZ, "warning: %s", fmt);
-
- va_init_list(args, fmt);
- warn_print(buf, args);
- va_end(args);
-}
-
-void
-#ifdef HAVE_STDARG_PROTOTYPES
-rb_bug(const char *fmt, ...)
-#else
-rb_bug(fmt, va_alist)
- const char *fmt;
- va_dcl
-#endif
-{
- char buf[BUFSIZ];
- va_list args;
-
- snprintf(buf, BUFSIZ, "[BUG] %s", fmt);
- ruby_in_eval = 0;
-
- va_init_list(args, fmt);
- warn_print(buf, args);
- va_end(args);
- fprintf(stderr, "ruby %s (%s) [%s]\n", RUBY_VERSION, RUBY_RELEASE_DATE, RUBY_PLATFORM);
- abort();
-}
-
-static struct types {
- int type;
- const char *name;
-} builtin_types[] = {
- T_NIL, "nil",
- T_OBJECT, "Object",
- T_CLASS, "Class",
- T_ICLASS, "iClass", /* internal use: mixed-in module holder */
- T_MODULE, "Module",
- T_FLOAT, "Float",
- T_STRING, "String",
- T_REGEXP, "Regexp",
- T_ARRAY, "Array",
- T_FIXNUM, "Fixnum",
- T_HASH, "Hash",
- T_STRUCT, "Struct",
- T_BIGNUM, "Bignum",
- T_FILE, "File",
- T_TRUE, "true",
- T_FALSE, "false",
- T_SYMBOL, "Symbol", /* :symbol */
- T_DATA, "Data", /* internal use: wrapped C pointers */
- T_MATCH, "Match", /* data of $~ */
- T_VARMAP, "Varmap", /* internal use: dynamic variables */
- T_SCOPE, "Scope", /* internal use: variable scope */
- T_NODE, "Node", /* internal use: syntax tree node */
- T_UNDEF, "undef", /* internal use: #undef; should not happen */
- -1, 0,
-};
-
-void
-rb_check_type(x, t)
- VALUE x;
- int t;
-{
- struct types *type = builtin_types;
-
- if (x == Qundef) {
- rb_bug("undef leaked to the Ruby space");
- }
-
- if (TYPE(x) != t) {
- while (type->type >= 0) {
- if (type->type == t) {
- char *etype;
-
- if (NIL_P(x)) {
- etype = "nil";
- }
- else if (FIXNUM_P(x)) {
- etype = "Fixnum";
- }
- else if (rb_special_const_p(x)) {
- etype = RSTRING(rb_obj_as_string(x))->ptr;
- }
- else {
- etype = rb_class2name(CLASS_OF(x));
- }
- rb_raise(rb_eTypeError, "wrong argument type %s (expected %s)",
- etype, type->name);
- }
- type++;
- }
- rb_bug("unknown type 0x%x", t);
- }
-}
-
-/* exception classes */
-#include <errno.h>
-
-VALUE rb_eException;
-VALUE rb_eSystemExit;
-VALUE rb_eInterrupt;
-VALUE rb_eSignal;
-VALUE rb_eFatal;
-VALUE rb_eStandardError;
-VALUE rb_eRuntimeError;
-VALUE rb_eTypeError;
-VALUE rb_eArgError;
-VALUE rb_eIndexError;
-VALUE rb_eRangeError;
-VALUE rb_eNameError;
-VALUE rb_eNoMethodError;
-VALUE rb_eSecurityError;
-VALUE rb_eNotImpError;
-VALUE rb_eNoMemError;
-
-VALUE rb_eScriptError;
-VALUE rb_eSyntaxError;
-VALUE rb_eLoadError;
-
-VALUE rb_eSystemCallError;
-VALUE rb_mErrno;
-
-VALUE
-rb_exc_new(etype, ptr, len)
- VALUE etype;
- const char *ptr;
- long len;
-{
- return rb_funcall(etype, rb_intern("new"), 1, rb_str_new(ptr, len));
-}
-
-VALUE
-rb_exc_new2(etype, s)
- VALUE etype;
- const char *s;
-{
- return rb_exc_new(etype, s, strlen(s));
-}
-
-VALUE
-rb_exc_new3(etype, str)
- VALUE etype, str;
-{
- StringValue(str);
- return rb_exc_new(etype, RSTRING(str)->ptr, RSTRING(str)->len);
-}
-
-static VALUE
-exc_initialize(argc, argv, exc)
- int argc;
- VALUE *argv;
- VALUE exc;
-{
- VALUE mesg;
-
- if (rb_scan_args(argc, argv, "01", &mesg) == 1) {
- StringValue(mesg); /* ensure mesg can be converted to String */
- }
- rb_iv_set(exc, "mesg", mesg);
-
- return exc;
-}
-
-static VALUE
-exc_exception(argc, argv, self)
- int argc;
- VALUE *argv;
- VALUE self;
-{
- VALUE exc;
-
- if (argc == 0) return self;
- if (argc == 1 && self == argv[0]) return self;
- exc = rb_obj_clone(self);
- exc_initialize(argc, argv, exc);
-
- return exc;
-}
-
-static VALUE
-exc_to_s(exc)
- VALUE exc;
-{
- VALUE mesg = rb_iv_get(exc, "mesg");
-
- if (NIL_P(mesg)) return rb_class_path(CLASS_OF(exc));
- if (OBJ_TAINTED(exc)) OBJ_TAINT(mesg);
- return mesg;
-}
-
-static VALUE
-exc_inspect(exc)
- VALUE exc;
-{
- VALUE str, klass;
-
- klass = CLASS_OF(exc);
- exc = rb_obj_as_string(exc);
- if (RSTRING(exc)->len == 0) {
- return rb_str_dup(rb_class_path(klass));
- }
-
- str = rb_str_buf_new2("#<");
- klass = rb_class_path(klass);
- rb_str_buf_append(str, klass);
- rb_str_buf_cat(str, ": ", 2);
- rb_str_buf_append(str, exc);
- rb_str_buf_cat(str, ">", 1);
-
- return str;
-}
-
-static VALUE
-exc_backtrace(exc)
- VALUE exc;
-{
- ID bt = rb_intern("bt");
-
- if (!rb_ivar_defined(exc, bt)) return Qnil;
- return rb_ivar_get(exc, bt);
-}
-
-static VALUE
-check_backtrace(bt)
- VALUE bt;
-{
- int i;
- static char *err = "backtrace must be Array of String";
-
- if (!NIL_P(bt)) {
- int t = TYPE(bt);
-
- if (t == T_STRING) return rb_ary_new3(1, bt);
- if (t != T_ARRAY) {
- rb_raise(rb_eTypeError, err);
- }
- for (i=0;i<RARRAY(bt)->len;i++) {
- if (TYPE(RARRAY(bt)->ptr[i]) != T_STRING) {
- rb_raise(rb_eTypeError, err);
- }
- }
- }
- return bt;
-}
-
-static VALUE
-exc_set_backtrace(exc, bt)
- VALUE exc;
- VALUE bt;
-{
- return rb_iv_set(exc, "bt", check_backtrace(bt));
-}
-
-static VALUE
-exit_status(exc)
- VALUE exc;
-{
- return rb_iv_get(exc, "status");
-}
-
-void
-#ifdef HAVE_STDARG_PROTOTYPES
-rb_name_error(ID id, const char *fmt, ...)
-#else
-rb_name_error(id, fmt, va_alist)
- ID id;
- const char *fmt;
- va_dcl
-#endif
-{
- VALUE exc;
-
- va_list args;
- char buf[BUFSIZ];
-
- va_init_list(args, fmt);
- vsnprintf(buf, BUFSIZ, fmt, args);
- va_end(args);
- exc = rb_exc_new2(rb_eNameError, buf);
- rb_iv_set(exc, "name", ID2SYM(id));
- rb_exc_raise(exc);
-}
-
-static VALUE
-name_err_name(self)
- VALUE self;
-{
- return rb_iv_get(self, "name");
-}
-
-static VALUE
-nometh_err_args(self)
- VALUE self;
-{
- return rb_iv_get(self, "args");
-}
-
-void
-rb_invalid_str(str, type)
- const char *str, *type;
-{
- VALUE s = rb_str_inspect(rb_str_new2(str));
-
- rb_raise(rb_eArgError, "invalid value for %s: %s", type, RSTRING(s)->ptr);
-}
-
-#ifdef __BEOS__
-typedef struct {
- VALUE *list;
- int n;
-} syserr_list_entry;
-
-typedef struct {
- int ix;
- int n;
-} syserr_index_entry;
-
-static VALUE syserr_error;
-static VALUE syserr_list_b_general[16+1];
-static VALUE syserr_list_b_os0[2+1];
-static VALUE syserr_list_b_os1[5+1];
-static VALUE syserr_list_b_os2[2+1];
-static VALUE syserr_list_b_os3[3+1];
-static VALUE syserr_list_b_os4[1+1];
-static VALUE syserr_list_b_app[15+1];
-static VALUE syserr_list_b_interface[0+1];
-static VALUE syserr_list_b_media[8+1];
-static VALUE syserr_list_b_midi[0+1];
-static VALUE syserr_list_b_storage[15+1];
-static VALUE syserr_list_b_posix[38+1];
-static VALUE syserr_list_b_mail[8+1];
-static VALUE syserr_list_b_print[1+1];
-static VALUE syserr_list_b_device[14+1];
-
-# define SYSERR_LIST_B(n) {(n), sizeof(n)/sizeof(VALUE)}
-static const syserr_list_entry syserr_list[] = {
- SYSERR_LIST_B(syserr_list_b_general),
- SYSERR_LIST_B(syserr_list_b_os0),
- SYSERR_LIST_B(syserr_list_b_os1),
- SYSERR_LIST_B(syserr_list_b_os2),
- SYSERR_LIST_B(syserr_list_b_os3),
- SYSERR_LIST_B(syserr_list_b_os4),
- SYSERR_LIST_B(syserr_list_b_app),
- SYSERR_LIST_B(syserr_list_b_interface),
- SYSERR_LIST_B(syserr_list_b_media),
- SYSERR_LIST_B(syserr_list_b_midi),
- SYSERR_LIST_B(syserr_list_b_storage),
- SYSERR_LIST_B(syserr_list_b_posix),
- SYSERR_LIST_B(syserr_list_b_mail),
- SYSERR_LIST_B(syserr_list_b_print),
- SYSERR_LIST_B(syserr_list_b_device),
-};
-# undef SYSERR_LIST_B
-
-static const syserr_index_entry syserr_index[]= {
- {0, 1}, {1, 5}, {6, 1}, {7, 1}, {8, 1}, {9, 1}, {10, 1}, {11, 1},
- {12, 1}, {13, 1}, {14, 1}, {0, 0},
-};
-#else
-static VALUE *syserr_list;
-#endif
-
-#if !defined(NT) && !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && !defined(sys_nerr)
-extern int sys_nerr;
-#endif
-
-static VALUE
-set_syserr(i, name)
- int i;
- const char *name;
-{
-#ifdef __BEOS__
- VALUE *list;
- int ix, offset;
-#endif
- VALUE error = rb_define_class_under(rb_mErrno, name, rb_eSystemCallError);
- rb_define_const(error, "Errno", INT2NUM(i));
-#ifdef __BEOS__
- if (i == B_ERROR) {
- syserr_error = error;
- rb_global_variable(&syserr_error);
- return error;
- }
- i -= B_GENERAL_ERROR_BASE;
- ix = (i >> 12) & 0xf;
- offset = (i >> 8) & 0xf;
- if (offset < syserr_index[ix].n) {
- ix = syserr_index[ix].ix;
- if ((i & 0xff) < syserr_list[ix + offset].n) {
- list = syserr_list[ix + offset].list;
- list[i & 0xff] = error;
- rb_global_variable(&list[i & 0xff]);
- }
- }
-#else
- if (i <= sys_nerr) {
- syserr_list[i] = error;
- }
-#endif
- return error;
-}
-
-static VALUE
-syserr_errno(self)
- VALUE self;
-{
- return rb_iv_get(self, "errno");
-}
-
-static VALUE
-syserr_eqq(self, exc)
- VALUE self, exc;
-{
- VALUE num;
-
- if (!rb_obj_is_kind_of(exc, rb_eSystemCallError)) return Qfalse;
- if (self == rb_eSystemCallError) return Qtrue;
-
- num = rb_iv_get(exc, "errno");
- if (NIL_P(num)) {
- VALUE klass = CLASS_OF(exc);
-
- while (TYPE(klass) == T_ICLASS || FL_TEST(klass, FL_SINGLETON)) {
- klass = (VALUE)RCLASS(klass)->super;
- }
- num = rb_const_get(klass, rb_intern("Errno"));
- }
- if (rb_const_get(self, rb_intern("Errno")) == num)
- return Qtrue;
- return Qfalse;
-}
-
-#ifdef __BEOS__
-static VALUE
-get_syserr(int i)
-{
- VALUE *list;
- int ix, offset;
-
- if (i == B_ERROR) return syserr_error;
- i -= B_GENERAL_ERROR_BASE;
- ix = (i >> 12) & 0xf;
- offset = (i >> 8) & 0xf;
- if (offset < syserr_index[ix].n) {
- ix = syserr_index[ix].ix;
- if ((i & 0xff) < syserr_list[ix + offset].n) {
- list = syserr_list[ix + offset].list;
- return list[i & 0xff];
- }
- }
- return 0;
-}
-#endif /* __BEOS__ */
-
-static void init_syserr _((void));
-
-void
-Init_Exception()
-{
- rb_eException = rb_define_class("Exception", rb_cObject);
- rb_define_singleton_method(rb_eException, "exception", rb_class_new_instance, -1);
- rb_define_method(rb_eException, "exception", exc_exception, -1);
- rb_define_method(rb_eException, "initialize", exc_initialize, -1);
- rb_define_method(rb_eException, "to_s", exc_to_s, 0);
- rb_define_method(rb_eException, "to_str", exc_to_s, 0);
- rb_define_method(rb_eException, "message", exc_to_s, 0);
- rb_define_method(rb_eException, "inspect", exc_inspect, 0);
- rb_define_method(rb_eException, "backtrace", exc_backtrace, 0);
- rb_define_method(rb_eException, "set_backtrace", exc_set_backtrace, 1);
-
- rb_eSystemExit = rb_define_class("SystemExit", rb_eException);
- rb_define_method(rb_eSystemExit, "status", exit_status, 0);
-
- rb_eFatal = rb_define_class("fatal", rb_eException);
- rb_eSignal = rb_define_class("SignalException", rb_eException);
- rb_eInterrupt = rb_define_class("Interrupt", rb_eSignal);
-
- rb_eStandardError = rb_define_class("StandardError", rb_eException);
- rb_eTypeError = rb_define_class("TypeError", rb_eStandardError);
- rb_eArgError = rb_define_class("ArgumentError", rb_eStandardError);
- rb_eIndexError = rb_define_class("IndexError", rb_eStandardError);
- rb_eRangeError = rb_define_class("RangeError", rb_eStandardError);
- rb_eNameError = rb_define_class("NameError", rb_eStandardError);
- rb_define_method(rb_eNameError, "name", name_err_name, 0);
- rb_eNoMethodError = rb_define_class("NoMethodError", rb_eNameError);
- rb_define_method(rb_eNoMethodError, "args", nometh_err_args, 0);
-
- rb_eScriptError = rb_define_class("ScriptError", rb_eException);
- rb_eSyntaxError = rb_define_class("SyntaxError", rb_eScriptError);
- rb_eLoadError = rb_define_class("LoadError", rb_eScriptError);
- rb_eNotImpError = rb_define_class("NotImplementedError", rb_eScriptError);
-
- rb_eRuntimeError = rb_define_class("RuntimeError", rb_eStandardError);
- rb_eSecurityError = rb_define_class("SecurityError", rb_eStandardError);
- rb_eNoMemError = rb_define_class("NoMemoryError", rb_eException);
-
- init_syserr();
-}
-
-void
-#ifdef HAVE_STDARG_PROTOTYPES
-rb_raise(VALUE exc, const char *fmt, ...)
-#else
-rb_raise(exc, fmt, va_alist)
- VALUE exc;
- const char *fmt;
- va_dcl
-#endif
-{
- va_list args;
- char buf[BUFSIZ];
-
- va_init_list(args,fmt);
- vsnprintf(buf, BUFSIZ, fmt, args);
- va_end(args);
- rb_exc_raise(rb_exc_new2(exc, buf));
-}
-
-void
-#ifdef HAVE_STDARG_PROTOTYPES
-rb_loaderror(const char *fmt, ...)
-#else
-rb_loaderror(fmt, va_alist)
- const char *fmt;
- va_dcl
-#endif
-{
- va_list args;
- char buf[BUFSIZ];
-
- va_init_list(args, fmt);
- vsnprintf(buf, BUFSIZ, fmt, args);
- va_end(args);
- rb_exc_raise(rb_exc_new2(rb_eLoadError, buf));
-}
-
-void
-rb_notimplement()
-{
- rb_raise(rb_eNotImpError,
- "The %s() function is unimplemented on this machine",
- rb_id2name(ruby_frame->last_func));
-}
-
-void
-#ifdef HAVE_STDARG_PROTOTYPES
-rb_fatal(const char *fmt, ...)
-#else
-rb_fatal(fmt, va_alist)
- const char *fmt;
- va_dcl
-#endif
-{
- va_list args;
- char buf[BUFSIZ];
-
- va_init_list(args, fmt);
- vsnprintf(buf, BUFSIZ, fmt, args);
- va_end(args);
-
- ruby_in_eval = 0;
- rb_exc_fatal(rb_exc_new2(rb_eFatal, buf));
-}
-
-void
-rb_sys_fail(mesg)
- const char *mesg;
-{
-#ifndef NT
- char *strerror();
-#endif
- char *err;
- char *buf;
- extern int errno;
- int n = errno;
- VALUE ee;
-
- if (errno == 0) {
- rb_bug("rb_sys_fail() - errno == 0");
- }
-
- err = strerror(errno);
- if (mesg) {
- volatile VALUE tmp = rb_str_inspect(rb_str_new2(mesg));
-
- buf = ALLOCA_N(char, strlen(err)+RSTRING(tmp)->len+4);
- sprintf(buf, "%s - %s", err, RSTRING(tmp)->ptr);
- }
- else {
- buf = ALLOCA_N(char, strlen(err)+1);
- strcpy(buf, err);
- }
-
- errno = 0;
-#ifdef __BEOS__
- ee = get_syserr(n);
- if (!ee) {
- char name[12];
-
- sprintf(name, "E%03d", n);
- ee = set_syserr(n, name);
- }
-#else
- if (n > sys_nerr || !syserr_list[n]) {
- char name[12];
-
- sprintf(name, "E%03d", n);
- ee = set_syserr(n, name);
- }
- else {
- ee = syserr_list[n];
- }
-#endif
- ee = rb_exc_new2(ee, buf);
- rb_iv_set(ee, "errno", INT2NUM(n));
- rb_exc_raise(ee);
-}
-
-void
-#ifdef HAVE_STDARG_PROTOTYPES
-rb_sys_warning(const char *fmt, ...)
-#else
-rb_sys_warning(fmt, va_alist)
- const char *fmt;
- va_dcl
-#endif
-{
- char buf[BUFSIZ];
- va_list args;
- int errno_save;
-
- errno_save = errno;
-
- if (!RTEST(ruby_verbose)) return;
-
- snprintf(buf, BUFSIZ, "warning: %s", fmt);
- snprintf(buf+strlen(buf), BUFSIZ-strlen(buf), ": %s", strerror(errno_save));
-
- va_init_list(args, fmt);
- warn_print(buf, args);
- va_end(args);
- errno = errno_save;
-}
-
-void
-rb_load_fail(path)
- char *path;
-{
- rb_loaderror("%s -- %s", strerror(errno), path);
-}
-
-void
-rb_error_frozen(what)
- char *what;
-{
- rb_raise(rb_eTypeError, "can't modify frozen %s", what);
-}
-
-static void
-init_syserr()
-{
-#ifdef __BEOS__
- int i, ix, offset;
-#endif
- rb_eSystemCallError = rb_define_class("SystemCallError", rb_eStandardError);
- rb_define_method(rb_eSystemCallError, "errno", syserr_errno, 0);
- rb_define_singleton_method(rb_eSystemCallError, "===", syserr_eqq, 1);
-
- rb_mErrno = rb_define_module("Errno");
-#ifdef __BEOS__
- for (i = 0; syserr_index[i].n != 0; i++) {
- ix = syserr_index[i].ix;
- for (offset = 0; offset < syserr_index[i].n; offset++) {
- MEMZERO(syserr_list[ix + offset].list, VALUE, syserr_list[ix + offset].n);
- }
- }
- set_syserr(B_ERROR, "ERROR");
-#else
- syserr_list = ALLOC_N(VALUE, sys_nerr+1);
- MEMZERO(syserr_list, VALUE, sys_nerr+1);
-#endif
-
-#ifdef EPERM
- set_syserr(EPERM, "EPERM");
-#endif
-#ifdef ENOENT
- set_syserr(ENOENT, "ENOENT");
-#endif
-#ifdef ESRCH
- set_syserr(ESRCH, "ESRCH");
-#endif
-#ifdef EINTR
- set_syserr(EINTR, "EINTR");
-#endif
-#ifdef EIO
- set_syserr(EIO, "EIO");
-#endif
-#ifdef ENXIO
- set_syserr(ENXIO, "ENXIO");
-#endif
-#ifdef E2BIG
- set_syserr(E2BIG, "E2BIG");
-#endif
-#ifdef ENOEXEC
- set_syserr(ENOEXEC, "ENOEXEC");
-#endif
-#ifdef EBADF
- set_syserr(EBADF, "EBADF");
-#endif
-#ifdef ECHILD
- set_syserr(ECHILD, "ECHILD");
-#endif
-#ifdef EAGAIN
- set_syserr(EAGAIN, "EAGAIN");
-#endif
-#ifdef ENOMEM
- set_syserr(ENOMEM, "ENOMEM");
-#endif
-#ifdef EACCES
- set_syserr(EACCES, "EACCES");
-#endif
-#ifdef EFAULT
- set_syserr(EFAULT, "EFAULT");
-#endif
-#ifdef ENOTBLK
- set_syserr(ENOTBLK, "ENOTBLK");
-#endif
-#ifdef EBUSY
- set_syserr(EBUSY, "EBUSY");
-#endif
-#ifdef EEXIST
- set_syserr(EEXIST, "EEXIST");
-#endif
-#ifdef EXDEV
- set_syserr(EXDEV, "EXDEV");
-#endif
-#ifdef ENODEV
- set_syserr(ENODEV, "ENODEV");
-#endif
-#ifdef ENOTDIR
- set_syserr(ENOTDIR, "ENOTDIR");
-#endif
-#ifdef EISDIR
- set_syserr(EISDIR, "EISDIR");
-#endif
-#ifdef EINVAL
- set_syserr(EINVAL, "EINVAL");
-#endif
-#ifdef ENFILE
- set_syserr(ENFILE, "ENFILE");
-#endif
-#ifdef EMFILE
- set_syserr(EMFILE, "EMFILE");
-#endif
-#ifdef ENOTTY
- set_syserr(ENOTTY, "ENOTTY");
-#endif
-#ifdef ETXTBSY
- set_syserr(ETXTBSY, "ETXTBSY");
-#endif
-#ifdef EFBIG
- set_syserr(EFBIG, "EFBIG");
-#endif
-#ifdef ENOSPC
- set_syserr(ENOSPC, "ENOSPC");
-#endif
-#ifdef ESPIPE
- set_syserr(ESPIPE, "ESPIPE");
-#endif
-#ifdef EROFS
- set_syserr(EROFS, "EROFS");
-#endif
-#ifdef EMLINK
- set_syserr(EMLINK, "EMLINK");
-#endif
-#ifdef EPIPE
- set_syserr(EPIPE, "EPIPE");
-#endif
-#ifdef EDOM
- set_syserr(EDOM, "EDOM");
-#endif
-#ifdef ERANGE
- set_syserr(ERANGE, "ERANGE");
-#endif
-#ifdef EDEADLK
- set_syserr(EDEADLK, "EDEADLK");
-#endif
-#ifdef ENAMETOOLONG
- set_syserr(ENAMETOOLONG, "ENAMETOOLONG");
-#endif
-#ifdef ENOLCK
- set_syserr(ENOLCK, "ENOLCK");
-#endif
-#ifdef ENOSYS
- set_syserr(ENOSYS, "ENOSYS");
-#endif
-#ifdef ENOTEMPTY
- set_syserr(ENOTEMPTY, "ENOTEMPTY");
-#endif
-#ifdef ELOOP
- set_syserr(ELOOP, "ELOOP");
-#endif
-#ifdef EWOULDBLOCK
- set_syserr(EWOULDBLOCK, "EWOULDBLOCK");
-#endif
-#ifdef ENOMSG
- set_syserr(ENOMSG, "ENOMSG");
-#endif
-#ifdef EIDRM
- set_syserr(EIDRM, "EIDRM");
-#endif
-#ifdef ECHRNG
- set_syserr(ECHRNG, "ECHRNG");
-#endif
-#ifdef EL2NSYNC
- set_syserr(EL2NSYNC, "EL2NSYNC");
-#endif
-#ifdef EL3HLT
- set_syserr(EL3HLT, "EL3HLT");
-#endif
-#ifdef EL3RST
- set_syserr(EL3RST, "EL3RST");
-#endif
-#ifdef ELNRNG
- set_syserr(ELNRNG, "ELNRNG");
-#endif
-#ifdef EUNATCH
- set_syserr(EUNATCH, "EUNATCH");
-#endif
-#ifdef ENOCSI
- set_syserr(ENOCSI, "ENOCSI");
-#endif
-#ifdef EL2HLT
- set_syserr(EL2HLT, "EL2HLT");
-#endif
-#ifdef EBADE
- set_syserr(EBADE, "EBADE");
-#endif
-#ifdef EBADR
- set_syserr(EBADR, "EBADR");
-#endif
-#ifdef EXFULL
- set_syserr(EXFULL, "EXFULL");
-#endif
-#ifdef ENOANO
- set_syserr(ENOANO, "ENOANO");
-#endif
-#ifdef EBADRQC
- set_syserr(EBADRQC, "EBADRQC");
-#endif
-#ifdef EBADSLT
- set_syserr(EBADSLT, "EBADSLT");
-#endif
-#ifdef EDEADLOCK
- set_syserr(EDEADLOCK, "EDEADLOCK");
-#endif
-#ifdef EBFONT
- set_syserr(EBFONT, "EBFONT");
-#endif
-#ifdef ENOSTR
- set_syserr(ENOSTR, "ENOSTR");
-#endif
-#ifdef ENODATA
- set_syserr(ENODATA, "ENODATA");
-#endif
-#ifdef ETIME
- set_syserr(ETIME, "ETIME");
-#endif
-#ifdef ENOSR
- set_syserr(ENOSR, "ENOSR");
-#endif
-#ifdef ENONET
- set_syserr(ENONET, "ENONET");
-#endif
-#ifdef ENOPKG
- set_syserr(ENOPKG, "ENOPKG");
-#endif
-#ifdef EREMOTE
- set_syserr(EREMOTE, "EREMOTE");
-#endif
-#ifdef ENOLINK
- set_syserr(ENOLINK, "ENOLINK");
-#endif
-#ifdef EADV
- set_syserr(EADV, "EADV");
-#endif
-#ifdef ESRMNT
- set_syserr(ESRMNT, "ESRMNT");
-#endif
-#ifdef ECOMM
- set_syserr(ECOMM, "ECOMM");
-#endif
-#ifdef EPROTO
- set_syserr(EPROTO, "EPROTO");
-#endif
-#ifdef EMULTIHOP
- set_syserr(EMULTIHOP, "EMULTIHOP");
-#endif
-#ifdef EDOTDOT
- set_syserr(EDOTDOT, "EDOTDOT");
-#endif
-#ifdef EBADMSG
- set_syserr(EBADMSG, "EBADMSG");
-#endif
-#ifdef EOVERFLOW
- set_syserr(EOVERFLOW, "EOVERFLOW");
-#endif
-#ifdef ENOTUNIQ
- set_syserr(ENOTUNIQ, "ENOTUNIQ");
-#endif
-#ifdef EBADFD
- set_syserr(EBADFD, "EBADFD");
-#endif
-#ifdef EREMCHG
- set_syserr(EREMCHG, "EREMCHG");
-#endif
-#ifdef ELIBACC
- set_syserr(ELIBACC, "ELIBACC");
-#endif
-#ifdef ELIBBAD
- set_syserr(ELIBBAD, "ELIBBAD");
-#endif
-#ifdef ELIBSCN
- set_syserr(ELIBSCN, "ELIBSCN");
-#endif
-#ifdef ELIBMAX
- set_syserr(ELIBMAX, "ELIBMAX");
-#endif
-#ifdef ELIBEXEC
- set_syserr(ELIBEXEC, "ELIBEXEC");
-#endif
-#ifdef EILSEQ
- set_syserr(EILSEQ, "EILSEQ");
-#endif
-#ifdef ERESTART
- set_syserr(ERESTART, "ERESTART");
-#endif
-#ifdef ESTRPIPE
- set_syserr(ESTRPIPE, "ESTRPIPE");
-#endif
-#ifdef EUSERS
- set_syserr(EUSERS, "EUSERS");
-#endif
-#ifdef ENOTSOCK
- set_syserr(ENOTSOCK, "ENOTSOCK");
-#endif
-#ifdef EDESTADDRREQ
- set_syserr(EDESTADDRREQ, "EDESTADDRREQ");
-#endif
-#ifdef EMSGSIZE
- set_syserr(EMSGSIZE, "EMSGSIZE");
-#endif
-#ifdef EPROTOTYPE
- set_syserr(EPROTOTYPE, "EPROTOTYPE");
-#endif
-#ifdef ENOPROTOOPT
- set_syserr(ENOPROTOOPT, "ENOPROTOOPT");
-#endif
-#ifdef EPROTONOSUPPORT
- set_syserr(EPROTONOSUPPORT, "EPROTONOSUPPORT");
-#endif
-#ifdef ESOCKTNOSUPPORT
- set_syserr(ESOCKTNOSUPPORT, "ESOCKTNOSUPPORT");
-#endif
-#ifdef EOPNOTSUPP
- set_syserr(EOPNOTSUPP, "EOPNOTSUPP");
-#endif
-#ifdef EPFNOSUPPORT
- set_syserr(EPFNOSUPPORT, "EPFNOSUPPORT");
-#endif
-#ifdef EAFNOSUPPORT
- set_syserr(EAFNOSUPPORT, "EAFNOSUPPORT");
-#endif
-#ifdef EADDRINUSE
- set_syserr(EADDRINUSE, "EADDRINUSE");
-#endif
-#ifdef EADDRNOTAVAIL
- set_syserr(EADDRNOTAVAIL, "EADDRNOTAVAIL");
-#endif
-#ifdef ENETDOWN
- set_syserr(ENETDOWN, "ENETDOWN");
-#endif
-#ifdef ENETUNREACH
- set_syserr(ENETUNREACH, "ENETUNREACH");
-#endif
-#ifdef ENETRESET
- set_syserr(ENETRESET, "ENETRESET");
-#endif
-#ifdef ECONNABORTED
- set_syserr(ECONNABORTED, "ECONNABORTED");
-#endif
-#ifdef ECONNRESET
- set_syserr(ECONNRESET, "ECONNRESET");
-#endif
-#ifdef ENOBUFS
- set_syserr(ENOBUFS, "ENOBUFS");
-#endif
-#ifdef EISCONN
- set_syserr(EISCONN, "EISCONN");
-#endif
-#ifdef ENOTCONN
- set_syserr(ENOTCONN, "ENOTCONN");
-#endif
-#ifdef ESHUTDOWN
- set_syserr(ESHUTDOWN, "ESHUTDOWN");
-#endif
-#ifdef ETOOMANYREFS
- set_syserr(ETOOMANYREFS, "ETOOMANYREFS");
-#endif
-#ifdef ETIMEDOUT
- set_syserr(ETIMEDOUT, "ETIMEDOUT");
-#endif
-#ifdef ECONNREFUSED
- set_syserr(ECONNREFUSED, "ECONNREFUSED");
-#endif
-#ifdef EHOSTDOWN
- set_syserr(EHOSTDOWN, "EHOSTDOWN");
-#endif
-#ifdef EHOSTUNREACH
- set_syserr(EHOSTUNREACH, "EHOSTUNREACH");
-#endif
-#ifdef EALREADY
- set_syserr(EALREADY, "EALREADY");
-#endif
-#ifdef EINPROGRESS
- set_syserr(EINPROGRESS, "EINPROGRESS");
-#endif
-#ifdef ESTALE
- set_syserr(ESTALE, "ESTALE");
-#endif
-#ifdef EUCLEAN
- set_syserr(EUCLEAN, "EUCLEAN");
-#endif
-#ifdef ENOTNAM
- set_syserr(ENOTNAM, "ENOTNAM");
-#endif
-#ifdef ENAVAIL
- set_syserr(ENAVAIL, "ENAVAIL");
-#endif
-#ifdef EISNAM
- set_syserr(EISNAM, "EISNAM");
-#endif
-#ifdef EREMOTEIO
- set_syserr(EREMOTEIO, "EREMOTEIO");
-#endif
-#ifdef EDQUOT
- set_syserr(EDQUOT, "EDQUOT");
-#endif
-}
-
-static void
-err_append(s)
- const char *s;
-{
- extern VALUE ruby_errinfo;
-
- if (ruby_in_eval) {
- if (NIL_P(ruby_errinfo)) {
- ruby_errinfo = rb_exc_new2(rb_eSyntaxError, s);
- }
- else {
- VALUE str = rb_str_to_str(ruby_errinfo);
-
- rb_str_cat2(str, "\n");
- rb_str_cat2(str, s);
- ruby_errinfo = rb_exc_new3(rb_eSyntaxError, str);
- }
- }
- else {
- fputs(s, stderr);
- fputs("\n", stderr);
- fflush(stderr);
- }
-}
diff --git a/eval.c b/eval.c
deleted file mode 100644
index 32f7972c39..0000000000
--- a/eval.c
+++ /dev/null
@@ -1,9266 +0,0 @@
-/**********************************************************************
-
- eval.c -
-
- $Author$
- $Date$
- created at: Thu Jun 10 14:22:17 JST 1993
-
- Copyright (C) 1993-2002 Yukihiro Matsumoto
- Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
- Copyright (C) 2000 Information-technology Promotion Agency, Japan
-
-**********************************************************************/
-
-#include "ruby.h"
-#include "node.h"
-#include "env.h"
-#include "util.h"
-#include "rubysig.h"
-
-#include <stdio.h>
-#include <setjmp.h>
-#include "st.h"
-#include "dln.h"
-
-/* Make alloca work the best possible way. */
-#ifdef __GNUC__
-# ifndef atarist
-# ifndef alloca
-# define alloca __builtin_alloca
-# endif
-# endif /* atarist */
-#else
-# if defined(HAVE_ALLOCA_H)
-# include <alloca.h>
-# elif !defined(alloca)
-char *alloca();
-# endif
-#endif /* __GNUC__ */
-
-#ifdef _AIX
-#pragma alloca
-#endif
-
-#ifdef HAVE_STDARG_PROTOTYPES
-#include <stdarg.h>
-#define va_init_list(a,b) va_start(a,b)
-#else
-#include <varargs.h>
-#define va_init_list(a,b) va_start(a)
-#endif
-
-#ifndef HAVE_STRING_H
-char *strrchr _((const char*,const char));
-#endif
-
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-
-#ifdef __BEOS__
-#include <net/socket.h>
-#endif
-
-#ifdef __MACOS__
-#include "macruby_private.h"
-#endif
-
-#ifndef setjmp
-#ifdef HAVE__SETJMP
-#define setjmp(env) _setjmp(env)
-#define longjmp(env,val) _longjmp(env,val)
-#endif
-#endif
-
-#include <sys/types.h>
-#ifdef HAVE_SYS_TIME_H
-# include <sys/time.h>
-#else
-#ifndef NT
-struct timeval {
- long tv_sec; /* seconds */
- long tv_usec; /* and microseconds */
-};
-#endif /* NT */
-#endif
-#include <signal.h>
-#include <errno.h>
-
-#ifdef HAVE_SYS_SELECT_H
-#include <sys/select.h>
-#endif
-
-#include <sys/stat.h>
-
-VALUE rb_cProc;
-static VALUE rb_cBinding;
-static VALUE proc_invoke _((VALUE,VALUE,int,VALUE));
-static VALUE rb_f_binding _((VALUE));
-static void rb_f_END _((void));
-static VALUE rb_f_block_given_p _((void));
-static VALUE block_pass _((VALUE,NODE*));
-static VALUE rb_cMethod;
-static VALUE method_proc _((VALUE));
-static VALUE method_call _((int, VALUE*, VALUE));
-static VALUE rb_cUnboundMethod;
-static VALUE umethod_bind _((VALUE, VALUE));
-static VALUE rb_mod_define_method _((int, VALUE*, VALUE));
-
-static int scope_vmode;
-#define SCOPE_PUBLIC 0
-#define SCOPE_PRIVATE 1
-#define SCOPE_PROTECTED 2
-#define SCOPE_MODFUNC 5
-#define SCOPE_MASK 7
-#define SCOPE_SET(f) do {scope_vmode=(f);} while(0)
-#define SCOPE_TEST(f) (scope_vmode&(f))
-
-int ruby_safe_level = 0;
-/* safe-level:
- 0 - strings from streams/environment/ARGV are tainted (default)
- 1 - no dangerous operation by tainted value
- 2 - process/file operations prohibited
- 3 - all genetated objects are tainted
- 4 - no global (non-tainted) variable modification/no direct output
-*/
-
-static VALUE safe_getter _((void));
-static void safe_setter _((VALUE val));
-
-void
-rb_secure(level)
- int level;
-{
- if (level <= ruby_safe_level) {
- rb_raise(rb_eSecurityError, "Insecure operation `%s' at level %d",
- rb_id2name(ruby_frame->last_func), ruby_safe_level);
- }
-}
-
-void
-rb_check_safe_str(x)
- VALUE x;
-{
- if (ruby_safe_level > 0 && OBJ_TAINTED(x)){
- if (ruby_frame->last_func) {
- rb_raise(rb_eSecurityError, "Insecure operation - %s",
- rb_id2name(ruby_frame->last_func));
- }
- else {
- rb_raise(rb_eSecurityError, "Insecure operation: -r");
- }
- }
- rb_secure(4);
- if (TYPE(x)!= T_STRING) {
- rb_raise(rb_eTypeError, "wrong argument type %s (expected String)",
- rb_class2name(CLASS_OF(x)));
- }
-}
-
-NORETURN(static void print_undef _((VALUE, ID)));
-static void
-print_undef(klass, id)
- VALUE klass;
- ID id;
-{
- rb_name_error(id, "undefined method `%s' for %s `%s'",
- rb_id2name(id),
- (TYPE(klass) == T_MODULE) ? "module" : "class",
- rb_class2name(klass));
-}
-
-static ID removed, singleton_removed, undefined, singleton_undefined;
-
-#define CACHE_SIZE 0x800
-#define CACHE_MASK 0x7ff
-#define EXPR1(c,m) ((((c)>>3)^(m))&CACHE_MASK)
-
-struct cache_entry { /* method hash table. */
- ID mid; /* method's id */
- ID mid0; /* method's original id */
- VALUE klass; /* receiver's class */
- VALUE origin; /* where method defined */
- NODE *method;
- int noex;
-};
-
-static struct cache_entry cache[CACHE_SIZE];
-
-void
-rb_clear_cache()
-{
- struct cache_entry *ent, *end;
-
- ent = cache; end = ent + CACHE_SIZE;
- while (ent < end) {
- ent->mid = 0;
- ent++;
- }
-}
-
-static void
-rb_clear_cache_by_id(id)
- ID id;
-{
- struct cache_entry *ent, *end;
-
- ent = cache; end = ent + CACHE_SIZE;
- while (ent < end) {
- if (ent->mid == id) {
- ent->mid = 0;
- }
- ent++;
- }
-}
-
-void
-rb_add_method(klass, mid, node, noex)
- VALUE klass;
- ID mid;
- NODE *node;
- int noex;
-{
- NODE *body;
-
- if (NIL_P(klass)) klass = rb_cObject;
- if (rb_safe_level() >= 4 && (klass == rb_cObject || !OBJ_TAINTED(klass))) {
- rb_raise(rb_eSecurityError, "Insecure: can't define method");
- }
- if (OBJ_FROZEN(klass)) rb_error_frozen("class/module");
- rb_clear_cache_by_id(mid);
- body = NEW_METHOD(node, noex);
- st_insert(RCLASS(klass)->m_tbl, mid, body);
-}
-
-static NODE*
-search_method(klass, id, origin)
- VALUE klass, *origin;
- ID id;
-{
- NODE *body;
-
- if (!klass) return 0;
- while (!st_lookup(RCLASS(klass)->m_tbl, id, &body)) {
- klass = RCLASS(klass)->super;
- if (!klass) return 0;
- }
-
- if (origin) *origin = klass;
- return body;
-}
-
-static NODE*
-rb_get_method_body(klassp, idp, noexp)
- VALUE *klassp;
- ID *idp;
- int *noexp;
-{
- ID id = *idp;
- VALUE klass = *klassp;
- VALUE origin;
- NODE * volatile body;
- struct cache_entry *ent;
-
- if ((body = search_method(klass, id, &origin)) == 0 || !body->nd_body) {
- /* store empty info in cache */
- ent = cache + EXPR1(klass, id);
- ent->klass = klass;
- ent->origin = klass;
- ent->mid = ent->mid0 = id;
- ent->noex = 0;
- ent->method = 0;
-
- return 0;
- }
-
- /* store in cache */
- ent = cache + EXPR1(klass, id);
- ent->klass = klass;
- ent->noex = body->nd_noex;
- body = body->nd_body;
- if (nd_type(body) == NODE_FBODY) {
- ent->mid = id;
- *klassp = body->nd_orig;
- ent->origin = body->nd_orig;
- *idp = ent->mid0 = body->nd_mid;
- body = ent->method = body->nd_head;
- }
- else {
- *klassp = origin;
- ent->origin = origin;
- ent->mid = ent->mid0 = id;
- ent->method = body;
- }
-
- if (noexp) *noexp = ent->noex;
- return body;
-}
-
-static void
-remove_method(klass, mid)
- VALUE klass;
- ID mid;
-{
- NODE *body;
-
- if (klass == rb_cObject) {
- rb_secure(4);
- }
- if (rb_safe_level() >= 4 && !OBJ_TAINTED(klass)) {
- rb_raise(rb_eSecurityError, "Insecure: can't remove method");
- }
- if (OBJ_FROZEN(klass)) rb_error_frozen("class/module");
- if (!st_delete(RCLASS(klass)->m_tbl, &mid, &body) || !body->nd_body) {
- rb_name_error(mid, "method `%s' not defined in %s",
- rb_id2name(mid), rb_class2name(klass));
- }
- rb_clear_cache_by_id(mid);
- if (FL_TEST(klass, FL_SINGLETON)) {
- rb_funcall(rb_iv_get(klass, "__attached__"), singleton_removed, 1, ID2SYM(mid));
- }
- else {
- rb_funcall(klass, removed, 1, ID2SYM(mid));
- }
-}
-
-void
-rb_remove_method(klass, name)
- VALUE klass;
- const char *name;
-{
- remove_method(klass, rb_intern(name));
-}
-
-static VALUE
-rb_mod_remove_method(mod, name)
- VALUE mod, name;
-{
- remove_method(mod, rb_to_id(name));
- return mod;
-}
-
-void
-rb_disable_super(klass, name)
- VALUE klass;
- const char *name;
-{
- VALUE origin;
- NODE *body;
- ID mid = rb_intern(name);
-
- body = search_method(klass, mid, &origin);
- if (!body || !body->nd_body) {
- print_undef(klass, mid);
- }
- if (origin == klass) {
- body->nd_noex |= NOEX_UNDEF;
- }
- else {
- rb_add_method(klass, mid, 0, NOEX_UNDEF);
- }
-}
-
-void
-rb_enable_super(klass, name)
- VALUE klass;
- const char *name;
-{
- VALUE origin;
- NODE *body;
- ID mid = rb_intern(name);
-
- body = search_method(klass, mid, &origin);
- if (!body) {
- print_undef(klass, mid);
- }
- if (!body->nd_body) {
- remove_method(klass, mid);
- }
- else {
- body->nd_noex &= ~NOEX_UNDEF;
- }
-}
-
-static void
-rb_export_method(klass, name, noex)
- VALUE klass;
- ID name;
- ID noex;
-{
- NODE *body;
- VALUE origin;
-
- if (klass == rb_cObject) {
- rb_secure(4);
- }
- body = search_method(klass, name, &origin);
- if (!body && TYPE(klass) == T_MODULE) {
- body = search_method(rb_cObject, name, &origin);
- }
- if (!body) {
- print_undef(klass, name);
- }
- if (body->nd_noex != noex) {
- if (klass == origin) {
- body->nd_noex = noex;
- }
- else {
- rb_add_method(klass, name, NEW_ZSUPER(), noex);
- }
- }
-}
-
-int
-rb_method_boundp(klass, id, ex)
- VALUE klass;
- ID id;
- int ex;
-{
- struct cache_entry *ent;
- int noex;
-
- /* is it in the method cache? */
- ent = cache + EXPR1(klass, id);
- if (ent->mid == id && ent->klass == klass) {
- if (ex && (ent->noex & NOEX_PRIVATE))
- return Qfalse;
- if (!ent->method) return Qfalse;
- return Qtrue;
- }
- if (rb_get_method_body(&klass, &id, &noex)) {
- if (ex && (noex & NOEX_PRIVATE))
- return Qfalse;
- return Qtrue;
- }
- return Qfalse;
-}
-
-static ID init, alloc, eqq, each, aref, aset, match, to_ary, missing;
-static ID added, singleton_added;
-static ID __id__, __send__;
-
-void
-rb_attr(klass, id, read, write, ex)
- VALUE klass;
- ID id;
- int read, write, ex;
-{
- const char *name;
- char *buf;
- ID attriv;
- int noex;
-
- if (!ex) noex = NOEX_PUBLIC;
- else {
- if (SCOPE_TEST(SCOPE_PRIVATE)) {
- noex = NOEX_PRIVATE;
- rb_warning((scope_vmode == SCOPE_MODFUNC) ?
- "attribute accessor as module_function" :
- "private attribute?");
- }
- else if (SCOPE_TEST(SCOPE_PROTECTED)) {
- noex = NOEX_PROTECTED;
- }
- else {
- noex = NOEX_PUBLIC;
- }
- }
-
- name = rb_id2name(id);
- if (!name) {
- rb_raise(rb_eArgError, "argument needs to be symbol or string");
- }
- buf = ALLOCA_N(char,strlen(name)+2);
- sprintf(buf, "@%s", name);
- attriv = rb_intern(buf);
- if (read) {
- rb_add_method(klass, id, NEW_IVAR(attriv), noex);
- rb_funcall(klass, added, 1, ID2SYM(id));
- }
- if (write) {
- sprintf(buf, "%s=", name);
- id = rb_intern(buf);
- rb_add_method(klass, id, NEW_ATTRSET(attriv), noex);
- rb_funcall(klass, added, 1, ID2SYM(id));
- }
-}
-
-extern int ruby_in_compile;
-
-VALUE ruby_errinfo = Qnil;
-extern NODE *ruby_eval_tree_begin;
-extern NODE *ruby_eval_tree;
-extern int ruby_nerrs;
-
-static VALUE rb_eLocalJumpError;
-static VALUE rb_eSysStackError;
-
-extern VALUE ruby_top_self;
-
-struct FRAME *ruby_frame;
-struct SCOPE *ruby_scope;
-static struct FRAME *top_frame;
-static struct SCOPE *top_scope;
-
-#define PUSH_FRAME() { \
- struct FRAME _frame; \
- _frame.prev = ruby_frame; \
- _frame.tmp = 0; \
- _frame.file = ruby_sourcefile; \
- _frame.line = ruby_sourceline; \
- _frame.iter = ruby_iter->iter; \
- _frame.cbase = ruby_frame->cbase; \
- _frame.argc = 0; \
- _frame.argv = 0; \
- _frame.flags = FRAME_ALLOCA; \
- ruby_frame = &_frame; \
-
-#define POP_FRAME() \
- ruby_sourcefile = _frame.file; \
- ruby_sourceline = _frame.line; \
- ruby_frame = _frame.prev; }
-
-struct BLOCKTAG {
- struct RBasic super;
- long dst;
- long flags;
-};
-
-struct BLOCK {
- NODE *var;
- NODE *body;
- VALUE self;
- struct FRAME frame;
- struct SCOPE *scope;
- struct BLOCKTAG *tag;
- VALUE klass;
- int iter;
- int vmode;
- int flags;
- struct RVarmap *dyna_vars;
- VALUE orig_thread;
- VALUE wrapper;
- struct BLOCK *prev;
-};
-
-#define BLOCK_D_SCOPE 1
-#define BLOCK_DYNAMIC 2
-#define BLOCK_ORPHAN 4
-
-static struct BLOCK *ruby_block;
-
-static struct BLOCKTAG*
-new_blktag()
-{
- NEWOBJ(blktag, struct BLOCKTAG);
- OBJSETUP(blktag, 0, T_BLKTAG);
- blktag->dst = 0;
- blktag->flags = 0;
- return blktag;
-}
-
-#define PUSH_BLOCK(v,b) { \
- struct BLOCK _block; \
- _block.tag = new_blktag(); \
- _block.var = v; \
- _block.body = b; \
- _block.self = self; \
- _block.frame = *ruby_frame; \
- _block.klass = ruby_class; \
- _block.frame.file = ruby_sourcefile;\
- _block.frame.line = ruby_sourceline;\
- _block.scope = ruby_scope; \
- _block.prev = ruby_block; \
- _block.iter = ruby_iter->iter; \
- _block.vmode = scope_vmode; \
- _block.flags = BLOCK_D_SCOPE; \
- _block.dyna_vars = ruby_dyna_vars; \
- _block.wrapper = ruby_wrapper; \
- ruby_block = &_block;
-
-#define POP_BLOCK() \
- if (_block.tag->flags & (BLOCK_DYNAMIC)) \
- _block.tag->flags |= BLOCK_ORPHAN; \
- else if (!(_block.scope->flags & SCOPE_DONT_RECYCLE)) \
- rb_gc_force_recycle((VALUE)_block.tag); \
- ruby_block = _block.prev; \
-}
-
-struct RVarmap *ruby_dyna_vars;
-#define PUSH_VARS() { \
- struct RVarmap * volatile _old; \
- _old = ruby_dyna_vars; \
- ruby_dyna_vars = 0;
-
-#define POP_VARS() \
- if (_old && (ruby_scope->flags & SCOPE_DONT_RECYCLE)) {\
- if (RBASIC(_old)->flags) /* unless it's already recycled */ \
- FL_SET(_old, DVAR_DONT_RECYCLE); \
- }\
- ruby_dyna_vars = _old; \
-}
-
-#define DVAR_DONT_RECYCLE FL_USER2
-
-static struct RVarmap*
-new_dvar(id, value, prev)
- ID id;
- VALUE value;
- struct RVarmap *prev;
-{
- NEWOBJ(vars, struct RVarmap);
- OBJSETUP(vars, 0, T_VARMAP);
- vars->id = id;
- vars->val = value;
- vars->next = prev;
-
- return vars;
-}
-
-VALUE
-rb_dvar_defined(id)
- ID id;
-{
- struct RVarmap *vars = ruby_dyna_vars;
-
- while (vars) {
- if (vars->id == id) return Qtrue;
- vars = vars->next;
- }
- return Qfalse;
-}
-
-VALUE
-rb_dvar_curr(id)
- ID id;
-{
- struct RVarmap *vars = ruby_dyna_vars;
-
- while (vars) {
- if (vars->id == 0) break;
- if (vars->id == id) return Qtrue;
- vars = vars->next;
- }
- return Qfalse;
-}
-
-VALUE
-rb_dvar_ref(id)
- ID id;
-{
- struct RVarmap *vars = ruby_dyna_vars;
-
- while (vars) {
- if (vars->id == id) {
- return vars->val;
- }
- vars = vars->next;
- }
- return Qnil;
-}
-
-void
-rb_dvar_push(id, value)
- ID id;
- VALUE value;
-{
- ruby_dyna_vars = new_dvar(id, value, ruby_dyna_vars);
-}
-
-static void
-dvar_asgn_internal(id, value, curr)
- ID id;
- VALUE value;
- int curr;
-{
- int n = 0;
- struct RVarmap *vars = ruby_dyna_vars;
-
- while (vars) {
- if (curr && vars->id == 0) {
- /* first null is a dvar header */
- n++;
- if (n == 2) break;
- }
- if (vars->id == id) {
- vars->val = value;
- return;
- }
- vars = vars->next;
- }
- if (!ruby_dyna_vars) {
- ruby_dyna_vars = new_dvar(id, value, 0);
- }
- else {
- vars = new_dvar(id, value, ruby_dyna_vars->next);
- ruby_dyna_vars->next = vars;
- }
-}
-
-static inline void
-dvar_asgn(id, value)
- ID id;
- VALUE value;
-{
- dvar_asgn_internal(id, value, 0);
-}
-
-static inline void
-dvar_asgn_curr(id, value)
- ID id;
- VALUE value;
-{
- dvar_asgn_internal(id, value, 1);
-}
-
-VALUE *
-rb_svar(cnt)
- int cnt;
-{
- struct RVarmap *vars = ruby_dyna_vars;
- ID id;
-
- if (!ruby_scope->local_tbl) return NULL;
- if (cnt >= ruby_scope->local_tbl[0]) return NULL;
- id = ruby_scope->local_tbl[cnt+1];
- while (vars) {
- if (vars->id == id) return &vars->val;
- vars = vars->next;
- }
- if (ruby_scope->local_vars == 0) return NULL;
- return &ruby_scope->local_vars[cnt];
-}
-
-struct iter {
- int iter;
- struct iter *prev;
-};
-static struct iter *ruby_iter;
-
-#define ITER_NOT 0
-#define ITER_PRE 1
-#define ITER_CUR 2
-
-#define PUSH_ITER(i) { \
- struct iter _iter; \
- _iter.prev = ruby_iter; \
- _iter.iter = (i); \
- ruby_iter = &_iter; \
-
-#define POP_ITER() \
- ruby_iter = _iter.prev; \
-}
-
-struct tag {
- jmp_buf buf;
- struct FRAME *frame;
- struct iter *iter;
- ID tag;
- VALUE retval;
- struct SCOPE *scope;
- int dst;
- struct tag *prev;
-};
-static struct tag *prot_tag;
-
-#define PUSH_TAG(ptag) { \
- struct tag _tag; \
- _tag.retval = Qnil; \
- _tag.frame = ruby_frame; \
- _tag.iter = ruby_iter; \
- _tag.prev = prot_tag; \
- _tag.scope = ruby_scope; \
- _tag.tag = ptag; \
- _tag.dst = 0; \
- prot_tag = &_tag;
-
-#define PROT_NONE 0
-#define PROT_FUNC -1
-#define PROT_THREAD -2
-
-#define EXEC_TAG() setjmp(prot_tag->buf)
-
-#define JUMP_TAG(st) { \
- ruby_frame = prot_tag->frame; \
- ruby_iter = prot_tag->iter; \
- longjmp(prot_tag->buf,(st)); \
-}
-
-#define POP_TAG() \
- if (_tag.prev) \
- _tag.prev->retval = _tag.retval;\
- prot_tag = _tag.prev; \
-}
-
-#define POP_TMPTAG() \
- prot_tag = _tag.prev; \
-}
-
-#define TAG_RETURN 0x1
-#define TAG_BREAK 0x2
-#define TAG_NEXT 0x3
-#define TAG_RETRY 0x4
-#define TAG_REDO 0x5
-#define TAG_RAISE 0x6
-#define TAG_THROW 0x7
-#define TAG_FATAL 0x8
-#define TAG_MASK 0xf
-
-VALUE ruby_class;
-static VALUE ruby_wrapper; /* security wrapper */
-
-#define PUSH_CLASS() { \
- VALUE _class = ruby_class; \
-
-#define POP_CLASS() ruby_class = _class; }
-
-static NODE *ruby_cref = 0;
-static NODE *top_cref;
-#define PUSH_CREF(c) ruby_cref = rb_node_newnode(NODE_CREF,(c),0,ruby_cref)
-#define POP_CREF() ruby_cref = ruby_cref->nd_next
-
-#define PUSH_SCOPE() { \
- volatile int _vmode = scope_vmode; \
- struct SCOPE * volatile _old; \
- NEWOBJ(_scope, struct SCOPE); \
- OBJSETUP(_scope, 0, T_SCOPE); \
- _scope->local_tbl = 0; \
- _scope->local_vars = 0; \
- _scope->flags = 0; \
- _old = ruby_scope; \
- ruby_scope = _scope; \
- scope_vmode = SCOPE_PUBLIC;
-
-typedef struct thread * rb_thread_t;
-static rb_thread_t curr_thread = 0;
-static rb_thread_t main_thread;
-static void scope_dup _((struct SCOPE *));
-
-#define POP_SCOPE() \
- if (ruby_scope->flags & SCOPE_DONT_RECYCLE) {\
- if (_old) scope_dup(_old); \
- } \
- if (!(ruby_scope->flags & SCOPE_MALLOC)) {\
- ruby_scope->local_vars = 0; \
- ruby_scope->local_tbl = 0; \
- if (!(ruby_scope->flags & SCOPE_DONT_RECYCLE) && \
- ruby_scope != top_scope) { \
- rb_gc_force_recycle((VALUE)ruby_scope);\
- } \
- } \
- ruby_scope->flags |= SCOPE_NOSTACK; \
- ruby_scope = _old; \
- scope_vmode = _vmode; \
-}
-
-static VALUE rb_eval _((VALUE,NODE*));
-static VALUE eval _((VALUE,VALUE,VALUE,char*,int));
-static NODE *compile _((VALUE, char*, int));
-
-static VALUE rb_yield_0 _((VALUE, VALUE, VALUE, int));
-static VALUE rb_call _((VALUE,VALUE,ID,int,VALUE*,int));
-static VALUE module_setup _((VALUE,NODE*));
-
-static VALUE massign _((VALUE,NODE*,VALUE,int));
-static void assign _((VALUE,NODE*,VALUE,int));
-
-static VALUE trace_func = 0;
-static int tracing = 0;
-static void call_trace_func _((char*,char*,int,VALUE,ID,VALUE));
-
-static void
-error_pos()
-{
- if (ruby_sourcefile) {
- if (ruby_frame->last_func) {
- fprintf(stderr, "%s:%d:in `%s'", ruby_sourcefile, ruby_sourceline,
- rb_id2name(ruby_frame->last_func));
- }
- else if (ruby_sourceline == 0) {
- fprintf(stderr, "%s", ruby_sourcefile);
- }
- else {
- fprintf(stderr, "%s:%d", ruby_sourcefile, ruby_sourceline);
- }
- }
-}
-
-static VALUE
-get_backtrace(info)
- VALUE info;
-{
- if (NIL_P(info)) return Qnil;
- return rb_funcall(info, rb_intern("backtrace"), 0);
-}
-
-static void
-set_backtrace(info, bt)
- VALUE info, bt;
-{
- rb_funcall(info, rb_intern("set_backtrace"), 1, bt);
-}
-
-static void
-error_print()
-{
- VALUE errat = Qnil; /* OK */
- volatile VALUE eclass;
- char *einfo;
- int elen;
-
- if (NIL_P(ruby_errinfo)) return;
-
- PUSH_TAG(PROT_NONE);
- if (EXEC_TAG() == 0) {
- errat = get_backtrace(ruby_errinfo);
- }
- else {
- errat = Qnil;
- }
- POP_TAG();
- if (NIL_P(errat)){
- if (ruby_sourcefile)
- fprintf(stderr, "%s:%d", ruby_sourcefile, ruby_sourceline);
- else
- fprintf(stderr, "%d", ruby_sourceline);
- }
- else if (RARRAY(errat)->len == 0) {
- error_pos();
- }
- else {
- VALUE mesg = RARRAY(errat)->ptr[0];
-
- if (NIL_P(mesg)) error_pos();
- else {
- fwrite(RSTRING(mesg)->ptr, 1, RSTRING(mesg)->len, stderr);
- }
- }
-
- eclass = CLASS_OF(ruby_errinfo);
- PUSH_TAG(PROT_NONE);
- if (EXEC_TAG() == 0) {
- VALUE e = rb_obj_as_string(ruby_errinfo);
- einfo = RSTRING(e)->ptr;
- elen = RSTRING(e)->len;
- }
- else {
- einfo = "";
- elen = 0;
- }
- POP_TAG();
- if (eclass == rb_eRuntimeError && elen == 0) {
- fprintf(stderr, ": unhandled exception\n");
- }
- else {
- VALUE epath;
-
- epath = rb_class_path(eclass);
- if (elen == 0) {
- fprintf(stderr, ": ");
- fwrite(RSTRING(epath)->ptr, 1, RSTRING(epath)->len, stderr);
- putc('\n', stderr);
- }
- else {
- char *tail = 0;
- int len = elen;
-
- if (RSTRING(epath)->ptr[0] == '#') epath = 0;
- if (tail = strchr(einfo, '\n')) {
- len = tail - einfo;
- tail++; /* skip newline */
- }
- fprintf(stderr, ": ");
- fwrite(einfo, 1, len, stderr);
- if (epath) {
- fprintf(stderr, " (");
- fwrite(RSTRING(epath)->ptr, 1, RSTRING(epath)->len, stderr);
- fprintf(stderr, ")\n");
- }
- if (tail) {
- fwrite(tail, 1, elen-len-1, stderr);
- putc('\n', stderr);
- }
- }
- }
-
- if (!NIL_P(errat)) {
- int i;
- struct RArray *ep = RARRAY(errat);
-
-#define TRACE_MAX (TRACE_HEAD+TRACE_TAIL+5)
-#define TRACE_HEAD 8
-#define TRACE_TAIL 5
-
- ep = RARRAY(errat);
- for (i=1; i<ep->len; i++) {
- if (TYPE(ep->ptr[i]) == T_STRING) {
- fprintf(stderr, "\tfrom %s\n", RSTRING(ep->ptr[i])->ptr);
- }
- if (i == TRACE_HEAD && ep->len > TRACE_MAX) {
- fprintf(stderr, "\t ... %ld levels...\n",
- ep->len - TRACE_HEAD - TRACE_TAIL);
- i = ep->len - TRACE_TAIL;
- }
- }
- }
-}
-
-#if !defined(NT) && !defined(__MACOS__)
-extern char **environ;
-#endif
-char **rb_origenviron;
-
-void rb_call_inits _((void));
-void Init_stack _((void*));
-void Init_heap _((void));
-void Init_ext _((void));
-
-void
-ruby_init()
-{
- static int initialized = 0;
- static struct FRAME frame;
- static struct iter iter;
- int state;
-
- if (initialized)
- return;
- initialized = 1;
-
- ruby_frame = top_frame = &frame;
- ruby_iter = &iter;
-
-#ifdef __MACOS__
- rb_origenviron = 0;
-#else
- rb_origenviron = environ;
-#endif
-
- Init_stack(0);
- Init_heap();
- PUSH_SCOPE();
- ruby_scope->local_vars = 0;
- ruby_scope->local_tbl = 0;
- top_scope = ruby_scope;
- /* default visibility is private at toplevel */
- SCOPE_SET(SCOPE_PRIVATE);
-
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- rb_call_inits();
- ruby_class = rb_cObject;
- ruby_frame->self = ruby_top_self;
- top_cref = rb_node_newnode(NODE_CREF,rb_cObject,0,0);
- ruby_cref = top_cref;
- ruby_frame->cbase = (VALUE)ruby_cref;
- rb_define_global_const("TOPLEVEL_BINDING", rb_f_binding(ruby_top_self));
-#ifdef __MACOS__
- _macruby_init();
-#endif
- ruby_prog_init();
- }
- POP_TAG();
- if (state) error_print();
- POP_SCOPE();
- ruby_scope = top_scope;
-}
-
-static VALUE
-eval_node(self, node)
- VALUE self;
- NODE *node;
-{
- NODE *beg_tree = ruby_eval_tree_begin;
-
- ruby_eval_tree_begin = 0;
- if (beg_tree) {
- rb_eval(self, beg_tree);
- }
-
- if (!node) return Qnil;
- return rb_eval(self, node);
-}
-
-int ruby_in_eval;
-
-static void rb_thread_cleanup _((void));
-static void rb_thread_wait_other_threads _((void));
-
-static int exit_status;
-
-static int
-error_handle(ex)
- int ex;
-{
- switch (ex & TAG_MASK) {
- case 0:
- ex = 0;
- break;
-
- case TAG_RETURN:
- error_pos();
- fprintf(stderr, ": unexpected return\n");
- ex = 1;
- break;
- case TAG_NEXT:
- error_pos();
- fprintf(stderr, ": unexpected next\n");
- ex = 1;
- break;
- case TAG_BREAK:
- error_pos();
- fprintf(stderr, ": unexpected break\n");
- ex = 1;
- break;
- case TAG_REDO:
- error_pos();
- fprintf(stderr, ": unexpected redo\n");
- ex = 1;
- break;
- case TAG_RETRY:
- error_pos();
- fprintf(stderr, ": retry outside of rescue clause\n");
- ex = 1;
- break;
- case TAG_RAISE:
- case TAG_FATAL:
- if (rb_obj_is_kind_of(ruby_errinfo, rb_eSystemExit)) {
- ex = exit_status;
- }
- else {
- error_print();
- ex = 1;
- }
- break;
- default:
- rb_bug("Unknown longjmp status %d", ex);
- break;
- }
- return ex;
-}
-
-void
-ruby_options(argc, argv)
- int argc;
- char **argv;
-{
- int state;
-
- PUSH_TAG(PROT_NONE)
- if ((state = EXEC_TAG()) == 0) {
- ruby_process_options(argc, argv);
- }
- POP_TAG();
- if (state) {
- trace_func = 0;
- tracing = 0;
- exit(error_handle(state));
- }
-}
-
-void rb_exec_end_proc _((void));
-
-void
-ruby_finalize()
-{
- int state;
-
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- rb_trap_exit();
- rb_exec_end_proc();
- rb_gc_call_finalizer_at_exit();
- }
- POP_TAG();
-}
-
-void
-ruby_stop(ex)
- int ex;
-{
- int state;
-
- PUSH_TAG(PROT_NONE);
- PUSH_ITER(ITER_NOT);
- if ((state = EXEC_TAG()) == 0) {
- rb_thread_cleanup();
- rb_thread_wait_other_threads();
- }
- else if (ex == 0) {
- ex = state;
- }
- POP_ITER();
- POP_TAG();
-
- trace_func = 0;
- tracing = 0;
- ex = error_handle(ex);
- ruby_finalize();
- exit(ex);
-}
-
-void
-ruby_run()
-{
- int state;
- static int ex;
- volatile NODE *tmp;
-
- if (ruby_nerrs > 0) exit(ruby_nerrs);
-
- Init_stack((void*)&tmp);
- PUSH_TAG(PROT_NONE);
- PUSH_ITER(ITER_NOT);
- if ((state = EXEC_TAG()) == 0) {
- eval_node(ruby_top_self, ruby_eval_tree);
- }
- POP_ITER();
- POP_TAG();
-
- if (state && !ex) ex = state;
- ruby_stop(ex);
-}
-
-static void
-compile_error(at)
- const char *at;
-{
- VALUE str;
-
- ruby_nerrs = 0;
- str = rb_str_buf_new2("compile error");
- if (at) {
- rb_str_buf_cat2(str, " in ");
- rb_str_buf_cat2(str, at);
- }
- rb_str_buf_cat(str, "\n", 1);
- if (!NIL_P(ruby_errinfo)) {
- rb_str_append(str, ruby_errinfo);
- }
- rb_exc_raise(rb_exc_new3(rb_eSyntaxError, str));
-}
-
-VALUE
-rb_eval_string(str)
- const char *str;
-{
- VALUE v;
- char *oldsrc = ruby_sourcefile;
-
- ruby_sourcefile = rb_source_filename("(eval)");
- v = eval(ruby_top_self, rb_str_new2(str), Qnil, 0, 0);
- ruby_sourcefile = oldsrc;
-
- return v;
-}
-
-VALUE
-rb_eval_string_protect(str, state)
- const char *str;
- int *state;
-{
- VALUE result; /* OK */
- int status;
-
- PUSH_TAG(PROT_NONE);
- if ((status = EXEC_TAG()) == 0) {
- result = rb_eval_string(str);
- }
- POP_TAG();
- if (state) {
- *state = status;
- }
- if (status != 0) {
- return Qnil;
- }
-
- return result;
-}
-
-VALUE
-rb_eval_string_wrap(str, state)
- const char *str;
- int *state;
-{
- int status;
- VALUE self = ruby_top_self;
- VALUE wrapper = ruby_wrapper;
- VALUE val;
-
- PUSH_CLASS();
- ruby_class = ruby_wrapper = rb_module_new();
- ruby_top_self = rb_obj_clone(ruby_top_self);
- rb_extend_object(ruby_top_self, ruby_wrapper);
- PUSH_FRAME();
- ruby_frame->last_func = 0;
- ruby_frame->last_class = 0;
- ruby_frame->self = self;
- ruby_frame->cbase = (VALUE)rb_node_newnode(NODE_CREF,ruby_wrapper,0,0);
- PUSH_SCOPE();
-
- val = rb_eval_string_protect(str, &status);
- ruby_top_self = self;
-
- POP_SCOPE();
- POP_FRAME();
- POP_CLASS();
- ruby_wrapper = wrapper;
- if (state) {
- *state = status;
- }
- else if (status) {
- JUMP_TAG(status);
- }
- return val;
-}
-
-static void
-localjump_error(mesg, status)
- const char *mesg;
-{
- VALUE exc = rb_exc_new2(rb_eLocalJumpError, mesg);
- rb_iv_set(exc, "@status", status);
- rb_exc_raise(exc);
-}
-
-static VALUE
-localjump_exitstatus(exc)
- VALUE exc;
-{
- return rb_iv_get(exc, "@status");
-}
-
-static void
-jump_tag_but_local_jump(state)
- int state;
-{
- switch (state) {
- case 0:
- break;
- case TAG_RETURN:
- localjump_error("unexpected return", Qnil);
- break;
- case TAG_NEXT:
- localjump_error("unexpected next", Qnil);
- break;
- case TAG_BREAK:
- localjump_error("unexpected break", Qnil);
- break;
- case TAG_REDO:
- localjump_error("unexpected redo", Qnil);
- break;
- case TAG_RETRY:
- localjump_error("retry outside of rescue clause", Qnil);
- break;
- default:
- JUMP_TAG(state);
- break;
- }
-}
-
-VALUE
-rb_eval_cmd(cmd, arg, tcheck)
- VALUE cmd, arg;
- int tcheck;
-{
- int state;
- VALUE val; /* OK */
- struct SCOPE *saved_scope;
- volatile int safe = ruby_safe_level;
-
- if (TYPE(cmd) != T_STRING) {
- PUSH_ITER(ITER_NOT);
- val = rb_funcall2(cmd, rb_intern("call"), RARRAY(arg)->len, RARRAY(arg)->ptr);
- POP_ITER();
- return val;
- }
-
- saved_scope = ruby_scope;
- ruby_scope = top_scope;
- PUSH_FRAME();
- ruby_frame->last_func = 0;
- ruby_frame->last_class = 0;
- ruby_frame->self = ruby_top_self;
- ruby_frame->cbase = (VALUE)rb_node_newnode(NODE_CREF,0,0,0);
- RNODE(ruby_frame->cbase)->nd_clss = ruby_wrapper ? ruby_wrapper : rb_cObject;
-
- if (tcheck && OBJ_TAINTED(cmd)) {
- ruby_safe_level = 4;
- }
-
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- val = eval(ruby_top_self, cmd, Qnil, 0, 0);
- }
-
- if (ruby_scope->flags & SCOPE_DONT_RECYCLE)
- scope_dup(saved_scope);
- ruby_scope = saved_scope;
- ruby_safe_level = safe;
- POP_TAG();
- POP_FRAME();
-
- jump_tag_but_local_jump(state);
- return val;
-}
-
-static VALUE
-rb_trap_eval(cmd, sig)
- VALUE cmd;
- int sig;
-{
- int state;
- VALUE val; /* OK */
-
- PUSH_TAG(PROT_NONE);
- PUSH_ITER(ITER_NOT);
- if ((state = EXEC_TAG()) == 0) {
- val = rb_eval_cmd(cmd, rb_ary_new3(1, INT2FIX(sig)), 0);
- }
- POP_ITER();
- POP_TAG();
- if (state) {
- rb_trap_immediate = 0;
- JUMP_TAG(state);
- }
- return val;
-}
-
-static VALUE
-superclass(self, node)
- VALUE self;
- NODE *node;
-{
- VALUE val; /* OK */
- int state;
-
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- val = rb_eval(self, node);
- }
- POP_TAG();
- if (state) {
- superclass_error:
- switch (nd_type(node)) {
- case NODE_COLON2:
- rb_raise(rb_eTypeError, "undefined superclass `%s'",
- rb_id2name(node->nd_mid));
- case NODE_CONST:
- rb_raise(rb_eTypeError, "undefined superclass `%s'",
- rb_id2name(node->nd_vid));
- default:
- break;
- }
- JUMP_TAG(state);
- }
- if (TYPE(val) != T_CLASS) goto superclass_error;
- if (FL_TEST(val, FL_SINGLETON)) {
- rb_raise(rb_eTypeError, "can't make subclass of virtual class");
- }
-
- return val;
-}
-
-#define ruby_cbase (RNODE(ruby_frame->cbase)->nd_clss)
-
-static VALUE
-ev_const_defined(cref, id, self)
- NODE *cref;
- ID id;
- VALUE self;
-{
- NODE *cbase = cref;
-
- while (cbase && cbase->nd_next) {
- struct RClass *klass = RCLASS(cbase->nd_clss);
-
- if (NIL_P(klass)) return rb_const_defined(CLASS_OF(self), id);
- if (klass->iv_tbl && st_lookup(klass->iv_tbl, id, 0)) {
- return Qtrue;
- }
- cbase = cbase->nd_next;
- }
- return rb_const_defined(cref->nd_clss, id);
-}
-
-static VALUE
-ev_const_get(cref, id, self)
- NODE *cref;
- ID id;
- VALUE self;
-{
- NODE *cbase = cref;
- VALUE result;
-
- while (cbase && cbase->nd_next) {
- VALUE klass = cbase->nd_clss;
-
- if (NIL_P(klass)) return rb_const_get(CLASS_OF(self), id);
- if (RCLASS(klass)->iv_tbl && st_lookup(RCLASS(klass)->iv_tbl, id, &result)) {
- return result;
- }
- cbase = cbase->nd_next;
- }
- return rb_const_get(cref->nd_clss, id);
-}
-
-static VALUE
-cvar_cbase()
-{
- NODE *cref = RNODE(ruby_frame->cbase);
-
- while (cref && cref->nd_next && FL_TEST(cref->nd_clss, FL_SINGLETON)) {
- cref = cref->nd_next;
- if (!cref->nd_next) {
- rb_warn("class variable access from toplevel singleton method");
- }
- }
- return cref->nd_clss;
-}
-
-static VALUE
-rb_mod_nesting()
-{
- NODE *cbase = RNODE(ruby_frame->cbase);
- VALUE ary = rb_ary_new();
-
- while (cbase && cbase->nd_next) {
- if (!NIL_P(cbase->nd_clss)) rb_ary_push(ary, cbase->nd_clss);
- cbase = cbase->nd_next;
- }
- return ary;
-}
-
-static VALUE
-rb_mod_s_constants()
-{
- NODE *cbase = RNODE(ruby_frame->cbase);
- void *data = 0;
-
- while (cbase) {
- if (!NIL_P(cbase->nd_clss)) {
- data = rb_mod_const_at(cbase->nd_clss, data);
- }
- cbase = cbase->nd_next;
- }
-
- if (!NIL_P(ruby_cbase)) {
- data = rb_mod_const_of(ruby_cbase, data);
- }
- return rb_const_list(data);
-}
-
-void
-rb_frozen_class_p(klass)
- VALUE klass;
-{
- char *desc = "something(?!)";
-
- if (OBJ_FROZEN(klass)) {
- if (FL_TEST(klass, FL_SINGLETON))
- desc = "object";
- else {
- switch (TYPE(klass)) {
- case T_MODULE:
- case T_ICLASS:
- desc = "module"; break;
- case T_CLASS:
- desc = "class"; break;
- }
- }
- rb_error_frozen(desc);
- }
-}
-
-void
-rb_undef(klass, id)
- VALUE klass;
- ID id;
-{
- VALUE origin;
- NODE *body;
-
- if (ruby_class == rb_cObject) {
- rb_secure(4);
- }
- if (rb_safe_level() >= 4 && !OBJ_TAINTED(klass)) {
- rb_raise(rb_eSecurityError, "Insecure: can't undef");
- if (id == __id__ || id == __send__ || id == init) {
- rb_name_error(id, "undefining `%s' prohibited", rb_id2name(id));
- }
- }
- rb_frozen_class_p(klass);
- if (id == __id__ || id == __send__ || id == init) {
- rb_warn("undefining `%s' may cause serious problem", rb_id2name(id));
- }
- body = search_method(ruby_class, id, &origin);
- if (!body || !body->nd_body) {
- char *s0 = " class";
- VALUE c = klass;
-
- if (FL_TEST(c, FL_SINGLETON)) {
- VALUE obj = rb_iv_get(klass, "__attached__");
-
- switch (TYPE(obj)) {
- case T_MODULE:
- case T_CLASS:
- c = obj;
- s0 = "";
- }
- }
- else if (TYPE(c) == T_MODULE) {
- s0 = " module";
- }
- rb_name_error(id, "undefined method `%s' for%s `%s'",
- rb_id2name(id),s0,rb_class2name(c));
- }
- rb_add_method(klass, id, 0, NOEX_PUBLIC);
- if (FL_TEST(klass, FL_SINGLETON)) {
- rb_funcall(rb_iv_get(klass, "__attached__"),
- singleton_undefined, 1, ID2SYM(id));
- }
- else {
- rb_funcall(klass, undefined, 1, ID2SYM(id));
- }
-}
-
-static VALUE
-rb_mod_undef_method(mod, name)
- VALUE mod, name;
-{
- rb_undef(mod, rb_to_id(name));
- return mod;
-}
-
-void
-rb_alias(klass, name, def)
- VALUE klass;
- ID name, def;
-{
- VALUE origin;
- NODE *orig, *body;
-
- rb_frozen_class_p(klass);
- if (name == def) return;
- if (klass == rb_cObject) {
- rb_secure(4);
- }
- orig = search_method(klass, def, &origin);
- if (!orig || !orig->nd_body) {
- if (TYPE(klass) == T_MODULE) {
- orig = search_method(rb_cObject, def, &origin);
- }
- }
- if (!orig || !orig->nd_body) {
- print_undef(klass, def);
- }
- body = orig->nd_body;
- orig->nd_cnt++;
- if (nd_type(body) == NODE_FBODY) { /* was alias */
- def = body->nd_mid;
- origin = body->nd_orig;
- body = body->nd_head;
- }
-
- rb_clear_cache_by_id(name);
- st_insert(RCLASS(klass)->m_tbl, name,
- NEW_METHOD(NEW_FBODY(body, def, origin), orig->nd_noex));
- if (FL_TEST(klass, FL_SINGLETON)) {
- rb_funcall(rb_iv_get(klass, "__attached__"),
- singleton_added, 1, ID2SYM(name));
- }
- else {
- rb_funcall(klass, added, 1, ID2SYM(name));
- }
-}
-
-static VALUE
-rb_mod_alias_method(mod, newname, oldname)
- VALUE mod, newname, oldname;
-{
- rb_alias(mod, rb_to_id(newname), rb_to_id(oldname));
- return mod;
-}
-
-static NODE*
-copy_node_scope(node, rval)
- NODE *node;
- VALUE rval;
-{
- NODE *copy = rb_node_newnode(NODE_SCOPE,0,rval,node->nd_next);
-
- if (node->nd_tbl) {
- copy->nd_tbl = ALLOC_N(ID, node->nd_tbl[0]+1);
- MEMCPY(copy->nd_tbl, node->nd_tbl, ID, node->nd_tbl[0]+1);
- }
- else {
- copy->nd_tbl = 0;
- }
- return copy;
-}
-
-#ifdef C_ALLOCA
-# define TMP_PROTECT NODE * volatile tmp__protect_tmp=0
-# define TMP_ALLOC(n) \
- (tmp__protect_tmp = rb_node_newnode(NODE_ALLOCA, \
- ALLOC_N(VALUE,n),tmp__protect_tmp,n), \
- (void*)tmp__protect_tmp->nd_head)
-#else
-# define TMP_PROTECT typedef int foobazzz
-# define TMP_ALLOC(n) ALLOCA_N(VALUE,n)
-#endif
-
-#define SETUP_ARGS(anode) {\
- NODE *n = anode;\
- if (!n) {\
- argc = 0;\
- argv = 0;\
- }\
- else if (nd_type(n) == NODE_ARRAY) {\
- argc=n->nd_alen;\
- if (argc > 0) {\
- char *file = ruby_sourcefile;\
- int line = ruby_sourceline;\
- int i;\
- n = anode;\
- argv = TMP_ALLOC(argc);\
- for (i=0;i<argc;i++) {\
- argv[i] = rb_eval(self,n->nd_head);\
- n=n->nd_next;\
- }\
- ruby_sourcefile = file;\
- ruby_sourceline = line;\
- }\
- else {\
- argc = 0;\
- argv = 0;\
- }\
- }\
- else {\
- VALUE args = rb_eval(self,n);\
- char *file = ruby_sourcefile;\
- int line = ruby_sourceline;\
- if (TYPE(args) != T_ARRAY)\
- args = rb_ary_to_ary(args);\
- argc = RARRAY(args)->len;\
- argv = ALLOCA_N(VALUE, argc);\
- MEMCPY(argv, RARRAY(args)->ptr, VALUE, argc);\
- ruby_sourcefile = file;\
- ruby_sourceline = line;\
- }\
-}
-
-#define BEGIN_CALLARGS {\
- struct BLOCK *tmp_block = ruby_block;\
- if (ruby_iter->iter == ITER_PRE) {\
- ruby_block = ruby_block->prev;\
- }\
- PUSH_ITER(ITER_NOT);
-
-#define END_CALLARGS \
- ruby_block = tmp_block;\
- POP_ITER();\
-}
-
-#define MATCH_DATA *rb_svar(node->nd_cnt)
-
-static char* is_defined _((VALUE, NODE*, char*));
-
-static char*
-arg_defined(self, node, buf, type)
- VALUE self;
- NODE *node;
- char *buf;
- char *type;
-{
- int argc;
- int i;
-
- if (!node) return type; /* no args */
- if (nd_type(node) == NODE_ARRAY) {
- argc=node->nd_alen;
- if (argc > 0) {
- for (i=0;i<argc;i++) {
- if (!is_defined(self, node->nd_head, buf))
- return 0;
- node = node->nd_next;
- }
- }
- }
- else if (!is_defined(self, node, buf)) {
- return 0;
- }
- return type;
-}
-
-static char*
-is_defined(self, node, buf)
- VALUE self;
- NODE *node; /* OK */
- char *buf;
-{
- VALUE val; /* OK */
- int state;
-
- again:
- if (!node) return "expression";
- switch (nd_type(node)) {
- case NODE_SUPER:
- case NODE_ZSUPER:
- if (ruby_frame->last_func == 0) return 0;
- else if (ruby_frame->last_class == 0) return 0;
- else if (rb_method_boundp(RCLASS(ruby_frame->last_class)->super,
- ruby_frame->last_func, 0)) {
- if (nd_type(node) == NODE_SUPER) {
- return arg_defined(self, node->nd_args, buf, "super");
- }
- return "super";
- }
- break;
-
- case NODE_VCALL:
- case NODE_FCALL:
- val = self;
- goto check_bound;
-
- case NODE_CALL:
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- val = rb_eval(self, node->nd_recv);
- }
- POP_TAG();
- if (state) {
- ruby_errinfo = Qnil;
- return 0;
- }
- check_bound:
- {
- int call = nd_type(node)== NODE_CALL;
-
- val = CLASS_OF(val);
- if (call) {
- int noex;
- ID id = node->nd_mid;
-
- if (!rb_get_method_body(&val, &id, &noex))
- break;
- if ((noex & NOEX_PRIVATE))
- break;
- if ((noex & NOEX_PROTECTED) &&
- !rb_obj_is_kind_of(self, rb_class_real(val)))
- break;
- }
- else if (!rb_method_boundp(val, node->nd_mid, call))
- break;
- return arg_defined(self, node->nd_args, buf, "method");
- }
- break;
-
- case NODE_MATCH2:
- case NODE_MATCH3:
- return "method";
-
- case NODE_YIELD:
- if (rb_block_given_p()) {
- return "yield";
- }
- break;
-
- case NODE_SELF:
- return "self";
-
- case NODE_NIL:
- return "nil";
-
- case NODE_TRUE:
- return "true";
-
- case NODE_FALSE:
- return "false";
-
- case NODE_ATTRSET:
- case NODE_OP_ASGN1:
- case NODE_OP_ASGN2:
- case NODE_MASGN:
- case NODE_LASGN:
- case NODE_DASGN:
- case NODE_DASGN_CURR:
- case NODE_GASGN:
- case NODE_CDECL:
- case NODE_CVDECL:
- case NODE_CVASGN:
- return "assignment";
-
- case NODE_LVAR:
- return "local-variable";
- case NODE_DVAR:
- return "local-variable(in-block)";
-
- case NODE_GVAR:
- if (rb_gvar_defined(node->nd_entry)) {
- return "global-variable";
- }
- break;
-
- case NODE_IVAR:
- if (rb_ivar_defined(self, node->nd_vid)) {
- return "instance-variable";
- }
- break;
-
- case NODE_CONST:
- if (ev_const_defined(RNODE(ruby_frame->cbase), node->nd_vid, self)) {
- return "constant";
- }
- break;
-
- case NODE_CVAR:
- if (rb_cvar_defined(cvar_cbase(), node->nd_vid)) {
- return "class variable";
- }
- break;
-
- case NODE_COLON2:
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- val = rb_eval(self, node->nd_head);
- }
- POP_TAG();
- if (state) {
- ruby_errinfo = Qnil;
- return 0;
- }
- else {
- switch (TYPE(val)) {
- case T_CLASS:
- case T_MODULE:
- if (rb_const_defined_at(val, node->nd_mid))
- return "constant";
- break;
- default:
- if (rb_method_boundp(CLASS_OF(val), node->nd_mid, 1)) {
- return "method";
- }
- }
- }
- break;
-
- case NODE_NTH_REF:
- if (RTEST(rb_reg_nth_defined(node->nd_nth, MATCH_DATA))) {
- sprintf(buf, "$%d", node->nd_nth);
- return buf;
- }
- break;
-
- case NODE_BACK_REF:
- if (RTEST(rb_reg_nth_defined(0, MATCH_DATA))) {
- sprintf(buf, "$%c", node->nd_nth);
- return buf;
- }
- break;
-
- case NODE_NEWLINE:
- node = node->nd_next;
- goto again;
-
- default:
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- rb_eval(self, node);
- }
- POP_TAG();
- if (!state) {
- return "expression";
- }
- ruby_errinfo = Qnil;
- break;
- }
- return 0;
-}
-
-static int handle_rescue _((VALUE,NODE*));
-
-static void blk_free();
-
-static VALUE
-rb_obj_is_block(block)
- VALUE block;
-{
- if (TYPE(block) == T_DATA && RDATA(block)->dfree == (RUBY_DATA_FUNC)blk_free) {
- return Qtrue;
- }
- return Qfalse;
-}
-
-static VALUE
-rb_obj_is_proc(proc)
- VALUE proc;
-{
- if (rb_obj_is_block(proc) && rb_obj_is_kind_of(proc, rb_cProc)) {
- return Qtrue;
- }
- return Qfalse;
-}
-
-static VALUE
-set_trace_func(obj, trace)
- VALUE obj, trace;
-{
- if (NIL_P(trace)) {
- trace_func = 0;
- return Qnil;
- }
- if (!rb_obj_is_proc(trace)) {
- rb_raise(rb_eTypeError, "trace_func needs to be Proc");
- }
- return trace_func = trace;
-}
-
-static void
-call_trace_func(event, file, line, self, id, klass)
- char *event;
- char *file;
- int line;
- VALUE self;
- ID id;
- VALUE klass; /* OK */
-{
- int state;
- struct FRAME *prev;
- char *file_save = ruby_sourcefile;
- int line_save = ruby_sourceline;
- VALUE srcfile;
-
- if (!trace_func) return;
- if (tracing) return;
-
- tracing = 1;
- prev = ruby_frame;
- PUSH_FRAME();
- *ruby_frame = *prev;
- ruby_frame->prev = prev;
- ruby_frame->iter = 0; /* blocks not available anyway */
-
- if (file) {
- ruby_frame->line = ruby_sourceline = line;
- ruby_frame->file = ruby_sourcefile = file;
- }
- if (klass) {
- if (TYPE(klass) == T_ICLASS) {
- klass = RBASIC(klass)->klass;
- }
- else if (FL_TEST(klass, FL_SINGLETON)) {
- klass = self;
- }
- }
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- srcfile = rb_str_new2(ruby_sourcefile?ruby_sourcefile:"(ruby)");
- proc_invoke(trace_func, rb_ary_new3(6, rb_str_new2(event),
- srcfile,
- INT2FIX(ruby_sourceline),
- id?ID2SYM(id):Qnil,
- self?rb_f_binding(self):Qnil,
- klass),
- Qtrue, Qundef);
- }
- POP_TMPTAG(); /* do not propagate retval */
- POP_FRAME();
-
- tracing = 0;
- ruby_sourceline = line_save;
- ruby_sourcefile = file_save;
- if (state) JUMP_TAG(state);
-}
-
-static VALUE
-svalue_to_avalue(v)
- VALUE v;
-{
- if (NIL_P(v)) return rb_ary_new2(0);
- if (TYPE(v) == T_ARRAY) {
- if (RARRAY(v)->len > 1) return v;
- return rb_ary_new3(1, v);
- }
- else {
- v = rb_ary_to_ary(v);
- }
- return v;
-}
-
-static VALUE
-avalue_to_svalue(v)
- VALUE v;
-{
- if (TYPE(v) != T_ARRAY) {
- v = rb_ary_to_ary(v);
- }
- if (RARRAY(v)->len == 0) {
- return Qnil;
- }
- if (RARRAY(v)->len == 1) {
- return RARRAY(v)->ptr[0];
- }
- return v;
-}
-
-static VALUE
-svalue_to_mvalue(v)
- VALUE v;
-{
- if (NIL_P(v)) return rb_ary_new2(0);
- if (TYPE(v) == T_ARRAY) {
- return v;
- }
- else {
- v = rb_ary_to_ary(v);
- }
- return v;
-}
-
-static VALUE
-mvalue_to_svalue(v)
- VALUE v;
-{
- if (TYPE(v) != T_ARRAY) {
- v = rb_ary_to_ary(v);
- }
- if (RARRAY(v)->len == 0) {
- return Qnil;
- }
- if (RARRAY(v)->len == 1 && TYPE(RARRAY(v)->ptr[0]) != T_ARRAY) {
- return RARRAY(v)->ptr[0];
- }
- return v;
-}
-
-static void return_check _((void));
-#define return_value(v) prot_tag->retval = (v)
-
-static VALUE
-rb_eval(self, n)
- VALUE self;
- NODE *n;
-{
- NODE * volatile node = n;
- int state;
- volatile VALUE result = Qnil;
-
-#define RETURN(v) { result = (v); goto finish; }
-
- again:
- if (!node) RETURN(Qnil);
-
- switch (nd_type(node)) {
- case NODE_BLOCK:
- while (node->nd_next) {
- rb_eval(self, node->nd_head);
- node = node->nd_next;
- }
- node = node->nd_head;
- goto again;
-
- case NODE_POSTEXE:
- rb_f_END();
- nd_set_type(node, NODE_NIL); /* exec just once */
- result = Qnil;
- break;
-
- /* begin .. end without clauses */
- case NODE_BEGIN:
- node = node->nd_body;
- goto again;
-
- /* nodes for speed-up(default match) */
- case NODE_MATCH:
- result = rb_reg_match2(node->nd_lit);
- break;
-
- /* nodes for speed-up(literal match) */
- case NODE_MATCH2:
- result = rb_reg_match(rb_eval(self,node->nd_recv),
- rb_eval(self,node->nd_value));
- break;
-
- /* nodes for speed-up(literal match) */
- case NODE_MATCH3:
- {
- VALUE r = rb_eval(self,node->nd_recv);
- VALUE l = rb_eval(self,node->nd_value);
- if (TYPE(l) == T_STRING) {
- result = rb_reg_match(r, l);
- }
- else {
- result = rb_funcall(l, match, 1, r);
- }
- }
- break;
-
- /* node for speed-up(top-level loop for -n/-p) */
- case NODE_OPT_N:
- PUSH_TAG(PROT_NONE);
- switch (state = EXEC_TAG()) {
- case 0:
- opt_n_next:
- while (!NIL_P(rb_gets())) {
- opt_n_redo:
- rb_eval(self, node->nd_body);
- }
- break;
-
- case TAG_REDO:
- state = 0;
- goto opt_n_redo;
- case TAG_NEXT:
- state = 0;
- goto opt_n_next;
- case TAG_BREAK:
- state = 0;
- default:
- break;
- }
- POP_TAG();
- if (state) JUMP_TAG(state);
- RETURN(Qnil);
-
- case NODE_SELF:
- RETURN(self);
-
- case NODE_NIL:
- RETURN(Qnil);
-
- case NODE_TRUE:
- RETURN(Qtrue);
-
- case NODE_FALSE:
- RETURN(Qfalse);
-
- case NODE_IF:
- ruby_sourceline = nd_line(node);
- if (trace_func) {
- call_trace_func("line", node->nd_file, ruby_sourceline, self,
- ruby_frame->last_func,
- ruby_frame->last_class);
- }
- if (RTEST(rb_eval(self, node->nd_cond))) {
- node = node->nd_body;
- }
- else {
- node = node->nd_else;
- }
- goto again;
-
- case NODE_WHEN:
- while (node) {
- NODE *tag;
-
- if (nd_type(node) != NODE_WHEN) goto again;
- tag = node->nd_head;
- while (tag) {
- if (trace_func) {
- call_trace_func("line", tag->nd_file, nd_line(tag), self,
- ruby_frame->last_func,
- ruby_frame->last_class);
- }
- ruby_sourcefile = tag->nd_file;
- ruby_sourceline = nd_line(tag);
- if (nd_type(tag->nd_head) == NODE_WHEN) {
- VALUE v = rb_eval(self, tag->nd_head->nd_head);
- int i;
-
- if (TYPE(v) != T_ARRAY) v = rb_ary_to_ary(v);
- for (i=0; i<RARRAY(v)->len; i++) {
- if (RTEST(RARRAY(v)->ptr[i])) {
- node = node->nd_body;
- goto again;
- }
- }
- tag = tag->nd_next;
- continue;
- }
- if (RTEST(rb_eval(self, tag->nd_head))) {
- node = node->nd_body;
- goto again;
- }
- tag = tag->nd_next;
- }
- node = node->nd_next;
- }
- RETURN(Qnil);
-
- case NODE_CASE:
- {
- VALUE val;
-
- val = rb_eval(self, node->nd_head);
- node = node->nd_body;
- while (node) {
- NODE *tag;
-
- if (nd_type(node) != NODE_WHEN) {
- goto again;
- }
- tag = node->nd_head;
- while (tag) {
- if (trace_func) {
- call_trace_func("line", tag->nd_file, nd_line(tag), self,
- ruby_frame->last_func,
- ruby_frame->last_class);
- }
- ruby_sourcefile = tag->nd_file;
- ruby_sourceline = nd_line(tag);
- if (nd_type(tag->nd_head) == NODE_WHEN) {
- VALUE v = rb_eval(self, tag->nd_head->nd_head);
- int i;
-
- if (TYPE(v) != T_ARRAY) v = rb_ary_to_ary(v);
- for (i=0; i<RARRAY(v)->len; i++) {
- if (RTEST(rb_funcall2(RARRAY(v)->ptr[i], eqq, 1, &val))){
- node = node->nd_body;
- goto again;
- }
- }
- tag = tag->nd_next;
- continue;
- }
- if (RTEST(rb_funcall2(rb_eval(self, tag->nd_head), eqq, 1, &val))) {
- node = node->nd_body;
- goto again;
- }
- tag = tag->nd_next;
- }
- node = node->nd_next;
- }
- }
- RETURN(Qnil);
-
- case NODE_WHILE:
- PUSH_TAG(PROT_NONE);
- result = Qnil;
- switch (state = EXEC_TAG()) {
- case 0:
- ruby_sourceline = nd_line(node);
- if (node->nd_state && !RTEST(rb_eval(self, node->nd_cond)))
- goto while_out;
- do {
- while_redo:
- rb_eval(self, node->nd_body);
- while_next:
- ;
- } while (RTEST(rb_eval(self, node->nd_cond)));
- break;
-
- case TAG_REDO:
- state = 0;
- goto while_redo;
- case TAG_NEXT:
- state = 0;
- goto while_next;
- case TAG_BREAK:
- state = 0;
- result = prot_tag->retval;
- default:
- break;
- }
- while_out:
- POP_TAG();
- if (state) JUMP_TAG(state);
- RETURN(result);
-
- case NODE_UNTIL:
- PUSH_TAG(PROT_NONE);
- result = Qnil;
- switch (state = EXEC_TAG()) {
- case 0:
- ruby_sourceline = nd_line(node);
- if (node->nd_state && RTEST(rb_eval(self, node->nd_cond)))
- goto until_out;
- do {
- until_redo:
- rb_eval(self, node->nd_body);
- until_next:
- ;
- } while (!RTEST(rb_eval(self, node->nd_cond)));
- break;
-
- case TAG_REDO:
- state = 0;
- goto until_redo;
- case TAG_NEXT:
- state = 0;
- goto until_next;
- case TAG_BREAK:
- state = 0;
- result = prot_tag->retval;
- default:
- break;
- }
- until_out:
- POP_TAG();
- if (state) JUMP_TAG(state);
- RETURN(result);
-
- case NODE_BLOCK_PASS:
- result = block_pass(self, node);
- break;
-
- case NODE_ITER:
- case NODE_FOR:
- {
- iter_retry:
- PUSH_TAG(PROT_FUNC);
- PUSH_BLOCK(node->nd_var, node->nd_body);
-
- state = EXEC_TAG();
- if (state == 0) {
- PUSH_ITER(ITER_PRE);
- if (nd_type(node) == NODE_ITER) {
- result = rb_eval(self, node->nd_iter);
- }
- else {
- VALUE recv;
- char *file = ruby_sourcefile;
- int line = ruby_sourceline;
-
- _block.flags &= ~BLOCK_D_SCOPE;
- BEGIN_CALLARGS;
- recv = rb_eval(self, node->nd_iter);
- END_CALLARGS;
- ruby_sourcefile = file;
- ruby_sourceline = line;
- result = rb_call(CLASS_OF(recv),recv,each,0,0,0);
- }
- POP_ITER();
- }
- else if (_block.tag->dst == state) {
- state &= TAG_MASK;
- if (state == TAG_RETURN || state == TAG_BREAK) {
- result = prot_tag->retval;
- }
- }
- POP_BLOCK();
- POP_TAG();
- switch (state) {
- case 0:
- break;
-
- case TAG_RETRY:
- goto iter_retry;
-
- case TAG_BREAK:
- break;
-
- case TAG_RETURN:
- return_value(result);
- /* fall through */
- default:
- JUMP_TAG(state);
- }
- }
- break;
-
- case NODE_BREAK:
- if (node->nd_stts) {
- return_value(avalue_to_svalue(rb_eval(self, node->nd_stts)));
- }
- else {
- return_value(Qnil);
- }
- JUMP_TAG(TAG_BREAK);
- break;
-
- case NODE_NEXT:
- CHECK_INTS;
- if (node->nd_stts) {
- return_value(avalue_to_svalue(rb_eval(self, node->nd_stts)));
- }
- else {
- return_value(Qnil);
- }
- JUMP_TAG(TAG_NEXT);
- break;
-
- case NODE_REDO:
- CHECK_INTS;
- JUMP_TAG(TAG_REDO);
- break;
-
- case NODE_RETRY:
- CHECK_INTS;
- JUMP_TAG(TAG_RETRY);
- break;
-
- case NODE_RESTARGS:
- case NODE_RESTARY:
- result = rb_ary_to_ary(rb_eval(self, node->nd_head));
- break;
-
- case NODE_REXPAND:
- result = avalue_to_svalue(rb_eval(self, node->nd_head));
- break;
-
- case NODE_YIELD:
- if (node->nd_stts) {
- result = avalue_to_svalue(rb_eval(self, node->nd_stts));
- }
- else {
- result = Qnil;
- }
- result = rb_yield_0(result, 0, 0, 0);
- break;
-
- case NODE_RESCUE:
- retry_entry:
- {
- volatile VALUE e_info = ruby_errinfo;
-
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- result = rb_eval(self, node->nd_head);
- }
- POP_TAG();
- if (state == TAG_RAISE) {
- NODE * volatile resq = node->nd_resq;
-
- ruby_sourceline = nd_line(node);
- while (resq) {
- if (handle_rescue(self, resq)) {
- state = 0;
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- result = rb_eval(self, resq->nd_body);
- }
- POP_TAG();
- if (state == TAG_RETRY) {
- state = 0;
- ruby_errinfo = Qnil;
- goto retry_entry;
- }
- if (state != TAG_RAISE) {
- ruby_errinfo = e_info;
- }
- break;
- }
- resq = resq->nd_head; /* next rescue */
- }
- }
- else if (node->nd_else) { /* else clause given */
- if (!state) { /* no exception raised */
- result = rb_eval(self, node->nd_else);
- }
- }
- if (state) JUMP_TAG(state);
- }
- break;
-
- case NODE_ENSURE:
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- result = rb_eval(self, node->nd_head);
- }
- POP_TAG();
- if (node->nd_ensr) {
- VALUE retval = prot_tag->retval; /* save retval */
- VALUE errinfo = ruby_errinfo;
-
- rb_eval(self, node->nd_ensr);
- return_value(retval);
- ruby_errinfo = errinfo;
- }
- if (state) JUMP_TAG(state);
- break;
-
- case NODE_AND:
- result = rb_eval(self, node->nd_1st);
- if (!RTEST(result)) break;
- node = node->nd_2nd;
- goto again;
-
- case NODE_OR:
- result = rb_eval(self, node->nd_1st);
- if (RTEST(result)) break;
- node = node->nd_2nd;
- goto again;
-
- case NODE_NOT:
- if (RTEST(rb_eval(self, node->nd_body))) result = Qfalse;
- else result = Qtrue;
- break;
-
- case NODE_DOT2:
- case NODE_DOT3:
- result = rb_range_new(rb_eval(self, node->nd_beg),
- rb_eval(self, node->nd_end),
- nd_type(node) == NODE_DOT3);
- if (node->nd_state) break;
- if (nd_type(node->nd_beg) == NODE_LIT && FIXNUM_P(node->nd_beg->nd_lit) &&
- nd_type(node->nd_end) == NODE_LIT && FIXNUM_P(node->nd_end->nd_lit))
- {
- nd_set_type(node, NODE_LIT);
- node->nd_lit = result;
- }
- else {
- node->nd_state = 1;
- }
- break;
-
- case NODE_FLIP2: /* like AWK */
- {
- VALUE *flip = rb_svar(node->nd_cnt);
- if (!flip) rb_bug("unexpected local variable");
- if (!RTEST(*flip)) {
- if (RTEST(rb_eval(self, node->nd_beg))) {
- *flip = RTEST(rb_eval(self, node->nd_end))?Qfalse:Qtrue;
- result = Qtrue;
- }
- else {
- result = Qfalse;
- }
- }
- else {
- if (RTEST(rb_eval(self, node->nd_end))) {
- *flip = Qfalse;
- }
- result = Qtrue;
- }
- }
- break;
-
- case NODE_FLIP3: /* like SED */
- {
- VALUE *flip = rb_svar(node->nd_cnt);
- if (!flip) rb_bug("unexpected local variable");
- if (!RTEST(*flip)) {
- result = RTEST(rb_eval(self, node->nd_beg)) ? Qtrue : Qfalse;
- *flip = result;
- }
- else {
- if (RTEST(rb_eval(self, node->nd_end))) {
- *flip = Qfalse;
- }
- result = Qtrue;
- }
- }
- break;
-
- case NODE_RETURN:
- if (node->nd_stts) {
- return_value(avalue_to_svalue(rb_eval(self, node->nd_stts)));
- }
- else {
- return_value(Qnil);
- }
- return_check();
- JUMP_TAG(TAG_RETURN);
- break;
-
- case NODE_ARGSCAT:
- result = rb_ary_concat(rb_eval(self, node->nd_head),
- rb_eval(self, node->nd_body));
- break;
-
- case NODE_ARGSPUSH:
- result = rb_ary_push(rb_ary_dup(rb_eval(self, node->nd_head)),
- rb_eval(self, node->nd_body));
- break;
-
- case NODE_CALL:
- {
- VALUE recv;
- int argc; VALUE *argv; /* used in SETUP_ARGS */
- TMP_PROTECT;
-
- BEGIN_CALLARGS;
- recv = rb_eval(self, node->nd_recv);
- SETUP_ARGS(node->nd_args);
- END_CALLARGS;
-
- result = rb_call(CLASS_OF(recv),recv,node->nd_mid,argc,argv,0);
- }
- break;
-
- case NODE_FCALL:
- {
- int argc; VALUE *argv; /* used in SETUP_ARGS */
- TMP_PROTECT;
-
- BEGIN_CALLARGS;
- SETUP_ARGS(node->nd_args);
- END_CALLARGS;
-
- result = rb_call(CLASS_OF(self),self,node->nd_mid,argc,argv,1);
- }
- break;
-
- case NODE_VCALL:
- result = rb_call(CLASS_OF(self),self,node->nd_mid,0,0,2);
- break;
-
- case NODE_SUPER:
- case NODE_ZSUPER:
- {
- int argc; VALUE *argv; /* used in SETUP_ARGS */
- TMP_PROTECT;
-
- if (ruby_frame->last_class == 0) {
- rb_name_error(ruby_frame->last_func,
- "superclass method `%s' disabled",
- rb_id2name(ruby_frame->last_func));
- }
- if (nd_type(node) == NODE_ZSUPER) {
- argc = ruby_frame->argc;
- argv = ruby_frame->argv;
- }
- else {
- BEGIN_CALLARGS;
- SETUP_ARGS(node->nd_args);
- END_CALLARGS;
- }
-
- PUSH_ITER(ruby_iter->iter?ITER_PRE:ITER_NOT);
- result = rb_call(RCLASS(ruby_frame->last_class)->super,
- ruby_frame->self, ruby_frame->last_func,
- argc, argv, 3);
- POP_ITER();
- }
- break;
-
- case NODE_SCOPE:
- {
- struct FRAME frame;
- NODE *saved_cref = 0;
-
- frame = *ruby_frame;
- frame.tmp = ruby_frame;
- ruby_frame = &frame;
-
- PUSH_SCOPE();
- PUSH_TAG(PROT_NONE);
- if (node->nd_rval) {
- saved_cref = ruby_cref;
- ruby_cref = (NODE*)node->nd_rval;
- ruby_frame->cbase = node->nd_rval;
- }
- if (node->nd_tbl) {
- VALUE *vars = ALLOCA_N(VALUE, node->nd_tbl[0]+1);
- *vars++ = (VALUE)node;
- ruby_scope->local_vars = vars;
- rb_mem_clear(ruby_scope->local_vars, node->nd_tbl[0]);
- ruby_scope->local_tbl = node->nd_tbl;
- }
- else {
- ruby_scope->local_vars = 0;
- ruby_scope->local_tbl = 0;
- }
- if ((state = EXEC_TAG()) == 0) {
- result = rb_eval(self, node->nd_next);
- }
- POP_TAG();
- POP_SCOPE();
- ruby_frame = frame.tmp;
- if (saved_cref)
- ruby_cref = saved_cref;
- if (state) JUMP_TAG(state);
- }
- break;
-
- case NODE_OP_ASGN1:
- {
- int argc; VALUE *argv; /* used in SETUP_ARGS */
- VALUE recv, val;
- NODE *rval;
- TMP_PROTECT;
-
- recv = rb_eval(self, node->nd_recv);
- rval = node->nd_args->nd_head;
- SETUP_ARGS(node->nd_args->nd_next);
- val = rb_funcall2(recv, aref, argc-1, argv);
- switch (node->nd_mid) {
- case 0: /* OR */
- if (RTEST(val)) RETURN(val);
- val = rb_eval(self, rval);
- break;
- case 1: /* AND */
- if (!RTEST(val)) RETURN(val);
- val = rb_eval(self, rval);
- break;
- default:
- val = rb_funcall(val, node->nd_mid, 1, rb_eval(self, rval));
- }
- argv[argc-1] = val;
- rb_funcall2(recv, aset, argc, argv);
- result = val;
- }
- break;
-
- case NODE_OP_ASGN2:
- {
- ID id = node->nd_next->nd_vid;
- VALUE recv, val;
-
- recv = rb_eval(self, node->nd_recv);
- val = rb_funcall(recv, id, 0);
- switch (node->nd_next->nd_mid) {
- case 0: /* OR */
- if (RTEST(val)) RETURN(val);
- val = rb_eval(self, node->nd_value);
- break;
- case 1: /* AND */
- if (!RTEST(val)) RETURN(val);
- val = rb_eval(self, node->nd_value);
- break;
- default:
- val = rb_funcall(val, node->nd_next->nd_mid, 1,
- rb_eval(self, node->nd_value));
- }
-
- rb_funcall2(recv, node->nd_next->nd_aid, 1, &val);
- result = val;
- }
- break;
-
- case NODE_OP_ASGN_AND:
- result = rb_eval(self, node->nd_head);
- if (!RTEST(result)) break;
- node = node->nd_value;
- goto again;
-
- case NODE_OP_ASGN_OR:
- if ((node->nd_aid && !rb_ivar_defined(self, node->nd_aid)) ||
- !RTEST(result = rb_eval(self, node->nd_head))) {
- node = node->nd_value;
- goto again;
- }
- break;
-
- case NODE_MASGN:
- result = massign(self, node, rb_eval(self, node->nd_value),0);
- break;
-
- case NODE_LASGN:
- if (ruby_scope->local_vars == 0)
- rb_bug("unexpected local variable assignment");
- result = rb_eval(self, node->nd_value);
- ruby_scope->local_vars[node->nd_cnt] = result;
- break;
-
- case NODE_DASGN:
- result = rb_eval(self, node->nd_value);
- dvar_asgn(node->nd_vid, result);
- break;
-
- case NODE_DASGN_CURR:
- result = rb_eval(self, node->nd_value);
- dvar_asgn_curr(node->nd_vid, result);
- break;
-
- case NODE_GASGN:
- result = rb_eval(self, node->nd_value);
- rb_gvar_set(node->nd_entry, result);
- break;
-
- case NODE_IASGN:
- result = rb_eval(self, node->nd_value);
- rb_ivar_set(self, node->nd_vid, result);
- break;
-
- case NODE_CDECL:
- if (NIL_P(ruby_class)) {
- rb_raise(rb_eTypeError, "no class/module to define constant");
- }
- result = rb_eval(self, node->nd_value);
- rb_const_set(ruby_class, node->nd_vid, result);
- break;
-
- case NODE_CVDECL:
- if (NIL_P(ruby_cbase)) {
- rb_raise(rb_eTypeError, "no class/module to define class variable");
- }
- result = rb_eval(self, node->nd_value);
- rb_cvar_set(cvar_cbase(), node->nd_vid, result, Qtrue);
- break;
-
- case NODE_CVASGN:
- result = rb_eval(self, node->nd_value);
- rb_cvar_set(cvar_cbase(), node->nd_vid, result, Qfalse);
- break;
-
- case NODE_LVAR:
- if (ruby_scope->local_vars == 0) {
- rb_bug("unexpected local variable");
- }
- result = ruby_scope->local_vars[node->nd_cnt];
- break;
-
- case NODE_DVAR:
- result = rb_dvar_ref(node->nd_vid);
- break;
-
- case NODE_GVAR:
- result = rb_gvar_get(node->nd_entry);
- break;
-
- case NODE_IVAR:
- result = rb_ivar_get(self, node->nd_vid);
- break;
-
- case NODE_CONST:
- result = ev_const_get(RNODE(ruby_frame->cbase), node->nd_vid, self);
- break;
-
- case NODE_CVAR:
- result = rb_cvar_get(cvar_cbase(), node->nd_vid);
- break;
-
- case NODE_BLOCK_ARG:
- if (ruby_scope->local_vars == 0)
- rb_bug("unexpected block argument");
- if (rb_block_given_p()) {
- result = rb_f_lambda();
- ruby_scope->local_vars[node->nd_cnt] = result;
- }
- else {
- result = Qnil;
- }
- break;
-
- case NODE_COLON2:
- {
- VALUE klass;
-
- klass = rb_eval(self, node->nd_head);
- switch (TYPE(klass)) {
- case T_CLASS:
- case T_MODULE:
- break;
- default:
- return rb_funcall(klass, node->nd_mid, 0, 0);
- }
- result = rb_const_get(klass, node->nd_mid);
- }
- break;
-
- case NODE_COLON3:
- result = rb_const_get_at(rb_cObject, node->nd_mid);
- break;
-
- case NODE_NTH_REF:
- result = rb_reg_nth_match(node->nd_nth, MATCH_DATA);
- break;
-
- case NODE_BACK_REF:
- switch (node->nd_nth) {
- case '&':
- result = rb_reg_last_match(MATCH_DATA);
- break;
- case '`':
- result = rb_reg_match_pre(MATCH_DATA);
- break;
- case '\'':
- result = rb_reg_match_post(MATCH_DATA);
- break;
- case '+':
- result = rb_reg_match_last(MATCH_DATA);
- break;
- default:
- rb_bug("unexpected back-ref");
- }
- break;
-
- case NODE_HASH:
- {
- NODE *list;
- VALUE hash = rb_hash_new();
- VALUE key, val;
-
- list = node->nd_head;
- while (list) {
- key = rb_eval(self, list->nd_head);
- list = list->nd_next;
- if (list == 0)
- rb_bug("odd number list for Hash");
- val = rb_eval(self, list->nd_head);
- list = list->nd_next;
- rb_hash_aset(hash, key, val);
- }
- result = hash;
- }
- break;
-
- case NODE_ZARRAY: /* zero length list */
- result = rb_ary_new();
- break;
-
- case NODE_ARRAY:
- {
- VALUE ary;
- int i;
-
- i = node->nd_alen;
- ary = rb_ary_new2(i);
- for (i=0;node;node=node->nd_next) {
- RARRAY(ary)->ptr[i++] = rb_eval(self, node->nd_head);
- RARRAY(ary)->len = i;
- }
-
- result = ary;
- }
- break;
-
- case NODE_STR:
- result = rb_str_new3(node->nd_lit);
- break;
-
- case NODE_DSTR:
- case NODE_DXSTR:
- case NODE_DREGX:
- case NODE_DREGX_ONCE:
- {
- VALUE str, str2;
- NODE *list = node->nd_next;
-
- str = rb_str_new3(node->nd_lit);
- while (list) {
- if (list->nd_head) {
- switch (nd_type(list->nd_head)) {
- case NODE_STR:
- str2 = list->nd_head->nd_lit;
- break;
- case NODE_EVSTR:
- result = ruby_errinfo;
- ruby_errinfo = Qnil;
- ruby_sourceline = nd_line(node);
- ruby_in_eval++;
- list->nd_head = compile(list->nd_head->nd_lit,
- ruby_sourcefile,
- ruby_sourceline);
- ruby_eval_tree = 0;
- ruby_in_eval--;
- if (ruby_nerrs > 0) {
- compile_error("string expansion");
- }
- if (!NIL_P(result)) ruby_errinfo = result;
- /* fall through */
- default:
- str2 = rb_obj_as_string(rb_eval(self, list->nd_head));
- break;
- }
- rb_str_append(str, str2);
- OBJ_INFECT(str, str2);
- }
- list = list->nd_next;
- }
- switch (nd_type(node)) {
- case NODE_DREGX:
- result = rb_reg_new(RSTRING(str)->ptr, RSTRING(str)->len,
- node->nd_cflag);
- break;
- case NODE_DREGX_ONCE: /* regexp expand once */
- result = rb_reg_new(RSTRING(str)->ptr, RSTRING(str)->len,
- node->nd_cflag);
- nd_set_type(node, NODE_LIT);
- node->nd_lit = result;
- break;
- case NODE_DXSTR:
- result = rb_funcall(self, '`', 1, str);
- break;
- default:
- result = str;
- break;
- }
- }
- break;
-
- case NODE_XSTR:
- result = rb_funcall(self, '`', 1, node->nd_lit);
- break;
-
- case NODE_LIT:
- result = node->nd_lit;
- break;
-
- case NODE_ATTRSET:
- if (ruby_frame->argc != 1)
- rb_raise(rb_eArgError, "wrong number of arguments(%d for 1)",
- ruby_frame->argc);
- result = rb_ivar_set(self, node->nd_vid, ruby_frame->argv[0]);
- break;
-
- case NODE_DEFN:
- if (node->nd_defn) {
- NODE *body, *defn;
- VALUE origin;
- int noex;
-
- if (NIL_P(ruby_class)) {
- rb_raise(rb_eTypeError, "no class/module to add method");
- }
- if (ruby_class == rb_cClass && node->nd_mid == alloc) {
- rb_raise(rb_eNameError, "redefining Class#allocate will cause infinite loop");
- }
- if (ruby_class == rb_cObject && node->nd_mid == init) {
- rb_warn("redefining Object#initialize may cause infinite loop");
- }
- if (node->nd_mid == __id__ || node->nd_mid == __send__) {
- rb_warn("redefining `%s' may cause serious problem",
- rb_id2name(node->nd_mid));
- }
- rb_frozen_class_p(ruby_class);
- body = search_method(ruby_class, node->nd_mid, &origin);
- if (body){
- if (RTEST(ruby_verbose) && ruby_class == origin && body->nd_cnt == 0) {
- rb_warning("discarding old %s", rb_id2name(node->nd_mid));
- }
- if (node->nd_noex) { /* toplevel */
- /* should upgrade to rb_warn() if no super was called inside? */
- rb_warning("overriding global function `%s'",
- rb_id2name(node->nd_mid));
- }
- }
-
- if (SCOPE_TEST(SCOPE_PRIVATE) || node->nd_mid == init) {
- noex = NOEX_PRIVATE;
- }
- else if (SCOPE_TEST(SCOPE_PROTECTED)) {
- noex = NOEX_PROTECTED;
- }
- else if (ruby_class == rb_cObject) {
- noex = node->nd_noex;
- }
- else {
- noex = NOEX_PUBLIC;
- }
- if (body && origin == ruby_class && body->nd_noex & NOEX_UNDEF) {
- noex |= NOEX_UNDEF;
- }
-
- defn = copy_node_scope(node->nd_defn, ruby_cref);
- rb_add_method(ruby_class, node->nd_mid, defn, noex);
- if (scope_vmode == SCOPE_MODFUNC) {
- rb_add_method(rb_singleton_class(ruby_class),
- node->nd_mid, defn, NOEX_PUBLIC);
- rb_funcall(ruby_class, singleton_added, 1, ID2SYM(node->nd_mid));
- }
- if (FL_TEST(ruby_class, FL_SINGLETON)) {
- rb_funcall(rb_iv_get(ruby_class, "__attached__"),
- singleton_added, 1, ID2SYM(node->nd_mid));
- }
- else {
- rb_funcall(ruby_class, added, 1, ID2SYM(node->nd_mid));
- }
- result = Qnil;
- }
- break;
-
- case NODE_DEFS:
- if (node->nd_defn) {
- VALUE recv = rb_eval(self, node->nd_recv);
- VALUE klass;
- NODE *body = 0, *defn;
-
- if (rb_safe_level() >= 4 && !OBJ_TAINTED(recv)) {
- rb_raise(rb_eSecurityError, "Insecure: can't define singleton method");
- }
- if (FIXNUM_P(recv) || SYMBOL_P(recv)) {
- rb_raise(rb_eTypeError,
- "can't define singleton method \"%s\" for %s",
- rb_id2name(node->nd_mid),
- rb_class2name(CLASS_OF(recv)));
- }
-
- if (OBJ_FROZEN(recv)) rb_error_frozen("object");
- klass = rb_singleton_class(recv);
- if (st_lookup(RCLASS(klass)->m_tbl, node->nd_mid, &body)) {
- if (rb_safe_level() >= 4) {
- rb_raise(rb_eSecurityError, "redefining method prohibited");
- }
- if (RTEST(ruby_verbose)) {
- rb_warning("redefine %s", rb_id2name(node->nd_mid));
- }
- }
- defn = copy_node_scope(node->nd_defn, ruby_cref);
- defn->nd_rval = (VALUE)ruby_cref;
- rb_add_method(klass, node->nd_mid, defn,
- NOEX_PUBLIC|(body?body->nd_noex&NOEX_UNDEF:0));
- rb_funcall(recv, singleton_added, 1, ID2SYM(node->nd_mid));
- result = Qnil;
- }
- break;
-
- case NODE_UNDEF:
- if (NIL_P(ruby_class)) {
- rb_raise(rb_eTypeError, "no class to undef method");
- }
- rb_undef(ruby_class, node->nd_mid);
- result = Qnil;
- break;
-
- case NODE_ALIAS:
- if (NIL_P(ruby_class)) {
- rb_raise(rb_eTypeError, "no class to make alias");
- }
- rb_alias(ruby_class, node->nd_new, node->nd_old);
- result = Qnil;
- break;
-
- case NODE_VALIAS:
- rb_alias_variable(node->nd_new, node->nd_old);
- result = Qnil;
- break;
-
- case NODE_CLASS:
- {
- VALUE super, klass, tmp;
-
- if (NIL_P(ruby_class)) {
- rb_raise(rb_eTypeError, "no outer class/module");
- }
- if (node->nd_super) {
- super = superclass(self, node->nd_super);
- }
- else {
- super = 0;
- }
-
- klass = 0;
- if ((ruby_class == rb_cObject) && rb_autoload_defined(node->nd_cname)) {
- rb_autoload_load(node->nd_cname);
- }
- if (rb_const_defined_at(ruby_class, node->nd_cname)) {
- klass = rb_const_get(ruby_class, node->nd_cname);
- }
- if (klass) {
- if (TYPE(klass) != T_CLASS) {
- rb_raise(rb_eTypeError, "%s is not a class",
- rb_id2name(node->nd_cname));
- }
- if (super) {
- tmp = rb_class_real(RCLASS(klass)->super);
- if (tmp != super) {
- goto override_class;
- }
- }
- if (rb_safe_level() >= 4) {
- rb_raise(rb_eSecurityError, "extending class prohibited");
- }
- }
- else {
- override_class:
- if (!super) super = rb_cObject;
- klass = rb_define_class_id(node->nd_cname, super);
- rb_set_class_path(klass,ruby_class,rb_id2name(node->nd_cname));
- rb_class_inherited(super, klass);
- rb_const_set(ruby_class, node->nd_cname, klass);
- }
- if (ruby_wrapper) {
- rb_extend_object(klass, ruby_wrapper);
- rb_include_module(klass, ruby_wrapper);
- }
-
- result = module_setup(klass, node->nd_body);
- }
- break;
-
- case NODE_MODULE:
- {
- VALUE module;
-
- if (NIL_P(ruby_class)) {
- rb_raise(rb_eTypeError, "no outer class/module");
- }
- module = 0;
- if ((ruby_class == rb_cObject) && rb_autoload_defined(node->nd_cname)) {
- rb_autoload_load(node->nd_cname);
- }
- if (rb_const_defined_at(ruby_class, node->nd_cname)) {
- module = rb_const_get(ruby_class, node->nd_cname);
- }
- if (module) {
- if (TYPE(module) != T_MODULE) {
- rb_raise(rb_eTypeError, "%s is not a module",
- rb_id2name(node->nd_cname));
- }
- if (rb_safe_level() >= 4) {
- rb_raise(rb_eSecurityError, "extending module prohibited");
- }
- }
- else {
- module = rb_define_module_id(node->nd_cname);
- rb_const_set(ruby_class, node->nd_cname, module);
- rb_set_class_path(module,ruby_class,rb_id2name(node->nd_cname));
- }
- if (ruby_wrapper) {
- rb_extend_object(module, ruby_wrapper);
- rb_include_module(module, ruby_wrapper);
- }
-
- result = module_setup(module, node->nd_body);
- }
- break;
-
- case NODE_SCLASS:
- {
- VALUE klass;
-
- result = rb_eval(self, node->nd_recv);
- if (FIXNUM_P(result) || SYMBOL_P(result)) {
- rb_raise(rb_eTypeError, "no virtual class for %s",
- rb_class2name(CLASS_OF(result)));
- }
- if (rb_safe_level() >= 4 && !OBJ_TAINTED(result))
- rb_raise(rb_eSecurityError, "Insecure: can't extend object");
- klass = rb_singleton_class(result);
-
- if (ruby_wrapper) {
- rb_extend_object(klass, ruby_wrapper);
- rb_include_module(klass, ruby_wrapper);
- }
-
- result = module_setup(klass, node->nd_body);
- }
- break;
-
- case NODE_DEFINED:
- {
- char buf[20];
- char *desc = is_defined(self, node->nd_head, buf);
-
- if (desc) result = rb_str_new2(desc);
- else result = Qnil;
- }
- break;
-
- case NODE_NEWLINE:
- ruby_sourcefile = node->nd_file;
- ruby_sourceline = node->nd_nth;
- if (trace_func) {
- call_trace_func("line", ruby_sourcefile, ruby_sourceline, self,
- ruby_frame->last_func,
- ruby_frame->last_class);
- }
- node = node->nd_next;
- goto again;
-
- default:
- rb_bug("unknown node type %d", nd_type(node));
- }
- finish:
- CHECK_INTS;
- return result;
-}
-
-static VALUE
-module_setup(module, n)
- VALUE module;
- NODE *n;
-{
- NODE * volatile node = n;
- int state;
- struct FRAME frame;
- VALUE result; /* OK */
- char *file = ruby_sourcefile;
- int line = ruby_sourceline;
- TMP_PROTECT;
-
- frame = *ruby_frame;
- frame.tmp = ruby_frame;
- ruby_frame = &frame;
-
- PUSH_CLASS();
- ruby_class = module;
- PUSH_SCOPE();
- PUSH_VARS();
-
- if (node->nd_tbl) {
- VALUE *vars = TMP_ALLOC(node->nd_tbl[0]+1);
- *vars++ = (VALUE)node;
- ruby_scope->local_vars = vars;
- rb_mem_clear(ruby_scope->local_vars, node->nd_tbl[0]);
- ruby_scope->local_tbl = node->nd_tbl;
- }
- else {
- ruby_scope->local_vars = 0;
- ruby_scope->local_tbl = 0;
- }
-
- PUSH_CREF(module);
- ruby_frame->cbase = (VALUE)ruby_cref;
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- if (trace_func) {
- call_trace_func("class", file, line, ruby_class,
- ruby_frame->last_func,
- ruby_frame->last_class);
- }
- result = rb_eval(ruby_class, node->nd_next);
- }
- POP_TAG();
- POP_CREF();
- POP_VARS();
- POP_SCOPE();
- POP_CLASS();
-
- ruby_frame = frame.tmp;
- if (trace_func) {
- call_trace_func("end", file, line, 0,
- ruby_frame->last_func, ruby_frame->last_class);
- }
- if (state) JUMP_TAG(state);
-
- return result;
-}
-
-int
-rb_respond_to(obj, id)
- VALUE obj;
- ID id;
-{
- if (rb_method_boundp(CLASS_OF(obj), id, 0)) {
- return Qtrue;
- }
- return Qfalse;
-}
-
-static VALUE
-rb_obj_respond_to(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- VALUE mid, priv;
- ID id;
-
- rb_scan_args(argc, argv, "11", &mid, &priv);
- id = rb_to_id(mid);
- if (rb_method_boundp(CLASS_OF(obj), id, !RTEST(priv))) {
- return Qtrue;
- }
- return Qfalse;
-}
-
-static VALUE
-rb_mod_method_defined(mod, mid)
- VALUE mod, mid;
-{
- if (rb_method_boundp(mod, rb_to_id(mid), 1)) {
- return Qtrue;
- }
- return Qfalse;
-}
-
-void
-rb_exit(status)
- int status;
-{
- if (prot_tag) {
- VALUE exit;
-
- exit_status = status;
- exit = rb_exc_new2(rb_eSystemExit, "exit");
- rb_iv_set(exit, "status", INT2NUM(status));
- rb_exc_raise(exit);
- }
- ruby_finalize();
- exit(status);
-}
-
-static VALUE
-rb_f_exit(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- VALUE status;
- int istatus;
-
- rb_secure(4);
- if (rb_scan_args(argc, argv, "01", &status) == 1) {
- istatus = NUM2INT(status);
- }
- else {
- istatus = 0;
- }
- rb_exit(istatus);
- return Qnil; /* not reached */
-}
-
-static void
-rb_abort()
-{
- if (!NIL_P(ruby_errinfo)) {
- error_print();
- }
- rb_exit(1);
-}
-
-static VALUE
-rb_f_abort(argc, argv)
- int argc;
- VALUE *argv;
-{
- rb_secure(4);
- if (argc == 0) {
- rb_abort();
- }
- else {
- VALUE mesg;
-
- rb_scan_args(argc, argv, "01", &mesg);
- rb_io_puts(argc, argv, rb_stderr);
- rb_exit(1);
- }
- return Qnil; /* not reached */
-}
-
-void
-rb_iter_break()
-{
- JUMP_TAG(TAG_BREAK);
-}
-
-NORETURN(static void rb_longjmp _((int, VALUE)));
-static VALUE make_backtrace _((void));
-
-static void
-rb_longjmp(tag, mesg)
- int tag;
- VALUE mesg;
-{
- VALUE at;
-
- if (NIL_P(mesg)) mesg = ruby_errinfo;
- if (NIL_P(mesg)) {
- mesg = rb_exc_new(rb_eRuntimeError, 0, 0);
- }
-
- if (ruby_sourcefile && !NIL_P(mesg)) {
- at = get_backtrace(mesg);
- if (NIL_P(at)) {
- at = make_backtrace();
- set_backtrace(mesg, at);
- }
- }
- if (!NIL_P(mesg)) {
- ruby_errinfo = mesg;
- }
-
- if (RTEST(ruby_debug) && !NIL_P(ruby_errinfo)
- && !rb_obj_is_kind_of(ruby_errinfo, rb_eSystemExit)) {
- VALUE e = ruby_errinfo;
-
- StringValue(e);
- fprintf(stderr, "Exception `%s' at %s:%d - %s\n",
- rb_class2name(CLASS_OF(ruby_errinfo)),
- ruby_sourcefile, ruby_sourceline,
- RSTRING(e)->ptr);
- }
-
- rb_trap_restore_mask();
- if (trace_func && tag != TAG_FATAL) {
- call_trace_func("raise", ruby_sourcefile, ruby_sourceline,
- ruby_frame->self,
- ruby_frame->last_func,
- ruby_frame->last_class);
- }
- if (!prot_tag) {
- error_print();
- }
- JUMP_TAG(tag);
-}
-
-void
-rb_exc_raise(mesg)
- VALUE mesg;
-{
- rb_longjmp(TAG_RAISE, mesg);
-}
-
-void
-rb_exc_fatal(mesg)
- VALUE mesg;
-{
- rb_longjmp(TAG_FATAL, mesg);
-}
-
-void
-rb_interrupt()
-{
- rb_raise(rb_eInterrupt, "");
-}
-
-static VALUE
-rb_f_raise(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE mesg;
- ID exception;
- int n;
-
- mesg = Qnil;
- switch (argc) {
- case 0:
- mesg = Qnil;
- break;
- case 1:
- if (NIL_P(argv[0])) break;
- if (TYPE(argv[0]) == T_STRING) {
- mesg = rb_exc_new3(rb_eRuntimeError, argv[0]);
- break;
- }
- n = 0;
- goto exception_call;
-
- case 2:
- case 3:
- n = 1;
- exception_call:
- exception = rb_intern("exception");
- if (!rb_respond_to(argv[0], exception)) {
- rb_raise(rb_eTypeError, "exception class/object expected");
- }
- mesg = rb_funcall(argv[0], exception, n, argv[1]);
- break;
- default:
- rb_raise(rb_eArgError, "wrong number of arguments");
- break;
- }
- if (argc > 0) {
- if (!rb_obj_is_kind_of(mesg, rb_eException))
- rb_raise(rb_eTypeError, "exception object expected");
- set_backtrace(mesg, (argc>2)?argv[2]:Qnil);
- }
-
- if (ruby_frame != top_frame) {
- PUSH_FRAME(); /* fake frame */
- *ruby_frame = *_frame.prev->prev;
- rb_longjmp(TAG_RAISE, mesg);
- POP_FRAME();
- }
- rb_longjmp(TAG_RAISE, mesg);
-
- return Qnil; /* not reached */
-}
-
-void
-rb_jump_tag(tag)
- int tag;
-{
- JUMP_TAG(tag);
-}
-
-int
-rb_block_given_p()
-{
- if (ruby_frame->iter && ruby_block)
- return Qtrue;
- return Qfalse;
-}
-
-int
-rb_iterator_p()
-{
- return rb_block_given_p();
-}
-
-static VALUE
-rb_f_block_given_p()
-{
- if (ruby_frame->prev && ruby_frame->prev->iter && ruby_block)
- return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-rb_yield_0(val, self, klass, pcall)
- VALUE val, self, klass; /* OK */
- int pcall;
-{
- NODE *node;
- volatile VALUE result = Qnil;
- volatile VALUE old_cref;
- volatile VALUE old_wrapper;
- struct BLOCK * volatile block;
- struct SCOPE * volatile old_scope;
- struct FRAME frame;
- char *const file = ruby_sourcefile;
- int line = ruby_sourceline;
- int state;
- static unsigned serial = 1;
-
- if (!rb_block_given_p()) {
- localjump_error("no block given", Qnil);
- }
-
- PUSH_VARS();
- PUSH_CLASS();
- block = ruby_block;
- frame = block->frame;
- frame.prev = ruby_frame;
- ruby_frame = &(frame);
- old_cref = (VALUE)ruby_cref;
- ruby_cref = (NODE*)ruby_frame->cbase;
- old_wrapper = ruby_wrapper;
- ruby_wrapper = block->wrapper;
- old_scope = ruby_scope;
- ruby_scope = block->scope;
- ruby_block = block->prev;
- if (block->flags & BLOCK_D_SCOPE) {
- /* put place holder for dynamic (in-block) local variables */
- ruby_dyna_vars = new_dvar(0, 0, block->dyna_vars);
- }
- else {
- /* FOR does not introduce new scope */
- ruby_dyna_vars = block->dyna_vars;
- }
- ruby_class = klass?klass:block->klass;
- if (!klass) self = block->self;
- node = block->body;
-
- if (block->var) {
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- if (block->var == (NODE*)1) {
- if (pcall && RARRAY(val)->len != 0) {
- rb_raise(rb_eArgError, "wrong number of arguments (%d for 0)",
- RARRAY(val)->len);
- }
- }
- else if (block->var == (NODE*)2) {
- if (TYPE(val) == T_ARRAY && RARRAY(val)->len != 0) {
- rb_raise(rb_eArgError, "wrong number of arguments (%d for 0)",
- RARRAY(val)->len);
- }
- }
- else {
- if (nd_type(block->var) == NODE_MASGN) {
- massign(self, block->var, val, pcall);
- }
- else {
- if (pcall) val = avalue_to_svalue(val);
- assign(self, block->var, val, pcall);
- }
- }
- }
- POP_TAG();
- if (state) goto pop_state;
- }
- else if (pcall) {
- val = avalue_to_svalue(val);
- }
-
- PUSH_ITER(block->iter);
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- redo:
- if (!node) {
- result = Qnil;
- }
- else if (nd_type(node) == NODE_CFUNC || nd_type(node) == NODE_IFUNC) {
- result = (*node->nd_cfnc)(val, node->nd_tval, self);
- }
- else {
- result = rb_eval(self, node);
- }
- }
- else {
- switch (state) {
- case TAG_REDO:
- state = 0;
- CHECK_INTS;
- goto redo;
- case TAG_NEXT:
- state = 0;
- result = prot_tag->retval;
- break;
- case TAG_BREAK:
- case TAG_RETURN:
- state |= (serial++ << 8);
- state |= 0x10;
- block->tag->dst = state;
- break;
- default:
- break;
- }
- }
- POP_TAG();
- pop_state:
- POP_ITER();
- POP_CLASS();
- if (ruby_dyna_vars && (block->flags & BLOCK_D_SCOPE) &&
- !FL_TEST(ruby_dyna_vars, DVAR_DONT_RECYCLE)) {
- struct RVarmap *vars = ruby_dyna_vars;
-
- if (ruby_dyna_vars->id == 0) {
- vars = ruby_dyna_vars->next;
- rb_gc_force_recycle((VALUE)ruby_dyna_vars);
- while (vars && vars->id != 0) {
- struct RVarmap *tmp = vars->next;
- rb_gc_force_recycle((VALUE)vars);
- vars = tmp;
- }
- }
- }
- POP_VARS();
- ruby_block = block;
- ruby_frame = ruby_frame->prev;
- ruby_cref = (NODE*)old_cref;
- ruby_wrapper = old_wrapper;
- if (ruby_scope->flags & SCOPE_DONT_RECYCLE)
- scope_dup(old_scope);
- ruby_scope = old_scope;
- ruby_sourcefile = file;
- ruby_sourceline = line;
- if (state) {
- if (!block->tag) {
- switch (state & TAG_MASK) {
- case TAG_BREAK:
- case TAG_RETURN:
- jump_tag_but_local_jump(state & TAG_MASK);
- break;
- }
- }
- JUMP_TAG(state);
- }
- return result;
-}
-
-VALUE
-rb_yield(val)
- VALUE val;
-{
- return rb_yield_0(val, 0, 0, 0);
-}
-
-static VALUE
-rb_f_loop()
-{
- for (;;) {
- rb_yield_0(Qnil, 0, 0, 0);
- CHECK_INTS;
- }
- return Qnil; /* dummy */
-}
-
-static VALUE
-massign(self, node, val, pcall)
- VALUE self;
- NODE *node;
- VALUE val;
- int pcall;
-{
- NODE *list;
- int i = 0, len;
-
- if (!pcall) {
- val = svalue_to_mvalue(val);
- }
- len = RARRAY(val)->len;
- list = node->nd_head;
- for (i=0; list && i<len; i++) {
- assign(self, list->nd_head, RARRAY(val)->ptr[i], pcall);
- list = list->nd_next;
- }
- if (pcall && list) goto arg_error;
- if (node->nd_args) {
- if (node->nd_args == (NODE*)-1) {
- /* no check for mere `*' */
- }
- else if (!list && i<len) {
- assign(self, node->nd_args, rb_ary_new4(len-i, RARRAY(val)->ptr+i), pcall);
- }
- else {
- assign(self, node->nd_args, rb_ary_new2(0), pcall);
- }
- }
- else if (pcall && i < len) {
- goto arg_error;
- }
-
- while (list) {
- i++;
- assign(self, list->nd_head, Qnil, pcall);
- list = list->nd_next;
- }
- return val;
-
- arg_error:
- while (list) {
- i++;
- list = list->nd_next;
- }
- rb_raise(rb_eArgError, "wrong number of arguments (%d for %d)", len, i);
-}
-
-static void
-assign(self, lhs, val, pcall)
- VALUE self;
- NODE *lhs;
- VALUE val;
- int pcall;
-{
- if (val == Qundef) val = Qnil;
- switch (nd_type(lhs)) {
- case NODE_GASGN:
- rb_gvar_set(lhs->nd_entry, val);
- break;
-
- case NODE_IASGN:
- rb_ivar_set(self, lhs->nd_vid, val);
- break;
-
- case NODE_LASGN:
- if (ruby_scope->local_vars == 0)
- rb_bug("unexpected local variable assignment");
- ruby_scope->local_vars[lhs->nd_cnt] = val;
- break;
-
- case NODE_DASGN:
- dvar_asgn(lhs->nd_vid, val);
- break;
-
- case NODE_DASGN_CURR:
- dvar_asgn_curr(lhs->nd_vid, val);
- break;
-
- case NODE_CDECL:
- rb_const_set(ruby_class, lhs->nd_vid, val);
- break;
-
- case NODE_CVDECL:
- if (ruby_verbose && FL_TEST(ruby_cbase, FL_SINGLETON)) {
- rb_warn("declaring singleton class variable");
- }
- rb_cvar_set(cvar_cbase(), lhs->nd_vid, val, Qtrue);
- break;
-
- case NODE_CVASGN:
- rb_cvar_set(cvar_cbase(), lhs->nd_vid, val, Qfalse);
- break;
-
- case NODE_MASGN:
- massign(self, lhs, val, pcall);
- break;
-
- case NODE_CALL:
- {
- VALUE recv;
- recv = rb_eval(self, lhs->nd_recv);
- if (!lhs->nd_args) {
- /* attr set */
- rb_call(CLASS_OF(recv), recv, lhs->nd_mid, 1, &val, 0);
- }
- else {
- /* array set */
- VALUE args;
-
- args = rb_eval(self, lhs->nd_args);
- rb_ary_push(args, val);
- rb_call(CLASS_OF(recv), recv, lhs->nd_mid,
- RARRAY(args)->len, RARRAY(args)->ptr, 0);
- }
- }
- break;
-
- default:
- rb_bug("bug in variable assignment");
- break;
- }
-}
-
-VALUE
-rb_iterate(it_proc, data1, bl_proc, data2)
- VALUE (*it_proc) _((VALUE)), (*bl_proc)(ANYARGS);
- VALUE data1, data2;
-{
- int state;
- volatile VALUE retval = Qnil;
- NODE *node = NEW_IFUNC(bl_proc, data2);
- VALUE self = ruby_top_self;
-
- iter_retry:
- PUSH_ITER(ITER_PRE);
- PUSH_BLOCK(0, node);
- PUSH_TAG(PROT_NONE);
-
- state = EXEC_TAG();
- if (state == 0) {
- retval = (*it_proc)(data1);
- }
- if (ruby_block->tag->dst == state) {
- state &= TAG_MASK;
- if (state == TAG_RETURN || state == TAG_BREAK) {
- retval = prot_tag->retval;
- }
- }
- POP_TAG();
- POP_BLOCK();
- POP_ITER();
-
- switch (state) {
- case 0:
- break;
-
- case TAG_RETRY:
- goto iter_retry;
-
- case TAG_BREAK:
- break;
-
- case TAG_RETURN:
- return_value(retval);
- /* fall through */
- default:
- JUMP_TAG(state);
- }
- return retval;
-}
-
-static int
-handle_rescue(self, node)
- VALUE self;
- NODE *node;
-{
- int argc; VALUE *argv; /* used in SETUP_ARGS */
- TMP_PROTECT;
-
- if (!node->nd_args) {
- return rb_obj_is_kind_of(ruby_errinfo, rb_eStandardError);
- }
-
- BEGIN_CALLARGS;
- SETUP_ARGS(node->nd_args);
- END_CALLARGS;
-
- while (argc--) {
- if (!rb_obj_is_kind_of(argv[0], rb_cModule)) {
- rb_raise(rb_eTypeError, "class or module required for rescue clause");
- }
- if (RTEST(rb_funcall(*argv, eqq, 1, ruby_errinfo))) return 1;
- argv++;
- }
- return 0;
-}
-
-VALUE
-#ifdef HAVE_STDARG_PROTOTYPES
-rb_rescue2(VALUE (*b_proc)(ANYARGS), VALUE data1, VALUE (*r_proc)(ANYARGS), VALUE data2, ...)
-#else
-rb_rescue2(b_proc, data1, r_proc, data2, va_alist)
- VALUE (*b_proc)(ANYARGS), (*r_proc)(ANYARGS);
- VALUE data1, data2;
- va_dcl
-#endif
-{
- int state;
- volatile VALUE result;
- volatile VALUE e_info = ruby_errinfo;
- va_list args;
-
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- retry_entry:
- result = (*b_proc)(data1);
- }
- else if (state == TAG_RAISE) {
- int handle = Qfalse;
- VALUE eclass;
-
- va_init_list(args, data2);
- while (eclass = va_arg(args, VALUE)) {
- if (rb_obj_is_kind_of(ruby_errinfo, eclass)) {
- handle = Qtrue;
- break;
- }
- }
- va_end(args);
-
- if (handle) {
- if (r_proc) {
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- result = (*r_proc)(data2, ruby_errinfo);
- }
- POP_TAG();
- if (state == TAG_RETRY) {
- state = 0;
- ruby_errinfo = Qnil;
- goto retry_entry;
- }
- }
- else {
- result = Qnil;
- state = 0;
- }
- if (state == 0) {
- ruby_errinfo = e_info;
- }
- }
- }
- POP_TAG();
- if (state) JUMP_TAG(state);
-
- return result;
-}
-
-VALUE
-rb_rescue(b_proc, data1, r_proc, data2)
- VALUE (*b_proc)(), (*r_proc)();
- VALUE data1, data2;
-{
- return rb_rescue2(b_proc, data1, r_proc, data2, rb_eStandardError, 0);
-}
-
-VALUE
-rb_protect(proc, data, state)
- VALUE (*proc) _((VALUE));
- VALUE data;
- int *state;
-{
- VALUE result; /* OK */
- int status;
-
- PUSH_TAG(PROT_NONE);
- if ((status = EXEC_TAG()) == 0) {
- result = (*proc)(data);
- }
- POP_TAG();
- if (state) {
- *state = status;
- }
- if (status != 0) {
- return Qnil;
- }
-
- return result;
-}
-
-VALUE
-rb_ensure(b_proc, data1, e_proc, data2)
- VALUE (*b_proc)();
- VALUE data1;
- VALUE (*e_proc)();
- VALUE data2;
-{
- int state;
- volatile VALUE result = Qnil;
- VALUE retval;
-
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- result = (*b_proc)(data1);
- }
- POP_TAG();
- retval = prot_tag ? prot_tag->retval : Qnil; /* save retval */
- (*e_proc)(data2);
- if (prot_tag) return_value(retval);
-
- if (state) JUMP_TAG(state);
- return result;
-}
-
-VALUE
-rb_with_disable_interrupt(proc, data)
- VALUE (*proc)();
- VALUE data;
-{
- VALUE result; /* OK */
- int status;
-
- DEFER_INTS;
- PUSH_TAG(PROT_NONE);
- if ((status = EXEC_TAG()) == 0) {
- result = (*proc)(data);
- }
- POP_TAG();
- ALLOW_INTS;
- if (status) JUMP_TAG(status);
-
- return result;
-}
-
-static void
-stack_check()
-{
- static int overflowing = 0;
-
- if (!overflowing && ruby_stack_check()) {
- int state;
- overflowing = 1;
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- rb_raise(rb_eSysStackError, "stack level too deep");
- }
- POP_TAG();
- overflowing = 0;
- JUMP_TAG(state);
- }
-}
-
-static int last_call_status;
-
-#define CSTAT_PRIV 1
-#define CSTAT_PROT 2
-#define CSTAT_VCALL 4
-
-static VALUE
-rb_f_missing(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- ID id;
- VALUE exc = rb_eNoMethodError;
- volatile VALUE d = 0;
- char *format = 0;
- char *desc = "";
- char *file = ruby_sourcefile;
- int line = ruby_sourceline;
-
- if (argc == 0 || !SYMBOL_P(argv[0])) {
- rb_raise(rb_eArgError, "no id given");
- }
-
- stack_check();
-
- id = SYM2ID(argv[0]);
-
- switch (TYPE(obj)) {
- case T_NIL:
- desc = "nil";
- break;
- case T_TRUE:
- desc = "true";
- break;
- case T_FALSE:
- desc = "false";
- break;
- case T_OBJECT:
- d = rb_any_to_s(obj);
- break;
- default:
- d = rb_inspect(obj);
- break;
- }
- if (d) {
- if (RSTRING(d)->len > 65) {
- d = rb_any_to_s(obj);
- }
- desc = RSTRING(d)->ptr;
- }
-
- if (last_call_status & CSTAT_PRIV) {
- format = "private method `%s' called for %s%s%s";
- }
- if (last_call_status & CSTAT_PROT) {
- format = "protected method `%s' called for %s%s%s";
- }
- else if (last_call_status & CSTAT_VCALL) {
- const char *mname = rb_id2name(id);
-
- if (('a' <= mname[0] && mname[0] <= 'z') || mname[0] == '_') {
- format = "undefined local variable or method `%s' for %s%s%s";
- exc = rb_eNameError;
- }
- }
- if (!format) {
- format = "undefined method `%s' for %s%s%s";
- }
-
- ruby_sourcefile = file;
- ruby_sourceline = line;
- PUSH_FRAME(); /* fake frame */
- *ruby_frame = *_frame.prev->prev;
- {
- char buf[BUFSIZ];
- int noclass = (!d || desc[0]=='#');
-
- snprintf(buf, BUFSIZ, format, rb_id2name(id),
- desc, noclass ? "" : ":",
- noclass ? "" : rb_class2name(CLASS_OF(obj)));
- exc = rb_exc_new2(exc, buf);
- rb_iv_set(exc, "name", argv[0]);
- rb_iv_set(exc, "args", rb_ary_new4(argc-1, argv+1));
- rb_exc_raise(exc);
- }
- POP_FRAME();
-
- return Qnil; /* not reached */
-}
-
-static VALUE
-rb_undefined(obj, id, argc, argv, call_status)
- VALUE obj;
- ID id;
- int argc;
- VALUE*argv;
- int call_status;
-{
- VALUE *nargv;
-
- last_call_status = call_status;
-
- if (id == missing) {
- PUSH_FRAME();
- rb_f_missing(argc, argv, obj);
- POP_FRAME();
- }
-
- nargv = ALLOCA_N(VALUE, argc+1);
- nargv[0] = ID2SYM(id);
- MEMCPY(nargv+1, argv, VALUE, argc);
-
- return rb_funcall2(obj, missing, argc+1, nargv);
-}
-
-static VALUE
-call_cfunc(func, recv, len, argc, argv)
- VALUE (*func)();
- VALUE recv;
- int len, argc;
- VALUE *argv;
-{
- if (len >= 0 && argc != len) {
- rb_raise(rb_eArgError, "wrong number of arguments(%d for %d)",
- argc, len);
- }
-
- switch (len) {
- case -2:
- return (*func)(recv, rb_ary_new4(argc, argv));
- break;
- case -1:
- return (*func)(argc, argv, recv);
- break;
- case 0:
- return (*func)(recv);
- break;
- case 1:
- return (*func)(recv, argv[0]);
- break;
- case 2:
- return (*func)(recv, argv[0], argv[1]);
- break;
- case 3:
- return (*func)(recv, argv[0], argv[1], argv[2]);
- break;
- case 4:
- return (*func)(recv, argv[0], argv[1], argv[2], argv[3]);
- break;
- case 5:
- return (*func)(recv, argv[0], argv[1], argv[2], argv[3], argv[4]);
- break;
- case 6:
- return (*func)(recv, argv[0], argv[1], argv[2], argv[3], argv[4],
- argv[5]);
- break;
- case 7:
- return (*func)(recv, argv[0], argv[1], argv[2], argv[3], argv[4],
- argv[5], argv[6]);
- break;
- case 8:
- return (*func)(recv, argv[0], argv[1], argv[2], argv[3], argv[4],
- argv[5], argv[6], argv[7]);
- break;
- case 9:
- return (*func)(recv, argv[0], argv[1], argv[2], argv[3], argv[4],
- argv[5], argv[6], argv[7], argv[8]);
- break;
- case 10:
- return (*func)(recv, argv[0], argv[1], argv[2], argv[3], argv[4],
- argv[5], argv[6], argv[7], argv[8], argv[9]);
- break;
- case 11:
- return (*func)(recv, argv[0], argv[1], argv[2], argv[3], argv[4],
- argv[5], argv[6], argv[7], argv[8], argv[9], argv[10]);
- break;
- case 12:
- return (*func)(recv, argv[0], argv[1], argv[2], argv[3], argv[4],
- argv[5], argv[6], argv[7], argv[8], argv[9],
- argv[10], argv[11]);
- break;
- case 13:
- return (*func)(recv, argv[0], argv[1], argv[2], argv[3], argv[4],
- argv[5], argv[6], argv[7], argv[8], argv[9], argv[10],
- argv[11], argv[12]);
- break;
- case 14:
- return (*func)(recv, argv[0], argv[1], argv[2], argv[3], argv[4],
- argv[5], argv[6], argv[7], argv[8], argv[9], argv[10],
- argv[11], argv[12], argv[13]);
- break;
- case 15:
- return (*func)(recv, argv[0], argv[1], argv[2], argv[3], argv[4],
- argv[5], argv[6], argv[7], argv[8], argv[9], argv[10],
- argv[11], argv[12], argv[13], argv[14]);
- break;
- default:
- rb_raise(rb_eArgError, "too many arguments(%d)", len);
- break;
- }
- return Qnil; /* not reached */
-}
-
-static VALUE
-rb_call0(klass, recv, id, argc, argv, body, nosuper)
- VALUE klass, recv;
- ID id;
- int argc; /* OK */
- VALUE *argv; /* OK */
- NODE *body; /* OK */
- int nosuper;
-{
- NODE *b2; /* OK */
- volatile VALUE result = Qnil;
- int itr;
- static int tick;
- TMP_PROTECT;
-
- switch (ruby_iter->iter) {
- case ITER_PRE:
- itr = ITER_CUR;
- break;
- case ITER_CUR:
- default:
- itr = ITER_NOT;
- break;
- }
-
- if ((++tick & 0xff) == 0) {
- CHECK_INTS; /* better than nothing */
- stack_check();
- }
- PUSH_ITER(itr);
- PUSH_FRAME();
-
- ruby_frame->last_func = id;
- ruby_frame->last_class = nosuper?0:klass;
- ruby_frame->self = recv;
- ruby_frame->argc = argc;
- ruby_frame->argv = argv;
-
- switch (nd_type(body)) {
- case NODE_CFUNC:
- {
- int len = body->nd_argc;
-
- if (len < -2) {
- rb_bug("bad argc(%d) specified for `%s(%s)'",
- len, rb_class2name(klass), rb_id2name(id));
- }
- if (trace_func) {
- int state;
- char *file = ruby_frame->prev->file;
- int line = ruby_frame->prev->line;
- if (!file) {
- file = ruby_sourcefile;
- line = ruby_sourceline;
- }
-
- call_trace_func("c-call", 0, 0, recv, id, klass);
- PUSH_TAG(PROT_FUNC);
- if ((state = EXEC_TAG()) == 0) {
- result = call_cfunc(body->nd_cfnc, recv, len, argc, argv);
- }
- POP_TAG();
- call_trace_func("c-return", 0, 0, recv, id, klass);
- if (state) JUMP_TAG(state);
- }
- else {
- result = call_cfunc(body->nd_cfnc, recv, len, argc, argv);
- }
- }
- break;
-
- /* for attr get/set */
- case NODE_IVAR:
- if (argc != 0) {
- rb_raise(rb_eArgError, "wrong number of arguments(%d for 0)", argc);
- }
- case NODE_ATTRSET:
- /* for re-scoped/renamed method */
- case NODE_ZSUPER:
- result = rb_eval(recv, body);
- break;
-
- case NODE_DMETHOD:
- result = method_call(argc, argv, umethod_bind(body->nd_cval, recv));
- break;
-
- case NODE_BMETHOD:
- result = proc_invoke(body->nd_cval, rb_ary_new4(argc, argv), Qtrue, recv);
- break;
-
- case NODE_SCOPE:
- {
- int state;
- VALUE *local_vars; /* OK */
- NODE *saved_cref = 0;
-
- PUSH_SCOPE();
-
- if (body->nd_rval) {
- saved_cref = ruby_cref;
- ruby_cref = (NODE*)body->nd_rval;
- ruby_frame->cbase = body->nd_rval;
- }
- if (body->nd_tbl) {
- local_vars = TMP_ALLOC(body->nd_tbl[0]+1);
- *local_vars++ = (VALUE)body;
- rb_mem_clear(local_vars, body->nd_tbl[0]);
- ruby_scope->local_tbl = body->nd_tbl;
- ruby_scope->local_vars = local_vars;
- }
- else {
- local_vars = ruby_scope->local_vars = 0;
- ruby_scope->local_tbl = 0;
- }
- b2 = body = body->nd_next;
-
- PUSH_VARS();
- PUSH_TAG(PROT_FUNC);
-
- if ((state = EXEC_TAG()) == 0) {
- NODE *node = 0;
- int i;
-
- if (nd_type(body) == NODE_ARGS) {
- node = body;
- body = 0;
- }
- else if (nd_type(body) == NODE_BLOCK) {
- node = body->nd_head;
- body = body->nd_next;
- }
- if (node) {
- if (nd_type(node) != NODE_ARGS) {
- rb_bug("no argument-node");
- }
-
- i = node->nd_cnt;
- if (i > argc) {
- rb_raise(rb_eArgError, "wrong number of arguments(%d for %d)",
- argc, i);
- }
- if (node->nd_rest == -1) {
- int opt = i;
- NODE *optnode = node->nd_opt;
-
- while (optnode) {
- opt++;
- optnode = optnode->nd_next;
- }
- if (opt < argc) {
- rb_raise(rb_eArgError, "wrong number of arguments(%d for %d)",
- argc, opt);
- }
- ruby_frame->argc = opt;
- ruby_frame->argv = local_vars+2;
- }
-
- if (local_vars) {
- if (i > 0) {
- /* +2 for $_ and $~ */
- MEMCPY(local_vars+2, argv, VALUE, i);
- }
- argv += i; argc -= i;
- if (node->nd_opt) {
- NODE *opt = node->nd_opt;
-
- while (opt && argc) {
- assign(recv, opt->nd_head, *argv, 1);
- argv++; argc--;
- opt = opt->nd_next;
- }
- if (opt) {
- ruby_sourcefile = opt->nd_file;
- ruby_sourceline = nd_line(opt);
- rb_eval(recv, opt);
- }
- }
- local_vars = ruby_scope->local_vars;
- if (node->nd_rest >= 0) {
- VALUE v;
-
- if (argc > 0)
- v = rb_ary_new4(argc,argv);
- else
- v = rb_ary_new2(0);
- ruby_scope->local_vars[node->nd_rest] = v;
- }
- }
- }
-
- if (trace_func) {
- call_trace_func("call", b2->nd_file, nd_line(b2),
- recv, id, klass);
- }
- result = rb_eval(recv, body);
- }
- else if (state == TAG_RETURN) {
- result = prot_tag->retval;
- state = 0;
- }
- POP_TAG();
- POP_VARS();
- POP_SCOPE();
- ruby_cref = saved_cref;
- if (trace_func) {
- char *file = ruby_frame->prev->file;
- int line = ruby_frame->prev->line;
- if (!file) {
- file = ruby_sourcefile;
- line = ruby_sourceline;
- }
- call_trace_func("return", file, line, recv, id, klass);
- }
- switch (state) {
- case 0:
- break;
-
- case TAG_RETRY:
- if (rb_block_given_p()) {
- JUMP_TAG(state);
- }
- /* fall through */
- default:
- jump_tag_but_local_jump(state);
- break;
- }
- }
- break;
-
- default:
- rb_bug("unknown node type %d", nd_type(body));
- break;
- }
- POP_FRAME();
- POP_ITER();
- return result;
-}
-
-static VALUE
-rb_call(klass, recv, mid, argc, argv, scope)
- VALUE klass, recv;
- ID mid;
- int argc; /* OK */
- VALUE *argv; /* OK */
- int scope;
-{
- NODE *body; /* OK */
- int noex;
- ID id = mid;
- struct cache_entry *ent;
-
- if (!klass) {
- rb_raise(rb_eNotImpError, "method `%s' called on terminated object (0x%x)",
- rb_id2name(mid), recv);
- }
- /* is it in the method cache? */
- ent = cache + EXPR1(klass, mid);
- if (ent->mid == mid && ent->klass == klass) {
- if (!ent->method)
- return rb_undefined(recv, mid, argc, argv, scope==2?CSTAT_VCALL:0);
- klass = ent->origin;
- id = ent->mid0;
- noex = ent->noex;
- body = ent->method;
- }
- else if ((body = rb_get_method_body(&klass, &id, &noex)) == 0) {
- if (scope == 3) {
- rb_name_error(mid, "super: no superclass method `%s'",
- rb_id2name(mid));
- }
- return rb_undefined(recv, mid, argc, argv, scope==2?CSTAT_VCALL:0);
- }
-
- if (mid != missing) {
- /* receiver specified form for private method */
- if ((noex & NOEX_PRIVATE) && scope == 0)
- return rb_undefined(recv, mid, argc, argv, CSTAT_PRIV);
-
- /* self must be kind of a specified form for private method */
- if ((noex & NOEX_PROTECTED)) {
- VALUE defined_class = klass;
-
- if (TYPE(defined_class) == T_ICLASS) {
- defined_class = RBASIC(defined_class)->klass;
- }
- if (!rb_obj_is_kind_of(ruby_frame->self, rb_class_real(defined_class)))
- return rb_undefined(recv, mid, argc, argv, CSTAT_PROT);
- }
- }
-
- return rb_call0(klass, recv, id, argc, argv, body, noex & NOEX_UNDEF);
-}
-
-VALUE
-rb_apply(recv, mid, args)
- VALUE recv;
- ID mid;
- VALUE args;
-{
- int argc;
- VALUE *argv;
-
- argc = RARRAY(args)->len;
- argv = ALLOCA_N(VALUE, argc);
- MEMCPY(argv, RARRAY(args)->ptr, VALUE, argc);
- return rb_call(CLASS_OF(recv), recv, mid, argc, argv, 1);
-}
-
-static VALUE
-rb_f_send(argc, argv, recv)
- int argc;
- VALUE *argv;
- VALUE recv;
-{
- VALUE vid;
-
- if (argc == 0) rb_raise(rb_eArgError, "no method name given");
-
- vid = *argv++; argc--;
- PUSH_ITER(rb_block_given_p()?ITER_PRE:ITER_NOT);
- vid = rb_call(CLASS_OF(recv), recv, rb_to_id(vid), argc, argv, 1);
- POP_ITER();
-
- return vid;
-}
-
-
-#ifdef HAVE_STDARG_PROTOTYPES
-#include <stdarg.h>
-#define va_init_list(a,b) va_start(a,b)
-#else
-#include <varargs.h>
-#define va_init_list(a,b) va_start(a)
-#endif
-
-VALUE
-#ifdef HAVE_STDARG_PROTOTYPES
-rb_funcall(VALUE recv, ID mid, int n, ...)
-#else
-rb_funcall(recv, mid, n, va_alist)
- VALUE recv;
- ID mid;
- int n;
- va_dcl
-#endif
-{
- va_list ar;
- VALUE *argv;
-
- if (n > 0) {
- int i;
-
- argv = ALLOCA_N(VALUE, n);
-
- va_init_list(ar, n);
- for (i=0;i<n;i++) {
- argv[i] = va_arg(ar, VALUE);
- }
- va_end(ar);
- }
- else {
- argv = 0;
- }
-
- return rb_call(CLASS_OF(recv), recv, mid, n, argv, 1);
-}
-
-VALUE
-rb_funcall2(recv, mid, argc, argv)
- VALUE recv;
- ID mid;
- int argc;
- VALUE *argv;
-{
- return rb_call(CLASS_OF(recv), recv, mid, argc, argv, 1);
-}
-
-VALUE
-rb_funcall3(recv, mid, argc, argv)
- VALUE recv;
- ID mid;
- int argc;
- VALUE *argv;
-{
- return rb_call(CLASS_OF(recv), recv, mid, argc, argv, 0);
-}
-
-VALUE
-rb_call_super(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE result;
-
- if (ruby_frame->last_class == 0) {
- rb_name_error(ruby_frame->last_func, "superclass method `%s' must be enabled by rb_enable_super()",
- rb_id2name(ruby_frame->last_func));
- }
-
- PUSH_ITER(ruby_iter->iter?ITER_PRE:ITER_NOT);
- result = rb_call(RCLASS(ruby_frame->last_class)->super,
- ruby_frame->self, ruby_frame->last_func,
- argc, argv, 3);
- POP_ITER();
-
- return result;
-}
-
-static VALUE
-backtrace(lev)
- int lev;
-{
- struct FRAME *frame = ruby_frame;
- char buf[BUFSIZ];
- VALUE ary;
-
- ary = rb_ary_new();
- if (lev < 0) {
- if (frame->last_func) {
- snprintf(buf, BUFSIZ, "%s:%d:in `%s'",
- ruby_sourcefile, ruby_sourceline,
- rb_id2name(frame->last_func));
- }
- else if (ruby_sourceline == 0) {
- snprintf(buf, BUFSIZ, "%s", ruby_sourcefile);
- }
- else {
- snprintf(buf, BUFSIZ, "%s:%d", ruby_sourcefile, ruby_sourceline);
- }
- rb_ary_push(ary, rb_str_new2(buf));
- }
- else {
- while (lev-- > 0) {
- frame = frame->prev;
- if (!frame) {
- ary = Qnil;
- break;
- }
- }
- }
- while (frame && frame->file) {
- if (frame->prev && frame->prev->last_func) {
- snprintf(buf, BUFSIZ, "%s:%d:in `%s'",
- frame->file, frame->line,
- rb_id2name(frame->prev->last_func));
- }
- else {
- snprintf(buf, BUFSIZ, "%s:%d", frame->file, frame->line);
- }
- rb_ary_push(ary, rb_str_new2(buf));
- frame = frame->prev;
- }
-
- return ary;
-}
-
-static VALUE
-rb_f_caller(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE level;
- int lev;
-
- rb_scan_args(argc, argv, "01", &level);
-
- if (NIL_P(level)) lev = 1;
- else lev = NUM2INT(level);
- if (lev < 0) rb_raise(rb_eArgError, "negative level(%d)", lev);
-
- return backtrace(lev);
-}
-
-void
-rb_backtrace()
-{
- int i;
- VALUE ary;
-
- ary = backtrace(-1);
- for (i=0; i<RARRAY(ary)->len; i++) {
- printf("\tfrom %s\n", RSTRING(RARRAY(ary)->ptr[i])->ptr);
- }
-}
-
-static VALUE
-make_backtrace()
-{
- return backtrace(-1);
-}
-
-ID
-rb_frame_last_func()
-{
- return ruby_frame->last_func;
-}
-
-static NODE*
-compile(src, file, line)
- VALUE src;
- char *file;
- int line;
-{
- NODE *node;
-
- ruby_nerrs = 0;
- Check_Type(src, T_STRING);
- node = rb_compile_string(file, src, line);
-
- if (ruby_nerrs == 0) return node;
- return 0;
-}
-
-static VALUE
-eval(self, src, scope, file, line)
- VALUE self, src, scope;
- char *file;
- int line;
-{
- struct BLOCK *data;
- volatile VALUE result = Qnil;
- struct SCOPE * volatile old_scope;
- struct BLOCK * volatile old_block;
- struct RVarmap * volatile old_dyna_vars;
- VALUE volatile old_cref;
- int volatile old_vmode;
- volatile VALUE old_wrapper;
- struct FRAME frame;
- char *filesave = ruby_sourcefile;
- int linesave = ruby_sourceline;
- volatile int iter = ruby_frame->iter;
- int state;
-
- if (!NIL_P(scope)) {
- if (!rb_obj_is_block(scope)) {
- rb_raise(rb_eTypeError, "wrong argument type %s (expected Proc/Binding)",
- rb_class2name(CLASS_OF(scope)));
- }
-
- Data_Get_Struct(scope, struct BLOCK, data);
- /* PUSH BLOCK from data */
- frame = data->frame;
- frame.tmp = ruby_frame; /* gc protection */
- ruby_frame = &(frame);
- old_scope = ruby_scope;
- ruby_scope = data->scope;
- old_block = ruby_block;
- ruby_block = data->prev;
- old_dyna_vars = ruby_dyna_vars;
- ruby_dyna_vars = data->dyna_vars;
- old_vmode = scope_vmode;
- scope_vmode = data->vmode;
- old_cref = (VALUE)ruby_cref;
- ruby_cref = (NODE*)ruby_frame->cbase;
- old_wrapper = ruby_wrapper;
- ruby_wrapper = data->wrapper;
- if ((file == 0 || (line == 1 && strcmp(file, "(eval)") == 0)) &&
- data->body && data->body->nd_file) {
- file = data->body->nd_file;
- line = nd_line(data->body);
- }
-
- self = data->self;
- ruby_frame->iter = data->iter;
- }
- else {
- if (ruby_frame->prev) {
- ruby_frame->iter = ruby_frame->prev->iter;
- }
- }
- if (file == 0) {
- file = ruby_sourcefile;
- line = ruby_sourceline;
- }
- PUSH_CLASS();
- ruby_class = ruby_cbase;
-
- ruby_in_eval++;
- if (TYPE(ruby_class) == T_ICLASS) {
- ruby_class = RBASIC(ruby_class)->klass;
- }
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- NODE *node;
-
- result = ruby_errinfo;
- ruby_errinfo = Qnil;
- node = compile(src, file, line);
- if (ruby_nerrs > 0) {
- compile_error(0);
- }
- if (!NIL_P(result)) ruby_errinfo = result;
- result = eval_node(self, node);
- }
- POP_TAG();
- POP_CLASS();
- ruby_in_eval--;
- if (!NIL_P(scope)) {
- int dont_recycle = ruby_scope->flags & SCOPE_DONT_RECYCLE;
-
- ruby_wrapper = old_wrapper;
- ruby_cref = (NODE*)old_cref;
- ruby_frame = frame.tmp;
- ruby_scope = old_scope;
- ruby_block = old_block;
- ruby_dyna_vars = old_dyna_vars;
- data->vmode = scope_vmode; /* write back visibility mode */
- scope_vmode = old_vmode;
- if (dont_recycle) {
- struct tag *tag;
- struct RVarmap *vars;
-
- scope_dup(ruby_scope);
- for (tag=prot_tag; tag; tag=tag->prev) {
- scope_dup(tag->scope);
- }
- if (ruby_block) {
- struct BLOCK *block = ruby_block;
- while (block) {
- block->tag->flags |= BLOCK_DYNAMIC;
- block = block->prev;
- }
- }
- for (vars = ruby_dyna_vars; vars; vars = vars->next) {
- FL_SET(vars, DVAR_DONT_RECYCLE);
- }
- }
- }
- else {
- ruby_frame->iter = iter;
- }
- ruby_sourcefile = filesave;
- ruby_sourceline = linesave;
- if (state) {
- if (state == TAG_RAISE) {
- VALUE err;
- VALUE errat;
-
- if (strcmp(file, "(eval)") == 0) {
- if (ruby_sourceline > 1) {
- errat = get_backtrace(ruby_errinfo);
- err = RARRAY(errat)->ptr[0];
- rb_str_cat2(err, ": ");
- rb_str_append(err, ruby_errinfo);
- }
- else {
- err = rb_str_dup(ruby_errinfo);
- }
- errat = Qnil;
- rb_exc_raise(rb_funcall(ruby_errinfo, rb_intern("exception"), 1, err));
- }
- rb_exc_raise(ruby_errinfo);
- }
- JUMP_TAG(state);
- }
-
- return result;
-}
-
-static VALUE
-rb_f_eval(argc, argv, self)
- int argc;
- VALUE *argv;
- VALUE self;
-{
- VALUE src, scope, vfile, vline;
- char *file = "(eval)";
- int line = 1;
-
- rb_scan_args(argc, argv, "13", &src, &scope, &vfile, &vline);
- if (ruby_safe_level >= 4) {
- StringValue(src);
- if (!NIL_P(scope) && !OBJ_TAINTED(scope)) {
- rb_raise(rb_eSecurityError, "Insecure: can't modify trusted binding");
- }
- }
- else {
- SafeStringValue(src);
- }
- if (argc >= 3) {
- file = StringValuePtr(vfile);
- }
- if (argc >= 4) {
- line = NUM2INT(vline);
- }
-
- if (NIL_P(scope) && ruby_frame->prev) {
- struct FRAME *prev;
- VALUE val;
-
- prev = ruby_frame;
- PUSH_FRAME();
- *ruby_frame = *prev->prev;
- ruby_frame->prev = prev;
- val = eval(self, src, scope, file, line);
- POP_FRAME();
-
- return val;
- }
- return eval(self, src, scope, file, line);
-}
-
-/* function to call func under the specified class/module context */
-static VALUE
-exec_under(func, under, args)
- VALUE (*func)();
- VALUE under;
- void *args;
-{
- VALUE val; /* OK */
- int state;
- int mode;
-
- PUSH_CLASS();
- ruby_class = under;
- PUSH_FRAME();
- ruby_frame->self = _frame.prev->self;
- ruby_frame->last_func = _frame.prev->last_func;
- ruby_frame->last_class = _frame.prev->last_class;
- ruby_frame->argc = _frame.prev->argc;
- ruby_frame->argv = _frame.prev->argv;
- if (ruby_cbase != under) {
- ruby_frame->cbase = (VALUE)rb_node_newnode(NODE_CREF,under,0,ruby_frame->cbase);
- }
- PUSH_CREF(under);
-
- mode = scope_vmode;
- SCOPE_SET(SCOPE_PUBLIC);
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- val = (*func)(args);
- }
- POP_TAG();
- POP_CREF();
- SCOPE_SET(mode);
- POP_FRAME();
- POP_CLASS();
- if (state) JUMP_TAG(state);
-
- return val;
-}
-
-static VALUE
-eval_under_i(args)
- VALUE *args;
-{
- return eval(args[0], args[1], Qnil, (char*)args[2], (int)args[3]);
-}
-
-/* string eval under the class/module context */
-static VALUE
-eval_under(under, self, src, file, line)
- VALUE under, self, src;
- const char *file;
- int line;
-{
- VALUE args[4];
-
- if (ruby_safe_level >= 4) {
- StringValue(src);
- }
- else {
- SafeStringValue(src);
- }
- args[0] = self;
- args[1] = src;
- args[2] = (VALUE)file;
- args[3] = (VALUE)line;
- return exec_under(eval_under_i, under, args);
-}
-
-static VALUE
-yield_under_i(self)
- VALUE self;
-{
- if (ruby_block->flags & BLOCK_DYNAMIC) {
- struct BLOCK * volatile old_block = ruby_block;
- struct BLOCK block;
-
- /* cbase should be pointed from volatile local variable */
- /* to be protected from GC. */
- VALUE result;
- int state;
-
- /* copy the block to avoid modifying global data. */
- block = *ruby_block;
- block.frame.cbase = ruby_frame->cbase;
- ruby_block = &block;
-
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- result = rb_yield_0(self, self, ruby_class, 0);
- }
- POP_TAG();
- ruby_block = old_block;
- if (state) JUMP_TAG(state);
-
- return result;
- }
- /* static block, no need to restore */
- ruby_block->frame.cbase = ruby_frame->cbase;
- return rb_yield_0(self, self, ruby_class, 0);
-}
-
-/* block eval under the class/module context */
-static VALUE
-yield_under(under, self)
- VALUE under, self;
-{
- return exec_under(yield_under_i, under, self);
-}
-
-static VALUE
-specific_eval(argc, argv, klass, self)
- int argc;
- VALUE *argv;
- VALUE klass, self;
-{
- if (rb_block_given_p()) {
- if (argc > 0) {
- rb_raise(rb_eArgError, "wrong number of arguments (%d for 0)", argc);
- }
- return yield_under(klass, self);
- }
- else {
- char *file = "(eval)";
- int line = 1;
-
- if (argc == 0) {
- rb_raise(rb_eArgError, "block not supplied");
- }
- else {
- if (ruby_safe_level >= 4) {
- StringValue(argv[0]);
- }
- else {
- SafeStringValue(argv[0]);
- }
- if (argc > 3) {
- rb_raise(rb_eArgError, "wrong number of arguments: %s(src) or %s{..}",
- rb_id2name(ruby_frame->last_func),
- rb_id2name(ruby_frame->last_func));
- }
- if (argc > 1) {
- file = StringValuePtr(argv[1]);
- }
- if (argc > 2) line = NUM2INT(argv[2]);
- }
- return eval_under(klass, self, argv[0], file, line);
- }
-}
-
-VALUE
-rb_obj_instance_eval(argc, argv, self)
- int argc;
- VALUE *argv;
- VALUE self;
-{
- VALUE klass;
-
- if (rb_special_const_p(self)) {
- klass = Qnil;
- }
- else {
- klass = rb_singleton_class(self);
- }
-
- return specific_eval(argc, argv, klass, self);
-}
-
-VALUE
-rb_mod_module_eval(argc, argv, mod)
- int argc;
- VALUE *argv;
- VALUE mod;
-{
- return specific_eval(argc, argv, mod, mod);
-}
-
-VALUE rb_load_path;
-
-void
-rb_load(fname, wrap)
- VALUE fname;
- int wrap;
-{
- VALUE tmp;
- int state;
- volatile ID last_func;
- volatile VALUE wrapper = 0;
- volatile VALUE self = ruby_top_self;
- NODE *saved_cref = ruby_cref;
- TMP_PROTECT;
-
- if (wrap && ruby_safe_level >= 4) {
- StringValue(fname);
- }
- else {
- SafeStringValue(fname);
- }
- tmp = rb_find_file(fname);
- if (!tmp) {
- rb_raise(rb_eLoadError, "No such file to load -- %s", RSTRING(fname)->ptr);
- }
- fname = tmp;
-
- ruby_errinfo = Qnil; /* ensure */
- PUSH_VARS();
- PUSH_CLASS();
- wrapper = ruby_wrapper;
- ruby_cref = top_cref;
- if (!wrap) {
- rb_secure(4); /* should alter global state */
- ruby_class = rb_cObject;
- ruby_wrapper = 0;
- }
- else {
- /* load in anonymous module as toplevel */
- ruby_class = ruby_wrapper = rb_module_new();
- self = rb_obj_clone(ruby_top_self);
- rb_extend_object(self, ruby_class);
- PUSH_CREF(ruby_wrapper);
- }
- PUSH_FRAME();
- ruby_frame->last_func = 0;
- ruby_frame->last_class = 0;
- ruby_frame->self = self;
- ruby_frame->cbase = (VALUE)rb_node_newnode(NODE_CREF,ruby_class,0,0);
- PUSH_SCOPE();
- /* default visibility is private at loading toplevel */
- SCOPE_SET(SCOPE_PRIVATE);
- PUSH_TAG(PROT_NONE);
- state = EXEC_TAG();
- last_func = ruby_frame->last_func;
- if (state == 0) {
- NODE *node;
-
- DEFER_INTS;
- ruby_in_eval++;
- rb_load_file(RSTRING(fname)->ptr);
- ruby_in_eval--;
- node = ruby_eval_tree;
- ALLOW_INTS;
- if (ruby_nerrs == 0) {
- eval_node(self, node);
- }
- }
- ruby_frame->last_func = last_func;
- if (ruby_scope->flags == SCOPE_ALLOCA && ruby_class == rb_cObject) {
- if (ruby_scope->local_tbl) /* toplevel was empty */
- free(ruby_scope->local_tbl);
- }
- POP_TAG();
- ruby_cref = saved_cref;
- POP_SCOPE();
- POP_FRAME();
- POP_CLASS();
- POP_VARS();
- ruby_wrapper = wrapper;
- if (ruby_nerrs > 0) {
- ruby_nerrs = 0;
- rb_exc_raise(ruby_errinfo);
- }
- if (state) jump_tag_but_local_jump(state);
- if (!NIL_P(ruby_errinfo)) /* exception during load */
- rb_exc_raise(ruby_errinfo);
-}
-
-void
-rb_load_protect(fname, wrap, state)
- VALUE fname;
- int wrap;
- int *state;
-{
- int status;
-
- PUSH_TAG(PROT_NONE);
- if ((status = EXEC_TAG()) == 0) {
- rb_load(fname, wrap);
- }
- POP_TAG();
- if (state) *state = status;
-}
-
-static VALUE
-rb_f_load(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE fname, wrap;
-
- rb_scan_args(argc, argv, "11", &fname, &wrap);
- rb_load(fname, RTEST(wrap));
- return Qtrue;
-}
-
-VALUE ruby_dln_librefs;
-static VALUE rb_features;
-static st_table *loading_tbl;
-
-static int
-rb_feature_p(feature, wait)
- const char *feature;
- int wait;
-{
- VALUE v;
- char *f;
- int i, len = strlen(feature);
-
- for (i = 0; i < RARRAY(rb_features)->len; ++i) {
- v = RARRAY(rb_features)->ptr[i];
- f = StringValuePtr(v);
- if (strcmp(f, feature) == 0) {
- goto load_wait;
- }
- if (strncmp(f, feature, len) == 0) {
- if (strcmp(f+len, ".so") == 0) {
- return Qtrue;
- }
- if (strcmp(f+len, ".rb") == 0) {
- if (wait) goto load_wait;
- return Qtrue;
- }
- }
- }
- return Qfalse;
-
- load_wait:
- if (loading_tbl) {
- char *ext = strrchr(f, '.');
- if (ext && strcmp(ext, ".rb") == 0) {
- rb_thread_t th;
-
- while (st_lookup(loading_tbl, f, &th)) {
- if (th == curr_thread) {
- return Qtrue;
- }
- CHECK_INTS;
- rb_thread_schedule();
- }
- }
- }
- return Qtrue;
-}
-
-static const char *const loadable_ext[] = {
- ".rb", DLEXT,
-#ifdef DLEXT2
- DLEXT2,
-#endif
- 0
-};
-
-int
-rb_provided(feature)
- const char *feature;
-{
- VALUE f = rb_str_new2(feature);
-
- if (strrchr(feature, '.') == 0) {
- if (rb_find_file_ext(&f, loadable_ext) == 0) {
- return rb_feature_p(feature, Qfalse);
- }
- }
- return rb_feature_p(RSTRING(f)->ptr, Qfalse);
-}
-
-static void
-rb_provide_feature(feature)
- VALUE feature;
-{
- rb_ary_push(rb_features, feature);
-}
-
-void
-rb_provide(feature)
- const char *feature;
-{
- rb_provide_feature(rb_str_new2(feature));
-}
-
-VALUE
-rb_f_require(obj, fname)
- VALUE obj, fname;
-{
- VALUE feature, tmp;
- char *ext, *ftptr; /* OK */
- volatile VALUE load;
- int state;
- volatile int safe = ruby_safe_level;
-
- SafeStringValue(fname);
- ext = strrchr(RSTRING(fname)->ptr, '.');
- if (ext) {
- if (strcmp(".rb", ext) == 0) {
- feature = rb_str_dup(fname);
- tmp = rb_find_file(fname);
- if (tmp) {
- fname = tmp;
- goto load_rb;
- }
- }
- else if (strcmp(".so", ext) == 0 || strcmp(".o", ext) == 0) {
- fname = rb_str_new(RSTRING(fname)->ptr, ext-RSTRING(fname)->ptr);
-#ifdef DLEXT2
- tmp = fname;
- if (rb_find_file_ext(&tmp, loadable_ext+1)) {
- feature = tmp;
- fname = rb_find_file(tmp);
- goto load_dyna;
- }
-#else
- feature = tmp = rb_str_dup(fname);
- rb_str_cat2(tmp, DLEXT);
- tmp = rb_find_file(tmp);
- if (tmp) {
- fname = tmp;
- goto load_dyna;
- }
-#endif
- }
- else if (strcmp(DLEXT, ext) == 0) {
- tmp = rb_find_file(fname);
- if (tmp) {
- feature = fname;
- fname = tmp;
- goto load_dyna;
- }
- }
-#ifdef DLEXT2
- else if (strcmp(DLEXT2, ext) == 0) {
- tmp = rb_find_file(fname);
- if (tmp) {
- feature = fname;
- fname = tmp;
- goto load_dyna;
- }
- }
-#endif
- }
- tmp = fname;
- switch (rb_find_file_ext(&tmp, loadable_ext)) {
- case 0:
- break;
-
- case 1:
- feature = fname = tmp;
- goto load_rb;
-
- default:
- feature = tmp;
- fname = rb_find_file(tmp);
- goto load_dyna;
- }
- if (rb_feature_p(RSTRING(fname)->ptr, Qfalse))
- return Qfalse;
- rb_raise(rb_eLoadError, "No such file to load -- %s", RSTRING(fname)->ptr);
-
- load_dyna:
- if (rb_feature_p(RSTRING(feature)->ptr, Qfalse))
- return Qfalse;
- rb_provide_feature(feature);
- {
- int volatile old_vmode = scope_vmode;
-
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- void *handle;
-
- SCOPE_SET(SCOPE_PUBLIC);
- handle = dln_load(RSTRING(fname)->ptr);
- rb_ary_push(ruby_dln_librefs, INT2NUM((long)handle));
- }
- POP_TAG();
- SCOPE_SET(old_vmode);
- }
- if (state) JUMP_TAG(state);
-
- return Qtrue;
-
- load_rb:
- if (rb_feature_p(RSTRING(feature)->ptr, Qtrue))
- return Qfalse;
- ruby_safe_level = 0;
- rb_provide_feature(feature);
- /* loading ruby library should be serialized. */
- if (!loading_tbl) {
- loading_tbl = st_init_strtable();
- }
- /* partial state */
- ftptr = ruby_strdup(RSTRING(feature)->ptr);
- st_insert(loading_tbl, ftptr, curr_thread);
-
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- rb_load(fname, 0);
- }
- POP_TAG();
- st_delete(loading_tbl, &ftptr, 0); /* loading done */
- free(ftptr);
- ruby_safe_level = safe;
- if (state) JUMP_TAG(state);
-
- return Qtrue;
-}
-
-VALUE
-rb_require(fname)
- const char *fname;
-{
- return rb_f_require(Qnil, rb_str_new2(fname));
-}
-
-static void
-secure_visibility(self)
- VALUE self;
-{
- if (rb_safe_level() >= 4 && !OBJ_TAINTED(self)) {
- rb_raise(rb_eSecurityError, "Insecure: can't change method visibility");
- }
-}
-
-static void
-set_method_visibility(self, argc, argv, ex)
- VALUE self;
- int argc;
- VALUE *argv;
- ID ex;
-{
- int i;
-
- secure_visibility(self);
- for (i=0; i<argc; i++) {
- rb_export_method(self, rb_to_id(argv[i]), ex);
- }
-}
-
-static VALUE
-rb_mod_public(argc, argv, module)
- int argc;
- VALUE *argv;
- VALUE module;
-{
- secure_visibility(module);
- if (argc == 0) {
- SCOPE_SET(SCOPE_PUBLIC);
- }
- else {
- set_method_visibility(module, argc, argv, NOEX_PUBLIC);
- }
- return module;
-}
-
-static VALUE
-rb_mod_protected(argc, argv, module)
- int argc;
- VALUE *argv;
- VALUE module;
-{
- secure_visibility(module);
- if (argc == 0) {
- SCOPE_SET(SCOPE_PROTECTED);
- }
- else {
- set_method_visibility(module, argc, argv, NOEX_PROTECTED);
- }
- return module;
-}
-
-static VALUE
-rb_mod_private(argc, argv, module)
- int argc;
- VALUE *argv;
- VALUE module;
-{
- secure_visibility(module);
- if (argc == 0) {
- SCOPE_SET(SCOPE_PRIVATE);
- }
- else {
- set_method_visibility(module, argc, argv, NOEX_PRIVATE);
- }
- return module;
-}
-
-static VALUE
-rb_mod_public_method(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- set_method_visibility(CLASS_OF(obj), argc, argv, NOEX_PUBLIC);
- return obj;
-}
-
-static VALUE
-rb_mod_private_method(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- set_method_visibility(CLASS_OF(obj), argc, argv, NOEX_PRIVATE);
- return obj;
-}
-
-static VALUE
-top_public(argc, argv)
- int argc;
- VALUE *argv;
-{
- return rb_mod_public(argc, argv, rb_cObject);
-}
-
-static VALUE
-top_private(argc, argv)
- int argc;
- VALUE *argv;
-{
- return rb_mod_private(argc, argv, rb_cObject);
-}
-
-static VALUE
-rb_mod_modfunc(argc, argv, module)
- int argc;
- VALUE *argv;
- VALUE module;
-{
- int i;
- ID id;
- NODE *body;
-
- if (TYPE(module) != T_MODULE) {
- rb_raise(rb_eTypeError, "module_function must be called for modules");
- }
-
- secure_visibility(module);
- if (argc == 0) {
- SCOPE_SET(SCOPE_MODFUNC);
- return module;
- }
-
- set_method_visibility(module, argc, argv, NOEX_PRIVATE);
- for (i=0; i<argc; i++) {
- VALUE m = module;
-
- id = rb_to_id(argv[i]);
- for (;;) {
- body = search_method(m, id, &m);
- if (body == 0 || body->nd_body == 0) {
- rb_bug("undefined method `%s'; can't happen", rb_id2name(id));
- }
- if (nd_type(body->nd_body) != NODE_ZSUPER) {
- break; /* normal case: need not to follow 'super' link */
- }
- m = RCLASS(m)->super;
- }
- rb_add_method(rb_singleton_class(module), id, body->nd_body, NOEX_PUBLIC);
- rb_funcall(module, singleton_added, 1, ID2SYM(id));
- }
- return module;
-}
-
-static VALUE
-rb_mod_append_features(module, include)
- VALUE module, include;
-{
- switch (TYPE(include)) {
- case T_CLASS:
- case T_MODULE:
- break;
- default:
- Check_Type(include, T_CLASS);
- break;
- }
- rb_include_module(include, module);
-
- return module;
-}
-
-static VALUE
-rb_mod_include(argc, argv, module)
- int argc;
- VALUE *argv;
- VALUE module;
-{
- while (argc--) {
- VALUE m = argv[argc];
-
- Check_Type(m, T_MODULE);
- rb_funcall(m, rb_intern("append_features"), 1, module);
- rb_funcall(m, rb_intern("included"), 1, module);
- }
- return module;
-}
-
-void
-rb_obj_call_init(obj, argc, argv)
- VALUE obj;
- int argc;
- VALUE *argv;
-{
- PUSH_ITER(rb_block_given_p()?ITER_PRE:ITER_NOT);
- rb_funcall2(obj, init, argc, argv);
- POP_ITER();
-}
-
-static VALUE
-top_include(argc, argv)
- int argc;
- VALUE *argv;
-{
- rb_secure(4);
- return rb_mod_include(argc, argv, rb_cObject);
-}
-
-void
-rb_extend_object(obj, module)
- VALUE obj, module;
-{
- rb_include_module(rb_singleton_class(obj), module);
-}
-
-static VALUE
-rb_mod_extend_object(mod, obj)
- VALUE mod, obj;
-{
- rb_extend_object(obj, mod);
- return obj;
-}
-
-static VALUE
-rb_obj_extend(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- int i;
-
- if (argc == 0) {
- rb_raise(rb_eArgError, "wrong number of arguments(0 for 1)");
- }
- for (i=0; i<argc; i++) Check_Type(argv[i], T_MODULE);
- while (argc--) {
- rb_funcall(argv[argc], rb_intern("extend_object"), 1, obj);
- }
- return obj;
-}
-
-VALUE rb_f_trace_var();
-VALUE rb_f_untrace_var();
-
-static void
-errinfo_setter(val, id, var)
- VALUE val;
- ID id;
- VALUE *var;
-{
- if (!NIL_P(val) && !rb_obj_is_kind_of(val, rb_eException)) {
- rb_raise(rb_eTypeError, "assigning non-exception to $!");
- }
- *var = val;
-}
-
-static VALUE
-errat_getter(id)
- ID id;
-{
- return get_backtrace(ruby_errinfo);
-}
-
-static void
-errat_setter(val, id, var)
- VALUE val;
- ID id;
- VALUE *var;
-{
- if (NIL_P(ruby_errinfo)) {
- rb_raise(rb_eArgError, "$! not set");
- }
- set_backtrace(ruby_errinfo, val);
-}
-
-static VALUE
-rb_f_local_variables()
-{
- ID *tbl;
- int n, i;
- VALUE ary = rb_ary_new();
- struct RVarmap *vars;
-
- tbl = ruby_scope->local_tbl;
- if (tbl) {
- n = *tbl++;
- for (i=2; i<n; i++) { /* skip first 2 ($_ and $~) */
- if (!rb_is_local_id(tbl[i])) continue; /* skip flip states */
- rb_ary_push(ary, rb_str_new2(rb_id2name(tbl[i])));
- }
- }
-
- vars = ruby_dyna_vars;
- while (vars) {
- if (vars->id) {
- rb_ary_push(ary, rb_str_new2(rb_id2name(vars->id)));
- }
- vars = vars->next;
- }
-
- return ary;
-}
-
-static VALUE rb_f_catch _((VALUE,VALUE));
-NORETURN(static VALUE rb_f_throw _((int,VALUE*)));
-
-struct end_proc_data {
- void (*func)();
- VALUE data;
- struct end_proc_data *next;
-};
-
-static struct end_proc_data *end_procs, *ephemeral_end_procs;
-
-void
-rb_set_end_proc(func, data)
- void (*func) _((VALUE));
- VALUE data;
-{
- struct end_proc_data *link = ALLOC(struct end_proc_data);
- struct end_proc_data **list;
-
- if (ruby_wrapper) list = &ephemeral_end_procs;
- else list = &end_procs;
- link->next = *list;
- link->func = func;
- link->data = data;
- *list = link;
-}
-
-void
-rb_mark_end_proc()
-{
- struct end_proc_data *link;
-
- link = end_procs;
- while (link) {
- rb_gc_mark(link->data);
- link = link->next;
- }
- link = ephemeral_end_procs;
- while (link) {
- rb_gc_mark(link->data);
- link = link->next;
- }
-}
-
-static void call_end_proc _((VALUE data));
-
-static void
-call_end_proc(data)
- VALUE data;
-{
- PUSH_ITER(ITER_NOT);
- PUSH_FRAME();
- ruby_frame->self = ruby_frame->prev->self;
- ruby_frame->last_func = 0;
- ruby_frame->last_class = 0;
- proc_invoke(data, rb_ary_new2(0), Qfalse, Qundef);
- POP_FRAME();
- POP_ITER();
-}
-
-static void
-rb_f_END()
-{
- PUSH_FRAME();
- ruby_frame->argc = 0;
- rb_set_end_proc(call_end_proc, rb_f_lambda());
- POP_FRAME();
-}
-
-static VALUE
-rb_f_at_exit()
-{
- VALUE proc;
-
- proc = rb_f_lambda();
-
- rb_set_end_proc(call_end_proc, proc);
- return proc;
-}
-
-void
-rb_exec_end_proc()
-{
- struct end_proc_data *link, *save;
- int status;
-
- save = link = end_procs;
- while (link) {
- rb_protect((VALUE(*)_((VALUE)))link->func, link->data, &status);
- if (status) {
- error_handle(status);
- }
- link = link->next;
- }
- link = end_procs;
- while (link != save) {
- rb_protect((VALUE(*)_((VALUE)))link->func, link->data, &status);
- if (status) {
- error_handle(status);
- }
- link = link->next;
- }
- while (ephemeral_end_procs) {
- link = ephemeral_end_procs;
- ephemeral_end_procs = link->next;
- rb_protect((VALUE(*)_((VALUE)))link->func, link->data, &status);
- if (status) {
- error_handle(status);
- }
- free(link);
- }
-}
-
-void
-Init_eval()
-{
- init = rb_intern("initialize");
- alloc = rb_intern("allocate");
- eqq = rb_intern("===");
- each = rb_intern("each");
-
- aref = rb_intern("[]");
- aset = rb_intern("[]=");
- match = rb_intern("=~");
- to_ary = rb_intern("to_ary");
- missing = rb_intern("method_missing");
- added = rb_intern("method_added");
- singleton_added = rb_intern("singleton_method_added");
- removed = rb_intern("method_removed");
- singleton_removed = rb_intern("singleton_method_removed");
- undefined = rb_intern("method_undefined");
- singleton_undefined = rb_intern("singleton_method_undefined");
-
- __id__ = rb_intern("__id__");
- __send__ = rb_intern("__send__");
-
- rb_global_variable((VALUE*)&top_scope);
- rb_global_variable((VALUE*)&ruby_eval_tree_begin);
-
- rb_global_variable((VALUE*)&ruby_eval_tree);
- rb_global_variable((VALUE*)&ruby_dyna_vars);
-
- rb_define_virtual_variable("$@", errat_getter, errat_setter);
- rb_define_hooked_variable("$!", &ruby_errinfo, 0, errinfo_setter);
-
- rb_define_global_function("eval", rb_f_eval, -1);
- rb_define_global_function("iterator?", rb_f_block_given_p, 0);
- rb_define_global_function("block_given?", rb_f_block_given_p, 0);
- rb_define_global_function("method_missing", rb_f_missing, -1);
- rb_define_global_function("loop", rb_f_loop, 0);
-
- rb_define_method(rb_mKernel, "respond_to?", rb_obj_respond_to, -1);
-
- rb_define_global_function("raise", rb_f_raise, -1);
- rb_define_global_function("fail", rb_f_raise, -1);
-
- rb_define_global_function("caller", rb_f_caller, -1);
-
- rb_define_global_function("exit", rb_f_exit, -1);
- rb_define_global_function("abort", rb_f_abort, -1);
-
- rb_define_global_function("at_exit", rb_f_at_exit, 0);
-
- rb_define_global_function("catch", rb_f_catch, 1);
- rb_define_global_function("throw", rb_f_throw, -1);
- rb_define_global_function("global_variables", rb_f_global_variables, 0);
- rb_define_global_function("local_variables", rb_f_local_variables, 0);
-
- rb_define_method(rb_mKernel, "send", rb_f_send, -1);
- rb_define_method(rb_mKernel, "__send__", rb_f_send, -1);
- rb_define_method(rb_mKernel, "instance_eval", rb_obj_instance_eval, -1);
-
- rb_define_private_method(rb_cModule, "append_features", rb_mod_append_features, 1);
- rb_define_private_method(rb_cModule, "extend_object", rb_mod_extend_object, 1);
- rb_define_private_method(rb_cModule, "include", rb_mod_include, -1);
- rb_define_private_method(rb_cModule, "public", rb_mod_public, -1);
- rb_define_private_method(rb_cModule, "protected", rb_mod_protected, -1);
- rb_define_private_method(rb_cModule, "private", rb_mod_private, -1);
- rb_define_private_method(rb_cModule, "module_function", rb_mod_modfunc, -1);
- rb_define_method(rb_cModule, "method_defined?", rb_mod_method_defined, 1);
- rb_define_method(rb_cModule, "public_class_method", rb_mod_public_method, -1);
- rb_define_method(rb_cModule, "private_class_method", rb_mod_private_method, -1);
- rb_define_method(rb_cModule, "module_eval", rb_mod_module_eval, -1);
- rb_define_method(rb_cModule, "class_eval", rb_mod_module_eval, -1);
-
- rb_undef_method(rb_cClass, "module_function");
-
- rb_define_private_method(rb_cModule, "remove_method", rb_mod_remove_method, 1);
- rb_define_private_method(rb_cModule, "undef_method", rb_mod_undef_method, 1);
- rb_define_private_method(rb_cModule, "alias_method", rb_mod_alias_method, 2);
- rb_define_private_method(rb_cModule, "define_method", rb_mod_define_method, -1);
-
- rb_define_singleton_method(rb_cModule, "nesting", rb_mod_nesting, 0);
- rb_define_singleton_method(rb_cModule, "constants", rb_mod_s_constants, 0);
-
- rb_define_singleton_method(ruby_top_self, "include", top_include, -1);
- rb_define_singleton_method(ruby_top_self, "public", top_public, -1);
- rb_define_singleton_method(ruby_top_self, "private", top_private, -1);
-
- rb_define_method(rb_mKernel, "extend", rb_obj_extend, -1);
-
- rb_define_global_function("trace_var", rb_f_trace_var, -1);
- rb_define_global_function("untrace_var", rb_f_untrace_var, -1);
-
- rb_define_global_function("set_trace_func", set_trace_func, 1);
- rb_global_variable(&trace_func);
-
- rb_define_virtual_variable("$SAFE", safe_getter, safe_setter);
-}
-
-VALUE rb_f_autoload();
-
-void
-Init_load()
-{
- rb_load_path = rb_ary_new();
- rb_define_readonly_variable("$:", &rb_load_path);
- rb_define_readonly_variable("$-I", &rb_load_path);
- rb_define_readonly_variable("$LOAD_PATH", &rb_load_path);
-
- rb_features = rb_ary_new();
- rb_define_readonly_variable("$\"", &rb_features);
-
- rb_define_global_function("load", rb_f_load, -1);
- rb_define_global_function("require", rb_f_require, 1);
- rb_define_global_function("autoload", rb_f_autoload, 2);
- rb_global_variable(&ruby_wrapper);
-
- ruby_dln_librefs = rb_ary_new();
- rb_global_variable(&ruby_dln_librefs);
-}
-
-static void
-scope_dup(scope)
- struct SCOPE *scope;
-{
- ID *tbl;
- VALUE *vars;
-
- scope->flags |= SCOPE_DONT_RECYCLE;
- if (scope->flags & SCOPE_MALLOC) return;
-
- if (scope->local_tbl) {
- tbl = scope->local_tbl;
- vars = ALLOC_N(VALUE, tbl[0]+1);
- *vars++ = scope->local_vars[-1];
- MEMCPY(vars, scope->local_vars, VALUE, tbl[0]);
- scope->local_vars = vars;
- scope->flags |= SCOPE_MALLOC;
- }
-}
-
-static void
-blk_mark(data)
- struct BLOCK *data;
-{
- while (data) {
- rb_gc_mark_frame(&data->frame);
- rb_gc_mark((VALUE)data->scope);
- rb_gc_mark((VALUE)data->var);
- rb_gc_mark((VALUE)data->body);
- rb_gc_mark((VALUE)data->self);
- rb_gc_mark((VALUE)data->dyna_vars);
- rb_gc_mark((VALUE)data->klass);
- rb_gc_mark((VALUE)data->tag);
- rb_gc_mark(data->wrapper);
- data = data->prev;
- }
-}
-
-static void
-blk_free(data)
- struct BLOCK *data;
-{
- struct FRAME *frame;
- void *tmp;
-
- frame = data->frame.prev;
- while (frame) {
- if (frame->argc > 0 && (frame->flags & FRAME_MALLOC))
- free(frame->argv);
- tmp = frame;
- frame = frame->prev;
- free(tmp);
- }
- while (data) {
- if (data->frame.argc > 0)
- free(data->frame.argv);
- tmp = data;
- data = data->prev;
- free(tmp);
- }
-}
-
-static void
-blk_copy_prev(block)
- struct BLOCK *block;
-{
- struct BLOCK *tmp;
- struct RVarmap* vars;
-
- while (block->prev) {
- tmp = ALLOC_N(struct BLOCK, 1);
- MEMCPY(tmp, block->prev, struct BLOCK, 1);
- if (tmp->frame.argc > 0) {
- tmp->frame.argv = ALLOC_N(VALUE, tmp->frame.argc);
- MEMCPY(tmp->frame.argv, block->prev->frame.argv, VALUE, tmp->frame.argc);
- tmp->frame.flags |= FRAME_MALLOC;
- }
- scope_dup(tmp->scope);
- tmp->tag->flags |= BLOCK_DYNAMIC;
-
- for (vars = tmp->dyna_vars; vars; vars = vars->next) {
- if (FL_TEST(vars, DVAR_DONT_RECYCLE)) break;
- FL_SET(vars, DVAR_DONT_RECYCLE);
- }
-
- block->prev = tmp;
- block = tmp;
- }
-}
-
-static void
-frame_dup(frame)
- struct FRAME *frame;
-{
- VALUE *argv;
- struct FRAME *tmp;
-
- for (;;) {
- if (frame->argc > 0) {
- argv = ALLOC_N(VALUE, frame->argc);
- MEMCPY(argv, frame->argv, VALUE, frame->argc);
- frame->argv = argv;
- frame->flags |= FRAME_MALLOC;
- }
- frame->tmp = 0; /* should not preserve tmp */
- if (!frame->prev) break;
- tmp = ALLOC(struct FRAME);
- *tmp = *frame->prev;
- frame->prev = tmp;
- frame = tmp;
- }
-}
-
-static VALUE
-bind_clone(self)
- VALUE self;
-{
- struct BLOCK *orig, *data;
- VALUE bind;
-
- Data_Get_Struct(self, struct BLOCK, orig);
- bind = Data_Make_Struct(rb_cBinding,struct BLOCK,blk_mark,blk_free,data);
- CLONESETUP(bind, self);
- MEMCPY(data, orig, struct BLOCK, 1);
- frame_dup(&data->frame);
-
- if (data->iter) {
- blk_copy_prev(data);
- }
- else {
- data->prev = 0;
- }
-
- return bind;
-}
-
-static VALUE
-rb_f_binding(self)
- VALUE self;
-{
- struct BLOCK *data, *p;
- struct RVarmap *vars;
- VALUE bind;
-
- PUSH_BLOCK(0,0);
- bind = Data_Make_Struct(rb_cBinding,struct BLOCK,blk_mark,blk_free,data);
- *data = *ruby_block;
-
- data->orig_thread = rb_thread_current();
- data->wrapper = ruby_wrapper;
- data->iter = rb_f_block_given_p();
- frame_dup(&data->frame);
- if (ruby_frame->prev) {
- data->frame.last_func = ruby_frame->prev->last_func;
- data->frame.last_class = ruby_frame->prev->last_class;
- }
-
- if (data->iter) {
- blk_copy_prev(data);
- }
- else {
- data->prev = 0;
- }
- data->flags |= BLOCK_DYNAMIC;
- data->tag->flags |= BLOCK_DYNAMIC;
-
- for (p = data; p; p = p->prev) {
- for (vars = p->dyna_vars; vars; vars = vars->next) {
- if (FL_TEST(vars, DVAR_DONT_RECYCLE)) break;
- FL_SET(vars, DVAR_DONT_RECYCLE);
- }
- }
- scope_dup(data->scope);
- POP_BLOCK();
-
- return bind;
-}
-
-#define PROC_T3 FL_USER1
-#define PROC_T4 FL_USER2
-#define PROC_TMAX (FL_USER1|FL_USER2)
-#define PROC_TMASK (FL_USER1|FL_USER2)
-
-static void
-proc_save_safe_level(data)
- VALUE data;
-{
- if (OBJ_TAINTED(data)) {
- switch (rb_safe_level()) {
- case 3:
- FL_SET(data, PROC_T3);
- break;
- case 4:
- FL_SET(data, PROC_T4);
- break;
- default:
- if (rb_safe_level() > 4) {
- FL_SET(data, PROC_TMAX);
- }
- break;
- }
- }
-}
-
-static int
-proc_get_safe_level(data)
- VALUE data;
-{
- if (OBJ_TAINTED(data)) {
- switch (RBASIC(data)->flags & PROC_TMASK) {
- case PROC_T3:
- return 3;
- case PROC_T4:
- return 4;
- case PROC_TMAX:
- return 5;
- }
- return 3;
- }
- return 0;
-}
-
-static void
-proc_set_safe_level(data)
- VALUE data;
-{
- if (OBJ_TAINTED(data)) {
- ruby_safe_level = proc_get_safe_level(data);
- }
-}
-
-static VALUE
-proc_new(klass)
- VALUE klass;
-{
- volatile VALUE proc;
- struct BLOCK *data, *p;
- struct RVarmap *vars;
-
- if (!rb_block_given_p() && !rb_f_block_given_p()) {
- rb_raise(rb_eArgError, "tried to create Proc object without a block");
- }
-
- proc = Data_Make_Struct(klass, struct BLOCK, blk_mark, blk_free, data);
- *data = *ruby_block;
-
- data->orig_thread = rb_thread_current();
- data->wrapper = ruby_wrapper;
- data->iter = data->prev?Qtrue:Qfalse;
- frame_dup(&data->frame);
- if (data->iter) {
- blk_copy_prev(data);
- }
- else {
- data->prev = 0;
- }
- data->flags |= BLOCK_DYNAMIC;
- data->tag->flags |= BLOCK_DYNAMIC;
-
- for (p = data; p; p = p->prev) {
- for (vars = p->dyna_vars; vars; vars = vars->next) {
- if (FL_TEST(vars, DVAR_DONT_RECYCLE)) break;
- FL_SET(vars, DVAR_DONT_RECYCLE);
- }
- }
- scope_dup(data->scope);
- proc_save_safe_level(proc);
-
- return proc;
-}
-
-static VALUE
-proc_s_new(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- VALUE proc = proc_new(klass);
-
- rb_obj_call_init(proc, argc, argv);
- return proc;
-}
-
-VALUE
-rb_f_lambda()
-{
- return proc_new(rb_cProc);
-}
-
-static int
-blk_orphan(data)
- struct BLOCK *data;
-{
- if (!(data->scope->flags & SCOPE_NOSTACK)) {
- return 0;
- }
- if ((data->tag->flags & BLOCK_ORPHAN)) {
- return 1;
- }
- if (data->orig_thread != rb_thread_current()) {
- return 1;
- }
- return 0;
-}
-
-static VALUE
-proc_invoke(proc, args, pcall, self)
- VALUE proc, args; /* OK */
- int pcall;
- VALUE self;
-{
- struct BLOCK * volatile old_block;
- struct BLOCK _block;
- struct BLOCK *data;
- volatile VALUE result = Qnil;
- int state;
- volatile int orphan;
- volatile int safe = ruby_safe_level;
- volatile VALUE old_wrapper = ruby_wrapper;
- struct RVarmap * volatile old_dvars = ruby_dyna_vars;
-
- if (rb_block_given_p() && ruby_frame->last_func) {
- rb_warning("block for %s#%s is useless",
- rb_class2name(CLASS_OF(proc)),
- rb_id2name(ruby_frame->last_func));
- }
-
- Data_Get_Struct(proc, struct BLOCK, data);
- orphan = blk_orphan(data);
-
- ruby_wrapper = data->wrapper;
- ruby_dyna_vars = data->dyna_vars;
- /* PUSH BLOCK from data */
- old_block = ruby_block;
- _block = *data;
- ruby_block = &_block;
-
- PUSH_ITER(ITER_CUR);
- ruby_frame->iter = ITER_CUR;
-
- if (!pcall) {
- args = avalue_to_svalue(args);
- }
- PUSH_TAG(PROT_NONE);
- state = EXEC_TAG();
- if (state == 0) {
- proc_set_safe_level(proc);
- result = rb_yield_0(args, self, self!=Qundef?CLASS_OF(self):0, pcall);
- }
- POP_TAG();
-
- POP_ITER();
- if (ruby_block->tag->dst == state) {
- state &= TAG_MASK;
- }
- ruby_block = old_block;
- ruby_wrapper = old_wrapper;
- ruby_dyna_vars = old_dvars;
- ruby_safe_level = safe;
-
- switch (state) {
- case 0:
- break;
- case TAG_BREAK:
- if (!pcall && orphan) {
- localjump_error("break from proc-closure", prot_tag->retval);
- }
- result = prot_tag->retval;
- break;
- case TAG_RETRY:
- localjump_error("retry from proc-closure", Qnil);
- break;
- case TAG_RETURN:
- if (orphan) { /* orphan procedure */
- localjump_error("return from proc-closure", prot_tag->retval);
- }
- /* fall through */
- default:
- JUMP_TAG(state);
- }
- return result;
-}
-
-static VALUE
-proc_call(proc, args)
- VALUE proc, args; /* OK */
-{
- return proc_invoke(proc, args, Qtrue, Qundef);
-}
-
-static VALUE
-proc_yield(proc, args)
- VALUE proc, args; /* OK */
-{
- return proc_invoke(proc, args, Qfalse, Qundef);
-}
-
-static VALUE
-proc_arity(proc)
- VALUE proc;
-{
- struct BLOCK *data;
- NODE *list;
- int n;
-
- Data_Get_Struct(proc, struct BLOCK, data);
- if (data->var == 0) return INT2FIX(-1);
- if (data->var == (NODE*)1) return INT2FIX(0);
- if (data->var == (NODE*)2) return INT2FIX(0);
- switch (nd_type(data->var)) {
- default:
- return INT2FIX(-1);
- case NODE_MASGN:
- list = data->var->nd_head;
- n = 0;
- while (list) {
- n++;
- list = list->nd_next;
- }
- if (data->var->nd_args) return INT2FIX(-n-1);
- return INT2FIX(n);
- }
-}
-
-static VALUE
-proc_eq(self, other)
- VALUE self, other;
-{
- struct BLOCK *data, *data2;
-
- if (self == other) return Qtrue;
- if (TYPE(other) != T_DATA) return Qfalse;
- if (RDATA(other)->dmark != (RUBY_DATA_FUNC)blk_mark) return Qfalse;
- if (CLASS_OF(self) != CLASS_OF(other)) return Qfalse;
- Data_Get_Struct(self, struct BLOCK, data);
- Data_Get_Struct(other, struct BLOCK, data2);
- if (data->tag == data2->tag) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-proc_to_s(self, other)
- VALUE self, other;
-{
- struct BLOCK *data;
- char *cname = rb_class2name(CLASS_OF(self));
- VALUE str;
-
- Data_Get_Struct(self, struct BLOCK, data);
- str = rb_str_new(0, strlen(cname)+6+16+1); /* 6:tags 16:addr 1:nul */
- sprintf(RSTRING(str)->ptr, "#<%s:0x%lx>", cname, data->tag);
- RSTRING(str)->len = strlen(RSTRING(str)->ptr);
- if (OBJ_TAINTED(self)) OBJ_TAINT(str);
-
- return str;
-}
-
-static VALUE
-block_pass(self, node)
- VALUE self;
- NODE *node;
-{
- VALUE block = rb_eval(self, node->nd_body); /* OK */
- struct BLOCK * volatile old_block;
- struct BLOCK _block;
- struct BLOCK *data;
- volatile VALUE result = Qnil;
- int state;
- volatile int orphan;
- volatile int safe = ruby_safe_level;
-
- if (NIL_P(block)) {
- PUSH_ITER(ITER_NOT);
- result = rb_eval(self, node->nd_iter);
- POP_ITER();
- return result;
- }
- if (rb_obj_is_kind_of(block, rb_cMethod)) {
- block = method_proc(block);
- }
- else if (!rb_obj_is_proc(block)) {
- rb_raise(rb_eTypeError, "wrong argument type %s (expected Proc)",
- rb_class2name(CLASS_OF(block)));
- }
-
- if (rb_safe_level() >= 1 && OBJ_TAINTED(block)) {
- if (rb_safe_level() > proc_get_safe_level(block)) {
- rb_raise(rb_eSecurityError, "Insecure: tainted block value");
- }
- }
-
- Data_Get_Struct(block, struct BLOCK, data);
- orphan = blk_orphan(data);
-
- retry:
- /* PUSH BLOCK from data */
- old_block = ruby_block;
- _block = *data;
- ruby_block = &_block;
- PUSH_ITER(ITER_PRE);
- ruby_frame->iter = ITER_PRE;
-
- PUSH_TAG(PROT_NONE);
- state = EXEC_TAG();
- if (state == 0) {
- proc_set_safe_level(block);
- if (safe > ruby_safe_level)
- ruby_safe_level = safe;
- result = rb_eval(self, node->nd_iter);
- }
- POP_TAG();
- POP_ITER();
- if (_block.tag->dst == state) {
- if (orphan) {
- state &= TAG_MASK;
- }
- else {
- struct BLOCK *ptr = old_block;
-
- while (ptr) {
- if (ptr->scope == _block.scope) {
- ptr->tag->dst = state;
- break;
- }
- ptr = ptr->prev;
- }
- if (!ptr) {
- state &= TAG_MASK;
- }
- }
- }
- ruby_block = old_block;
- ruby_safe_level = safe;
-
- switch (state) {/* escape from orphan procedure */
- case 0:
- break;
- case TAG_BREAK:
- result = prot_tag->retval;
- break;
- case TAG_RETRY:
- goto retry;
- case TAG_RETURN:
- if (orphan) {
- localjump_error("return from proc-closure", prot_tag->retval);
- }
- default:
- JUMP_TAG(state);
- }
-
- return result;
-}
-
-struct METHOD {
- VALUE klass, rklass;
- VALUE recv;
- ID id, oid;
- NODE *body;
-};
-
-static void
-bm_mark(data)
- struct METHOD *data;
-{
- rb_gc_mark(data->rklass);
- rb_gc_mark(data->klass);
- rb_gc_mark(data->recv);
- rb_gc_mark((VALUE)data->body);
-}
-
-static VALUE
-mnew(klass, obj, id, mklass)
- VALUE klass, obj, mklass;
- ID id;
-{
- VALUE method;
- NODE *body;
- int noex;
- struct METHOD *data;
- VALUE rklass = klass;
- ID oid = id;
-
- again:
- if ((body = rb_get_method_body(&klass, &id, &noex)) == 0) {
- print_undef(rklass, oid);
- }
-
- if (nd_type(body) == NODE_ZSUPER) {
- klass = RCLASS(klass)->super;
- goto again;
- }
-
- method = Data_Make_Struct(mklass, struct METHOD, bm_mark, free, data);
- data->klass = klass;
- data->recv = obj;
- data->id = id;
- data->body = body;
- data->rklass = rklass;
- data->oid = oid;
- OBJ_INFECT(method, klass);
-
- return method;
-}
-
-static VALUE
-method_eq(method, other)
- VALUE method, other;
-{
- struct METHOD *m1, *m2;
-
- if (TYPE(other) != T_DATA || RDATA(other)->dmark != (RUBY_DATA_FUNC)bm_mark)
- return Qfalse;
- if (CLASS_OF(method) != CLASS_OF(other))
- return Qfalse;
-
- Data_Get_Struct(method, struct METHOD, m1);
- Data_Get_Struct(other, struct METHOD, m2);
-
- if (m1->klass != m2->klass || m1->rklass != m2->rklass ||
- m1->recv != m2->recv || m1->body != m2->body)
- return Qfalse;
-
- return Qtrue;
-}
-
-static VALUE
-method_unbind(obj)
- VALUE obj;
-{
- VALUE method;
- struct METHOD *orig, *data;
-
- Data_Get_Struct(obj, struct METHOD, orig);
- method = Data_Make_Struct(rb_cUnboundMethod, struct METHOD, bm_mark, free, data);
- data->klass = orig->klass;
- data->recv = Qundef;
- data->id = orig->id;
- data->body = orig->body;
- data->rklass = orig->rklass;
- data->oid = orig->oid;
- OBJ_INFECT(method, obj);
-
- return method;
-}
-
-static VALUE
-umethod_unbind(obj)
- VALUE obj;
-{
- return obj;
-}
-
-static VALUE
-rb_obj_method(obj, vid)
- VALUE obj;
- VALUE vid;
-{
- return mnew(CLASS_OF(obj), obj, rb_to_id(vid), rb_cMethod);
-}
-
-static VALUE
-rb_mod_method(mod, vid)
- VALUE mod;
- VALUE vid;
-{
- return mnew(mod, Qundef, rb_to_id(vid), rb_cUnboundMethod);
-}
-
-static VALUE
-method_clone(self)
- VALUE self;
-{
- VALUE clone;
- struct METHOD *orig, *data;
-
- Data_Get_Struct(self, struct METHOD, orig);
- clone = Data_Make_Struct(CLASS_OF(self),struct METHOD, bm_mark, free, data);
- CLONESETUP(clone, self);
- *data = *orig;
-
- return clone;
-}
-
-static VALUE
-method_call(argc, argv, method)
- int argc;
- VALUE *argv;
- VALUE method;
-{
- VALUE result;
- struct METHOD *data;
- int state;
- volatile int safe = ruby_safe_level;
-
- Data_Get_Struct(method, struct METHOD, data);
- PUSH_ITER(rb_block_given_p()?ITER_PRE:ITER_NOT);
- PUSH_TAG(PROT_NONE);
- if (OBJ_TAINTED(method) && ruby_safe_level < 4) {
- ruby_safe_level = 4;
- }
- if ((state = EXEC_TAG()) == 0) {
- result = rb_call0(data->klass,data->recv,data->id,argc,argv,data->body,0);
- }
- POP_TAG();
- POP_ITER();
- ruby_safe_level = safe;
- if (state) JUMP_TAG(state);
- return result;
-}
-
-static VALUE
-umethod_call(argc, argv, method)
- int argc;
- VALUE *argv;
- VALUE method;
-{
- rb_raise(rb_eTypeError, "you cannot call unbound method; bind first");
- return Qnil; /* not reached */
-}
-
-static VALUE
-umethod_bind(method, recv)
- VALUE method, recv;
-{
- struct METHOD *data, *bound;
-
- Data_Get_Struct(method, struct METHOD, data);
- if (data->rklass != CLASS_OF(recv)) {
- if (FL_TEST(data->rklass, FL_SINGLETON)) {
- rb_raise(rb_eTypeError, "singleton method called for a different object");
- }
- if (FL_TEST(CLASS_OF(recv), FL_SINGLETON) &&
- st_lookup(RCLASS(CLASS_OF(recv))->m_tbl, data->oid, 0)) {
- rb_raise(rb_eTypeError, "method `%s' overridden", rb_id2name(data->oid));
- }
- if (!((TYPE(data->rklass) == T_MODULE) ?
- rb_obj_is_kind_of(recv, data->rklass) :
- rb_obj_is_instance_of(recv, data->rklass))) {
- rb_raise(rb_eTypeError, "bind argument must be an instance of %s",
- rb_class2name(data->rklass));
- }
- }
-
- method = Data_Make_Struct(rb_cMethod,struct METHOD,bm_mark,free,bound);
- *bound = *data;
- bound->recv = recv;
- bound->rklass = CLASS_OF(recv);
-
- return method;
-}
-
-static VALUE
-method_arity(method)
- VALUE method;
-{
- struct METHOD *data;
- NODE *body;
- int n;
-
- Data_Get_Struct(method, struct METHOD, data);
-
- body = data->body;
- switch (nd_type(body)) {
- case NODE_CFUNC:
- if (body->nd_argc < 0) return INT2FIX(-1);
- return INT2FIX(body->nd_argc);
- case NODE_ZSUPER:
- return INT2FIX(-1);
- case NODE_ATTRSET:
- return INT2FIX(1);
- case NODE_IVAR:
- return INT2FIX(0);
- default:
- body = body->nd_next; /* skip NODE_SCOPE */
- if (nd_type(body) == NODE_BLOCK)
- body = body->nd_head;
- if (!body) return INT2FIX(0);
- n = body->nd_cnt;
- if (body->nd_opt || body->nd_rest != -1)
- n = -n-1;
- return INT2FIX(n);
- }
-}
-
-static VALUE
-method_inspect(method)
- VALUE method;
-{
- struct METHOD *data;
- VALUE str;
- const char *s;
- char *sharp = "#";
-
- Data_Get_Struct(method, struct METHOD, data);
- str = rb_str_buf_new2("#<");
- s = rb_class2name(CLASS_OF(method));
- rb_str_buf_cat2(str, s);
- rb_str_buf_cat2(str, ": ");
-
- if (FL_TEST(data->klass, FL_SINGLETON)) {
- VALUE v = rb_iv_get(data->klass, "__attached__");
-
- if (data->recv == Qundef) {
- rb_str_buf_append(str, rb_inspect(data->klass));
- }
- else if (data->recv == v) {
- rb_str_buf_append(str, rb_inspect(v));
- sharp = ".";
- }
- else {
- rb_str_buf_append(str, rb_inspect(data->recv));
- rb_str_buf_cat2(str, "(");
- rb_str_buf_append(str, rb_inspect(v));
- rb_str_buf_cat2(str, ")");
- sharp = ".";
- }
- }
- else {
- rb_str_buf_cat2(str, rb_class2name(data->rklass));
- if (data->rklass != data->klass) {
- rb_str_buf_cat2(str, "(");
- rb_str_buf_cat2(str, rb_class2name(data->klass));
- rb_str_buf_cat2(str, ")");
- }
- }
- rb_str_buf_cat2(str, sharp);
- rb_str_buf_cat2(str, rb_id2name(data->oid));
- rb_str_buf_cat2(str, ">");
-
- return str;
-}
-
-static VALUE
-mproc()
-{
- VALUE proc;
-
- /* emulate ruby's method call */
- PUSH_ITER(ITER_CUR);
- PUSH_FRAME();
- proc = rb_f_lambda();
- POP_FRAME();
- POP_ITER();
-
- return proc;
-}
-
-static VALUE
-bmcall(args, method)
- VALUE args, method;
-{
- args = svalue_to_avalue(args);
- return method_call(RARRAY(args)->len, RARRAY(args)->ptr, method);
-}
-
-static VALUE
-umcall(args, method)
- VALUE args, method;
-{
- return umethod_call(0, 0, method);
-}
-
-static VALUE
-method_proc(method)
- VALUE method;
-{
- return rb_iterate((VALUE(*)_((VALUE)))mproc, 0, bmcall, method);
-}
-
-static VALUE
-umethod_proc(method)
- VALUE method;
-{
- return rb_iterate((VALUE(*)_((VALUE)))mproc, 0, umcall, method);
-}
-
-static VALUE
-rb_mod_define_method(argc, argv, mod)
- int argc;
- VALUE *argv;
- VALUE mod;
-{
- ID id;
- VALUE body;
- NODE *node;
- int noex;
-
- if (argc == 1) {
- id = rb_to_id(argv[0]);
- body = rb_f_lambda();
- }
- else if (argc == 2) {
- id = rb_to_id(argv[0]);
- body = argv[1];
- if (!rb_obj_is_kind_of(body, rb_cMethod) && !rb_obj_is_proc(body)) {
- rb_raise(rb_eTypeError, "wrong argument type %s (expected Proc/Method)",
- rb_class2name(CLASS_OF(body)));
- }
- }
- else {
- rb_raise(rb_eArgError, "wrong number of arguments(%d for 1)", argc);
- }
- if (RDATA(body)->dmark == (RUBY_DATA_FUNC)bm_mark) {
- node = NEW_DMETHOD(method_unbind(body));
- }
- else if (RDATA(body)->dmark == (RUBY_DATA_FUNC)blk_mark) {
- node = NEW_BMETHOD(body);
- }
- else {
- /* type error */
- rb_raise(rb_eTypeError, "wrong argument type (expected Proc/Method)");
- }
-
- if (SCOPE_TEST(SCOPE_PRIVATE)) {
- noex = NOEX_PRIVATE;
- }
- else if (SCOPE_TEST(SCOPE_PROTECTED)) {
- noex = NOEX_PROTECTED;
- }
- else {
- noex = NOEX_PUBLIC;
- }
- rb_add_method(mod, id, node, noex);
- if (scope_vmode == SCOPE_MODFUNC) {
- rb_add_method(rb_singleton_class(mod), id, node, NOEX_PUBLIC);
- rb_funcall(mod, singleton_added, 1, ID2SYM(id));
- }
- if (FL_TEST(mod, FL_SINGLETON)) {
- rb_funcall(rb_iv_get(mod, "__attached__"), singleton_added, 1, ID2SYM(id));
- }
- else {
- rb_funcall(mod, added, 1, ID2SYM(id));
- }
- return body;
-}
-
-void
-Init_Proc()
-{
- rb_eLocalJumpError = rb_define_class("LocalJumpError", rb_eStandardError);
- rb_define_method(rb_eLocalJumpError, "exitstatus", localjump_exitstatus, 0);
-
- rb_eSysStackError = rb_define_class("SystemStackError", rb_eStandardError);
-
- rb_cProc = rb_define_class("Proc", rb_cObject);
- rb_undef_method(CLASS_OF(rb_cProc), "allocate");
- rb_define_singleton_method(rb_cProc, "new", proc_s_new, -1);
-
- rb_define_method(rb_cProc, "call", proc_call, -2);
- rb_define_method(rb_cProc, "yield", proc_yield, -2);
- rb_define_method(rb_cProc, "arity", proc_arity, 0);
- rb_define_method(rb_cProc, "[]", proc_call, -2);
- rb_define_method(rb_cProc, "==", proc_eq, 1);
- rb_define_method(rb_cProc, "to_s", proc_to_s, 0);
- rb_define_global_function("proc", rb_f_lambda, 0);
- rb_define_global_function("lambda", rb_f_lambda, 0);
- rb_define_global_function("binding", rb_f_binding, 0);
- rb_cBinding = rb_define_class("Binding", rb_cObject);
- rb_undef_method(CLASS_OF(rb_cBinding), "allocate");
- rb_undef_method(CLASS_OF(rb_cBinding), "new");
- rb_define_method(rb_cBinding, "clone", bind_clone, 0);
-
- rb_cMethod = rb_define_class("Method", rb_cObject);
- rb_undef_method(CLASS_OF(rb_cMethod), "allocate");
- rb_undef_method(CLASS_OF(rb_cMethod), "new");
- rb_define_method(rb_cMethod, "==", method_eq, 1);
- rb_define_method(rb_cMethod, "clone", method_clone, 0);
- rb_define_method(rb_cMethod, "call", method_call, -1);
- rb_define_method(rb_cMethod, "[]", method_call, -1);
- rb_define_method(rb_cMethod, "arity", method_arity, 0);
- rb_define_method(rb_cMethod, "inspect", method_inspect, 0);
- rb_define_method(rb_cMethod, "to_s", method_inspect, 0);
- rb_define_method(rb_cMethod, "to_proc", method_proc, 0);
- rb_define_method(rb_cMethod, "unbind", method_unbind, 0);
- rb_define_method(rb_mKernel, "method", rb_obj_method, 1);
-
- rb_cUnboundMethod = rb_define_class("UnboundMethod", rb_cMethod);
- rb_define_method(rb_cUnboundMethod, "call", umethod_call, -1);
- rb_define_method(rb_cUnboundMethod, "[]", umethod_call, -1);
- rb_define_method(rb_cUnboundMethod, "to_proc", umethod_proc, 0);
- rb_define_method(rb_cUnboundMethod, "bind", umethod_bind, 1);
- rb_define_method(rb_cUnboundMethod, "unbind", umethod_unbind, 0);
- rb_define_method(rb_cModule, "instance_method", rb_mod_method, 1);
-}
-
-static VALUE rb_eThreadError;
-
-int rb_thread_pending = 0;
-
-VALUE rb_cThread;
-
-extern VALUE rb_last_status;
-
-enum thread_status {
- THREAD_TO_KILL,
- THREAD_RUNNABLE,
- THREAD_STOPPED,
- THREAD_KILLED
-};
-
-#define WAIT_FD (1<<0)
-#define WAIT_SELECT (1<<1)
-#define WAIT_TIME (1<<2)
-#define WAIT_JOIN (1<<3)
-#define WAIT_PID (1<<4)
-
-/* +infty, for this purpose */
-#define DELAY_INFTY 1E30
-
-/* typedef struct thread * rb_thread_t; */
-
-struct thread {
- struct thread *next, *prev;
- jmp_buf context;
-
- VALUE result;
-
- int stk_len;
- int stk_max;
- VALUE*stk_ptr;
- VALUE*stk_pos;
-
- struct FRAME *frame;
- struct SCOPE *scope;
- struct RVarmap *dyna_vars;
- struct BLOCK *block;
- struct iter *iter;
- struct tag *tag;
- VALUE klass;
- VALUE wrapper;
- NODE *cref;
-
- int flags; /* misc. states (vmode/rb_trap_immediate/raised) */
-
- char *file;
- int line;
-
- int tracing;
- VALUE errinfo;
- VALUE last_status;
- VALUE last_line;
- VALUE last_match;
-
- int safe;
-
- enum thread_status status;
- int wait_for;
- int fd;
- fd_set readfds;
- fd_set writefds;
- fd_set exceptfds;
- int select_value;
- double delay;
- rb_thread_t join;
-
- int abort;
- int priority;
- int gid;
-
- st_table *locals;
-
- VALUE thread;
-};
-
-#define THREAD_RAISED 0x200 /* temporary flag */
-#define THREAD_TERMINATING 0x400 /* persistent flag */
-#define THREAD_FLAGS_MASK 0x400 /* mask for persistent flags */
-
-#define FOREACH_THREAD_FROM(f,x) x = f; do { x = x->next;
-#define END_FOREACH_FROM(f,x) } while (x != f)
-
-#define FOREACH_THREAD(x) FOREACH_THREAD_FROM(curr_thread,x)
-#define END_FOREACH(x) END_FOREACH_FROM(curr_thread,x)
-
-static const char *
-thread_status_name(status)
- enum thread_status status;
-{
- switch (status) {
- case THREAD_RUNNABLE:
- return "run";
- case THREAD_STOPPED:
- return "sleep";
- case THREAD_TO_KILL:
- return "aborting";
- case THREAD_KILLED:
- return "dead";
- default:
- return "unknown";
- }
-}
-
-/* $SAFE accessor */
-void
-rb_set_safe_level(level)
- int level;
-{
- if (level > ruby_safe_level) {
- ruby_safe_level = level;
- curr_thread->safe = level;
- }
-}
-
-static VALUE
-safe_getter()
-{
- return INT2NUM(ruby_safe_level);
-}
-
-static void
-safe_setter(val)
- VALUE val;
-{
- int level = NUM2INT(val);
-
- if (level < ruby_safe_level) {
- rb_raise(rb_eSecurityError, "tried to downgrade safe level from %d to %d",
- ruby_safe_level, level);
- }
- ruby_safe_level = level;
- curr_thread->safe = level;
-}
-
-/* Return the current time as a floating-point number */
-static double
-timeofday()
-{
- struct timeval tv;
- gettimeofday(&tv, NULL);
- return (double)tv.tv_sec + (double)tv.tv_usec * 1e-6;
-}
-
-#define STACK(addr) (th->stk_pos<(VALUE*)(addr) && (VALUE*)(addr)<th->stk_pos+th->stk_len)
-#define ADJ(addr) (void*)(STACK(addr)?(((VALUE*)(addr)-th->stk_pos)+th->stk_ptr):(VALUE*)(addr))
-
-static void
-thread_mark(th)
- rb_thread_t th;
-{
- struct FRAME *frame;
- struct BLOCK *block;
-
- rb_gc_mark(th->result);
- rb_gc_mark(th->thread);
- if (th->join) rb_gc_mark(th->join->thread);
-
- rb_gc_mark(th->klass);
- rb_gc_mark(th->wrapper);
- rb_gc_mark((VALUE)th->cref);
-
- rb_gc_mark((VALUE)th->scope);
- rb_gc_mark((VALUE)th->dyna_vars);
- rb_gc_mark(th->errinfo);
- rb_gc_mark(th->last_line);
- rb_gc_mark(th->last_match);
- rb_mark_tbl(th->locals);
-
- /* mark data in copied stack */
- if (th == curr_thread) return;
- if (th->status == THREAD_KILLED) return;
- if (th->stk_len == 0) return; /* stack not active, no need to mark. */
- if (th->stk_ptr) {
- rb_gc_mark_locations(th->stk_ptr, th->stk_ptr+th->stk_len);
-#if defined(THINK_C) || defined(__human68k__)
- rb_gc_mark_locations(th->stk_ptr+2, th->stk_ptr+th->stk_len+2);
-#endif
- }
- frame = th->frame;
- while (frame && frame != top_frame) {
- frame = ADJ(frame);
- rb_gc_mark_frame(frame);
- if (frame->tmp) {
- struct FRAME *tmp = frame->tmp;
-
- while (tmp && tmp != top_frame) {
- tmp = ADJ(tmp);
- rb_gc_mark_frame(tmp);
- tmp = tmp->prev;
- }
- }
- frame = frame->prev;
- }
- block = th->block;
- while (block) {
- block = ADJ(block);
- rb_gc_mark_frame(&block->frame);
- block = block->prev;
- }
-}
-
-void
-rb_gc_mark_threads()
-{
- rb_thread_t th;
-
- /* static global mark */
- rb_gc_mark((VALUE)ruby_cref);
-
- if (!curr_thread) return;
- FOREACH_THREAD(th) {
- rb_gc_mark(th->thread);
- } END_FOREACH(th);
-}
-
-static void
-thread_free(th)
- rb_thread_t th;
-{
- if (th->stk_ptr) free(th->stk_ptr);
- th->stk_ptr = 0;
- if (th->locals) st_free_table(th->locals);
- if (th->status != THREAD_KILLED) {
- if (th->prev) th->prev->next = th->next;
- if (th->next) th->next->prev = th->prev;
- }
- if (th != main_thread) free(th);
-}
-
-static rb_thread_t
-rb_thread_check(data)
- VALUE data;
-{
- if (TYPE(data) != T_DATA || RDATA(data)->dmark != (RUBY_DATA_FUNC)thread_mark) {
- rb_raise(rb_eTypeError, "wrong argument type %s (expected Thread)",
- rb_class2name(CLASS_OF(data)));
- }
- return (rb_thread_t)RDATA(data)->data;
-}
-
-static VALUE rb_thread_raise _((int, VALUE*, rb_thread_t));
-
-static int th_raise_argc;
-static VALUE th_raise_argv[2];
-static char *th_raise_file;
-static int th_raise_line;
-static VALUE th_cmd;
-static int th_sig;
-static char *th_signm;
-
-#define RESTORE_NORMAL 1
-#define RESTORE_FATAL 2
-#define RESTORE_INTERRUPT 3
-#define RESTORE_TRAP 4
-#define RESTORE_RAISE 5
-#define RESTORE_SIGNAL 6
-
-extern VALUE *rb_gc_stack_start;
-
-static void
-rb_thread_save_context(th)
- rb_thread_t th;
-{
- VALUE *pos;
- int len;
- static VALUE tval;
-
- len = ruby_stack_length(&pos);
- th->stk_len = 0;
- th->stk_pos = (rb_gc_stack_start<pos)?rb_gc_stack_start
- :rb_gc_stack_start - len;
- if (len > th->stk_max) {
- REALLOC_N(th->stk_ptr, VALUE, len);
- th->stk_max = len;
- }
- th->stk_len = len;
- FLUSH_REGISTER_WINDOWS;
- MEMCPY(th->stk_ptr, th->stk_pos, VALUE, th->stk_len);
-
- th->frame = ruby_frame;
- th->scope = ruby_scope;
- th->klass = ruby_class;
- th->wrapper = ruby_wrapper;
- th->cref = ruby_cref;
- th->dyna_vars = ruby_dyna_vars;
- th->block = ruby_block;
- th->flags &= THREAD_FLAGS_MASK;
- th->flags |= (rb_trap_immediate<<8) | scope_vmode;
- th->iter = ruby_iter;
- th->tag = prot_tag;
- th->tracing = tracing;
- th->errinfo = ruby_errinfo;
- th->last_status = rb_last_status;
- tval = rb_lastline_get();
- rb_lastline_set(th->last_line);
- th->last_line = tval;
- tval = rb_backref_get();
- rb_backref_set(th->last_match);
- th->last_match = tval;
- th->safe = ruby_safe_level;
-
- th->file = ruby_sourcefile;
- th->line = ruby_sourceline;
-}
-
-static int
-thread_switch(n)
- int n;
-{
- switch (n) {
- case 0:
- return 0;
- case RESTORE_FATAL:
- JUMP_TAG(TAG_FATAL);
- break;
- case RESTORE_INTERRUPT:
- rb_interrupt();
- break;
- case RESTORE_TRAP:
- rb_trap_eval(th_cmd, th_sig);
- errno = EINTR;
- break;
- case RESTORE_RAISE:
- ruby_frame->last_func = 0;
- ruby_sourcefile = th_raise_file;
- ruby_sourceline = th_raise_line;
- rb_f_raise(th_raise_argc, th_raise_argv);
- break;
- case RESTORE_SIGNAL:
- rb_raise(rb_eSignal, "SIG%s", th_signm);
- break;
- case RESTORE_NORMAL:
- default:
- break;
- }
- return 1;
-}
-
-#define THREAD_SAVE_CONTEXT(th) \
- (rb_thread_save_context(th),thread_switch(setjmp((th)->context)))
-
-static void rb_thread_restore_context _((rb_thread_t,int));
-
-static void
-stack_extend(th, exit)
- rb_thread_t th;
- int exit;
-{
- VALUE space[1024];
-
- memset(space, 0, 1); /* prevent array from optimization */
- rb_thread_restore_context(th, exit);
-}
-
-static void
-rb_thread_restore_context(th, exit)
- rb_thread_t th;
- int exit;
-{
- VALUE v;
- static rb_thread_t tmp;
- static int ex;
- static VALUE tval;
-
- if (!th->stk_ptr) rb_bug("unsaved context");
-
- if (&v < rb_gc_stack_start) {
- /* Stack grows downward */
- if (&v > th->stk_pos) stack_extend(th, exit);
- }
- else {
- /* Stack grows upward */
- if (&v < th->stk_pos + th->stk_len) stack_extend(th, exit);
- }
-
- ruby_frame = th->frame;
- ruby_scope = th->scope;
- ruby_class = th->klass;
- ruby_wrapper = th->wrapper;
- ruby_cref = th->cref;
- ruby_dyna_vars = th->dyna_vars;
- ruby_block = th->block;
- scope_vmode = th->flags&SCOPE_MASK;
- rb_trap_immediate = (th->flags&0x100)?1:0;
- ruby_iter = th->iter;
- prot_tag = th->tag;
- tracing = th->tracing;
- ruby_errinfo = th->errinfo;
- rb_last_status = th->last_status;
- ruby_safe_level = th->safe;
-
- ruby_sourcefile = th->file;
- ruby_sourceline = th->line;
-
- tmp = th;
- ex = exit;
- FLUSH_REGISTER_WINDOWS;
- MEMCPY(tmp->stk_pos, tmp->stk_ptr, VALUE, tmp->stk_len);
-
- tval = rb_lastline_get();
- rb_lastline_set(tmp->last_line);
- tmp->last_line = tval;
- tval = rb_backref_get();
- rb_backref_set(tmp->last_match);
- tmp->last_match = tval;
-
- longjmp(tmp->context, ex);
-}
-
-static void
-rb_thread_ready(th)
- rb_thread_t th;
-{
- th->wait_for = 0;
- th->status = THREAD_RUNNABLE;
-}
-
-static void
-rb_thread_remove(th)
- rb_thread_t th;
-{
- if (th->status == THREAD_KILLED) return;
-
- rb_thread_ready(th);
- th->status = THREAD_KILLED;
- th->prev->next = th->next;
- th->next->prev = th->prev;
-}
-
-static int
-rb_thread_dead(th)
- rb_thread_t th;
-{
- return th->status == THREAD_KILLED;
-}
-
-void
-rb_thread_fd_close(fd)
- int fd;
-{
- rb_thread_t th;
-
- FOREACH_THREAD(th) {
- if ((th->wait_for & WAIT_FD) && fd == th->fd) {
- VALUE exc = rb_exc_new2(rb_eIOError, "stream closed");
- rb_thread_raise(1, &exc, th);
- }
- }
- END_FOREACH(th);
-}
-
-static void
-rb_thread_deadlock()
-{
- if (curr_thread == main_thread) {
- rb_raise(rb_eFatal, "Thread: deadlock");
- }
- curr_thread = main_thread;
- th_raise_argc = 1;
- th_raise_argv[0] = rb_exc_new2(rb_eFatal, "Thread: deadlock");
- th_raise_file = ruby_sourcefile;
- th_raise_line = ruby_sourceline;
- rb_thread_restore_context(main_thread, RESTORE_RAISE);
-}
-
-static void
-copy_fds(dst, src, max)
- fd_set *dst, *src;
- int max;
-{
- int n = 0;
- int i;
-
- for (i=0; i<=max; i++) {
- if (FD_ISSET(i, src)) {
- n = i;
- FD_SET(i, dst);
- }
- }
-}
-
-static int
-match_fds(dst, src, max)
- fd_set *dst, *src;
- int max;
-{
- int i;
-
- for (i=0; i<=max; i++) {
- if (FD_ISSET(i, src) && FD_ISSET(i, dst)) {
- return Qtrue;
- }
- }
- return Qfalse;
-}
-
-static int
-intersect_fds(src, dst, max)
- fd_set *src, *dst;
- int max;
-{
- int i, n = 0;
-
- for (i=0; i<=max; i++) {
- if (FD_ISSET(i, dst)) {
- if (FD_ISSET(i, src)) {
- /* Wake up only one thread per fd. */
- FD_CLR(i, src);
- ++n;
- }
- else {
- FD_CLR(i, dst);
- }
- }
- }
- return n;
-}
-
-static int
-find_bad_fds(dst, src, max)
- fd_set *dst, *src;
- int max;
-{
- int i, test = Qfalse;
-
- for (i=0; i<=max; i++) {
- if (FD_ISSET(i, src) && !FD_ISSET(i, dst)) {
- FD_CLR(i, src);
- test = Qtrue;
- }
- }
- return test;
-}
-
-void
-rb_thread_schedule()
-{
- rb_thread_t next; /* OK */
- rb_thread_t th;
- rb_thread_t curr;
- int found = 0;
-
- fd_set readfds;
- fd_set writefds;
- fd_set exceptfds;
- struct timeval delay_tv, *delay_ptr;
- double delay, now; /* OK */
- int n, max;
- int need_select = 0;
- int select_timeout = 0;
-
- rb_thread_pending = 0;
- if (curr_thread == curr_thread->next
- && curr_thread->status == THREAD_RUNNABLE)
- return;
-
- next = 0;
- curr = curr_thread; /* starting thread */
-
- while (curr->status == THREAD_KILLED) {
- curr = curr->prev;
- }
-
- again:
- max = -1;
- FD_ZERO(&readfds);
- FD_ZERO(&writefds);
- FD_ZERO(&exceptfds);
- delay = DELAY_INFTY;
- now = -1.0;
-
- FOREACH_THREAD_FROM(curr, th) {
- if (!found && th->status <= THREAD_RUNNABLE) {
- found = 1;
- }
- if (th->status != THREAD_STOPPED) continue;
- if (th->wait_for & WAIT_JOIN) {
- if (rb_thread_dead(th->join)) {
- th->status = THREAD_RUNNABLE;
- found = 1;
- }
- }
- if (th->wait_for & WAIT_FD) {
- FD_SET(th->fd, &readfds);
- if (max < th->fd) max = th->fd;
- need_select = 1;
- }
- if (th->wait_for & WAIT_SELECT) {
- copy_fds(&readfds, &th->readfds, th->fd);
- copy_fds(&writefds, &th->writefds, th->fd);
- copy_fds(&exceptfds, &th->exceptfds, th->fd);
- if (max < th->fd) max = th->fd;
- need_select = 1;
- if (th->wait_for & WAIT_TIME) {
- select_timeout = 1;
- }
- th->select_value = 0;
- }
- if (th->wait_for & WAIT_TIME) {
- double th_delay;
-
- if (now < 0.0) now = timeofday();
- th_delay = th->delay - now;
- if (th_delay <= 0.0) {
- th->status = THREAD_RUNNABLE;
- found = 1;
- }
- else if (th_delay < delay) {
- delay = th_delay;
- need_select = 1;
- }
- else if (th->delay == DELAY_INFTY) {
- need_select = 1;
- }
- }
- }
- END_FOREACH_FROM(curr, th);
-
- /* Do the select if needed */
- if (need_select) {
- /* Convert delay to a timeval */
- /* If a thread is runnable, just poll */
- if (found) {
- delay_tv.tv_sec = 0;
- delay_tv.tv_usec = 0;
- delay_ptr = &delay_tv;
- }
- else if (delay == DELAY_INFTY) {
- delay_ptr = 0;
- }
- else {
- delay_tv.tv_sec = delay;
- delay_tv.tv_usec = (delay - (double)delay_tv.tv_sec)*1e6;
- delay_ptr = &delay_tv;
- }
-
- n = select(max+1, &readfds, &writefds, &exceptfds, delay_ptr);
- if (n < 0) {
- if (rb_trap_pending) rb_trap_exec();
- if (errno == EINTR) goto again;
- FOREACH_THREAD_FROM(curr, th) {
- if (th->wait_for & WAIT_SELECT) {
- int v = 0;
-
- v |= find_bad_fds(&readfds, &th->readfds, th->fd);
- v |= find_bad_fds(&writefds, &th->writefds, th->fd);
- v |= find_bad_fds(&exceptfds, &th->exceptfds, th->fd);
- if (v) {
- th->select_value = n;
- n = max;
- }
- }
- }
- END_FOREACH_FROM(curr, th);
- }
- if (select_timeout && n == 0) {
- if (now < 0.0) now = timeofday();
- FOREACH_THREAD_FROM(curr, th) {
- if (((th->wait_for&(WAIT_SELECT|WAIT_TIME)) == (WAIT_SELECT|WAIT_TIME)) &&
- th->delay <= now) {
- th->status = THREAD_RUNNABLE;
- th->wait_for = 0;
- th->select_value = 0;
- found = 1;
- intersect_fds(&readfds, &th->readfds, max);
- intersect_fds(&writefds, &th->writefds, max);
- intersect_fds(&exceptfds, &th->exceptfds, max);
- }
- }
- END_FOREACH_FROM(curr, th);
- }
- if (n > 0) {
- now = -1.0;
- /* Some descriptors are ready.
- Make the corresponding threads runnable. */
- FOREACH_THREAD_FROM(curr, th) {
- if ((th->wait_for&WAIT_FD) && FD_ISSET(th->fd, &readfds)) {
- /* Wake up only one thread per fd. */
- FD_CLR(th->fd, &readfds);
- th->status = THREAD_RUNNABLE;
- th->fd = 0;
- th->wait_for = 0;
- found = 1;
- }
- if ((th->wait_for&WAIT_SELECT) &&
- (match_fds(&readfds, &th->readfds, max) ||
- match_fds(&writefds, &th->writefds, max) ||
- match_fds(&exceptfds, &th->exceptfds, max))) {
- /* Wake up only one thread per fd. */
- th->status = THREAD_RUNNABLE;
- th->wait_for = 0;
- n = intersect_fds(&readfds, &th->readfds, max) +
- intersect_fds(&writefds, &th->writefds, max) +
- intersect_fds(&exceptfds, &th->exceptfds, max);
- th->select_value = n;
- found = 1;
- }
- }
- END_FOREACH_FROM(curr, th);
- }
- /* The delays for some of the threads should have expired.
- Go through the loop once more, to check the delays. */
- if (!found && delay != DELAY_INFTY)
- goto again;
- }
-
- FOREACH_THREAD_FROM(curr, th) {
- if (th->status == THREAD_TO_KILL) {
- next = th;
- break;
- }
- if (th->status == THREAD_RUNNABLE && th->stk_ptr) {
- if (!next || next->priority < th->priority)
- next = th;
- }
- }
- END_FOREACH_FROM(curr, th);
-
- if (!next) {
- /* raise fatal error to main thread */
- curr_thread->file = ruby_sourcefile;
- curr_thread->line = ruby_sourceline;
- FOREACH_THREAD_FROM(curr, th) {
- fprintf(stderr, "deadlock 0x%lx: %d:%d %s - %s:%d\n",
- th->thread, th->status,
- th->wait_for, th==main_thread ? "(main)" : "",
- th->file, th->line);
- }
- END_FOREACH_FROM(curr, th);
- next = main_thread;
- next->gid = 0;
- rb_thread_ready(next);
- next->status = THREAD_TO_KILL;
- rb_thread_save_context(curr_thread);
- rb_thread_deadlock();
- }
- next->wait_for = 0;
- if (next->status == THREAD_RUNNABLE && next == curr_thread) {
- return;
- }
-
- /* context switch */
- if (curr == curr_thread) {
- if (THREAD_SAVE_CONTEXT(curr)) {
- return;
- }
- }
-
- curr_thread = next;
- if (next->status == THREAD_TO_KILL) {
- if (!(next->flags & THREAD_TERMINATING)) {
- next->flags |= THREAD_TERMINATING;
- /* terminate; execute ensure-clause if any */
- rb_thread_restore_context(next, RESTORE_FATAL);
- }
- }
- rb_thread_restore_context(next, RESTORE_NORMAL);
-}
-
-void
-rb_thread_wait_fd(fd)
- int fd;
-{
- if (rb_thread_critical) return;
- if (curr_thread == curr_thread->next) return;
- if (curr_thread->status == THREAD_TO_KILL) return;
-
- curr_thread->status = THREAD_STOPPED;
- curr_thread->fd = fd;
- curr_thread->wait_for = WAIT_FD;
- rb_thread_schedule();
-}
-
-int
-rb_thread_fd_writable(fd)
- int fd;
-{
- if (rb_thread_critical) return Qtrue;
- if (curr_thread == curr_thread->next) return Qtrue;
- if (curr_thread->status == THREAD_TO_KILL) return Qtrue;
-
- curr_thread->status = THREAD_STOPPED;
- FD_ZERO(&curr_thread->readfds);
- FD_ZERO(&curr_thread->writefds);
- FD_SET(fd, &curr_thread->writefds);
- FD_ZERO(&curr_thread->exceptfds);
- curr_thread->fd = fd+1;
- curr_thread->wait_for = WAIT_SELECT;
- rb_thread_schedule();
- return Qfalse;
-}
-
-void
-rb_thread_wait_for(time)
- struct timeval time;
-{
- double date;
-
- if (rb_thread_critical ||
- curr_thread == curr_thread->next ||
- curr_thread->status == THREAD_TO_KILL) {
- int n;
-#ifndef linux
- double d, limit;
- limit = timeofday()+(double)time.tv_sec+(double)time.tv_usec*1e-6;
-#endif
- for (;;) {
- TRAP_BEG;
- n = select(0, 0, 0, 0, &time);
- TRAP_END;
- if (n == 0) return;
- if (n < 0) {
- switch (errno) {
- case EINTR:
-#ifdef ERESTART
- case ERESTART:
-#endif
- return;
- default:
- rb_sys_fail("sleep");
- }
- }
-#ifndef linux
- d = limit - timeofday();
-
- time.tv_sec = (int)d;
- time.tv_usec = (int)((d - (int)d)*1e6);
- if (time.tv_usec < 0) {
- time.tv_usec += (long)1e6;
- time.tv_sec -= 1;
- }
- if (time.tv_sec < 0) return;
-#endif
- }
- }
-
- date = timeofday() + (double)time.tv_sec + (double)time.tv_usec*1e-6;
- curr_thread->status = THREAD_STOPPED;
- curr_thread->delay = date;
- curr_thread->wait_for = WAIT_TIME;
- rb_thread_schedule();
-}
-
-void rb_thread_sleep_forever _((void));
-
-int
-rb_thread_alone()
-{
- return curr_thread == curr_thread->next;
-}
-
-int
-rb_thread_select(max, read, write, except, timeout)
- int max;
- fd_set *read, *write, *except;
- struct timeval *timeout;
-{
- double limit;
- int n;
-
- if (!read && !write && !except) {
- if (!timeout) {
- rb_thread_sleep_forever();
- return 0;
- }
- rb_thread_wait_for(*timeout);
- return 0;
- }
-
- if (timeout) {
- limit = timeofday()+
- (double)timeout->tv_sec+(double)timeout->tv_usec*1e-6;
- }
-
- if (rb_thread_critical ||
- curr_thread == curr_thread->next ||
- curr_thread->status == THREAD_TO_KILL) {
-#ifndef linux
- struct timeval tv, *tvp = timeout;
-
- if (timeout) {
- tv = *timeout;
- tvp = &tv;
- }
- for (;;) {
- TRAP_BEG;
- n = select(max, read, write, except, tvp);
- TRAP_END;
- if (n < 0) {
- switch (errno) {
- case EINTR:
-#ifdef ERESTART
- case ERESTART:
-#endif
- if (timeout) {
- double d = limit - timeofday();
-
- tv.tv_sec = (unsigned int)d;
- tv.tv_usec = (long)((d-(double)tv.tv_sec)*1e6);
- if (tv.tv_sec < 0) tv.tv_sec = 0;
- if (tv.tv_usec < 0) tv.tv_usec = 0;
- }
- continue;
- default:
- break;
- }
- }
- return n;
- }
-#else
- for (;;) {
- TRAP_BEG;
- n = select(max, read, write, except, timeout);
- TRAP_END;
- if (n < 0) {
- switch (errno) {
- case EINTR:
-#ifdef ERESTART
- case ERESTART:
-#endif
- continue;
- }
- }
- return n;
- }
-#endif
-
- }
-
- curr_thread->status = THREAD_STOPPED;
- if (read) curr_thread->readfds = *read;
- else FD_ZERO(&curr_thread->readfds);
- if (write) curr_thread->writefds = *write;
- else FD_ZERO(&curr_thread->writefds);
- if (except) curr_thread->exceptfds = *except;
- else FD_ZERO(&curr_thread->exceptfds);
- curr_thread->fd = max;
- curr_thread->wait_for = WAIT_SELECT;
- if (timeout) {
- curr_thread->delay = timeofday() +
- (double)timeout->tv_sec + (double)timeout->tv_usec*1e-6;
- curr_thread->wait_for |= WAIT_TIME;
- }
- rb_thread_schedule();
- if (read) *read = curr_thread->readfds;
- if (write) *write = curr_thread->writefds;
- if (except) *except = curr_thread->exceptfds;
- return curr_thread->select_value;
-}
-
-static VALUE
-rb_thread_join(thread)
- VALUE thread;
-{
- rb_thread_t th = rb_thread_check(thread);
- enum thread_status last_status = THREAD_RUNNABLE;
-
- if (rb_thread_critical) rb_thread_deadlock();
- if (!rb_thread_dead(th)) {
- if (th == curr_thread)
- rb_raise(rb_eThreadError, "thread tried to join itself");
- if ((th->wait_for & WAIT_JOIN) && th->join == curr_thread)
- rb_raise(rb_eThreadError, "Thread#join: deadlock - mutual join");
- if (curr_thread->status == THREAD_TO_KILL)
- last_status = THREAD_TO_KILL;
- curr_thread->status = THREAD_STOPPED;
- curr_thread->join = th;
- curr_thread->wait_for = WAIT_JOIN;
- rb_thread_schedule();
- curr_thread->status = last_status;
- }
-
- if (!NIL_P(th->errinfo) && (th->flags & THREAD_RAISED)) {
- VALUE oldbt = get_backtrace(th->errinfo);
- VALUE errat = make_backtrace();
-
- if (TYPE(oldbt) == T_ARRAY && RARRAY(oldbt)->len > 0) {
- rb_ary_unshift(errat, rb_ary_entry(oldbt, 0));
- }
- set_backtrace(th->errinfo, errat);
- rb_exc_raise(th->errinfo);
- }
-
- return thread;
-}
-
-VALUE
-rb_thread_current()
-{
- return curr_thread->thread;
-}
-
-VALUE
-rb_thread_main()
-{
- return main_thread->thread;
-}
-
-VALUE
-rb_thread_list()
-{
- rb_thread_t th;
- VALUE ary = rb_ary_new();
-
- FOREACH_THREAD(th) {
- switch (th->status) {
- case THREAD_RUNNABLE:
- case THREAD_STOPPED:
- rb_ary_push(ary, th->thread);
- default:
- break;
- }
- }
- END_FOREACH(th);
-
- return ary;
-}
-
-VALUE
-rb_thread_wakeup(thread)
- VALUE thread;
-{
- rb_thread_t th = rb_thread_check(thread);
-
- if (th->status == THREAD_KILLED)
- rb_raise(rb_eThreadError, "killed thread");
- rb_thread_ready(th);
-
- return thread;
-}
-
-VALUE
-rb_thread_run(thread)
- VALUE thread;
-{
- rb_thread_wakeup(thread);
- if (!rb_thread_critical) rb_thread_schedule();
-
- return thread;
-}
-
-static VALUE
-rb_thread_kill(thread)
- VALUE thread;
-{
- rb_thread_t th = rb_thread_check(thread);
-
- if (th != curr_thread && th->safe < 4) {
- rb_secure(4);
- }
- if (th->status == THREAD_TO_KILL || th->status == THREAD_KILLED)
- return thread;
- if (th == th->next || th == main_thread) rb_exit(0);
-
- rb_thread_ready(th);
- th->gid = 0;
- th->status = THREAD_TO_KILL;
- if (!rb_thread_critical) rb_thread_schedule();
- return thread;
-}
-
-static VALUE
-rb_thread_s_kill(obj, th)
- VALUE obj, th;
-{
- return rb_thread_kill(th);
-}
-
-static VALUE
-rb_thread_exit()
-{
- return rb_thread_kill(curr_thread->thread);
-}
-
-static VALUE
-rb_thread_pass()
-{
- rb_thread_schedule();
- return Qnil;
-}
-
-VALUE
-rb_thread_stop()
-{
- enum thread_status last_status = THREAD_RUNNABLE;
-
- rb_thread_critical = 0;
- if (curr_thread == curr_thread->next) {
- rb_raise(rb_eThreadError, "stopping only thread\n\tnote: use sleep to stop forever");
- }
- if (curr_thread->status == THREAD_TO_KILL)
- last_status = THREAD_TO_KILL;
- curr_thread->status = THREAD_STOPPED;
- rb_thread_schedule();
- curr_thread->status = last_status;
-
- return Qnil;
-}
-
-struct timeval rb_time_timeval();
-
-void
-rb_thread_polling()
-{
- if (curr_thread != curr_thread->next) {
- curr_thread->status = THREAD_STOPPED;
- curr_thread->delay = timeofday() + (double)0.06;
- curr_thread->wait_for = WAIT_TIME;
- rb_thread_schedule();
- }
-}
-
-void
-rb_thread_sleep(sec)
- int sec;
-{
- if (curr_thread == curr_thread->next) {
- TRAP_BEG;
- sleep(sec);
- TRAP_END;
- return;
- }
- rb_thread_wait_for(rb_time_timeval(INT2FIX(sec)));
-}
-
-#if !defined HAVE_PAUSE
-# if defined _WIN32 && !defined __CYGWIN__
-# define pause() Sleep(INFINITE)
-# else
-# define pause() sleep(0x7fffffff)
-# endif
-#endif
-
-void
-rb_thread_sleep_forever()
-{
- if (curr_thread == curr_thread->next ||
- curr_thread->status == THREAD_TO_KILL) {
- TRAP_BEG;
- pause();
- TRAP_END;
- return;
- }
-
- curr_thread->delay = DELAY_INFTY;
- curr_thread->wait_for = WAIT_TIME;
- curr_thread->status = THREAD_STOPPED;
- rb_thread_schedule();
-}
-
-static VALUE
-rb_thread_priority(thread)
- VALUE thread;
-{
- return INT2NUM(rb_thread_check(thread)->priority);
-}
-
-static VALUE
-rb_thread_priority_set(thread, prio)
- VALUE thread, prio;
-{
- rb_thread_t th;
-
- rb_secure(4);
- th = rb_thread_check(thread);
-
- th->priority = NUM2INT(prio);
- rb_thread_schedule();
- return prio;
-}
-
-static VALUE
-rb_thread_safe_level(thread)
- VALUE thread;
-{
- rb_thread_t th;
-
- th = rb_thread_check(thread);
- if (th == curr_thread) {
- return INT2NUM(rb_safe_level());
- }
- return INT2NUM(th->safe);
-}
-
-static int thread_abort;
-
-static VALUE
-rb_thread_s_abort_exc()
-{
- return thread_abort?Qtrue:Qfalse;
-}
-
-static VALUE
-rb_thread_s_abort_exc_set(self, val)
- VALUE self, val;
-{
- rb_secure(4);
- thread_abort = RTEST(val);
- return val;
-}
-
-static VALUE
-rb_thread_abort_exc(thread)
- VALUE thread;
-{
- return rb_thread_check(thread)->abort?Qtrue:Qfalse;
-}
-
-static VALUE
-rb_thread_abort_exc_set(thread, val)
- VALUE thread, val;
-{
- rb_secure(4);
- rb_thread_check(thread)->abort = RTEST(val);
- return val;
-}
-
-#define THREAD_ALLOC(th) do {\
- th = ALLOC(struct thread);\
-\
- th->next = 0;\
- th->prev = 0;\
-\
- th->status = THREAD_RUNNABLE;\
- th->result = 0;\
- th->flags = 0;\
-\
- th->stk_ptr = 0;\
- th->stk_len = 0;\
- th->stk_max = 0;\
- th->wait_for = 0;\
- FD_ZERO(&th->readfds);\
- FD_ZERO(&th->writefds);\
- FD_ZERO(&th->exceptfds);\
- th->delay = 0.0;\
- th->join = 0;\
-\
- th->frame = 0;\
- th->scope = 0;\
- th->klass = 0;\
- th->wrapper = 0;\
- th->cref = ruby_cref;\
- th->dyna_vars = ruby_dyna_vars;\
- th->block = 0;\
- th->iter = 0;\
- th->tag = 0;\
- th->tracing = 0;\
- th->errinfo = Qnil;\
- th->last_status = 0;\
- th->last_line = 0;\
- th->last_match = Qnil;\
- th->abort = 0;\
- th->priority = 0;\
- th->gid = 1;\
- th->locals = 0;\
-} while(0)
-
-static rb_thread_t
-rb_thread_alloc(klass)
- VALUE klass;
-{
- rb_thread_t th;
- struct RVarmap *vars;
-
- THREAD_ALLOC(th);
- th->thread = Data_Wrap_Struct(klass, thread_mark, thread_free, th);
-
- for (vars = th->dyna_vars; vars; vars = vars->next) {
- if (FL_TEST(vars, DVAR_DONT_RECYCLE)) break;
- FL_SET(vars, DVAR_DONT_RECYCLE);
- }
- return th;
-}
-
-#if defined(HAVE_SETITIMER)
-static void
-catch_timer(sig)
- int sig;
-{
-#if !defined(POSIX_SIGNAL) && !defined(BSD_SIGNAL)
- signal(sig, catch_timer);
-#endif
- if (!rb_thread_critical) {
- if (rb_trap_immediate) {
- rb_thread_schedule();
- }
- else rb_thread_pending = 1;
- }
-}
-#else
-int rb_thread_tick = THREAD_TICK;
-#endif
-
-#if defined(HAVE_SETITIMER)
-static int thread_init = 0;
-
-void
-rb_thread_start_timer()
-{
- struct itimerval tval;
-
- if (!thread_init) return;
- tval.it_interval.tv_sec = 0;
- tval.it_interval.tv_usec = 10000;
- tval.it_value = tval.it_interval;
- setitimer(ITIMER_VIRTUAL, &tval, NULL);
-}
-
-void
-rb_thread_stop_timer()
-{
- struct itimerval tval;
-
- if (!thread_init) return;
- tval.it_interval.tv_sec = 0;
- tval.it_interval.tv_usec = 0;
- tval.it_value = tval.it_interval;
- setitimer(ITIMER_VIRTUAL, &tval, NULL);
-}
-#endif
-
-static VALUE
-rb_thread_start_0(fn, arg, th_arg)
- VALUE (*fn)();
- void *arg;
- rb_thread_t th_arg;
-{
- volatile rb_thread_t th = th_arg;
- volatile VALUE thread = th->thread;
- struct BLOCK* saved_block = 0;
- enum thread_status status;
- int state;
-
-#if defined(HAVE_SETITIMER)
- if (!thread_init) {
-#ifdef POSIX_SIGNAL
- posix_signal(SIGVTALRM, catch_timer);
-#else
- signal(SIGVTALRM, catch_timer);
-#endif
-
- thread_init = 1;
- rb_thread_start_timer();
- }
-#endif
-
- if (THREAD_SAVE_CONTEXT(curr_thread)) {
- return thread;
- }
-
- if (ruby_block) { /* should nail down higher blocks */
- struct BLOCK dummy;
-
- dummy.prev = ruby_block;
- blk_copy_prev(&dummy);
- saved_block = ruby_block = dummy.prev;
- }
- scope_dup(ruby_scope);
-
- if (!th->next) {
- /* merge in thread list */
- th->prev = curr_thread;
- curr_thread->next->prev = th;
- th->next = curr_thread->next;
- curr_thread->next = th;
- th->priority = curr_thread->priority;
- th->gid = curr_thread->gid;
- }
-
- PUSH_TAG(PROT_THREAD);
- if ((state = EXEC_TAG()) == 0) {
- if (THREAD_SAVE_CONTEXT(th) == 0) {
- curr_thread = th;
- th->result = (*fn)(arg, th);
- }
- }
- POP_TAG();
- status = th->status;
-
- if (th == main_thread) ruby_stop(state);
- rb_thread_remove(th);
-
- while (saved_block) {
- struct BLOCK *tmp = saved_block;
-
- if (tmp->frame.argc > 0)
- free(tmp->frame.argv);
- saved_block = tmp->prev;
- free(tmp);
- }
-
- if (state && status != THREAD_TO_KILL && !NIL_P(ruby_errinfo)) {
- th->flags |= THREAD_RAISED;
- if (state == TAG_FATAL) {
- /* fatal error within this thread, need to stop whole script */
- main_thread->errinfo = ruby_errinfo;
- rb_thread_cleanup();
- }
- else if (rb_obj_is_kind_of(ruby_errinfo, rb_eSystemExit)) {
- if (th->safe >= 4) {
- char buf[32];
-
- sprintf(buf, "Insecure exit at level %d", th->safe);
- th->errinfo = rb_exc_new2(rb_eSecurityError, buf);
- }
- else {
- /* delegate exception to main_thread */
- rb_thread_raise(1, &ruby_errinfo, main_thread);
- }
- }
- else if (th->safe < 4 && (thread_abort || th->abort || RTEST(ruby_debug))) {
- VALUE err = rb_exc_new(rb_eSystemExit, 0, 0);
- error_print();
- /* exit on main_thread */
- rb_thread_raise(1, &err, main_thread);
- }
- else {
- th->errinfo = ruby_errinfo;
- }
- }
- rb_thread_schedule();
- return 0; /* not reached */
-}
-
-VALUE
-rb_thread_create(fn, arg)
- VALUE (*fn)();
- void *arg;
-{
- return rb_thread_start_0(fn, arg, rb_thread_alloc(rb_cThread));
-}
-
-static VALUE
-rb_thread_yield(arg, th)
- VALUE arg;
- rb_thread_t th;
-{
- const ID *tbl;
-
- scope_dup(ruby_block->scope);
-
- tbl = ruby_scope->local_tbl;
- if (tbl) {
- int n = *tbl++;
- for (tbl += 2, n -= 2; n > 0; --n) { /* skip first 2 ($_ and $~) */
- ID id = *tbl++;
- if (id != 0 && !rb_is_local_id(id)) /* push flip states */
- rb_dvar_push(id, Qfalse);
- }
- }
- rb_dvar_push('_', Qnil);
- rb_dvar_push('~', Qnil);
- ruby_block->dyna_vars = ruby_dyna_vars;
-
- return rb_yield_0(mvalue_to_svalue(arg), 0, 0, Qtrue);
-}
-
-static VALUE
-rb_thread_s_new(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- rb_thread_t th = rb_thread_alloc(klass);
- volatile VALUE *pos;
-
- pos = th->stk_pos;
- rb_obj_call_init(th->thread, argc, argv);
- if (th->stk_pos == 0) {
- rb_raise(rb_eThreadError, "uninitialized thread - check `%s#initialize'",
- rb_class2name(klass));
- }
-
- return th->thread;
-}
-
-static VALUE
-rb_thread_initialize(thread, args)
- VALUE thread, args;
-{
- if (!rb_block_given_p()) {
- rb_raise(rb_eThreadError, "must be called with a block");
- }
- return rb_thread_start_0(rb_thread_yield, args, rb_thread_check(thread));
-}
-
-static VALUE
-rb_thread_start(klass, args)
- VALUE klass, args;
-{
- if (!rb_block_given_p()) {
- rb_raise(rb_eThreadError, "must be called with a block");
- }
- return rb_thread_start_0(rb_thread_yield, args, rb_thread_alloc(klass));
-}
-
-static VALUE
-rb_thread_value(thread)
- VALUE thread;
-{
- rb_thread_t th = rb_thread_check(thread);
-
- rb_thread_join(thread);
-
- return th->result;
-}
-
-static VALUE
-rb_thread_status(thread)
- VALUE thread;
-{
- rb_thread_t th = rb_thread_check(thread);
-
- if (rb_thread_dead(th)) {
- if (!NIL_P(th->errinfo) && (th->flags & THREAD_RAISED))
- return Qnil;
- return Qfalse;
- }
-
- return rb_str_new2(thread_status_name(th->status));
-}
-
-static VALUE
-rb_thread_alive_p(thread)
- VALUE thread;
-{
- rb_thread_t th = rb_thread_check(thread);
-
- if (rb_thread_dead(th)) return Qfalse;
- return Qtrue;
-}
-
-static VALUE
-rb_thread_stop_p(thread)
- VALUE thread;
-{
- rb_thread_t th = rb_thread_check(thread);
-
- if (rb_thread_dead(th)) return Qtrue;
- if (th->status == THREAD_STOPPED) return Qtrue;
- return Qfalse;
-}
-
-static void
-rb_thread_wait_other_threads()
-{
- rb_thread_t th;
- int found;
-
- /* wait other threads to terminate */
- while (curr_thread != curr_thread->next) {
- found = 0;
- FOREACH_THREAD(th) {
- if (th != curr_thread && th->status != THREAD_STOPPED) {
- found = 1;
- break;
- }
- }
- END_FOREACH(th);
- if (!found) return;
- rb_thread_schedule();
- }
-}
-
-static void
-rb_thread_cleanup()
-{
- rb_thread_t th;
-
- while (curr_thread->status == THREAD_KILLED) {
- curr_thread = curr_thread->prev;
- }
-
- FOREACH_THREAD(th) {
- if (th != curr_thread && th->status != THREAD_KILLED) {
- rb_thread_ready(th);
- th->gid = 0;
- th->priority = 0;
- th->status = THREAD_TO_KILL;
- RDATA(th->thread)->dfree = NULL;
- }
- }
- END_FOREACH(th);
-}
-
-int rb_thread_critical;
-
-static VALUE
-rb_thread_critical_get()
-{
- return rb_thread_critical?Qtrue:Qfalse;
-}
-
-static VALUE
-rb_thread_critical_set(obj, val)
- VALUE obj, val;
-{
- rb_thread_critical = RTEST(val);
- return val;
-}
-
-void
-rb_thread_interrupt()
-{
- rb_thread_critical = 0;
- rb_thread_ready(main_thread);
- if (curr_thread == main_thread) {
- rb_interrupt();
- }
- if (THREAD_SAVE_CONTEXT(curr_thread)) {
- return;
- }
- curr_thread = main_thread;
- rb_thread_restore_context(curr_thread, RESTORE_INTERRUPT);
-}
-
-void
-rb_thread_signal_raise(sig)
- char *sig;
-{
- if (sig == 0) return; /* should not happen */
- rb_thread_critical = 0;
- if (curr_thread == main_thread) {
- rb_thread_ready(curr_thread);
- rb_raise(rb_eSignal, "SIG%s", sig);
- }
- rb_thread_ready(main_thread);
- if (THREAD_SAVE_CONTEXT(curr_thread)) {
- return;
- }
- th_signm = sig;
- curr_thread = main_thread;
- rb_thread_restore_context(curr_thread, RESTORE_SIGNAL);
-}
-
-void
-rb_thread_trap_eval(cmd, sig)
- VALUE cmd;
- int sig;
-{
-#if 0
- rb_thread_critical = 0;
- if (!rb_thread_dead(curr_thread)) {
- rb_thread_ready(curr_thread);
- rb_trap_eval(cmd, sig);
- return;
- }
- rb_thread_ready(main_thread);
- if (THREAD_SAVE_CONTEXT(curr_thread)) {
- return;
- }
- th_cmd = cmd;
- th_sig = sig;
- curr_thread = main_thread;
- rb_thread_restore_context(curr_thread, RESTORE_TRAP);
-#else
- rb_thread_critical = 0;
- if (!rb_thread_dead(curr_thread)) {
- if (THREAD_SAVE_CONTEXT(curr_thread)) {
- return;
- }
- }
- rb_thread_ready(main_thread);
- th_cmd = cmd;
- th_sig = sig;
- curr_thread = main_thread;
- rb_thread_restore_context(curr_thread, RESTORE_TRAP);
-#endif
-}
-
-static VALUE
-rb_thread_raise(argc, argv, th)
- int argc;
- VALUE *argv;
- rb_thread_t th;
-{
- if (rb_thread_dead(th)) return Qnil;
- if (curr_thread == th) {
- rb_f_raise(argc, argv);
- }
-
- if (THREAD_SAVE_CONTEXT(curr_thread)) {
- return th->thread;
- }
-
- rb_scan_args(argc, argv, "11", &th_raise_argv[0], &th_raise_argv[1]);
- rb_thread_ready(th);
- curr_thread = th;
-
- th_raise_argc = argc;
- th_raise_file = ruby_sourcefile;
- th_raise_line = ruby_sourceline;
- rb_thread_restore_context(curr_thread, RESTORE_RAISE);
- return Qnil; /* not reached */
-}
-
-static VALUE
-rb_thread_raise_m(argc, argv, thread)
- int argc;
- VALUE *argv;
- VALUE thread;
-{
- rb_thread_t th = rb_thread_check(thread);
-
- if (ruby_safe_level > th->safe) {
- rb_secure(4);
- }
- rb_thread_raise(argc, argv, th);
- return Qnil; /* not reached */
-}
-
-VALUE
-rb_thread_local_aref(thread, id)
- VALUE thread;
- ID id;
-{
- rb_thread_t th;
- VALUE val;
-
- th = rb_thread_check(thread);
- if (rb_safe_level() >= 4 && th != curr_thread) {
- rb_raise(rb_eSecurityError, "Insecure: thread locals");
- }
- if (!th->locals) return Qnil;
- if (st_lookup(th->locals, id, &val)) {
- return val;
- }
- return Qnil;
-}
-
-static VALUE
-rb_thread_aref(thread, id)
- VALUE thread, id;
-{
- return rb_thread_local_aref(thread, rb_to_id(id));
-}
-
-VALUE
-rb_thread_local_aset(thread, id, val)
- VALUE thread;
- ID id;
- VALUE val;
-{
- rb_thread_t th = rb_thread_check(thread);
-
- if (rb_safe_level() >= 4 && th != curr_thread) {
- rb_raise(rb_eSecurityError, "Insecure: can't modify thread locals");
- }
- if (OBJ_FROZEN(thread)) rb_error_frozen("thread locals");
-
- if (!th->locals) {
- th->locals = st_init_numtable();
- }
- if (NIL_P(val)) {
- st_delete(th->locals, &id, 0);
- return Qnil;
- }
- st_insert(th->locals, id, val);
-
- return val;
-}
-
-static VALUE
-rb_thread_aset(thread, id, val)
- VALUE thread, id, val;
-{
- return rb_thread_local_aset(thread, rb_to_id(id), val);
-}
-
-static VALUE
-rb_thread_key_p(thread, id)
- VALUE thread, id;
-{
- rb_thread_t th = rb_thread_check(thread);
-
- if (!th->locals) return Qfalse;
- if (st_lookup(th->locals, rb_to_id(id), 0))
- return Qtrue;
- return Qfalse;
-}
-
-static int
-thread_keys_i(key, value, ary)
- ID key;
- VALUE value, ary;
-{
- rb_ary_push(ary, ID2SYM(key));
- return ST_CONTINUE;
-}
-
-static VALUE
-rb_thread_keys(thread)
- VALUE thread;
-{
- rb_thread_t th = rb_thread_check(thread);
- VALUE ary = rb_ary_new();
-
- if (th->locals) {
- st_foreach(th->locals, thread_keys_i, ary);
- }
- return ary;
-}
-
-static VALUE
-rb_thread_inspect(thread)
- VALUE thread;
-{
- char *cname = rb_class2name(CLASS_OF(thread));
- rb_thread_t th = rb_thread_check(thread);
- const char *status = thread_status_name(th->status);
- VALUE str;
-
- str = rb_str_new(0, strlen(cname)+7+16+9+1); /* 7:tags 16:addr 9:status 1:nul */
- sprintf(RSTRING(str)->ptr, "#<%s:0x%lx %s>", cname, thread, status);
- RSTRING(str)->len = strlen(RSTRING(str)->ptr);
- OBJ_INFECT(str, thread);
-
- return str;
-}
-
-void
-rb_thread_atfork()
-{
-#if 1 /* enable on 1.7 */
- rb_thread_t th;
-
- if (rb_thread_alone()) return;
- FOREACH_THREAD(th) {
- if (th != curr_thread) {
- th->status = THREAD_KILLED;
- }
- }
- END_FOREACH(th);
- main_thread = curr_thread;
- curr_thread->next = curr_thread;
- curr_thread->prev = curr_thread;
-#endif
-}
-
-static VALUE rb_cCont;
-
-static VALUE
-rb_callcc(self)
- VALUE self;
-{
- volatile VALUE cont;
- rb_thread_t th;
- struct tag *tag;
- struct RVarmap *vars;
-
- THREAD_ALLOC(th);
- cont = Data_Wrap_Struct(rb_cCont, thread_mark, thread_free, th);
-
- scope_dup(ruby_scope);
- for (tag=prot_tag; tag; tag=tag->prev) {
- scope_dup(tag->scope);
- }
- if (ruby_block) {
- struct BLOCK *block = ruby_block;
-
- while (block) {
- block->tag->flags |= BLOCK_DYNAMIC;
- block = block->prev;
- }
- }
- th->thread = curr_thread->thread;
-
- for (vars = th->dyna_vars; vars; vars = vars->next) {
- if (FL_TEST(vars, DVAR_DONT_RECYCLE)) break;
- FL_SET(vars, DVAR_DONT_RECYCLE);
- }
-
- if (THREAD_SAVE_CONTEXT(th)) {
- return th->result;
- }
- else {
- return rb_yield(cont);
- }
-}
-
-static VALUE
-rb_cont_call(argc, argv, cont)
- int argc;
- VALUE *argv;
- VALUE cont;
-{
- rb_thread_t th = rb_thread_check(cont);
-
- if (th->thread != curr_thread->thread) {
- rb_raise(rb_eRuntimeError, "continuation called across threads");
- }
- switch (argc) {
- case 0:
- th->result = Qnil;
- break;
- case 1:
- th->result = *argv;
- break;
- default:
- th->result = rb_ary_new4(argc, argv);
- break;
- }
-
- rb_thread_restore_context(th, RESTORE_NORMAL);
- return Qnil;
-}
-
-struct thgroup {
- int gid;
-};
-
-static VALUE
-thgroup_s_alloc(klass)
- VALUE klass;
-{
- VALUE group;
- struct thgroup *data;
- static int serial = 1;
-
- group = Data_Make_Struct(klass, struct thgroup, 0, free, data);
- data->gid = serial++;
-
- return group;
-}
-
-static VALUE
-thgroup_list(group)
- VALUE group;
-{
- struct thgroup *data;
- rb_thread_t th;
- VALUE ary;
-
- Data_Get_Struct(group, struct thgroup, data);
- ary = rb_ary_new();
-
- FOREACH_THREAD(th) {
- if (th->gid == data->gid) {
- rb_ary_push(ary, th->thread);
- }
- }
- END_FOREACH(th);
-
- return ary;
-}
-
-static VALUE
-thgroup_add(group, thread)
- VALUE group, thread;
-{
- rb_thread_t th;
- struct thgroup *data;
-
- rb_secure(4);
- th = rb_thread_check(thread);
- Data_Get_Struct(group, struct thgroup, data);
-
- th->gid = data->gid;
- return group;
-}
-
-void
-Init_Thread()
-{
- VALUE cThGroup;
-
- rb_eThreadError = rb_define_class("ThreadError", rb_eStandardError);
- rb_cThread = rb_define_class("Thread", rb_cObject);
- rb_undef_method(CLASS_OF(rb_cThread), "allocate");
-
- rb_define_singleton_method(rb_cThread, "new", rb_thread_s_new, -1);
- rb_define_method(rb_cThread, "initialize", rb_thread_initialize, -2);
- rb_define_singleton_method(rb_cThread, "start", rb_thread_start, -2);
- rb_define_singleton_method(rb_cThread, "fork", rb_thread_start, -2);
-
- rb_define_singleton_method(rb_cThread, "stop", rb_thread_stop, 0);
- rb_define_singleton_method(rb_cThread, "kill", rb_thread_s_kill, 1);
- rb_define_singleton_method(rb_cThread, "exit", rb_thread_exit, 0);
- rb_define_singleton_method(rb_cThread, "pass", rb_thread_pass, 0);
- rb_define_singleton_method(rb_cThread, "current", rb_thread_current, 0);
- rb_define_singleton_method(rb_cThread, "main", rb_thread_main, 0);
- rb_define_singleton_method(rb_cThread, "list", rb_thread_list, 0);
-
- rb_define_singleton_method(rb_cThread, "critical", rb_thread_critical_get, 0);
- rb_define_singleton_method(rb_cThread, "critical=", rb_thread_critical_set, 1);
-
- rb_define_singleton_method(rb_cThread, "abort_on_exception", rb_thread_s_abort_exc, 0);
- rb_define_singleton_method(rb_cThread, "abort_on_exception=", rb_thread_s_abort_exc_set, 1);
-
- rb_define_method(rb_cThread, "run", rb_thread_run, 0);
- rb_define_method(rb_cThread, "wakeup", rb_thread_wakeup, 0);
- rb_define_method(rb_cThread, "kill", rb_thread_kill, 0);
- rb_define_method(rb_cThread, "exit", rb_thread_kill, 0);
- rb_define_method(rb_cThread, "value", rb_thread_value, 0);
- rb_define_method(rb_cThread, "status", rb_thread_status, 0);
- rb_define_method(rb_cThread, "join", rb_thread_join, 0);
- rb_define_method(rb_cThread, "alive?", rb_thread_alive_p, 0);
- rb_define_method(rb_cThread, "stop?", rb_thread_stop_p, 0);
- rb_define_method(rb_cThread, "raise", rb_thread_raise_m, -1);
-
- rb_define_method(rb_cThread, "abort_on_exception", rb_thread_abort_exc, 0);
- rb_define_method(rb_cThread, "abort_on_exception=", rb_thread_abort_exc_set, 1);
-
- rb_define_method(rb_cThread, "priority", rb_thread_priority, 0);
- rb_define_method(rb_cThread, "priority=", rb_thread_priority_set, 1);
- rb_define_method(rb_cThread, "safe_level", rb_thread_safe_level, 0);
-
- rb_define_method(rb_cThread, "[]", rb_thread_aref, 1);
- rb_define_method(rb_cThread, "[]=", rb_thread_aset, 2);
- rb_define_method(rb_cThread, "key?", rb_thread_key_p, 1);
- rb_define_method(rb_cThread, "keys", rb_thread_keys, 0);
-
- rb_define_method(rb_cThread, "inspect", rb_thread_inspect, 0);
-
- /* allocate main thread */
- main_thread = rb_thread_alloc(rb_cThread);
- curr_thread = main_thread->prev = main_thread->next = main_thread;
-
- rb_cCont = rb_define_class("Continuation", rb_cObject);
- rb_undef_method(CLASS_OF(rb_cCont), "allocate");
- rb_undef_method(CLASS_OF(rb_cCont), "new");
- rb_define_method(rb_cCont, "call", rb_cont_call, -1);
- rb_define_global_function("callcc", rb_callcc, 0);
-
- cThGroup = rb_define_class("ThreadGroup", rb_cObject);
- rb_define_singleton_method(cThGroup, "allocate", thgroup_s_alloc, 0);
- rb_define_method(cThGroup, "list", thgroup_list, 0);
- rb_define_method(cThGroup, "add", thgroup_add, 1);
- rb_define_const(cThGroup, "Default", rb_obj_alloc(cThGroup));
-}
-
-static VALUE
-rb_f_catch(dmy, tag)
- VALUE dmy, tag;
-{
- int state;
- ID t;
- VALUE val; /* OK */
-
- t = rb_to_id(tag);
- PUSH_TAG(t);
- if ((state = EXEC_TAG()) == 0) {
- val = rb_yield_0(tag, 0, 0, 0);
- }
- else if (state == TAG_THROW && t == prot_tag->dst) {
- val = prot_tag->retval;
- state = 0;
- }
- POP_TAG();
- if (state) JUMP_TAG(state);
-
- return val;
-}
-
-static VALUE
-catch_i(tag)
- ID tag;
-{
- return rb_funcall(Qnil, rb_intern("catch"), 1, ID2SYM(tag));
-}
-
-VALUE
-rb_catch(tag, proc, data)
- const char *tag;
- VALUE (*proc)();
- VALUE data;
-{
- return rb_iterate((VALUE(*)_((VALUE)))catch_i, rb_intern(tag), proc, data);
-}
-
-static VALUE
-rb_f_throw(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE tag, value;
- ID t;
- struct tag *tt = prot_tag;
-
- rb_scan_args(argc, argv, "11", &tag, &value);
- t = rb_to_id(tag);
-
- while (tt) {
- if (tt->tag == t) {
- tt->dst = t;
- break;
- }
- if (tt->tag == PROT_THREAD) {
- rb_raise(rb_eThreadError, "uncaught throw `%s' in thread 0x%x",
- rb_id2name(t),
- curr_thread);
- }
- tt = tt->prev;
- }
- if (!tt) {
- rb_name_error(t, "uncaught throw `%s'", rb_id2name(t));
- }
- return_value(value);
- rb_trap_restore_mask();
- JUMP_TAG(TAG_THROW);
-}
-
-void
-rb_throw(tag, val)
- const char *tag;
- VALUE val;
-{
- VALUE argv[2];
- ID t = rb_intern(tag);
-
- argv[0] = ID2SYM(t);
- argv[1] = val;
- rb_f_throw(2, argv);
-}
-
-static void
-return_check()
-{
- struct tag *tt = prot_tag;
-
- while (tt) {
- if (tt->tag == PROT_FUNC) {
- break;
- }
- if (tt->tag == PROT_THREAD) {
- rb_raise(rb_eThreadError, "return from within thread 0x%x",
- curr_thread);
- }
- tt = tt->prev;
- }
-}
diff --git a/ext/.cvsignore b/ext/.cvsignore
deleted file mode 100644
index a3fac48ae6..0000000000
--- a/ext/.cvsignore
+++ /dev/null
@@ -1,3 +0,0 @@
-extinit.c
-extmk.log
-extmk.rb
diff --git a/ext/Setup b/ext/Setup
deleted file mode 100644
index df88155294..0000000000
--- a/ext/Setup
+++ /dev/null
@@ -1,20 +0,0 @@
-#option nodynamic
-
-#GD
-#curses
-#dbm
-#digest
-#digest/md5
-#digest/rmd160
-#digest/sha1
-#digest/sha2
-#etc
-#fcntl
-#kconv
-#pty
-#sdbm
-#socket
-#syslog
-#tk
-#tcltklib
-#gtk
diff --git a/ext/Setup.dj b/ext/Setup.dj
deleted file mode 100644
index 7d7aa7f87e..0000000000
--- a/ext/Setup.dj
+++ /dev/null
@@ -1,20 +0,0 @@
-option nodynamic
-
-#GD
-#curses
-dbm
-digest
-digest/md5
-digest/rmd160
-digest/sha1
-digest/sha2
-gdbm
-#etc
-fcntl
-nkf
-marshal
-readline
-sdbm
-#socket
-#syslog
-#tkutil
diff --git a/ext/Setup.emx b/ext/Setup.emx
deleted file mode 100644
index bba3d76887..0000000000
--- a/ext/Setup.emx
+++ /dev/null
@@ -1,21 +0,0 @@
-option nodynamic
-
-#Win32API
-curses
-#dbm
-digest
-digest/md5
-digest/rmd160
-digest/sha1
-digest/sha2
-etc
-fcntl
-#gdbm
-nkf
-#pty
-#readline
-#sdbm
-socket
-#syslog
-#tcltklib
-#tk
diff --git a/ext/Setup.nt b/ext/Setup.nt
deleted file mode 100644
index cb0014350b..0000000000
--- a/ext/Setup.nt
+++ /dev/null
@@ -1,24 +0,0 @@
-#option nodynamic
-
-#GD
-Win32API
-#curses
-#dbm
-digest
-digest/md5
-digest/rmd160
-digest/sha1
-digest/sha2
-#etc
-fcntl
-#gdbm
-#gtk
-marshal
-nkf
-#pty
-#readline
-sdbm
-socket
-#syslog
-#tcltklib
-#tk
diff --git a/ext/Setup.x68 b/ext/Setup.x68
deleted file mode 100644
index 84b8902732..0000000000
--- a/ext/Setup.x68
+++ /dev/null
@@ -1,17 +0,0 @@
-option nodynamic
-
-#GD
-#curses
-dbm
-digest
-digest/md5
-digest/rmd160
-digest/sha1
-digest/sha2
-#etc
-fcntl
-kconv
-marshal
-#socket
-#syslog
-#tkutil
diff --git a/ext/Win32API/.cvsignore b/ext/Win32API/.cvsignore
deleted file mode 100644
index f3c7a7c5da..0000000000
--- a/ext/Win32API/.cvsignore
+++ /dev/null
@@ -1 +0,0 @@
-Makefile
diff --git a/ext/Win32API/MANIFEST b/ext/Win32API/MANIFEST
deleted file mode 100644
index 7cc9ac445e..0000000000
--- a/ext/Win32API/MANIFEST
+++ /dev/null
@@ -1,7 +0,0 @@
-MANIFEST
-depend
-MANIFEST
-Win32API.c
-extconf.rb
-getch.rb
-point.rb
diff --git a/ext/Win32API/Win32API.c b/ext/Win32API/Win32API.c
deleted file mode 100644
index 65b6a558c1..0000000000
--- a/ext/Win32API/Win32API.c
+++ /dev/null
@@ -1,307 +0,0 @@
-/*
- Win32API - Ruby Win32 API Import Facility
-*/
-
-#if !defined _MSC_VER && !defined NT
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#include <stdio.h>
-#endif
-
-#if defined(_MSC_VER)
-#if defined(_M_ALPHA)
-#ifdef __cplusplus
-extern "C" { long __asm(char *,...); };
-#else
-long __asm(char *,...);
-#endif
-#pragma intrinsic(__asm)
-#endif
-#endif
-
-#define _T_VOID 0
-#define _T_NUMBER 1
-#define _T_POINTER 2
-#define _T_INTEGER 3
-
-typedef char *ApiPointer(void);
-typedef long ApiNumber(void);
-typedef void ApiVoid(void);
-typedef int ApiInteger(void);
-
-#include "ruby.h"
-
-typedef struct {
- HANDLE dll;
- HANDLE proc;
- VALUE dllname;
- VALUE import;
- VALUE export;
-} Win32API;
-
-static void
-Win32API_FreeLibrary(hdll)
- HINSTANCE hdll;
-{
- FreeLibrary(hdll);
-}
-
-static VALUE
-Win32API_initialize(self, dllname, proc, import, export)
- VALUE self;
- VALUE dllname;
- VALUE proc;
- VALUE import;
- VALUE export;
-{
- HANDLE hproc;
- HINSTANCE hdll;
- VALUE str;
- VALUE a_import;
- VALUE *ptr;
- char *s;
- int i;
- int len;
- int ex;
-
- SafeStringValue(dllname);
- SafeStringValue(proc);
- hdll = LoadLibrary(RSTRING(dllname)->ptr);
- if (!hdll)
- rb_raise(rb_eRuntimeError, "LoadLibrary: %s\n", RSTRING(dllname)->ptr);
- rb_iv_set(self, "__hdll__", Data_Wrap_Struct(self, 0, Win32API_FreeLibrary, hdll));
- hproc = GetProcAddress(hdll, RSTRING(proc)->ptr);
- if (!hproc) {
- str = rb_str_new3(proc);
- str = rb_str_cat(str, "A", 1);
- hproc = GetProcAddress(hdll, RSTRING(str)->ptr);
- if (!hproc)
- rb_raise(rb_eRuntimeError, "GetProcAddress: %s or %s\n",
- RSTRING(proc)->ptr, RSTRING(str)->ptr);
- }
- rb_iv_set(self, "__dll__", UINT2NUM((unsigned long)hdll));
- rb_iv_set(self, "__dllname__", dllname);
- rb_iv_set(self, "__proc__", UINT2NUM((unsigned long)hproc));
-
- a_import = rb_ary_new();
- switch (TYPE(import)) {
- case T_NIL:
- break;
- case T_ARRAY:
- ptr = RARRAY(import)->ptr;
- for (i = 0, len = RARRAY(import)->len; i < len; i++) {
- SafeStringValue(ptr[i]);
- switch (*(char *)RSTRING(ptr[i])->ptr) {
- case 'N': case 'n': case 'L': case 'l':
- rb_ary_push(a_import, INT2FIX(_T_NUMBER));
- break;
- case 'P': case 'p':
- rb_ary_push(a_import, INT2FIX(_T_POINTER));
- break;
- case 'I': case 'i':
- rb_ary_push(a_import, INT2FIX(_T_INTEGER));
- break;
- }
- }
- break;
- default:
- SafeStringValue(import);
- s = RSTRING(import)->ptr;
- for (i = 0, len = RSTRING(import)->len; i < len; i++) {
- switch (*s++) {
- case 'N': case 'n': case 'L': case 'l':
- rb_ary_push(a_import, INT2FIX(_T_NUMBER));
- break;
- case 'P': case 'p':
- rb_ary_push(a_import, INT2FIX(_T_POINTER));
- break;
- case 'I': case 'i':
- rb_ary_push(a_import, INT2FIX(_T_INTEGER));
- break;
- }
- }
- break;
- }
- rb_iv_set(self, "__import__", a_import);
-
- if (NIL_P(export)) {
- ex = _T_VOID;
- } else {
- SafeStringValue(export);
- switch (*RSTRING(export)->ptr) {
- case 'V': case 'v':
- ex = _T_VOID;
- break;
- case 'N': case 'n': case 'L': case 'l':
- ex = _T_NUMBER;
- break;
- case 'P': case 'p':
- ex = _T_POINTER;
- break;
- case 'I': case 'i':
- ex = _T_INTEGER;
- break;
- }
- }
- rb_iv_set(self, "__export__", INT2FIX(ex));
-
- return Qnil;
-}
-
-static VALUE
-Win32API_Call(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- VALUE args;
-
- FARPROC ApiFunction;
-
- ApiPointer *ApiFunctionPointer;
- ApiNumber *ApiFunctionNumber;
- ApiVoid *ApiFunctionVoid;
- ApiInteger *ApiFunctionInteger;
-
- long lParam;
- char *pParam;
-
- VALUE Return;
-
- VALUE obj_proc;
- VALUE obj_import;
- VALUE obj_export;
- VALUE import_type;
- int nimport, timport, texport, i;
- int items;
- int ret;
-
- items = rb_scan_args(argc, argv, "0*", &args);
-
- obj_proc = rb_iv_get(obj, "__proc__");
-
- ApiFunction = (FARPROC)NUM2ULONG(obj_proc);
-
- obj_import = rb_iv_get(obj, "__import__");
- obj_export = rb_iv_get(obj, "__export__");
- nimport = RARRAY(obj_import)->len;
- texport = FIX2INT(obj_export);
-
- if (items != nimport)
- rb_raise(rb_eRuntimeError, "Wrong number of parameters: expected %d, got %d.\n",
- nimport, items);
-
- if (0 < nimport) {
- for (i = nimport - 1; 0 <= i; i--) {
- VALUE str;
- import_type = rb_ary_entry(obj_import, i);
- timport = FIX2INT(import_type);
- switch (timport) {
- case _T_NUMBER:
- case _T_INTEGER:
- lParam = NUM2ULONG(rb_ary_entry(args, i));
-#if defined(_MSC_VER) || defined(__LCC__)
-#if defined(_M_IX86)
- _asm {
- mov eax, lParam
- push eax
- }
-#elif defined(_M_ALPHA)
- __asm(
- "ldl r0, 0(%0);"
- "stq r0, -(sp);"
- , lParam
- );
-#else
-#error
-#endif
-#elif defined __GNUC__
- asm volatile ("pushl %0" :: "g" (lParam));
-#else
-#error
-#endif
- break;
- case _T_POINTER:
- str = rb_ary_entry(args, i);
- if (NIL_P(str)) {
- pParam = 0;
- } else if (FIXNUM_P(str)){
- pParam = (char *)NUM2ULONG(str);
- } else {
- StringValue(str);
- rb_str_modify(str);
- pParam = RSTRING(str)->ptr;
- }
-#if defined(_MSC_VER) || defined(__LCC__)
-#if defined(_M_IX86)
- _asm {
- mov eax, pParam
- push eax
- }
-#elif defined(_M_ALPHA)
- __asm(
- "ldl r0, 0(%0);"
- "stq r0, -(sp);"
- , pParam
- );
-#else
-#error
-#endif
-#elif defined __GNUC__
- asm volatile ("pushl %0" :: "g" (pParam));
-#else
-#error
-#endif
- break;
- }
- }
- }
-
-#if defined __GNUC__
- asm volatile ("call *%1" : "=r" (ret) : "g" (ApiFunction));
- switch (texport) {
- case _T_NUMBER:
- case _T_INTEGER:
- Return = INT2NUM(ret);
- break;
- case _T_POINTER:
- Return = rb_str_new2((char *)ret);
- break;
- case _T_VOID:
- default:
- Return = INT2NUM(0);
- break;
- }
-#else
- switch (texport) {
- case _T_NUMBER:
- ApiFunctionNumber = (ApiNumber *) ApiFunction;
- Return = INT2NUM(ApiFunctionNumber());
- break;
- case _T_POINTER:
- ApiFunctionPointer = (ApiPointer *) ApiFunction;
- Return = rb_str_new2((char *)ApiFunctionPointer());
- break;
- case _T_INTEGER:
- ApiFunctionInteger = (ApiInteger *) ApiFunction;
- Return = INT2NUM(ApiFunctionInteger());
- break;
- case _T_VOID:
- default:
- ApiFunctionVoid = (ApiVoid *) ApiFunction;
- ApiFunctionVoid();
- Return = INT2NUM(0);
- break;
- }
-#endif
- return Return;
-}
-
-void
-Init_Win32API()
-{
- VALUE cWin32API = rb_define_class("Win32API", rb_cObject);
- rb_define_method(cWin32API, "initialize", Win32API_initialize, 4);
- rb_define_method(cWin32API, "call", Win32API_Call, -1);
- rb_define_alias(cWin32API, "Call", "call");
-}
diff --git a/ext/Win32API/depend b/ext/Win32API/depend
deleted file mode 100644
index b224bb66c9..0000000000
--- a/ext/Win32API/depend
+++ /dev/null
@@ -1 +0,0 @@
-Win32API.o : Win32API.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h
diff --git a/ext/Win32API/extconf.rb b/ext/Win32API/extconf.rb
deleted file mode 100644
index 5e42f62558..0000000000
--- a/ext/Win32API/extconf.rb
+++ /dev/null
@@ -1,7 +0,0 @@
-case RUBY_PLATFORM
-when /cygwin/,/mingw/
- $CFLAGS = "-fno-defer-pop -fno-omit-frame-pointer"
- create_makefile("Win32API")
-when /win32/
- create_makefile("Win32API")
-end
diff --git a/ext/Win32API/getch.rb b/ext/Win32API/getch.rb
deleted file mode 100644
index c015bbe9bc..0000000000
--- a/ext/Win32API/getch.rb
+++ /dev/null
@@ -1,5 +0,0 @@
-require 'Win32API'
-
-getch = Win32API.new("crtdll", "_getch", [], 'L')
-
-puts getch.Call.chr
diff --git a/ext/Win32API/point.rb b/ext/Win32API/point.rb
deleted file mode 100644
index 60e265f3ee..0000000000
--- a/ext/Win32API/point.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-require 'Win32API'
-
-getCursorPos = Win32API.new("user32", "GetCursorPos", ['P'], 'V')
-
-lpPoint = " " * 8 # store two LONGs
-getCursorPos.Call(lpPoint)
-x, y = lpPoint.unpack("LL") # get the actual values
-
-print "x: ", x, "\n"
-print "y: ", y, "\n"
-
-ods = Win32API.new("kernel32", "OutputDebugString", ['P'], 'V')
-ods.Call("Hello, World\n");
-
-GetDesktopWindow = Win32API.new("user32", "GetDesktopWindow", [], 'L')
-GetActiveWindow = Win32API.new("user32", "GetActiveWindow", [], 'L')
-SendMessage = Win32API.new("user32", "SendMessage", ['L'] * 4, 'L')
-SendMessage.Call GetDesktopWindow.Call, 274, 0xf140, 0
diff --git a/ext/aix_mksym.rb b/ext/aix_mksym.rb
deleted file mode 100644
index 7e1af283dc..0000000000
--- a/ext/aix_mksym.rb
+++ /dev/null
@@ -1,33 +0,0 @@
-
-def uniq(data)
- last=nil
- data.delete_if do |name|
- if last == name
- TRUE
- else
- last = name
- FALSE
- end
- end
-end
-
-def extract(nm, out)
- data = nm.readlines.collect{|line|
- line = line.split
- case line[1]
- when "B", "D"
- line[0]
- else
- next
- end
- }.compact!.sort!
- uniq(data)
- exp = open(out, "w")
- exp.printf "#!\n"
- for line in data
- exp.printf "%s\n", line
- end
- exp.close
- nm.close
-end
-extract(open("|/usr/ccs/bin/nm -p ../libruby.a"), "../ruby.imp")
diff --git a/ext/configsub.rb b/ext/configsub.rb
deleted file mode 100644
index 47689d7ec0..0000000000
--- a/ext/configsub.rb
+++ /dev/null
@@ -1,32 +0,0 @@
-#!./miniruby -ps
-
-BEGIN {
- CONFIG = {}
-
- RUBY_VERSION.scan(/(\d+)\.(\d+)\.(\d+)/) do
- # overridden if config.status has version
- CONFIG['MAJOR'] = $1
- CONFIG['MINOR'] = $2
- CONFIG['TEENY'] = $3
- end
-
- File.foreach($config || "config.status") do |line|
- next if /^#/ =~ line
- if /^s[%,]@(\w+)@[%,](.*)[%,][g;]/ =~ line
- name = $1
- val = $2 || ""
- next if /^(INSTALL|DEFS|configure_input|srcdir)$/ =~ name
- val.gsub!(/\$\{([^{}]+)\}/) { "$(#{$1})" }
- CONFIG[name] = val
- end
- end
-
- CONFIG['top_srcdir'] = File.expand_path($srcdir || ".")
- CONFIG['RUBY_INSTALL_NAME'] = $install_name if $install_name
- CONFIG['RUBY_SO_NAME'] = $so_name if $so_name
- $defout = open($output, 'w') if $output
-}
-
-gsub!(/@(\w+)@/) {CONFIG[$1] || $&}
-
-# vi:set sw=2:
diff --git a/ext/curses/.cvsignore b/ext/curses/.cvsignore
deleted file mode 100644
index fc802ff1c2..0000000000
--- a/ext/curses/.cvsignore
+++ /dev/null
@@ -1,2 +0,0 @@
-Makefile
-mkmf.log
diff --git a/ext/curses/MANIFEST b/ext/curses/MANIFEST
deleted file mode 100644
index 5882d682f0..0000000000
--- a/ext/curses/MANIFEST
+++ /dev/null
@@ -1,9 +0,0 @@
-MANIFEST
-curses.c
-depend
-extconf.rb
-hello.rb
-rain.rb
-view.rb
-view2.rb
-mouse.rb
diff --git a/ext/curses/curses.c b/ext/curses/curses.c
deleted file mode 100644
index 2a48508b01..0000000000
--- a/ext/curses/curses.c
+++ /dev/null
@@ -1,1874 +0,0 @@
-/* -*- C -*-
- * $Id$
- *
- * ext/curses/curses.c
- *
- * by MAEDA Shugo (ender@pic-internet.or.jp)
- * modified by Yukihiro Matsumoto (matz@netlab.co.jp),
- * Toki Yoshinori,
- * Hitoshi Takahashi,
- * and Takaaki Tateishi (ttate@kt.jaist.ac.jp)
- *
- * maintainers:
- * - Takaaki Tateishi (ttate@kt.jaist.ac.jp)
- */
-
-#ifdef HAVE_NCURSES_H
-# include <ncurses.h>
-#else
-# ifdef HAVE_NCURSES_CURSES_H
-# include <ncurses/curses.h>
-#else
-# ifdef HAVE_CURSES_COLR_CURSES_H
-# include <varargs.h>
-# include <curses_colr/curses.h>
-# else
-# include <curses.h>
-# if (defined(__bsdi__) || defined(__NetBSD__) || defined(__APPLE__)) && !defined(_maxx)
-# define _maxx maxx
-# endif
-# if (defined(__bsdi__) || defined(__NetBSD__) || defined(__APPLE__)) && !defined(_maxy)
-# define _maxy maxy
-# endif
-# if (defined(__bsdi__) || defined(__NetBSD__) || defined(__APPLE__)) && !defined(_begx)
-# define _begx begx
-# endif
-# if (defined(__bsdi__) || defined(__NetBSD__) || defined(__APPLE__)) && !defined(_begy)
-# define _begy begy
-# endif
-# endif
-#endif
-#endif
-
-#ifdef HAVE_INIT_COLOR
-# define USE_COLOR 1
-#endif
-
-/* supports only ncurses mouse routines */
-#ifdef NCURSES_MOUSE_VERSION
-# define USE_MOUSE 1
-#endif
-
-#include "stdio.h"
-#include "ruby.h"
-#include "rubyio.h"
-
-static VALUE mCurses;
-static VALUE mKey;
-static VALUE cWindow;
-#ifdef USE_MOUSE
-static VALUE cMouseEvent;
-#endif
-
-VALUE rb_stdscr;
-
-struct windata {
- WINDOW *window;
-};
-
-#define CHECK(c) c
-
-static VALUE window_attroff();
-static VALUE window_attron();
-static VALUE window_attrset();
-
-static void
-no_window()
-{
- rb_raise(rb_eRuntimeError, "already closed window");
-}
-
-
-#define GetWINDOW(obj, winp) {\
- Data_Get_Struct(obj, struct windata, winp);\
- if (winp->window == 0) no_window();\
-}
-
-
-static void
-free_window(winp)
- struct windata *winp;
-{
- if (winp->window && winp->window != stdscr) delwin(winp->window);
- winp->window = 0;
- free(winp);
-}
-
-static VALUE
-prep_window(class, window)
- VALUE class;
- WINDOW *window;
-{
- VALUE obj;
- struct windata *winp;
-
- if (window == NULL) {
- rb_raise(rb_eRuntimeError, "failed to create window");
- }
-
- obj = Data_Make_Struct(class, struct windata, 0, free_window, winp);
- winp->window = window;
-
- return obj;
-}
-
-/*-------------------------- module Curses --------------------------*/
-
-/* def init_screen */
-static VALUE
-curses_init_screen()
-{
- initscr();
- if (stdscr == 0) {
- rb_raise(rb_eRuntimeError, "cannot initialize curses");
- }
- clear();
- rb_stdscr = prep_window(cWindow, stdscr);
- return rb_stdscr;
-}
-
-/* def stdscr */
-static VALUE
-curses_stdscr()
-{
- if (rb_stdscr == 0) curses_init_screen();
- return rb_stdscr;
-}
-
-/* def close_screen */
-static VALUE
-curses_close_screen()
-{
-#ifdef HAVE_ISENDWIN
- if (!isendwin())
-#endif
- endwin();
- return Qnil;
-}
-
-static void
-curses_finalize()
-{
- if (stdscr
-#ifdef HAVE_ISENDWIN
- && !isendwin()
-#endif
- )
- endwin();
-}
-
-/* def closed? */
-static VALUE
-curses_closed()
-{
-#ifdef HAVE_ISENDWIN
- if (isendwin()) {
- return Qtrue;
- }
- return Qfalse;
-#else
- rb_notimplement();
-#endif
-}
-
-/* def clear */
-static VALUE
-curses_clear(obj)
- VALUE obj;
-{
- wclear(stdscr);
- return Qnil;
-}
-
-/* def refresh */
-static VALUE
-curses_refresh(obj)
- VALUE obj;
-{
- refresh();
- return Qnil;
-}
-
-/* def doupdate */
-static VALUE
-curses_doupdate(obj)
- VALUE obj;
-{
-#ifdef HAVE_DOUPDATE
- doupdate();
-#else
- refresh();
-#endif
- return Qnil;
-}
-
-/* def echo */
-static VALUE
-curses_echo(obj)
- VALUE obj;
-{
- echo();
- return Qnil;
-}
-
-/* def noecho */
-static VALUE
-curses_noecho(obj)
- VALUE obj;
-{
- noecho();
- return Qnil;
-}
-
-/* def raw */
-static VALUE
-curses_raw(obj)
- VALUE obj;
-{
- raw();
- return Qnil;
-}
-
-/* def noraw */
-static VALUE
-curses_noraw(obj)
- VALUE obj;
-{
- noraw();
- return Qnil;
-}
-
-/* def cbreak */
-static VALUE
-curses_cbreak(obj)
- VALUE obj;
-{
- cbreak();
- return Qnil;
-}
-
-/* def nocbreak */
-static VALUE
-curses_nocbreak(obj)
- VALUE obj;
-{
- nocbreak();
- return Qnil;
-}
-
-/* def nl */
-static VALUE
-curses_nl(obj)
- VALUE obj;
-{
- nl();
- return Qnil;
-}
-
-/* def nonl */
-static VALUE
-curses_nonl(obj)
- VALUE obj;
-{
- nonl();
- return Qnil;
-}
-
-/* def beep */
-static VALUE
-curses_beep(obj)
- VALUE obj;
-{
-#ifdef HAVE_BEEP
- beep();
-#endif
- return Qnil;
-}
-
-/* def flash */
-static VALUE
-curses_flash(obj)
- VALUE obj;
-{
-#ifdef HAVE_FLASH
- flash();
-#endif
- return Qnil;
-}
-
-/* def ungetch */
-static VALUE
-curses_ungetch(obj, ch)
- VALUE obj;
- VALUE ch;
-{
-#ifdef HAVE_UNGETCH
- ungetch(NUM2INT(ch));
-#else
- rb_notimplement();
-#endif
- return Qnil;
-}
-
-/* def setpos(y, x) */
-static VALUE
-curses_setpos(obj, y, x)
- VALUE obj;
- VALUE y;
- VALUE x;
-{
- move(NUM2INT(y), NUM2INT(x));
- return Qnil;
-}
-
-/* def standout */
-static VALUE
-curses_standout(obj)
- VALUE obj;
-{
- standout();
- return Qnil;
-}
-
-/* def standend */
-static VALUE
-curses_standend(obj)
- VALUE obj;
-{
- standend();
- return Qnil;
-}
-
-/* def inch */
-static VALUE
-curses_inch(obj)
- VALUE obj;
-{
- return CHR2FIX(inch());
-}
-
-/* def addch(ch) */
-static VALUE
-curses_addch(obj, ch)
- VALUE obj;
- VALUE ch;
-{
- addch(NUM2CHR(ch));
- return Qnil;
-}
-
-/* def insch(ch) */
-static VALUE
-curses_insch(obj, ch)
- VALUE obj;
- VALUE ch;
-{
- insch(NUM2CHR(ch));
- return Qnil;
-}
-
-/* def addstr(str) */
-static VALUE
-curses_addstr(obj, str)
- VALUE obj;
- VALUE str;
-{
- if (!NIL_P(str)) {
- addstr(STR2CSTR(str));
- }
- return Qnil;
-}
-
-/* def getch */
-static VALUE
-curses_getch(obj)
- VALUE obj;
-{
- rb_read_check(stdin);
- return UINT2NUM(getch());
-}
-
-/* def getstr */
-static VALUE
-curses_getstr(obj)
- VALUE obj;
-{
- char rtn[1024]; /* This should be big enough.. I hope */
-
- rb_read_check(stdin);
-#if defined(HAVE_GETNSTR)
- getnstr(rtn,1023);
-#else
- getstr(rtn);
-#endif
- return rb_tainted_str_new2(rtn);
-}
-
-/* def delch */
-static VALUE
-curses_delch(obj)
- VALUE obj;
-{
- delch();
- return Qnil;
-}
-
-/* def delelteln */
-static VALUE
-curses_deleteln(obj)
- VALUE obj;
-{
-#if defined(HAVE_DELETELN) || defined(deleteln)
- deleteln();
-#endif
- return Qnil;
-}
-
-/* def keyname */
-static VALUE
-curses_keyname(obj, c)
- VALUE obj;
- VALUE c;
-{
-#ifdef HAVE_KEYNAME
- const char *name;
-
- name = keyname(NUM2INT(c));
- if (name) {
- return rb_str_new2(name);
- } else {
- return Qnil;
- }
-#else
- return Qnil;
-#endif
-}
-
-static VALUE
-curses_lines()
-{
- return INT2FIX(LINES);
-}
-
-static VALUE
-curses_cols()
-{
- return INT2FIX(COLS);
-}
-
-static VALUE
-curses_curs_set(VALUE obj, VALUE visibility)
-{
- int n;
- return (n = curs_set(NUM2INT(visibility)) != ERR) ? INT2FIX(n) : Qnil;
-}
-
-static VALUE
-curses_scrl(VALUE obj, VALUE n)
-{
- /* may have to raise exception on ERR */
- return (scrl(NUM2INT(n)) == OK) ? Qtrue : Qfalse;
-}
-
-static VALUE
-curses_setscrreg(VALUE obj, VALUE top, VALUE bottom)
-{
- /* may have to raise exception on ERR */
- return (setscrreg(NUM2INT(top), NUM2INT(bottom)) == OK) ? Qtrue : Qfalse;
-}
-
-static VALUE
-curses_attroff(VALUE obj, VALUE attrs)
-{
- return window_attroff(rb_stdscr,attrs);
- /* return INT2FIX(attroff(NUM2INT(attrs))); */
-}
-
-static VALUE
-curses_attron(VALUE obj, VALUE attrs)
-{
- return window_attron(rb_stdscr,attrs);
- /* return INT2FIX(attroff(NUM2INT(attrs))); */
-}
-
-static VALUE
-curses_attrset(VALUE obj, VALUE attrs)
-{
- return window_attrset(rb_stdscr,attrs);
- /* return INT2FIX(attroff(NUM2INT(attrs))); */
-}
-
-static VALUE
-curses_bkgdset(VALUE obj, VALUE ch)
-{
- bkgdset(NUM2CHR(ch));
- return Qnil;
-}
-
-static VALUE
-curses_bkgd(VALUE obj, VALUE ch)
-{
- return CHR2FIX(bkgd(NUM2CHR(ch)));
-}
-
-static VALUE
-curses_resizeterm(VALUE obj, VALUE lines, VALUE columns)
-{
-#if defined(HAVE_RESIZETERM)
- return (resizeterm(NUM2INT(lines),NUM2INT(columns)) == OK) ? Qtrue : Qfalse;
-#else
- return Qnil;
-#endif
-}
-
-#ifdef USE_COLOR
-static VALUE
-curses_start_color(VALUE obj)
-{
- /* may have to raise exception on ERR */
- return (start_color() == OK) ? Qtrue : Qfalse;
-}
-
-static VALUE
-curses_init_pair(VALUE obj, VALUE pair, VALUE f, VALUE b)
-{
- /* may have to raise exception on ERR */
- return (init_pair(NUM2INT(pair),NUM2INT(f),NUM2INT(b)) == OK) ? Qtrue : Qfalse;
-}
-
-static VALUE
-curses_init_color(VALUE obj, VALUE color, VALUE r, VALUE g, VALUE b)
-{
- /* may have to raise exception on ERR */
- return (init_color(NUM2INT(color),NUM2INT(r),
- NUM2INT(g),NUM2INT(b)) == OK) ? Qtrue : Qfalse;
-}
-
-static VALUE
-curses_has_colors(VALUE obj)
-{
- return has_colors() ? Qtrue : Qfalse;
-}
-
-static VALUE
-curses_can_change_color(VALUE obj)
-{
- return can_change_color() ? Qtrue : Qfalse;
-}
-
-static VALUE
-curses_color_content(VALUE obj, VALUE color)
-{
- short r,g,b;
-
- color_content(NUM2INT(color),&r,&g,&b);
- return rb_ary_new3(3,INT2FIX(r),INT2FIX(g),INT2FIX(b));
-}
-
-static VALUE
-curses_pair_content(VALUE obj, VALUE pair)
-{
- short f,b;
-
- pair_content(NUM2INT(pair),&f,&b);
- return rb_ary_new3(2,INT2FIX(f),INT2FIX(b));
-}
-
-static VALUE
-curses_color_pair(VALUE obj, VALUE attrs)
-{
- return INT2FIX(COLOR_PAIR(NUM2INT(attrs)));
-}
-
-static VALUE
-curses_pair_number(VALUE obj, VALUE attrs)
-{
- return INT2FIX(PAIR_NUMBER(NUM2INT(attrs)));
-}
-#endif
-
-#ifdef USE_MOUSE
-struct mousedata {
- MEVENT *mevent;
-};
-
-static void
-no_mevent()
-{
- rb_raise(rb_eRuntimeError, "no such mouse event");
-};
-
-#define GetMOUSE(obj, data) {\
- Data_Get_Struct(obj, struct mousedata, data);\
- if (data->mevent == 0) no_mevent();\
-}
-
-static void
-curses_mousedata_free(struct mousedata *mdata)
-{
- if (mdata->mevent)
- free(mdata->mevent);
-};
-
-static VALUE
-curses_getmouse(VALUE obj)
-{
- struct mousedata *mdata;
- VALUE val;
-
- val = Data_Make_Struct(cMouseEvent,struct mousedata,
- 0,curses_mousedata_free,mdata);
- mdata->mevent = (MEVENT*)malloc(sizeof(MEVENT));
- return (getmouse(mdata->mevent) == OK) ? val : Qnil;
-};
-
-static VALUE
-curses_ungetmouse(VALUE obj, VALUE mevent)
-{
- struct mousedata *mdata;
-
- GetMOUSE(mevent,mdata);
- return (ungetmouse(mdata->mevent) == OK) ? Qtrue : Qfalse;
-};
-
-static VALUE
-curses_mouseinterval(VALUE obj, VALUE interval)
-{
- return mouseinterval(NUM2INT(interval)) ? Qtrue : Qfalse;
-};
-
-static VALUE
-curses_mousemask(VALUE obj, VALUE mask)
-{
- return INT2NUM(mousemask(NUM2UINT(mask),NULL));
-};
-
-#define DEFINE_MOUSE_GET_MEMBER(func_name,mem) \
-static VALUE func_name (VALUE mouse) \
-{ \
- struct mousedata *mdata; \
- GetMOUSE(mouse, mdata); \
- return (UINT2NUM(mdata->mevent -> mem)); \
-}
-
-DEFINE_MOUSE_GET_MEMBER(curs_mouse_id, id);
-DEFINE_MOUSE_GET_MEMBER(curs_mouse_x, x);
-DEFINE_MOUSE_GET_MEMBER(curs_mouse_y, y);
-DEFINE_MOUSE_GET_MEMBER(curs_mouse_z, z);
-DEFINE_MOUSE_GET_MEMBER(curs_mouse_bstate, bstate);
-#undef define_curs_mouse_member
-#endif /* USE_MOUSE */
-
-/*-------------------------- class Window --------------------------*/
-
-/* def new(h, w, top, left) */
-static VALUE
-window_s_new(class, h, w, top, left)
- VALUE class;
- VALUE h;
- VALUE w;
- VALUE top;
- VALUE left;
-{
- VALUE win;
- WINDOW *window;
- VALUE args[4];
-
- window = newwin(NUM2INT(h), NUM2INT(w), NUM2INT(top), NUM2INT(left));
- wclear(window);
- win = prep_window(class, window);
- args[0] = h; args[1] = w; args[2] = top; args[3] = left;
-
- return win;
-}
-
-/* def subwin(h, w, top, left) */
-static VALUE
-window_subwin(obj, h, w, top, left)
- VALUE obj;
- VALUE h;
- VALUE w;
- VALUE top;
- VALUE left;
-{
- struct windata *winp;
- WINDOW *window;
- VALUE win;
- VALUE args[4];
-
- GetWINDOW(obj, winp);
- window = subwin(winp->window, NUM2INT(h), NUM2INT(w),
- NUM2INT(top), NUM2INT(left));
- win = prep_window(cWindow, window);
- args[0] = h; args[1] = w; args[2] = top; args[3] = left;
-
- return win;
-}
-
-/* def close */
-static VALUE
-window_close(obj)
- VALUE obj;
-{
- struct windata *winp;
-
- GetWINDOW(obj, winp);
- delwin(winp->window);
- winp->window = 0;
-
- return Qnil;
-}
-
-/* def clear */
-static VALUE
-window_clear(obj)
- VALUE obj;
-{
- struct windata *winp;
-
- GetWINDOW(obj, winp);
- wclear(winp->window);
-
- return Qnil;
-}
-
-/* def refresh */
-static VALUE
-window_refresh(obj)
- VALUE obj;
-{
- struct windata *winp;
-
- GetWINDOW(obj, winp);
- wrefresh(winp->window);
-
- return Qnil;
-}
-
-/* def noutrefresh */
-static VALUE
-window_noutrefresh(obj)
- VALUE obj;
-{
- struct windata *winp;
-
- GetWINDOW(obj, winp);
-#ifdef HAVE_DOUPDATE
- wnoutrefresh(winp->window);
-#else
- wrefresh(winp->window);
-#endif
-
- return Qnil;
-}
-
-/* def move(y, x) */
-static VALUE
-window_move(obj, y, x)
- VALUE obj;
- VALUE y;
- VALUE x;
-{
- struct windata *winp;
-
- GetWINDOW(obj, winp);
- mvwin(winp->window, NUM2INT(y), NUM2INT(x));
-
- return Qnil;
-}
-
-/* def setpos(y, x) */
-static VALUE
-window_setpos(obj, y, x)
- VALUE obj;
- VALUE y;
- VALUE x;
-{
- struct windata *winp;
-
- GetWINDOW(obj, winp);
- wmove(winp->window, NUM2INT(y), NUM2INT(x));
- return Qnil;
-}
-
-/* def cury */
-static VALUE
-window_cury(obj)
- VALUE obj;
-{
- struct windata *winp;
- int x, y;
-
- GetWINDOW(obj, winp);
- getyx(winp->window, y, x);
- return INT2FIX(y);
-}
-
-/* def curx */
-static VALUE
-window_curx(obj)
- VALUE obj;
-{
- struct windata *winp;
- int x, y;
-
- GetWINDOW(obj, winp);
- getyx(winp->window, y, x);
- return INT2FIX(x);
-}
-
-/* def maxy */
-static VALUE
-window_maxy(obj)
- VALUE obj;
-{
- struct windata *winp;
- int x, y;
-
- GetWINDOW(obj, winp);
-#ifdef getmaxy
- return INT2FIX(getmaxy(winp->window));
-#else
-#ifdef getmaxyx
- getmaxyx(winp->window, y, x);
- return INT2FIX(y);
-#else
- return INT2FIX(winp->window->_maxy+1);
-#endif
-#endif
-}
-
-/* def maxx */
-static VALUE
-window_maxx(obj)
- VALUE obj;
-{
- struct windata *winp;
- int x, y;
-
- GetWINDOW(obj, winp);
-#ifdef getmaxx
- return INT2FIX(getmaxx(winp->window));
-#else
-#ifdef getmaxyx
- getmaxyx(winp->window, y, x);
- return INT2FIX(x);
-#else
- return INT2FIX(winp->window->_maxx+1);
-#endif
-#endif
-}
-
-/* def begy */
-static VALUE
-window_begy(obj)
- VALUE obj;
-{
- struct windata *winp;
- int x, y;
-
- GetWINDOW(obj, winp);
-#ifdef getbegyx
- getbegyx(winp->window, y, x);
- return INT2FIX(y);
-#else
- return INT2FIX(winp->window->_begy);
-#endif
-}
-
-/* def begx */
-static VALUE
-window_begx(obj)
- VALUE obj;
-{
- struct windata *winp;
- int x, y;
-
- GetWINDOW(obj, winp);
-#ifdef getbegyx
- getbegyx(winp->window, y, x);
- return INT2FIX(x);
-#else
- return INT2FIX(winp->window->_begx);
-#endif
-}
-
-/* def box(vert, hor) */
-static VALUE
-window_box(argc, argv, self)
- int argc;
- VALUE argv[], self;
-{
- struct windata *winp;
- VALUE vert, hor, corn;
-
- rb_scan_args(argc, argv, "21", &vert, &hor, &corn);
-
- GetWINDOW(self, winp);
- box(winp->window, NUM2CHR(vert), NUM2CHR(hor));
-
- if( argc == 3 ){
- int cur_x, cur_y, x, y;
- char c;
-
- c = NUM2CHR(corn);
- getyx(winp->window, cur_y, cur_x);
- x = NUM2INT(window_maxx(self)) - 1;
- y = NUM2INT(window_maxy(self)) - 1;
- wmove(winp->window, 0, 0);
- waddch(winp->window, c);
- wmove(winp->window, y, 0);
- waddch(winp->window, c);
- wmove(winp->window, y, x);
- waddch(winp->window, c);
- wmove(winp->window, 0, x);
- waddch(winp->window, c);
- wmove(winp->window, cur_y, cur_x);
- }
-
- return Qnil;
-}
-
-/* def standout */
-static VALUE
-window_standout(obj)
- VALUE obj;
-{
- struct windata *winp;
-
- GetWINDOW(obj, winp);
- wstandout(winp->window);
- return Qnil;
-}
-
-/* def standend */
-static VALUE
-window_standend(obj)
- VALUE obj;
-{
- struct windata *winp;
-
- GetWINDOW(obj, winp);
- wstandend(winp->window);
- return Qnil;
-}
-
-/* def inch */
-static VALUE
-window_inch(obj)
- VALUE obj;
-{
- struct windata *winp;
-
- GetWINDOW(obj, winp);
- return CHR2FIX(winch(winp->window));
-}
-
-/* def addch(ch) */
-static VALUE
-window_addch(obj, ch)
- VALUE obj;
- VALUE ch;
-{
- struct windata *winp;
-
- GetWINDOW(obj, winp);
- waddch(winp->window, NUM2CHR(ch));
-
- return Qnil;
-}
-
-/* def insch(ch) */
-static VALUE
-window_insch(obj, ch)
- VALUE obj;
- VALUE ch;
-{
- struct windata *winp;
-
- GetWINDOW(obj, winp);
- winsch(winp->window, NUM2CHR(ch));
-
- return Qnil;
-}
-
-/* def addstr(str) */
-static VALUE
-window_addstr(obj, str)
- VALUE obj;
- VALUE str;
-{
- if (!NIL_P(str)) {
- struct windata *winp;
-
- GetWINDOW(obj, winp);
- waddstr(winp->window, STR2CSTR(str));
- }
- return Qnil;
-}
-
-/* def <<(str) */
-static VALUE
-window_addstr2(obj, str)
- VALUE obj;
- VALUE str;
-{
- window_addstr(obj, str);
- return obj;
-}
-
-/* def getch */
-static VALUE
-window_getch(obj)
- VALUE obj;
-{
- struct windata *winp;
-
- rb_read_check(stdin);
- GetWINDOW(obj, winp);
- return UINT2NUM(wgetch(winp->window));
-}
-
-/* def getstr */
-static VALUE
-window_getstr(obj)
- VALUE obj;
-{
- struct windata *winp;
- char rtn[1024]; /* This should be big enough.. I hope */
-
- GetWINDOW(obj, winp);
- rb_read_check(stdin);
-#if defined(HAVE_WGETNSTR)
- wgetnstr(winp->window, rtn, 1023);
-#else
- wgetstr(winp->window, rtn);
-#endif
- return rb_tainted_str_new2(rtn);
-}
-
-/* def delch */
-static VALUE
-window_delch(obj)
- VALUE obj;
-{
- struct windata *winp;
-
- GetWINDOW(obj, winp);
- wdelch(winp->window);
- return Qnil;
-}
-
-/* def delelteln */
-static VALUE
-window_deleteln(obj)
- VALUE obj;
-{
-#if defined(HAVE_WDELETELN) || defined(wdeleteln)
- struct windata *winp;
-
- GetWINDOW(obj, winp);
- wdeleteln(winp->window);
-#endif
- return Qnil;
-}
-
-static VALUE
-window_scrollok(VALUE obj, VALUE bf)
-{
- struct windata *winp;
-
- GetWINDOW(obj, winp);
- scrollok(winp->window, RTEST(bf) ? TRUE : FALSE);
- return Qnil;
-}
-
-static VALUE
-window_idlok(VALUE obj, VALUE bf)
-{
- struct windata *winp;
- int res;
-
- GetWINDOW(obj, winp);
- idlok(winp->window, RTEST(bf) ? TRUE : FALSE);
- return Qnil;
-}
-
-static VALUE
-window_setscrreg(VALUE obj, VALUE top, VALUE bottom)
-{
- struct windata *winp;
- int res;
-
- GetWINDOW(obj, winp);
- res = wsetscrreg(winp->window, NUM2INT(top), NUM2INT(bottom));
- /* may have to raise exception on ERR */
- return (res == OK) ? Qtrue : Qfalse;
-};
-
-static VALUE
-window_scroll(VALUE obj)
-{
- struct windata *winp;
-
- GetWINDOW(obj, winp);
- /* may have to raise exception on ERR */
- return (scroll(winp->window) == OK) ? Qtrue : Qfalse;
-}
-
-static VALUE
-window_scrl(VALUE obj, VALUE n)
-{
- struct windata *winp;
-
- GetWINDOW(obj, winp);
- /* may have to raise exception on ERR */
- return (wscrl(winp->window,NUM2INT(n)) == OK) ? Qtrue : Qfalse;
-}
-
-static VALUE
-window_attroff(VALUE obj, VALUE attrs)
-{
- struct windata *winp;
-
- GetWINDOW(obj,winp);
- return INT2FIX(wattroff(winp->window,NUM2INT(attrs)));
-};
-
-static VALUE
-window_attron(VALUE obj, VALUE attrs)
-{
- struct windata *winp;
- VALUE val;
-
- GetWINDOW(obj,winp);
- val = INT2FIX(wattron(winp->window,NUM2INT(attrs)));
- if( rb_block_given_p() ){
- rb_yield(val);
- wattroff(winp->window,NUM2INT(attrs));
- return val;
- }
- else{
- return val;
- };
-};
-
-static VALUE
-window_attrset(VALUE obj, VALUE attrs)
-{
- struct windata *winp;
-
- GetWINDOW(obj,winp);
- return INT2FIX(wattrset(winp->window,NUM2INT(attrs)));
-}
-
-static VALUE
-window_bkgdset(VALUE obj, VALUE ch)
-{
- struct windata *winp;
-
- GetWINDOW(obj,winp);
- wbkgdset(winp->window, NUM2CHR(ch));
- return Qnil;
-}
-
-static VALUE
-window_bkgd(VALUE obj, VALUE ch)
-{
- struct windata *winp;
-
- GetWINDOW(obj,winp);
- return CHR2FIX(wbkgd(winp->window, NUM2CHR(ch)));
-}
-
-static VALUE
-window_getbkgd(VALUE obj)
-{
- struct windata *winp;
-
- GetWINDOW(obj,winp);
- return CHR2FIX(getbkgd(winp->window));
-}
-
-static VALUE
-window_resize(VALUE obj, VALUE lines, VALUE columns)
-{
-#if defined(HAVE_WRESIZE)
- struct windata *winp;
-
- GetWINDOW(obj,winp);
- return wresize(winp->window, NUM2INT(lines), NUM2INT(columns)) == OK ? Qtrue : Qfalse;
-#else
- return Qnil;
-#endif
-}
-
-
-#ifdef HAVE_KEYPAD
-static VALUE
-window_keypad(VALUE obj, VALUE val)
-{
- struct windata *winp;
-
- GetWINDOW(obj,winp);
- /* keypad() of NetBSD's libcurses returns no value */
-#if defined(__NetBSD__) && !defined(NCURSES_VERSION)
- keypad(winp->window,(RTEST(val) ? TRUE : FALSE));
- return Qnil;
-#else
- /* may have to raise exception on ERR */
- return (keypad(winp->window,RTEST(val) ? TRUE : FALSE)) == OK ?
- Qtrue : Qfalse;
-#endif
-};
-#endif /* HAVE_KEYPAD */
-
-/*------------------------- Initialization -------------------------*/
-void
-Init_curses()
-{
- mCurses = rb_define_module("Curses");
- mKey = rb_define_module_under(mCurses, "Key");
-
-#ifdef USE_MOUSE
- cMouseEvent = rb_define_class_under(mCurses,"MouseEvent",rb_cObject);
- rb_undef_method(CLASS_OF(cMouseEvent),"new");
- rb_define_method(cMouseEvent, "eid", curs_mouse_id, 0);
- rb_define_method(cMouseEvent, "x", curs_mouse_x, 0);
- rb_define_method(cMouseEvent, "y", curs_mouse_y, 0);
- rb_define_method(cMouseEvent, "z", curs_mouse_z, 0);
- rb_define_method(cMouseEvent, "bstate", curs_mouse_bstate, 0);
-#endif /* USE_MOUSE */
-
- rb_define_module_function(mCurses, "init_screen", curses_init_screen, 0);
- rb_define_module_function(mCurses, "close_screen", curses_close_screen, 0);
- rb_define_module_function(mCurses, "closed?", curses_closed, 0);
- rb_define_module_function(mCurses, "stdscr", curses_stdscr, 0);
- rb_define_module_function(mCurses, "refresh", curses_refresh, 0);
- rb_define_module_function(mCurses, "doupdate", curses_doupdate, 0);
- rb_define_module_function(mCurses, "clear", curses_clear, 0);
- rb_define_module_function(mCurses, "echo", curses_echo, 0);
- rb_define_module_function(mCurses, "noecho", curses_noecho, 0);
- rb_define_module_function(mCurses, "raw", curses_raw, 0);
- rb_define_module_function(mCurses, "noraw", curses_noraw, 0);
- rb_define_module_function(mCurses, "cbreak", curses_cbreak, 0);
- rb_define_module_function(mCurses, "nocbreak", curses_nocbreak, 0);
- rb_define_alias(mCurses, "crmode", "cbreak");
- rb_define_alias(mCurses, "nocrmode", "nocbreak");
- rb_define_module_function(mCurses, "nl", curses_nl, 0);
- rb_define_module_function(mCurses, "nonl", curses_nonl, 0);
- rb_define_module_function(mCurses, "beep", curses_beep, 0);
- rb_define_module_function(mCurses, "flash", curses_flash, 0);
- rb_define_module_function(mCurses, "ungetch", curses_ungetch, 1);
- rb_define_module_function(mCurses, "setpos", curses_setpos, 2);
- rb_define_module_function(mCurses, "standout", curses_standout, 0);
- rb_define_module_function(mCurses, "standend", curses_standend, 0);
- rb_define_module_function(mCurses, "inch", curses_inch, 0);
- rb_define_module_function(mCurses, "addch", curses_addch, 1);
- rb_define_module_function(mCurses, "insch", curses_insch, 1);
- rb_define_module_function(mCurses, "addstr", curses_addstr, 1);
- rb_define_module_function(mCurses, "getch", curses_getch, 0);
- rb_define_module_function(mCurses, "getstr", curses_getstr, 0);
- rb_define_module_function(mCurses, "delch", curses_delch, 0);
- rb_define_module_function(mCurses, "deleteln", curses_deleteln, 0);
- rb_define_module_function(mCurses, "keyname", curses_keyname, 1);
- rb_define_module_function(mCurses, "lines", curses_lines, 0);
- rb_define_module_function(mCurses, "cols", curses_cols, 0);
- rb_define_module_function(mCurses, "curs_set", curses_curs_set, 1);
- rb_define_module_function(mCurses, "scrl", curses_scrl, 1);
- rb_define_module_function(mCurses, "setscrreg", curses_setscrreg, 2);
- rb_define_module_function(mCurses, "attroff", curses_attroff, 1);
- rb_define_module_function(mCurses, "attron", curses_attron, 1);
- rb_define_module_function(mCurses, "attrset", curses_attrset, 1);
- rb_define_module_function(mCurses, "bkgdset", curses_bkgdset, 1);
- rb_define_module_function(mCurses, "bkgd", curses_bkgd, 1);
- rb_define_module_function(mCurses, "resizeterm", curses_resizeterm, 2);
- rb_define_module_function(mCurses, "resize", curses_resizeterm, 2);
-#ifdef USE_COLOR
- rb_define_module_function(mCurses, "start_color", curses_start_color, 0);
- rb_define_module_function(mCurses, "init_pair", curses_init_pair, 3);
- rb_define_module_function(mCurses, "init_color", curses_init_color, 4);
- rb_define_module_function(mCurses, "has_colors?", curses_has_colors, 0);
- rb_define_module_function(mCurses, "can_change_color?",
- curses_can_change_color, 0);
- rb_define_module_function(mCurses, "color_content", curses_color_content, 1);
- rb_define_module_function(mCurses, "pair_content", curses_pair_content, 1);
- rb_define_module_function(mCurses, "color_pair", curses_color_pair, 1);
- rb_define_module_function(mCurses, "pair_number", curses_pair_number, 1);
-#endif /* USE_COLOR */
-#ifdef USE_MOUSE
- rb_define_module_function(mCurses, "getmouse", curses_getmouse, 0);
- rb_define_module_function(mCurses, "ungetmouse", curses_getmouse, 1);
- rb_define_module_function(mCurses, "mouseinterval", curses_mouseinterval, 1);
- rb_define_module_function(mCurses, "mousemask", curses_mousemask, 1);
-#endif /* USE_MOUSE */
-
- cWindow = rb_define_class_under(mCurses, "Window", rb_cObject);
- rb_define_singleton_method(cWindow, "new", window_s_new, 4);
- rb_define_method(cWindow, "subwin", window_subwin, 4);
- rb_define_method(cWindow, "close", window_close, 0);
- rb_define_method(cWindow, "clear", window_clear, 0);
- rb_define_method(cWindow, "refresh", window_refresh, 0);
- rb_define_method(cWindow, "noutrefresh", window_noutrefresh, 0);
- rb_define_method(cWindow, "box", window_box, -1);
- rb_define_method(cWindow, "move", window_move, 2);
- rb_define_method(cWindow, "setpos", window_setpos, 2);
- rb_define_method(cWindow, "cury", window_cury, 0);
- rb_define_method(cWindow, "curx", window_curx, 0);
- rb_define_method(cWindow, "maxy", window_maxy, 0);
- rb_define_method(cWindow, "maxx", window_maxx, 0);
- rb_define_method(cWindow, "begy", window_begy, 0);
- rb_define_method(cWindow, "begx", window_begx, 0);
- rb_define_method(cWindow, "standout", window_standout, 0);
- rb_define_method(cWindow, "standend", window_standend, 0);
- rb_define_method(cWindow, "inch", window_inch, 0);
- rb_define_method(cWindow, "addch", window_addch, 1);
- rb_define_method(cWindow, "insch", window_insch, 1);
- rb_define_method(cWindow, "addstr", window_addstr, 1);
- rb_define_method(cWindow, "<<", window_addstr2, 1);
- rb_define_method(cWindow, "getch", window_getch, 0);
- rb_define_method(cWindow, "getstr", window_getstr, 0);
- rb_define_method(cWindow, "delch", window_delch, 0);
- rb_define_method(cWindow, "deleteln", window_deleteln, 0);
- rb_define_method(cWindow, "scroll", window_scroll, 0);
- rb_define_method(cWindow, "scrollok", window_scrollok, 1);
- rb_define_method(cWindow, "idlok", window_idlok, 1);
- rb_define_method(cWindow, "setscrreg", window_setscrreg, 2);
- rb_define_method(cWindow, "scrl", window_scrl, 1);
- rb_define_method(cWindow, "resize", window_resize, 2);
-#ifdef HAVE_KEYPAD
- rb_define_method(cWindow, "keypad", window_keypad, 1);
- rb_define_method(cWindow, "keypad=", window_keypad, 1);
-#endif
-#ifdef USE_COLOR
- rb_define_method(cWindow, "attroff", window_attroff, 1);
- rb_define_method(cWindow, "attron", window_attron, 1);
- rb_define_method(cWindow, "attrset", window_attrset, 1);
- rb_define_method(cWindow, "bkgdset", window_bkgdset, 1);
- rb_define_method(cWindow, "bkgd", window_bkgd, 1);
- rb_define_method(cWindow, "getbkgd", window_getbkgd, 0);
-#endif /* USE_COLOR */
-
-
-#define rb_curses_define_const(c) rb_define_const(mCurses,#c,UINT2NUM(c))
-
-#ifdef USE_COLOR
- rb_curses_define_const(A_ATTRIBUTES);
-#ifdef A_NORMAL
- rb_curses_define_const(A_NORMAL);
-#endif
- rb_curses_define_const(A_STANDOUT);
- rb_curses_define_const(A_UNDERLINE);
- rb_curses_define_const(A_REVERSE);
- rb_curses_define_const(A_BLINK);
- rb_curses_define_const(A_DIM);
- rb_curses_define_const(A_BOLD);
- rb_curses_define_const(A_PROTECT);
-#ifdef A_INVIS /* for NetBSD */
- rb_curses_define_const(A_INVIS);
-#endif
- rb_curses_define_const(A_ALTCHARSET);
- rb_curses_define_const(A_CHARTEXT);
-#ifdef A_HORIZONTAL
- rb_curses_define_const(A_HORIZONTAL);
-#endif
-#ifdef A_LEFT
- rb_curses_define_const(A_LEFT);
-#endif
-#ifdef A_LOW
- rb_curses_define_const(A_LOW);
-#endif
-#ifdef A_RIGHT
- rb_curses_define_const(A_RIGHT);
-#endif
-#ifdef A_TOP
- rb_curses_define_const(A_TOP);
-#endif
-#ifdef A_VERTICAL
- rb_curses_define_const(A_VERTICAL);
-#endif
- rb_curses_define_const(A_COLOR);
-
-#ifdef COLORS
- rb_curses_define_const(COLORS);
-#endif
- rb_curses_define_const(COLOR_BLACK);
- rb_curses_define_const(COLOR_RED);
- rb_curses_define_const(COLOR_GREEN);
- rb_curses_define_const(COLOR_YELLOW);
- rb_curses_define_const(COLOR_BLUE);
- rb_curses_define_const(COLOR_MAGENTA);
- rb_curses_define_const(COLOR_CYAN);
- rb_curses_define_const(COLOR_WHITE);
-#endif /* USE_COLOR */
-#ifdef USE_MOUSE
-#ifdef BUTTON1_PRESSED
- rb_curses_define_const(BUTTON1_PRESSED);
-#endif
-#ifdef BUTTON1_RELEASED
- rb_curses_define_const(BUTTON1_RELEASED);
-#endif
-#ifdef BUTTON1_CLICKED
- rb_curses_define_const(BUTTON1_CLICKED);
-#endif
-#ifdef BUTTON1_DOUBLE_CLICKED
- rb_curses_define_const(BUTTON1_DOUBLE_CLICKED);
-#endif
-#ifdef BUTTON1_TRIPLE_CLICKED
- rb_curses_define_const(BUTTON1_TRIPLE_CLICKED);
-#endif
-#ifdef BUTTON2_PRESSED
- rb_curses_define_const(BUTTON2_PRESSED);
-#endif
-#ifdef BUTTON2_RELEASED
- rb_curses_define_const(BUTTON2_RELEASED);
-#endif
-#ifdef BUTTON2_CLICKED
- rb_curses_define_const(BUTTON2_CLICKED);
-#endif
-#ifdef BUTTON2_DOUBLE_CLICKED
- rb_curses_define_const(BUTTON2_DOUBLE_CLICKED);
-#endif
-#ifdef BUTTON2_TRIPLE_CLICKED
- rb_curses_define_const(BUTTON2_TRIPLE_CLICKED);
-#endif
-#ifdef BUTTON3_PRESSED
- rb_curses_define_const(BUTTON3_PRESSED);
-#endif
-#ifdef BUTTON3_RELEASED
- rb_curses_define_const(BUTTON3_RELEASED);
-#endif
-#ifdef BUTTON3_CLICKED
- rb_curses_define_const(BUTTON3_CLICKED);
-#endif
-#ifdef BUTTON3_DOUBLE_CLICKED
- rb_curses_define_const(BUTTON3_DOUBLE_CLICKED);
-#endif
-#ifdef BUTTON3_TRIPLE_CLICKED
- rb_curses_define_const(BUTTON3_TRIPLE_CLICKED);
-#endif
-#ifdef BUTTON4_PRESSED
- rb_curses_define_const(BUTTON4_PRESSED);
-#endif
-#ifdef BUTTON4_RELEASED
- rb_curses_define_const(BUTTON4_RELEASED);
-#endif
-#ifdef BUTTON4_CLICKED
- rb_curses_define_const(BUTTON4_CLICKED);
-#endif
-#ifdef BUTTON4_DOUBLE_CLICKED
- rb_curses_define_const(BUTTON4_DOUBLE_CLICKED);
-#endif
-#ifdef BUTTON4_TRIPLE_CLICKED
- rb_curses_define_const(BUTTON4_TRIPLE_CLICKED);
-#endif
-#ifdef BUTTON_SHIFT
- rb_curses_define_const(BUTTON_SHIFT);
-#endif
-#ifdef BUTTON_CTRL
- rb_curses_define_const(BUTTON_CTRL);
-#endif
-#ifdef BUTTON_ALT
- rb_curses_define_const(BUTTON_ALT);
-#endif
-#ifdef ALL_MOUSE_EVENTS
- rb_curses_define_const(ALL_MOUSE_EVENTS);
-#endif
-#ifdef REPORT_MOUSE_POSITION
- rb_curses_define_const(REPORT_MOUSE_POSITION);
-#endif
-#endif /* USE_MOUSE */
-
-#if defined(KEY_MOUSE) && defined(USE_MOUSE)
- rb_curses_define_const(KEY_MOUSE);
- rb_define_const(mKey, "MOUSE", INT2NUM(KEY_MOUSE));
-#endif
-#ifdef KEY_MIN
- rb_curses_define_const(KEY_MIN);
- rb_define_const(mKey, "MIN", INT2NUM(KEY_MIN));
-#endif
-#ifdef KEY_BREAK
- rb_curses_define_const(KEY_BREAK);
- rb_define_const(mKey, "BREAK", INT2NUM(KEY_BREAK));
-#endif
-#ifdef KEY_DOWN
- rb_curses_define_const(KEY_DOWN);
- rb_define_const(mKey, "DOWN", INT2NUM(KEY_DOWN));
-#endif
-#ifdef KEY_UP
- rb_curses_define_const(KEY_UP);
- rb_define_const(mKey, "UP", INT2NUM(KEY_UP));
-#endif
-#ifdef KEY_LEFT
- rb_curses_define_const(KEY_LEFT);
- rb_define_const(mKey, "LEFT", INT2NUM(KEY_LEFT));
-#endif
-#ifdef KEY_RIGHT
- rb_curses_define_const(KEY_RIGHT);
- rb_define_const(mKey, "RIGHT", INT2NUM(KEY_RIGHT));
-#endif
-#ifdef KEY_HOME
- rb_curses_define_const(KEY_HOME);
- rb_define_const(mKey, "HOME", INT2NUM(KEY_HOME));
-#endif
-#ifdef KEY_BACKSPACE
- rb_curses_define_const(KEY_BACKSPACE);
- rb_define_const(mKey, "BACKSPACE", INT2NUM(KEY_BACKSPACE));
-#endif
-#ifdef KEY_F
- /* KEY_F(n) : 0 <= n <= 63 */
- {
- int i;
- char c[8];
- for( i=0; i<64; i++ ){
- sprintf(c, "KEY_F%d", i);
- rb_define_const(mCurses, c, INT2NUM(KEY_F(i)));
- sprintf(c, "F%d", i);
- rb_define_const(mKey, c, INT2NUM(KEY_F(i)));
- };
- };
-#endif
-#ifdef KEY_DL
- rb_curses_define_const(KEY_DL);
- rb_define_const(mKey, "DL", INT2NUM(KEY_DL));
-#endif
-#ifdef KEY_IL
- rb_curses_define_const(KEY_IL);
- rb_define_const(mKey, "IL", INT2NUM(KEY_IL));
-#endif
-#ifdef KEY_DC
- rb_curses_define_const(KEY_DC);
- rb_define_const(mKey, "DC", INT2NUM(KEY_DC));
-#endif
-#ifdef KEY_IC
- rb_curses_define_const(KEY_IC);
- rb_define_const(mKey, "IC", INT2NUM(KEY_IC));
-#endif
-#ifdef KEY_EIC
- rb_curses_define_const(KEY_EIC);
- rb_define_const(mKey, "EIC", INT2NUM(KEY_EIC));
-#endif
-#ifdef KEY_CLEAR
- rb_curses_define_const(KEY_CLEAR);
- rb_define_const(mKey, "CLEAR", INT2NUM(KEY_CLEAR));
-#endif
-#ifdef KEY_EOS
- rb_curses_define_const(KEY_EOS);
- rb_define_const(mKey, "EOS", INT2NUM(KEY_EOS));
-#endif
-#ifdef KEY_EOL
- rb_curses_define_const(KEY_EOL);
- rb_define_const(mKey, "EOL", INT2NUM(KEY_EOL));
-#endif
-#ifdef KEY_SF
- rb_curses_define_const(KEY_SF);
- rb_define_const(mKey, "SF", INT2NUM(KEY_SF));
-#endif
-#ifdef KEY_SR
- rb_curses_define_const(KEY_SR);
- rb_define_const(mKey, "SR", INT2NUM(KEY_SR));
-#endif
-#ifdef KEY_NPAGE
- rb_curses_define_const(KEY_NPAGE);
- rb_define_const(mKey, "NPAGE", INT2NUM(KEY_NPAGE));
-#endif
-#ifdef KEY_PPAGE
- rb_curses_define_const(KEY_PPAGE);
- rb_define_const(mKey, "PPAGE", INT2NUM(KEY_PPAGE));
-#endif
-#ifdef KEY_STAB
- rb_curses_define_const(KEY_STAB);
- rb_define_const(mKey, "STAB", INT2NUM(KEY_STAB));
-#endif
-#ifdef KEY_CTAB
- rb_curses_define_const(KEY_CTAB);
- rb_define_const(mKey, "CTAB", INT2NUM(KEY_CTAB));
-#endif
-#ifdef KEY_CATAB
- rb_curses_define_const(KEY_CATAB);
- rb_define_const(mKey, "CATAB", INT2NUM(KEY_CATAB));
-#endif
-#ifdef KEY_ENTER
- rb_curses_define_const(KEY_ENTER);
- rb_define_const(mKey, "ENTER", INT2NUM(KEY_ENTER));
-#endif
-#ifdef KEY_SRESET
- rb_curses_define_const(KEY_SRESET);
- rb_define_const(mKey, "SRESET", INT2NUM(KEY_SRESET));
-#endif
-#ifdef KEY_RESET
- rb_curses_define_const(KEY_RESET);
- rb_define_const(mKey, "RESET", INT2NUM(KEY_RESET));
-#endif
-#ifdef KEY_PRINT
- rb_curses_define_const(KEY_PRINT);
- rb_define_const(mKey, "PRINT", INT2NUM(KEY_PRINT));
-#endif
-#ifdef KEY_LL
- rb_curses_define_const(KEY_LL);
- rb_define_const(mKey, "LL", INT2NUM(KEY_LL));
-#endif
-#ifdef KEY_A1
- rb_curses_define_const(KEY_A1);
- rb_define_const(mKey, "A1", INT2NUM(KEY_A1));
-#endif
-#ifdef KEY_A3
- rb_curses_define_const(KEY_A3);
- rb_define_const(mKey, "A3", INT2NUM(KEY_A3));
-#endif
-#ifdef KEY_B2
- rb_curses_define_const(KEY_B2);
- rb_define_const(mKey, "B2", INT2NUM(KEY_B2));
-#endif
-#ifdef KEY_C1
- rb_curses_define_const(KEY_C1);
- rb_define_const(mKey, "C1", INT2NUM(KEY_C1));
-#endif
-#ifdef KEY_C3
- rb_curses_define_const(KEY_C3);
- rb_define_const(mKey, "C3", INT2NUM(KEY_C3));
-#endif
-#ifdef KEY_BTAB
- rb_curses_define_const(KEY_BTAB);
- rb_define_const(mKey, "BTAB", INT2NUM(KEY_BTAB));
-#endif
-#ifdef KEY_BEG
- rb_curses_define_const(KEY_BEG);
- rb_define_const(mKey, "BEG", INT2NUM(KEY_BEG));
-#endif
-#ifdef KEY_CANCEL
- rb_curses_define_const(KEY_CANCEL);
- rb_define_const(mKey, "CANCEL", INT2NUM(KEY_CANCEL));
-#endif
-#ifdef KEY_CLOSE
- rb_curses_define_const(KEY_CLOSE);
- rb_define_const(mKey, "CLOSE", INT2NUM(KEY_CLOSE));
-#endif
-#ifdef KEY_COMMAND
- rb_curses_define_const(KEY_COMMAND);
- rb_define_const(mKey, "COMMAND", INT2NUM(KEY_COMMAND));
-#endif
-#ifdef KEY_COPY
- rb_curses_define_const(KEY_COPY);
- rb_define_const(mKey, "COPY", INT2NUM(KEY_COPY));
-#endif
-#ifdef KEY_CREATE
- rb_curses_define_const(KEY_CREATE);
- rb_define_const(mKey, "CREATE", INT2NUM(KEY_CREATE));
-#endif
-#ifdef KEY_END
- rb_curses_define_const(KEY_END);
- rb_define_const(mKey, "END", INT2NUM(KEY_END));
-#endif
-#ifdef KEY_EXIT
- rb_curses_define_const(KEY_EXIT);
- rb_define_const(mKey, "EXIT", INT2NUM(KEY_EXIT));
-#endif
-#ifdef KEY_FIND
- rb_curses_define_const(KEY_FIND);
- rb_define_const(mKey, "FIND", INT2NUM(KEY_FIND));
-#endif
-#ifdef KEY_HELP
- rb_curses_define_const(KEY_HELP);
- rb_define_const(mKey, "HELP", INT2NUM(KEY_HELP));
-#endif
-#ifdef KEY_MARK
- rb_curses_define_const(KEY_MARK);
- rb_define_const(mKey, "MARK", INT2NUM(KEY_MARK));
-#endif
-#ifdef KEY_MESSAGE
- rb_curses_define_const(KEY_MESSAGE);
- rb_define_const(mKey, "MESSAGE", INT2NUM(KEY_MESSAGE));
-#endif
-#ifdef KEY_MOVE
- rb_curses_define_const(KEY_MOVE);
- rb_define_const(mKey, "MOVE", INT2NUM(KEY_MOVE));
-#endif
-#ifdef KEY_NEXT
- rb_curses_define_const(KEY_NEXT);
- rb_define_const(mKey, "NEXT", INT2NUM(KEY_NEXT));
-#endif
-#ifdef KEY_OPEN
- rb_curses_define_const(KEY_OPEN);
- rb_define_const(mKey, "OPEN", INT2NUM(KEY_OPEN));
-#endif
-#ifdef KEY_OPTIONS
- rb_curses_define_const(KEY_OPTIONS);
- rb_define_const(mKey, "OPTIONS", INT2NUM(KEY_OPTIONS));
-#endif
-#ifdef KEY_PREVIOUS
- rb_curses_define_const(KEY_PREVIOUS);
- rb_define_const(mKey, "PREVIOUS", INT2NUM(KEY_PREVIOUS));
-#endif
-#ifdef KEY_REDO
- rb_curses_define_const(KEY_REDO);
- rb_define_const(mKey, "REDO", INT2NUM(KEY_REDO));
-#endif
-#ifdef KEY_REFERENCE
- rb_curses_define_const(KEY_REFERENCE);
- rb_define_const(mKey, "REFERENCE", INT2NUM(KEY_REFERENCE));
-#endif
-#ifdef KEY_REFRESH
- rb_curses_define_const(KEY_REFRESH);
- rb_define_const(mKey, "REFRESH", INT2NUM(KEY_REFRESH));
-#endif
-#ifdef KEY_REPLACE
- rb_curses_define_const(KEY_REPLACE);
- rb_define_const(mKey, "REPLACE", INT2NUM(KEY_REPLACE));
-#endif
-#ifdef KEY_RESTART
- rb_curses_define_const(KEY_RESTART);
- rb_define_const(mKey, "RESTART", INT2NUM(KEY_RESTART));
-#endif
-#ifdef KEY_RESUME
- rb_curses_define_const(KEY_RESUME);
- rb_define_const(mKey, "RESUME", INT2NUM(KEY_RESUME));
-#endif
-#ifdef KEY_SAVE
- rb_curses_define_const(KEY_SAVE);
- rb_define_const(mKey, "SAVE", INT2NUM(KEY_SAVE));
-#endif
-#ifdef KEY_SBEG
- rb_curses_define_const(KEY_SBEG);
- rb_define_const(mKey, "SBEG", INT2NUM(KEY_SBEG));
-#endif
-#ifdef KEY_SCANCEL
- rb_curses_define_const(KEY_SCANCEL);
- rb_define_const(mKey, "SCANCEL", INT2NUM(KEY_SCANCEL));
-#endif
-#ifdef KEY_SCOMMAND
- rb_curses_define_const(KEY_SCOMMAND);
- rb_define_const(mKey, "SCOMMAND", INT2NUM(KEY_SCOMMAND));
-#endif
-#ifdef KEY_SCOPY
- rb_curses_define_const(KEY_SCOPY);
- rb_define_const(mKey, "SCOPY", INT2NUM(KEY_SCOPY));
-#endif
-#ifdef KEY_SCREATE
- rb_curses_define_const(KEY_SCREATE);
- rb_define_const(mKey, "SCREATE", INT2NUM(KEY_SCREATE));
-#endif
-#ifdef KEY_SDC
- rb_curses_define_const(KEY_SDC);
- rb_define_const(mKey, "SDC", INT2NUM(KEY_SDC));
-#endif
-#ifdef KEY_SDL
- rb_curses_define_const(KEY_SDL);
- rb_define_const(mKey, "SDL", INT2NUM(KEY_SDL));
-#endif
-#ifdef KEY_SELECT
- rb_curses_define_const(KEY_SELECT);
- rb_define_const(mKey, "SELECT", INT2NUM(KEY_SELECT));
-#endif
-#ifdef KEY_SEND
- rb_curses_define_const(KEY_SEND);
- rb_define_const(mKey, "SEND", INT2NUM(KEY_SEND));
-#endif
-#ifdef KEY_SEOL
- rb_curses_define_const(KEY_SEOL);
- rb_define_const(mKey, "SEOL", INT2NUM(KEY_SEOL));
-#endif
-#ifdef KEY_SEXIT
- rb_curses_define_const(KEY_SEXIT);
- rb_define_const(mKey, "SEXIT", INT2NUM(KEY_SEXIT));
-#endif
-#ifdef KEY_SFIND
- rb_curses_define_const(KEY_SFIND);
- rb_define_const(mKey, "SFIND", INT2NUM(KEY_SFIND));
-#endif
-#ifdef KEY_SHELP
- rb_curses_define_const(KEY_SHELP);
- rb_define_const(mKey, "SHELP", INT2NUM(KEY_SHELP));
-#endif
-#ifdef KEY_SHOME
- rb_curses_define_const(KEY_SHOME);
- rb_define_const(mKey, "SHOME", INT2NUM(KEY_SHOME));
-#endif
-#ifdef KEY_SIC
- rb_curses_define_const(KEY_SIC);
- rb_define_const(mKey, "SIC", INT2NUM(KEY_SIC));
-#endif
-#ifdef KEY_SLEFT
- rb_curses_define_const(KEY_SLEFT);
- rb_define_const(mKey, "SLEFT", INT2NUM(KEY_SLEFT));
-#endif
-#ifdef KEY_SMESSAGE
- rb_curses_define_const(KEY_SMESSAGE);
- rb_define_const(mKey, "SMESSAGE", INT2NUM(KEY_SMESSAGE));
-#endif
-#ifdef KEY_SMOVE
- rb_curses_define_const(KEY_SMOVE);
- rb_define_const(mKey, "SMOVE", INT2NUM(KEY_SMOVE));
-#endif
-#ifdef KEY_SNEXT
- rb_curses_define_const(KEY_SNEXT);
- rb_define_const(mKey, "SNEXT", INT2NUM(KEY_SNEXT));
-#endif
-#ifdef KEY_SOPTIONS
- rb_curses_define_const(KEY_SOPTIONS);
- rb_define_const(mKey, "SOPTIONS", INT2NUM(KEY_SOPTIONS));
-#endif
-#ifdef KEY_SPREVIOUS
- rb_curses_define_const(KEY_SPREVIOUS);
- rb_define_const(mKey, "SPREVIOUS", INT2NUM(KEY_SPREVIOUS));
-#endif
-#ifdef KEY_SPRINT
- rb_curses_define_const(KEY_SPRINT);
- rb_define_const(mKey, "SPRINT", INT2NUM(KEY_SPRINT));
-#endif
-#ifdef KEY_SREDO
- rb_curses_define_const(KEY_SREDO);
- rb_define_const(mKey, "SREDO", INT2NUM(KEY_SREDO));
-#endif
-#ifdef KEY_SREPLACE
- rb_curses_define_const(KEY_SREPLACE);
- rb_define_const(mKey, "SREPLACE", INT2NUM(KEY_SREPLACE));
-#endif
-#ifdef KEY_SRIGHT
- rb_curses_define_const(KEY_SRIGHT);
- rb_define_const(mKey, "SRIGHT", INT2NUM(KEY_SRIGHT));
-#endif
-#ifdef KEY_SRSUME
- rb_curses_define_const(KEY_SRSUME);
- rb_define_const(mKey, "SRSUME", INT2NUM(KEY_SRSUME));
-#endif
-#ifdef KEY_SSAVE
- rb_curses_define_const(KEY_SSAVE);
- rb_define_const(mKey, "SSAVE", INT2NUM(KEY_SSAVE));
-#endif
-#ifdef KEY_SSUSPEND
- rb_curses_define_const(KEY_SSUSPEND);
- rb_define_const(mKey, "SSUSPEND", INT2NUM(KEY_SSUSPEND));
-#endif
-#ifdef KEY_SUNDO
- rb_curses_define_const(KEY_SUNDO);
- rb_define_const(mKey, "SUNDO", INT2NUM(KEY_SUNDO));
-#endif
-#ifdef KEY_SUSPEND
- rb_curses_define_const(KEY_SUSPEND);
- rb_define_const(mKey, "SUSPEND", INT2NUM(KEY_SUSPEND));
-#endif
-#ifdef KEY_UNDO
- rb_curses_define_const(KEY_UNDO);
- rb_define_const(mKey, "UNDO", INT2NUM(KEY_UNDO));
-#endif
-#ifdef KEY_RESIZE
- rb_curses_define_const(KEY_RESIZE);
- rb_define_const(mKey, "RESIZE", INT2NUM(KEY_RESIZE));
-#endif
-#ifdef KEY_MAX
- rb_curses_define_const(KEY_MAX);
- rb_define_const(mKey, "MAX", INT2NUM(KEY_MAX));
-#endif
- {
- int c;
- char name[] = "KEY_CTRL_x";
- for( c = 'A'; c <= 'Z'; c++ ){
- sprintf(name, "KEY_CTRL_%c", c);
- rb_define_const(mCurses, name, INT2FIX(c - 'A' + 1));
- };
- }
-#undef rb_curses_define_const
-
- rb_set_end_proc(curses_finalize, 0);
-}
diff --git a/ext/curses/depend b/ext/curses/depend
deleted file mode 100644
index ecb79e512d..0000000000
--- a/ext/curses/depend
+++ /dev/null
@@ -1 +0,0 @@
-curses.o: curses.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h
diff --git a/ext/curses/extconf.rb b/ext/curses/extconf.rb
deleted file mode 100644
index 94443b45e6..0000000000
--- a/ext/curses/extconf.rb
+++ /dev/null
@@ -1,27 +0,0 @@
-require 'mkmf'
-
-dir_config('curses')
-dir_config('ncurses')
-dir_config('termcap')
-
-make=false
-have_library("mytinfo", "tgetent") if /bow/ =~ RUBY_PLATFORM
-if have_header("ncurses.h") and have_library("ncurses", "initscr")
- make=true
-elsif have_header("ncurses/curses.h") and have_library("ncurses", "initscr")
- make=true
-elsif have_header("curses_colr/curses.h") and have_library("cur_colr", "initscr")
- make=true
-else
- have_library("termcap", "tgetent")
- if have_header("curses.h") and have_library("curses", "initscr")
- make=true
- end
-end
-
-if make
- for f in %w(isendwin ungetch beep getnstr wgetnstr doupdate flash deleteln wdeleteln keypad keyname init_color wresize resizeterm)
- have_func(f)
- end
- create_makefile("curses")
-end
diff --git a/ext/curses/hello.rb b/ext/curses/hello.rb
deleted file mode 100644
index 7f57d801a3..0000000000
--- a/ext/curses/hello.rb
+++ /dev/null
@@ -1,30 +0,0 @@
-#!/usr/local/bin/ruby
-
-require "curses"
-include Curses
-
-def show_message(message)
- width = message.length + 6
- win = Window.new(5, width,
- (lines - 5) / 2, (cols - width) / 2)
- win.box(?|, ?-)
- win.setpos(2, 3)
- win.addstr(message)
- win.refresh
- win.getch
- win.close
-end
-
-init_screen
-begin
- crmode
-# show_message("Hit any key")
- setpos((lines - 5) / 2, (cols - 10) / 2)
- addstr("Hit any key")
- refresh
- getch
- show_message("Hello, World!")
- refresh
-ensure
- close_screen
-end
diff --git a/ext/curses/mouse.rb b/ext/curses/mouse.rb
deleted file mode 100644
index c42bc31f33..0000000000
--- a/ext/curses/mouse.rb
+++ /dev/null
@@ -1,53 +0,0 @@
-#!/usr/local/bin/ruby
-
-require "curses"
-include Curses
-
-def show_message(*msgs)
- message = msgs.join
- width = message.length + 6
- win = Window.new(5, width,
- (lines - 5) / 2, (cols - width) / 2)
- win.keypad = true
- win.attron(color_pair(COLOR_RED)){
- win.box(?|, ?-, ?+)
- }
- win.setpos(2, 3)
- win.addstr(message)
- win.refresh
- win.getch
- win.close
-end
-
-init_screen
-start_color
-init_pair(COLOR_BLUE,COLOR_BLUE,COLOR_WHITE)
-init_pair(COLOR_RED,COLOR_RED,COLOR_WHITE)
-crmode
-noecho
-stdscr.keypad(true)
-
-begin
- mousemask(BUTTON1_CLICKED|BUTTON2_CLICKED|BUTTON3_CLICKED|BUTTON4_CLICKED)
- setpos((lines - 5) / 2, (cols - 10) / 2)
- attron(color_pair(COLOR_BLUE)|A_BOLD){
- addstr("click")
- }
- refresh
- while( true )
- c = getch
- case c
- when KEY_MOUSE
- m = getmouse
- if( m )
- show_message("getch = #{c.inspect}, ",
- "mouse event = #{'0x%x' % m.bstate}, ",
- "axis = (#{m.x},#{m.y},#{m.z})")
- end
- break
- end
- end
- refresh
-ensure
- close_screen
-end
diff --git a/ext/curses/rain.rb b/ext/curses/rain.rb
deleted file mode 100644
index 36f0f84de2..0000000000
--- a/ext/curses/rain.rb
+++ /dev/null
@@ -1,76 +0,0 @@
-#!/usr/local/bin/ruby
-# rain for a curses test
-
-require "curses"
-include Curses
-
-def onsig(sig)
- close_screen
- exit sig
-end
-
-def ranf
- rand(32767).to_f / 32767
-end
-
-# main #
-for i in 1 .. 15 # SIGHUP .. SIGTERM
- if trap(i, "SIG_IGN") != 0 then # 0 for SIG_IGN
- trap(i) {|sig| onsig(sig) }
- end
-end
-
-init_screen
-nl
-noecho
-srand
-
-xpos = {}
-ypos = {}
-r = lines - 4
-c = cols - 4
-for i in 0 .. 4
- xpos[i] = (c * ranf).to_i + 2
- ypos[i] = (r * ranf).to_i + 2
-end
-
-i = 0
-while TRUE
- x = (c * ranf).to_i + 2
- y = (r * ranf).to_i + 2
-
-
- setpos(y, x); addstr(".")
-
- setpos(ypos[i], xpos[i]); addstr("o")
-
- i = if i == 0 then 4 else i - 1 end
- setpos(ypos[i], xpos[i]); addstr("O")
-
- i = if i == 0 then 4 else i - 1 end
- setpos(ypos[i] - 1, xpos[i]); addstr("-")
- setpos(ypos[i], xpos[i] - 1); addstr("|.|")
- setpos(ypos[i] + 1, xpos[i]); addstr("-")
-
- i = if i == 0 then 4 else i - 1 end
- setpos(ypos[i] - 2, xpos[i]); addstr("-")
- setpos(ypos[i] - 1, xpos[i] - 1); addstr("/ \\")
- setpos(ypos[i], xpos[i] - 2); addstr("| O |")
- setpos(ypos[i] + 1, xpos[i] - 1); addstr("\\ /")
- setpos(ypos[i] + 2, xpos[i]); addstr("-")
-
- i = if i == 0 then 4 else i - 1 end
- setpos(ypos[i] - 2, xpos[i]); addstr(" ")
- setpos(ypos[i] - 1, xpos[i] - 1); addstr(" ")
- setpos(ypos[i], xpos[i] - 2); addstr(" ")
- setpos(ypos[i] + 1, xpos[i] - 1); addstr(" ")
- setpos(ypos[i] + 2, xpos[i]); addstr(" ")
-
-
- xpos[i] = x
- ypos[i] = y
- refresh
- sleep(0.5)
-end
-
-# end of main
diff --git a/ext/curses/view.rb b/ext/curses/view.rb
deleted file mode 100644
index 5ba1a8413c..0000000000
--- a/ext/curses/view.rb
+++ /dev/null
@@ -1,91 +0,0 @@
-#!/usr/local/bin/ruby
-
-require "curses"
-include Curses
-
-#
-# main
-#
-
-if ARGV.size != 1 then
- printf("usage: view file\n");
- exit
-end
-begin
- fp = open(ARGV[0], "r")
-rescue
- raise "cannot open file: #{ARGV[1]}"
-end
-
-# signal(SIGINT, finish)
-
-init_screen
-#keypad(stdscr, TRUE)
-nonl
-cbreak
-noecho
-#scrollok(stdscr, TRUE)
-
-# slurp the file
-data_lines = []
-fp.each_line { |l|
- data_lines.push(l)
-}
-fp.close
-
-
-lptr = 0
-while TRUE
- i = 0
- while i < lines
- setpos(i, 0)
- #clrtoeol
- addstr(data_lines[lptr + i]) #if data_lines[lptr + i]
- i += 1
- end
- refresh
-
- explicit = FALSE
- n = 0
- while TRUE
- c = getch.chr
- if c =~ "[0-9]" then
- n = 10 * n + c.to_i
- else
- break
- end
- end
-
- n = 1 if !explicit && n == 0
-
- case c
- when "n" #when KEY_DOWN
- i = 0
- while i < n
- if lptr + lines < data_lines.size then
- lptr += 1
- else
- break
- end
- i += 1
- end
- #wscrl(i)
-
- when "p" #when KEY_UP
- i = 0
- while i < n
- if lptr > 0 then
- lptr -= 1
- else
- break
- end
- i += 1
- end
- #wscrl(-i)
-
- when "q"
- break
- end
-
-end
-close_screen
diff --git a/ext/curses/view2.rb b/ext/curses/view2.rb
deleted file mode 100644
index f953cdf7f5..0000000000
--- a/ext/curses/view2.rb
+++ /dev/null
@@ -1,115 +0,0 @@
-#!/usr/local/bin/ruby
-
-require "curses"
-
-if ARGV.size != 1 then
- printf("usage: view file\n");
- exit
-end
-begin
- fp = open(ARGV[0], "r")
-rescue
- raise "cannot open file: #{ARGV[1]}"
-end
-
-# signal(SIGINT, finish)
-
-Curses.init_screen
-Curses.nonl
-Curses.cbreak
-Curses.noecho
-
-$screen = Curses.stdscr
-
-$screen.scrollok(true)
-#$screen.keypad(true)
-
-# slurp the file
-$data_lines = []
-fp.each_line { |l|
- $data_lines.push(l.chop)
-}
-fp.close
-
-$top = 0
-$data_lines[0..$screen.maxy-1].each_with_index{|line, idx|
- $screen.setpos(idx, 0)
- $screen.addstr(line)
-}
-$screen.setpos(0,0)
-$screen.refresh
-
-def scroll_up
- if( $top > 0 )
- $screen.scrl(-1)
- $top -= 1
- str = $data_lines[$top]
- if( str )
- $screen.setpos(0, 0)
- $screen.addstr(str)
- end
- return true
- else
- return false
- end
-end
-
-def scroll_down
- if( $top + $screen.maxy < $data_lines.length )
- $screen.scrl(1)
- $top += 1
- str = $data_lines[$top + $screen.maxy - 1]
- if( str )
- $screen.setpos($screen.maxy - 1, 0)
- $screen.addstr(str)
- end
- return true
- else
- return false
- end
-end
-
-while true
- result = true
- c = Curses.getch
- case c
- when Curses::KEY_DOWN, Curses::KEY_CTRL_N
- result = scroll_down
- when Curses::KEY_UP, Curses::KEY_CTRL_P
- result = scroll_up
- when Curses::KEY_NPAGE, ? # white space
- for i in 0..($screen.maxy - 2)
- if( ! scroll_down )
- if( i == 0 )
- result = false
- end
- break
- end
- end
- when Curses::KEY_PPAGE
- for i in 0..($screen.maxy - 2)
- if( ! scroll_up )
- if( i == 0 )
- result = false
- end
- break
- end
- end
- when Curses::KEY_LEFT, Curses::KEY_CTRL_T
- while( scroll_up )
- end
- when Curses::KEY_RIGHT, Curses::KEY_CTRL_B
- while( scroll_down )
- end
- when ?q
- break
- else
- $screen.setpos(0,0)
- $screen.addstr("[unknown key `#{Curses.keyname(c)}'=#{c}] ")
- end
- if( !result )
- Curses.beep
- end
- $screen.setpos(0,0)
-end
-Curses.close_screen
diff --git a/ext/dbm/.cvsignore b/ext/dbm/.cvsignore
deleted file mode 100644
index fc802ff1c2..0000000000
--- a/ext/dbm/.cvsignore
+++ /dev/null
@@ -1,2 +0,0 @@
-Makefile
-mkmf.log
diff --git a/ext/dbm/MANIFEST b/ext/dbm/MANIFEST
deleted file mode 100644
index 8beec6783d..0000000000
--- a/ext/dbm/MANIFEST
+++ /dev/null
@@ -1,4 +0,0 @@
-MANIFEST
-dbm.c
-depend
-extconf.rb
diff --git a/ext/dbm/dbm.c b/ext/dbm/dbm.c
deleted file mode 100644
index f81f7efcb1..0000000000
--- a/ext/dbm/dbm.c
+++ /dev/null
@@ -1,764 +0,0 @@
-/************************************************
-
- dbm.c -
-
- $Author$
- $Date$
- created at: Mon Jan 24 15:59:52 JST 1994
-
- Copyright (C) 1995-2001 Yukihiro Matsumoto
-
-************************************************/
-
-#include "ruby.h"
-
-#ifdef HAVE_CDEFS_H
-# include <cdefs.h>
-#endif
-#ifdef HAVE_SYS_CDEFS_H
-# include <sys/cdefs.h>
-#endif
-#include DBM_HDR
-#include <fcntl.h>
-#include <errno.h>
-
-static VALUE rb_cDBM, rb_eDBMError;
-
-struct dbmdata {
- int di_size;
- DBM *di_dbm;
-};
-
-static void
-closed_dbm()
-{
- rb_raise(rb_eDBMError, "closed DBM file");
-}
-
-#define GetDBM(obj, dbmp) {\
- Data_Get_Struct(obj, struct dbmdata, dbmp);\
- if (dbmp == 0) closed_dbm();\
- if (dbmp->di_dbm == 0) closed_dbm();\
-}
-
-static void
-free_dbm(dbmp)
- struct dbmdata *dbmp;
-{
- if (dbmp) {
- if (dbmp->di_dbm) dbm_close(dbmp->di_dbm);
- free(dbmp);
- }
-}
-
-static VALUE
-fdbm_close(obj)
- VALUE obj;
-{
- struct dbmdata *dbmp;
-
- GetDBM(obj, dbmp);
- dbm_close(dbmp->di_dbm);
- dbmp->di_dbm = 0;
-
- return Qnil;
-}
-
-static VALUE
-fdbm_s_new(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- VALUE obj = Data_Wrap_Struct(klass, 0, free_dbm, 0);
- rb_obj_call_init(obj, argc, argv);
- return obj;
-}
-
-static VALUE
-fdbm_initialize(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- VALUE file, vmode;
- DBM *dbm;
- struct dbmdata *dbmp;
- int mode;
-
- if (rb_scan_args(argc, argv, "11", &file, &vmode) == 1) {
- mode = 0666; /* default value */
- }
- else if (NIL_P(vmode)) {
- mode = -1; /* return nil if DB not exist */
- }
- else {
- mode = NUM2INT(vmode);
- }
- SafeStringValue(file);
-
- dbm = 0;
- if (mode >= 0) {
- dbm = dbm_open(RSTRING(file)->ptr, O_RDWR|O_CREAT, mode);
- }
- if (!dbm) {
- dbm = dbm_open(RSTRING(file)->ptr, O_RDWR, 0);
- }
- if (!dbm) {
- dbm = dbm_open(RSTRING(file)->ptr, O_RDONLY, 0);
- }
-
- if (!dbm) {
- if (mode == -1) return Qnil;
- rb_sys_fail(RSTRING(file)->ptr);
- }
-
- dbmp = ALLOC(struct dbmdata);
- DATA_PTR(obj) = dbmp;
- dbmp->di_dbm = dbm;
- dbmp->di_size = -1;
-
- return obj;
-}
-
-static VALUE
-fdbm_s_open(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- VALUE obj = Data_Wrap_Struct(klass, 0, free_dbm, 0);
-
- if (NIL_P(fdbm_initialize(argc, argv, obj))) {
- return Qnil;
- }
-
- if (rb_block_given_p()) {
- return rb_ensure(rb_yield, obj, fdbm_close, obj);
- }
-
- return obj;
-}
-
-static VALUE
-fdbm_fetch(obj, keystr, ifnone)
- VALUE obj, keystr, ifnone;
-{
- datum key, value;
- struct dbmdata *dbmp;
- DBM *dbm;
-
- StringValue(keystr);
- key.dptr = RSTRING(keystr)->ptr;
- key.dsize = RSTRING(keystr)->len;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- value = dbm_fetch(dbm, key);
- if (value.dptr == 0) {
- if (ifnone == Qnil && rb_block_given_p())
- return rb_yield(rb_tainted_str_new(key.dptr, key.dsize));
- return ifnone;
- }
- return rb_tainted_str_new(value.dptr, value.dsize);
-}
-
-static VALUE
-fdbm_aref(obj, keystr)
- VALUE obj, keystr;
-{
- return fdbm_fetch(obj, keystr, Qnil);
-}
-
-static VALUE
-fdbm_fetch_m(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- VALUE keystr, valstr, ifnone;
-
- rb_scan_args(argc, argv, "11", &keystr, &ifnone);
- valstr = fdbm_fetch(obj, keystr, ifnone);
- if (argc == 1 && !rb_block_given_p() && NIL_P(valstr))
- rb_raise(rb_eIndexError, "key not found");
-
- return valstr;
-}
-
-static VALUE
-fdbm_index(obj, valstr)
- VALUE obj, valstr;
-{
- datum key, val;
- struct dbmdata *dbmp;
- DBM *dbm;
-
- StringValue(valstr);
- val.dptr = RSTRING(valstr)->ptr;
- val.dsize = RSTRING(valstr)->len;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
- val = dbm_fetch(dbm, key);
- if (val.dsize == RSTRING(valstr)->len &&
- memcmp(val.dptr, RSTRING(valstr)->ptr, val.dsize) == 0) {
- return rb_tainted_str_new(key.dptr, key.dsize);
- }
- }
- return Qnil;
-}
-
-static VALUE
-fdbm_indexes(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- VALUE new;
- int i;
-
- new = rb_ary_new2(argc);
- for (i=0; i<argc; i++) {
- rb_ary_push(new, fdbm_fetch(obj, argv[i]));
- }
-
- return new;
-}
-
-static VALUE
-fdbm_select(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- VALUE new = rb_ary_new2(argc);
- int i;
-
- if (rb_block_given_p()) {
- datum key, val;
- DBM *dbm;
- struct dbmdata *dbmp;
- VALUE keystr, valstr;
-
- if (argc > 0) {
- rb_raise(rb_eArgError, "wrong number arguments(%d for 0)", argc);
- }
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
- VALUE assoc;
- val = dbm_fetch(dbm, key);
- assoc = rb_assoc_new(rb_tainted_str_new(key.dptr, key.dsize),
- rb_tainted_str_new(val.dptr, val.dsize));
- if (RTEST(rb_yield(assoc)))
- rb_ary_push(new, assoc);
- }
- }
- else {
- for (i=0; i<argc; i++) {
- rb_ary_push(new, fdbm_fetch(obj, argv[i]));
- }
- }
-
- return new;
-}
-
-static VALUE
-fdbm_delete(obj, keystr)
- VALUE obj, keystr;
-{
- datum key, value;
- struct dbmdata *dbmp;
- DBM *dbm;
- VALUE valstr;
-
- rb_secure(4);
- StringValue(keystr);
- key.dptr = RSTRING(keystr)->ptr;
- key.dsize = RSTRING(keystr)->len;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- value = dbm_fetch(dbm, key);
- if (value.dptr == 0) {
- if (rb_block_given_p()) return rb_yield(keystr);
- return Qnil;
- }
-
- /* need to save value before dbm_delete() */
- valstr = rb_tainted_str_new(value.dptr, value.dsize);
-
- if (dbm_delete(dbm, key)) {
- dbmp->di_size = -1;
- rb_raise(rb_eDBMError, "dbm_delete failed");
- }
- else if (dbmp->di_size >= 0) {
- dbmp->di_size--;
- }
- return valstr;
-}
-
-static VALUE
-fdbm_shift(obj)
- VALUE obj;
-{
- datum key, val;
- struct dbmdata *dbmp;
- DBM *dbm;
- VALUE keystr, valstr;
-
- rb_secure(4);
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- dbmp->di_size = -1;
-
- key = dbm_firstkey(dbm);
- if (!key.dptr) return Qnil;
- val = dbm_fetch(dbm, key);
- keystr = rb_tainted_str_new(key.dptr, key.dsize);
- valstr = rb_tainted_str_new(val.dptr, val.dsize);
- dbm_delete(dbm, key);
-
- return rb_assoc_new(keystr, valstr);
-}
-
-static VALUE
-fdbm_delete_if(obj)
- VALUE obj;
-{
- datum key, val;
- struct dbmdata *dbmp;
- DBM *dbm;
- VALUE keystr, valstr;
- VALUE ret, ary = rb_ary_new();
- int i, status = 0, n;
-
- rb_secure(4);
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- n = dbmp->di_size;
- dbmp->di_size = -1;
-
- for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
- val = dbm_fetch(dbm, key);
- keystr = rb_tainted_str_new(key.dptr, key.dsize);
- valstr = rb_tainted_str_new(val.dptr, val.dsize);
- ret = rb_protect(rb_yield, rb_assoc_new(rb_str_dup(keystr), valstr), &status);
- if (status != 0) break;
- if (RTEST(ret)) rb_ary_push(ary, keystr);
- }
-
- for (i = 0; i < RARRAY(ary)->len; i++) {
- keystr = RARRAY(ary)->ptr[i];
- key.dptr = RSTRING(keystr)->ptr;
- key.dsize = RSTRING(keystr)->len;
- if (dbm_delete(dbm, key)) {
- rb_raise(rb_eDBMError, "dbm_delete failed");
- }
- }
- if (status) rb_jump_tag(status);
- if (n > 0) dbmp->di_size = n - RARRAY(ary)->len;
-
- return obj;
-}
-
-static VALUE
-fdbm_clear(obj)
- VALUE obj;
-{
- datum key;
- struct dbmdata *dbmp;
- DBM *dbm;
-
- rb_secure(4);
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- dbmp->di_size = -1;
- while (key = dbm_firstkey(dbm), key.dptr) {
- if (dbm_delete(dbm, key)) {
- rb_raise(rb_eDBMError, "dbm_delete failed");
- }
- }
- dbmp->di_size = 0;
-
- return obj;
-}
-
-static VALUE
-fdbm_invert(obj)
- VALUE obj;
-{
- datum key, val;
- struct dbmdata *dbmp;
- DBM *dbm;
- VALUE keystr, valstr;
- VALUE hash = rb_hash_new();
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
- val = dbm_fetch(dbm, key);
- keystr = rb_tainted_str_new(key.dptr, key.dsize);
- valstr = rb_tainted_str_new(val.dptr, val.dsize);
- rb_hash_aset(hash, valstr, keystr);
- }
- return hash;
-}
-
-static VALUE
-each_pair(obj)
- VALUE obj;
-{
- return rb_funcall(obj, rb_intern("each_pair"), 0, 0);
-}
-
-static VALUE fdbm_store _((VALUE,VALUE,VALUE));
-
-static VALUE
-update_i(pair, dbm)
- VALUE pair, dbm;
-{
- Check_Type(pair, T_ARRAY);
- if (RARRAY(pair)->len < 2) {
- rb_raise(rb_eArgError, "pair must be [key, value]");
- }
- fdbm_store(dbm, RARRAY(pair)->ptr[0], RARRAY(pair)->ptr[1]);
- return Qnil;
-}
-
-static VALUE
-fdbm_update(obj, other)
- VALUE obj, other;
-{
- rb_iterate(each_pair, other, update_i, obj);
- return obj;
-}
-
-static VALUE
-fdbm_replace(obj, other)
- VALUE obj, other;
-{
- fdbm_clear(obj);
- rb_iterate(each_pair, other, update_i, obj);
- return obj;
-}
-
-static VALUE
-fdbm_store(obj, keystr, valstr)
- VALUE obj, keystr, valstr;
-{
- datum key, val;
- struct dbmdata *dbmp;
- DBM *dbm;
-
- rb_secure(4);
- keystr = rb_obj_as_string(keystr);
-
- key.dptr = RSTRING(keystr)->ptr;
- key.dsize = RSTRING(keystr)->len;
-
- valstr = rb_obj_as_string(valstr);
- val.dptr = RSTRING(valstr)->ptr;
- val.dsize = RSTRING(valstr)->len;
-
- GetDBM(obj, dbmp);
- dbmp->di_size = -1;
- dbm = dbmp->di_dbm;
- if (dbm_store(dbm, key, val, DBM_REPLACE)) {
-#ifdef HAVE_DBM_CLEARERR
- dbm_clearerr(dbm);
-#endif
- if (errno == EPERM) rb_sys_fail(0);
- rb_raise(rb_eDBMError, "dbm_store failed");
- }
-
- return valstr;
-}
-
-static VALUE
-fdbm_length(obj)
- VALUE obj;
-{
- datum key;
- struct dbmdata *dbmp;
- DBM *dbm;
- int i = 0;
-
- GetDBM(obj, dbmp);
- if (dbmp->di_size > 0) return INT2FIX(dbmp->di_size);
- dbm = dbmp->di_dbm;
-
- for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
- i++;
- }
- dbmp->di_size = i;
-
- return INT2FIX(i);
-}
-
-static VALUE
-fdbm_empty_p(obj)
- VALUE obj;
-{
- datum key;
- struct dbmdata *dbmp;
- DBM *dbm;
- int i = 0;
-
- GetDBM(obj, dbmp);
- if (dbmp->di_size < 0) {
- dbm = dbmp->di_dbm;
-
- for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
- i++;
- }
- }
- else {
- i = dbmp->di_size;
- }
- if (i == 0) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-fdbm_each_value(obj)
- VALUE obj;
-{
- datum key, val;
- struct dbmdata *dbmp;
- DBM *dbm;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
- val = dbm_fetch(dbm, key);
- rb_yield(rb_tainted_str_new(val.dptr, val.dsize));
- }
- return obj;
-}
-
-static VALUE
-fdbm_each_key(obj)
- VALUE obj;
-{
- datum key;
- struct dbmdata *dbmp;
- DBM *dbm;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
- rb_yield(rb_tainted_str_new(key.dptr, key.dsize));
- }
- return obj;
-}
-
-static VALUE
-fdbm_each_pair(obj)
- VALUE obj;
-{
- datum key, val;
- DBM *dbm;
- struct dbmdata *dbmp;
- VALUE keystr, valstr;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
- val = dbm_fetch(dbm, key);
- keystr = rb_tainted_str_new(key.dptr, key.dsize);
- valstr = rb_tainted_str_new(val.dptr, val.dsize);
- rb_yield(rb_assoc_new(keystr, valstr));
- }
-
- return obj;
-}
-
-static VALUE
-fdbm_keys(obj)
- VALUE obj;
-{
- datum key;
- struct dbmdata *dbmp;
- DBM *dbm;
- VALUE ary;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- ary = rb_ary_new();
- for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
- rb_ary_push(ary, rb_tainted_str_new(key.dptr, key.dsize));
- }
-
- return ary;
-}
-
-static VALUE
-fdbm_values(obj)
- VALUE obj;
-{
- datum key, val;
- struct dbmdata *dbmp;
- DBM *dbm;
- VALUE ary;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- ary = rb_ary_new();
- for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
- val = dbm_fetch(dbm, key);
- rb_ary_push(ary, rb_tainted_str_new(val.dptr, val.dsize));
- }
-
- return ary;
-}
-
-static VALUE
-fdbm_has_key(obj, keystr)
- VALUE obj, keystr;
-{
- datum key, val;
- struct dbmdata *dbmp;
- DBM *dbm;
-
- StringValue(keystr);
- key.dptr = RSTRING(keystr)->ptr;
- key.dsize = RSTRING(keystr)->len;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- val = dbm_fetch(dbm, key);
- if (val.dptr) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-fdbm_has_value(obj, valstr)
- VALUE obj, valstr;
-{
- datum key, val;
- struct dbmdata *dbmp;
- DBM *dbm;
-
- StringValue(valstr);
- val.dptr = RSTRING(valstr)->ptr;
- val.dsize = RSTRING(valstr)->len;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
- val = dbm_fetch(dbm, key);
- if (val.dsize == RSTRING(valstr)->len &&
- memcmp(val.dptr, RSTRING(valstr)->ptr, val.dsize) == 0)
- return Qtrue;
- }
- return Qfalse;
-}
-
-static VALUE
-fdbm_to_a(obj)
- VALUE obj;
-{
- datum key, val;
- struct dbmdata *dbmp;
- DBM *dbm;
- VALUE ary;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- ary = rb_ary_new();
- for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
- val = dbm_fetch(dbm, key);
- rb_ary_push(ary, rb_assoc_new(rb_tainted_str_new(key.dptr, key.dsize),
- rb_tainted_str_new(val.dptr, val.dsize)));
- }
-
- return ary;
-}
-
-static VALUE
-fdbm_to_hash(obj)
- VALUE obj;
-{
- datum key, val;
- struct dbmdata *dbmp;
- DBM *dbm;
- VALUE hash;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- hash = rb_hash_new();
- for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
- val = dbm_fetch(dbm, key);
- rb_hash_aset(hash, rb_tainted_str_new(key.dptr, key.dsize),
- rb_tainted_str_new(val.dptr, val.dsize));
- }
-
- return hash;
-}
-
-static VALUE
-fdbm_reject(obj)
- VALUE obj;
-{
- return rb_hash_delete_if(fdbm_to_hash(obj));
-}
-
-void
-Init_dbm()
-{
- rb_cDBM = rb_define_class("DBM", rb_cObject);
- rb_eDBMError = rb_define_class("DBMError", rb_eStandardError);
- rb_include_module(rb_cDBM, rb_mEnumerable);
-
- rb_define_singleton_method(rb_cDBM, "new", fdbm_s_new, -1);
- rb_define_singleton_method(rb_cDBM, "open", fdbm_s_open, -1);
-
- rb_define_method(rb_cDBM, "initialize", fdbm_initialize, -1);
- rb_define_method(rb_cDBM, "close", fdbm_close, 0);
- rb_define_method(rb_cDBM, "[]", fdbm_aref, 1);
- rb_define_method(rb_cDBM, "fetch", fdbm_fetch_m, -1);
- rb_define_method(rb_cDBM, "[]=", fdbm_store, 2);
- rb_define_method(rb_cDBM, "store", fdbm_store, 2);
- rb_define_method(rb_cDBM, "index", fdbm_index, 1);
- rb_define_method(rb_cDBM, "indexes", fdbm_indexes, -1);
- rb_define_method(rb_cDBM, "indices", fdbm_indexes, -1);
- rb_define_method(rb_cDBM, "select", fdbm_select, -1);
- rb_define_method(rb_cDBM, "length", fdbm_length, 0);
- rb_define_method(rb_cDBM, "size", fdbm_length, 0);
- rb_define_method(rb_cDBM, "empty?", fdbm_empty_p, 0);
- rb_define_method(rb_cDBM, "each", fdbm_each_pair, 0);
- rb_define_method(rb_cDBM, "each_value", fdbm_each_value, 0);
- rb_define_method(rb_cDBM, "each_key", fdbm_each_key, 0);
- rb_define_method(rb_cDBM, "each_pair", fdbm_each_pair, 0);
- rb_define_method(rb_cDBM, "keys", fdbm_keys, 0);
- rb_define_method(rb_cDBM, "values", fdbm_values, 0);
- rb_define_method(rb_cDBM, "shift", fdbm_shift, 0);
- rb_define_method(rb_cDBM, "delete", fdbm_delete, 1);
- rb_define_method(rb_cDBM, "delete_if", fdbm_delete_if, 0);
- rb_define_method(rb_cDBM, "reject!", fdbm_delete_if, 0);
- rb_define_method(rb_cDBM, "reject", fdbm_reject, 0);
- rb_define_method(rb_cDBM, "clear", fdbm_clear, 0);
- rb_define_method(rb_cDBM,"invert", fdbm_invert, 0);
- rb_define_method(rb_cDBM,"update", fdbm_update, 1);
- rb_define_method(rb_cDBM,"replace", fdbm_replace, 1);
-
- rb_define_method(rb_cDBM, "include?", fdbm_has_key, 1);
- rb_define_method(rb_cDBM, "has_key?", fdbm_has_key, 1);
- rb_define_method(rb_cDBM, "member?", fdbm_has_key, 1);
- rb_define_method(rb_cDBM, "has_value?", fdbm_has_value, 1);
- rb_define_method(rb_cDBM, "key?", fdbm_has_key, 1);
- rb_define_method(rb_cDBM, "value?", fdbm_has_value, 1);
-
- rb_define_method(rb_cDBM, "to_a", fdbm_to_a, 0);
- rb_define_method(rb_cDBM, "to_hash", fdbm_to_hash, 0);
-}
diff --git a/ext/dbm/depend b/ext/dbm/depend
deleted file mode 100644
index 5fae80b096..0000000000
--- a/ext/dbm/depend
+++ /dev/null
@@ -1 +0,0 @@
-dbm.o: dbm.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h
diff --git a/ext/dbm/extconf.rb b/ext/dbm/extconf.rb
deleted file mode 100644
index 51b1bfd81b..0000000000
--- a/ext/dbm/extconf.rb
+++ /dev/null
@@ -1,56 +0,0 @@
-require 'mkmf'
-
-dir_config("dbm")
-
-dblib = with_config("dbm-type", nil)
-
-$dbm_conf_headers = {
- "db" => ["db.h"],
- "db1" => ["db1/ndbm.h", "db1.h", "ndbm.h"],
- "db2" => ["db2/db.h", "db2.h", "db.h"],
- "dbm" => ["ndbm.h"],
- "gdbm" => ["gdbm-ndbm.h", "ndbm.h"],
-}
-
-def db_check(db)
- $dbm_conf_db_prefix = ""
- $dbm_conf_have_gdbm = false
- hsearch = ""
-
- case db
- when /^db2?$/
- $dbm_conf_db_prefix = "__db_n"
- hsearch = "-DDB_DBM_HSEARCH "
- when "gdbm"
- $dbm_conf_have_gdbm = true
- end
-
- if have_func(db_prefix("dbm_open")) || have_library(db, db_prefix("dbm_open"))
- for hdr in $dbm_conf_headers.fetch(db, ["ndbm.h"])
- if have_header(hdr.dup)
- $CFLAGS += " " + hsearch + "-DDBM_HDR='<"+hdr+">'"
- return true
- end
- end
- end
- return false
-end
-
-def db_prefix(func)
- $dbm_conf_db_prefix+func
-end
-
-if dblib
- db_check(dblib)
-else
- for dblib in %w(db db2 db1 dbm gdbm)
- db_check(dblib) and break
- end
-end
-
-have_header("cdefs.h")
-have_header("sys/cdefs.h")
-if /DBM_HDR/ =~ $CFLAGS and have_func(db_prefix("dbm_open"))
- have_func(db_prefix("dbm_clearerr")) unless $dbm_conf_have_gdbm
- create_makefile("dbm")
-end
diff --git a/ext/dbm/testdbm.rb b/ext/dbm/testdbm.rb
deleted file mode 100644
index 0be627d346..0000000000
--- a/ext/dbm/testdbm.rb
+++ /dev/null
@@ -1,590 +0,0 @@
-require 'runit/testcase'
-require 'runit/cui/testrunner'
-
-if $".grep(/\bdbm.so\b/).empty?
- begin
- require './dbm'
- rescue LoadError
- require 'dbm'
- end
-end
-
-def uname_s
- require 'rbconfig'
- case Config::CONFIG['host_os']
- when 'cygwin'
- require 'Win32API'
- uname = Win32API.new 'cygwin1', 'uname', 'P', 'I'
- utsname = ' ' * 100
- raise 'cannot get system name' if uname.call(utsname) == -1
-
- utsname.unpack('A20' * 5)[0]
- else
- Config::CONFIG['host_os']
- end
-end
-
-SYSTEM = uname_s
-
-class TestDBM < RUNIT::TestCase
- def setup
- @path = "tmptest_dbm_"
- assert_instance_of(DBM, @dbm = DBM.new(@path))
-
- # prepare to make readonly DBM file
- DBM.open("tmptest_dbm_rdonly", 0400) {|dbm|
- dbm['foo'] = 'FOO'
- }
- assert_instance_of(DBM, @dbm_rdonly = DBM.new("tmptest_dbm_rdonly", nil))
- end
- def teardown
- assert_nil(@dbm.close)
- assert_nil(@dbm_rdonly.close)
- GC.start
- File.delete *Dir.glob("tmptest_dbm*").to_a
- p Dir.glob("tmptest_dbm*") if $DEBUG
- end
-
- def check_size(expect, dbm=@dbm)
- assert_equals(expect, dbm.size)
- n = 0
- dbm.each { n+=1 }
- assert_equals(expect, n)
- if expect == 0
- assert_equals(true, dbm.empty?)
- else
- assert_equals(false, dbm.empty?)
- end
- end
-
- def test_version
- STDERR.print DBM::VERSION
- end
-
- def test_s_new_has_no_block
- # DBM.new ignore the block
- foo = true
- assert_instance_of(DBM, dbm = DBM.new("tmptest_dbm") { foo = false })
- assert_equals(foo, true)
- assert_nil(dbm.close)
- end
- def test_s_open_no_create
- assert_nil(dbm = DBM.open("tmptest_dbm", nil))
- ensure
- dbm.close if dbm
- end
- def test_s_open_with_block
- assert_equals(DBM.open("tmptest_dbm") { :foo }, :foo)
- end
- def test_s_open_lock
- fork() {
- assert_instance_of(DBM, dbm = DBM.open("tmptest_dbm", 0644))
- sleep 2
- }
- begin
- sleep 1
- assert_exception(Errno::EWOULDBLOCK) {
- begin
- assert_instance_of(DBM, dbm2 = DBM.open("tmptest_dbm", 0644))
- rescue Errno::EAGAIN, Errno::EACCES, Errno::EINVAL
- raise Errno::EWOULDBLOCK
- end
- }
- ensure
- Process.wait
- end
- end
-
-=begin
- # Is it guaranteed on many OS?
- def test_s_open_lock_one_process
- # locking on one process
- assert_instance_of(DBM, dbm = DBM.open("tmptest_dbm", 0644))
- assert_exception(Errno::EWOULDBLOCK) {
- begin
- DBM.open("tmptest_dbm", 0644)
- rescue Errno::EAGAIN
- raise Errno::EWOULDBLOCK
- end
- }
- end
-=end
-
- def test_s_open_nolock
- # dbm 1.8.0 specific
- if not defined? DBM::NOLOCK
- return
- end
-
- fork() {
- assert_instance_of(DBM, dbm = DBM.open("tmptest_dbm", 0644,
- DBM::NOLOCK))
- sleep 2
- }
- sleep 1
- begin
- dbm2 = nil
- assert_no_exception(Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EACCES) {
- assert_instance_of(DBM, dbm2 = DBM.open("tmptest_dbm", 0644))
- }
- ensure
- Process.wait
- dbm2.close if dbm2
- end
-
- p Dir.glob("tmptest_dbm*") if $DEBUG
-
- fork() {
- assert_instance_of(DBM, dbm = DBM.open("tmptest_dbm", 0644))
- sleep 2
- }
- begin
- sleep 1
- dbm2 = nil
- assert_no_exception(Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EACCES) {
- # this test is failed on Cygwin98 (???)
- assert_instance_of(DBM, dbm2 = DBM.open("tmptest_dbm", 0644,
- DBM::NOLOCK))
- }
- ensure
- Process.wait
- dbm2.close if dbm2
- end
- end
-
- def test_s_open_error
- assert_instance_of(DBM, dbm = DBM.open("tmptest_dbm", 0))
- assert_exception(Errno::EACCES) {
- DBM.open("tmptest_dbm", 0)
- }
- dbm.close
- end
-
- def test_close
- assert_instance_of(DBM, dbm = DBM.open("tmptest_dbm"))
- assert_nil(dbm.close)
-
- # closed DBM file
- assert_exception(DBMError) { dbm.close }
- end
-
- def test_aref
- assert_equals('bar', @dbm['foo'] = 'bar')
- assert_equals('bar', @dbm['foo'])
-
- assert_nil(@dbm['bar'])
- end
-
- def test_fetch
- assert_equals('bar', @dbm['foo']='bar')
- assert_equals('bar', @dbm.fetch('foo'))
-
- # key not found
- assert_exception(IndexError) {
- @dbm.fetch('bar')
- }
-
- # test for `ifnone' arg
- assert_equals('baz', @dbm.fetch('bar', 'baz'))
-
- # test for `ifnone' block
- assert_equals('foobar', @dbm.fetch('bar') {|key| 'foo' + key })
- end
-
- def test_aset
- num = 0
- 2.times {|i|
- assert_equals('foo', @dbm['foo'] = 'foo')
- assert_equals('foo', @dbm['foo'])
- assert_equals('bar', @dbm['foo'] = 'bar')
- assert_equals('bar', @dbm['foo'])
-
- num += 1 if i == 0
- assert_equals(num, @dbm.size)
-
- # assign nil
- assert_equals('', @dbm['bar'] = '')
- assert_equals('', @dbm['bar'])
-
- num += 1 if i == 0
- assert_equals(num, @dbm.size)
-
- # empty string
- assert_equals('', @dbm[''] = '')
- assert_equals('', @dbm[''])
-
- num += 1 if i == 0
- assert_equals(num, @dbm.size)
-
- # Fixnum
- assert_equals('200', @dbm['100'] = '200')
- assert_equals('200', @dbm['100'])
-
- num += 1 if i == 0
- assert_equals(num, @dbm.size)
-
- # Big key and value
- assert_equals('y' * 100, @dbm['x' * 100] = 'y' * 100)
- assert_equals('y' * 100, @dbm['x' * 100])
-
- num += 1 if i == 0
- assert_equals(num, @dbm.size)
- }
- end
-
- def test_index
- assert_equals('bar', @dbm['foo'] = 'bar')
- assert_equals('foo', @dbm.index('bar'))
- assert_nil(@dbm['bar'])
- end
-
- def test_indexes
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
- @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
- assert_equals(values.reverse, @dbm.indexes(*keys.reverse))
- end
-
- def test_select
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
- @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
- assert_equals(values.reverse, @dbm.select(*keys.reverse))
- end
-
- def test_select_with_block
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
- @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
- ret = @dbm.select {|k,v|
- assert_equals(k.upcase, v)
- k != "bar"
- }
- assert_equals([['baz', 'BAZ'], ['foo', 'FOO']],
- ret.sort)
- end
-
- def test_length
- num = 10
- assert_equals(0, @dbm.size)
- num.times {|i|
- i = i.to_s
- @dbm[i] = i
- }
- assert_equals(num, @dbm.size)
-
- @dbm.shift
-
- assert_equals(num - 1, @dbm.size)
- end
-
- def test_empty?
- assert_equals(true, @dbm.empty?)
- @dbm['foo'] = 'FOO'
- assert_equals(false, @dbm.empty?)
- end
-
- def test_each_pair
- n = 0
- @dbm.each_pair { n += 1 }
- assert_equals(0, n)
-
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
-
- @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
-
- n = 0
- ret = @dbm.each_pair {|key, val|
- assert_not_nil(i = keys.index(key))
- assert_equals(val, values[i])
-
- n += 1
- }
- assert_equals(keys.size, n)
- assert_equals(@dbm, ret)
- end
-
- def test_each_value
- n = 0
- @dbm.each_value { n += 1 }
- assert_equals(0, n)
-
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
-
- @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
-
- n = 0
- ret = @dbm.each_value {|val|
- assert_not_nil(key = @dbm.index(val))
- assert_not_nil(i = keys.index(key))
- assert_equals(val, values[i])
-
- n += 1
- }
- assert_equals(keys.size, n)
- assert_equals(@dbm, ret)
- end
-
- def test_each_key
- n = 0
- @dbm.each_key { n += 1 }
- assert_equals(0, n)
-
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
-
- @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
-
- n = 0
- ret = @dbm.each_key {|key|
- assert_not_nil(i = keys.index(key))
- assert_equals(@dbm[key], values[i])
-
- n += 1
- }
- assert_equals(keys.size, n)
- assert_equals(@dbm, ret)
- end
-
- def test_keys
- assert_equals([], @dbm.keys)
-
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
-
- @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
-
- assert_equals(keys.sort, @dbm.keys.sort)
- assert_equals(values.sort, @dbm.values.sort)
- end
-
- def test_values
- test_keys
- end
-
- def test_shift
- assert_nil(@dbm.shift)
- assert_equals(0, @dbm.size)
-
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
-
- @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
-
- ret_keys = []
- ret_values = []
- while ret = @dbm.shift
- ret_keys.push ret[0]
- ret_values.push ret[1]
-
- assert_equals(keys.size - ret_keys.size, @dbm.size)
- end
-
- assert_equals(keys.sort, ret_keys.sort)
- assert_equals(values.sort, ret_values.sort)
- end
-
- def test_delete
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
- key = keys[1]
-
- assert_nil(@dbm.delete(key))
- assert_equals(0, @dbm.size)
-
- @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
-
- assert_equals('BAR', @dbm.delete(key))
- assert_nil(@dbm[key])
- assert_equals(2, @dbm.size)
-
- assert_nil(@dbm.delete(key))
-
- if /^CYGWIN_9/ !~ SYSTEM
- assert_exception(DBMError) {
- @dbm_rdonly.delete("foo")
- }
-
- assert_nil(@dbm_rdonly.delete("bar"))
- end
- end
- def test_delete_with_block
- key = 'no called block'
- @dbm[key] = 'foo'
- assert_equals('foo', @dbm.delete(key) {|k| k.replace 'called block'})
- assert_equals('no called block', key)
- assert_equals(0, @dbm.size)
-
- key = 'no called block'
- assert_equals(:blockval,
- @dbm.delete(key) {|k| k.replace 'called block'; :blockval})
- assert_equals('called block', key)
- assert_equals(0, @dbm.size)
- end
-
- def test_delete_if
- v = "0"
- 100.times {@dbm[v] = v; v = v.next}
-
- ret = @dbm.delete_if {|key, val| key.to_i < 50}
- assert_equals(@dbm, ret)
- check_size(50, @dbm)
-
- ret = @dbm.delete_if {|key, val| key.to_i >= 50}
- assert_equals(@dbm, ret)
- check_size(0, @dbm)
-
- # break
- v = "0"
- 100.times {@dbm[v] = v; v = v.next}
- check_size(100, @dbm)
- n = 0;
- @dbm.delete_if {|key, val|
- break if n > 50
- n+=1
- true
- }
- assert_equals(51, n)
- check_size(49, @dbm)
-
- @dbm.clear
-
- # raise
- v = "0"
- 100.times {@dbm[v] = v; v = v.next}
- check_size(100, @dbm)
- n = 0;
- begin
- @dbm.delete_if {|key, val|
- raise "runtime error" if n > 50
- n+=1
- true
- }
- rescue
- end
- assert_equals(51, n)
- check_size(49, @dbm)
- end
-
- def test_reject
- v = "0"
- 100.times {@dbm[v] = v; v = v.next}
-
- hash = @dbm.reject {|key, val| key.to_i < 50}
- assert_instance_of(Hash, hash)
- assert_equals(100, @dbm.size)
-
- assert_equals(50, hash.size)
- hash.each_pair {|key,val|
- assert_equals(false, key.to_i < 50)
- assert_equals(key, val)
- }
-
- hash = @dbm.reject {|key, val| key.to_i < 100}
- assert_instance_of(Hash, hash)
- assert_equals(true, hash.empty?)
- end
-
- def test_clear
- v = "1"
- 100.times {v = v.next; @dbm[v] = v}
-
- assert_equals(@dbm, @dbm.clear)
-
- # validate DBM#size
- i = 0
- @dbm.each { i += 1 }
- assert_equals(@dbm.size, i)
- assert_equals(0, i)
- end
-
- def test_invert
- v = "0"
- 100.times {@dbm[v] = v; v = v.next}
-
- hash = @dbm.invert
- assert_instance_of(Hash, hash)
- assert_equals(100, hash.size)
- hash.each_pair {|key, val|
- assert_equals(key.to_i, val.to_i)
- }
- end
-
- def test_update
- hash = {}
- v = "0"
- 100.times {v = v.next; hash[v] = v}
-
- @dbm["101"] = "101"
- @dbm.update hash
- assert_equals(101, @dbm.size)
- @dbm.each_pair {|key, val|
- assert_equals(key.to_i, val.to_i)
- }
- end
-
- def test_replace
- hash = {}
- v = "0"
- 100.times {v = v.next; hash[v] = v}
-
- @dbm["101"] = "101"
- @dbm.replace hash
- assert_equals(100, @dbm.size)
- @dbm.each_pair {|key, val|
- assert_equals(key.to_i, val.to_i)
- }
- end
-
- def test_haskey?
- assert_equals('bar', @dbm['foo']='bar')
- assert_equals(true, @dbm.has_key?('foo'))
- assert_equals(false, @dbm.has_key?('bar'))
- end
-
- def test_has_value?
- assert_equals('bar', @dbm['foo']='bar')
- assert_equals(true, @dbm.has_value?('bar'))
- assert_equals(false, @dbm.has_value?('foo'))
- end
-
- def test_to_a
- v = "0"
- 100.times {v = v.next; @dbm[v] = v}
-
- ary = @dbm.to_a
- assert_instance_of(Array, ary)
- assert_equals(100, ary.size)
- ary.each {|key,val|
- assert_equals(key.to_i, val.to_i)
- }
- end
-
- def test_to_hash
- v = "0"
- 100.times {v = v.next; @dbm[v] = v}
-
- hash = @dbm.to_hash
- assert_instance_of(Hash, hash)
- assert_equals(100, hash.size)
- hash.each {|key,val|
- assert_equals(key.to_i, val.to_i)
- }
- end
-end
-
-if $0 == __FILE__
- if ARGV.size == 0
- suite = RUNIT::TestSuite.new
- suite.add_test(TestDBM.suite)
- else
- suite = RUNIT::TestSuite.new
- ARGV.each do |testmethod|
- suite.add_test(TestDBM.new(testmethod))
- end
- end
-
- RUNIT::CUI::TestRunner.run(suite)
-end
diff --git a/ext/digest/.cvsignore b/ext/digest/.cvsignore
deleted file mode 100644
index fc802ff1c2..0000000000
--- a/ext/digest/.cvsignore
+++ /dev/null
@@ -1,2 +0,0 @@
-Makefile
-mkmf.log
diff --git a/ext/digest/MANIFEST b/ext/digest/MANIFEST
deleted file mode 100644
index fd26581c63..0000000000
--- a/ext/digest/MANIFEST
+++ /dev/null
@@ -1,39 +0,0 @@
-MANIFEST
-defs.h
-digest.c
-digest.h
-digest.txt
-digest.txt.ja
-extconf.rb
-lib/md5.rb
-lib/sha1.rb
-md5/MANIFEST
-md5/extconf.rb
-md5/md5.c
-md5/md5.h
-md5/md5init.c
-md5/depend
-rmd160/MANIFEST
-rmd160/extconf.rb
-rmd160/rmd160.c
-rmd160/rmd160.h
-rmd160/rmd160hl.c
-rmd160/rmd160init.c
-rmd160/depend
-sha1/MANIFEST
-sha1/extconf.rb
-sha1/sha1.c
-sha1/sha1.h
-sha1/sha1hl.c
-sha1/sha1init.c
-sha1/depend
-sha2/MANIFEST
-sha2/extconf.rb
-sha2/sha2.c
-sha2/sha2.h
-sha2/sha2hl.c
-sha2/sha2init.c
-sha2/depend
-test.rb
-test.sh
-depend
diff --git a/ext/digest/defs.h b/ext/digest/defs.h
deleted file mode 100644
index df7df377b9..0000000000
--- a/ext/digest/defs.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/* -*- C -*-
- * $Id$
- */
-
-#ifndef DEFS_H
-#define DEFS_H
-
-#include "ruby.h"
-#include <sys/types.h>
-
-#if defined(HAVE_SYS_CDEFS_H)
-# include <sys/cdefs.h>
-#endif
-#if !defined(__BEGIN_DECLS)
-# define __BEGIN_DECLS
-# define __END_DECLS
-#endif
-
-#if defined(HAVE_INTTYPES_H)
-# include <inttypes.h>
-#else
- typedef unsigned char uint8_t;
- typedef unsigned int uint32_t;
-# if SIZEOF_LONG == 8
- typedef unsigned long uint64_t;
-# elif defined(__GNUC__)
- typedef unsigned long long uint64_t;
-# elif defined(_MSC_VER)
- typedef unsigned _int64 uint64_t;
-# else
-# define NO_UINT64_T
-# endif
-#endif
-
-#endif /* DEFS_H */
diff --git a/ext/digest/depend b/ext/digest/depend
deleted file mode 100644
index 43601a208f..0000000000
--- a/ext/digest/depend
+++ /dev/null
@@ -1,2 +0,0 @@
-digest.o: digest.c digest.h $(hdrdir)/ruby.h $(topdir)/config.h \
- $(hdrdir)/defines.h $(hdrdir)/intern.h
diff --git a/ext/digest/digest.c b/ext/digest/digest.c
deleted file mode 100644
index 3d47685aac..0000000000
--- a/ext/digest/digest.c
+++ /dev/null
@@ -1,343 +0,0 @@
-/************************************************
-
- digest.c -
-
- $Author$
- created at: Fri May 25 08:57:27 JST 2001
-
- Copyright (C) 1995-2001 Yukihiro Matsumoto
- Copyright (C) 2001 Akinori MUSHA
-
- $RoughId: digest.c,v 1.16 2001/07/13 15:38:27 knu Exp $
- $Id$
-
-************************************************/
-
-/*
- * This module provides an interface to the following hash algorithms:
- *
- * - the MD5 Message-Digest Algorithm by the RSA Data Security,
- * Inc., described in RFC 1321
- *
- * - the SHA-1 Secure Hash Algorithm by NIST (the US' National
- * Institute of Standards and Technology), described in FIPS PUB
- * 180-1.
- *
- * - the SHA-256/384/512 Secure Hash Algorithm by NIST (the US'
- * National Institute of Standards and Technology), described in
- * FIPS PUB 180-2.
- *
- * - the RIPEMD-160 cryptographic hash function, designed by Hans
- * Dobbertin, Antoon Bosselaers, and Bart Preneel.
- */
-
-#include "digest.h"
-
-static VALUE mDigest, cDigest_Base;
-static ID id_metadata;
-
-/*
- * Digest::Base
- */
-
-static algo_t *
-get_digest_base_metadata(class)
- VALUE class;
-{
- VALUE obj;
- algo_t *algo;
-
- if (rb_cvar_defined(class, id_metadata) == Qfalse)
- rb_notimplement();
-
- obj = rb_cvar_get(class, id_metadata);
-
- Data_Get_Struct(obj, algo_t, algo);
-
- return algo;
-}
-
-static VALUE
-rb_digest_base_s_new(argc, argv, class)
- int argc;
- VALUE* argv;
- VALUE class;
-{
- algo_t *algo;
- VALUE obj;
- void *pctx;
-
- if (class == cDigest_Base)
- rb_raise(rb_eNotImpError, "Digest::Base is an abstract class");
-
- algo = get_digest_base_metadata(class);
-
- pctx = xmalloc(algo->ctx_size);
- algo->init_func(pctx);
-
- obj = Data_Wrap_Struct(class, 0, free, pctx);
-
- rb_obj_call_init(obj, argc, argv);
-
- return obj;
-}
-
-static VALUE
-rb_digest_base_s_digest(class, str)
- VALUE class;
- VALUE str;
-{
- algo_t *algo;
- void *pctx;
- size_t len;
- unsigned char *digest;
- VALUE obj;
-
- if (class == cDigest_Base)
- rb_raise(rb_eNotImpError, "Digest::Base is an abstract class");
-
-#ifdef StringValue
- StringValue(str);
-#else
- Check_Type(str, T_STRING);
-#endif
-
- algo = get_digest_base_metadata(class);
-
- pctx = xmalloc(algo->ctx_size);
- algo->init_func(pctx);
- algo->update_func(pctx, RSTRING(str)->ptr, RSTRING(str)->len);
-
- len = algo->digest_len;
-
- digest = xmalloc(len);
- algo->final_func(digest, pctx);
-
- obj = rb_str_new(digest, len);
-
- free(digest);
- free(pctx);
-
- return obj;
-}
-
-static VALUE
-rb_digest_base_s_hexdigest(class, str)
- VALUE class;
- VALUE str;
-{
- algo_t *algo;
- void *pctx;
- size_t len;
- unsigned char *hexdigest;
- VALUE obj;
-
- if (class == cDigest_Base)
- rb_raise(rb_eNotImpError, "Digest::Base is an abstract class");
-
-#ifdef StringValue
- StringValue(str);
-#else
- Check_Type(str, T_STRING);
-#endif
-
- algo = get_digest_base_metadata(class);
-
- pctx = xmalloc(algo->ctx_size);
- algo->init_func(pctx);
- algo->update_func(pctx, RSTRING(str)->ptr, RSTRING(str)->len);
-
- len = algo->digest_len * 2;
-
- hexdigest = xmalloc(len + 1); /* +1 is for '\0' */
- algo->end_func(pctx, hexdigest);
-
- obj = rb_str_new(hexdigest, len);
-
- free(hexdigest);
- free(pctx);
-
- return obj;
-}
-
-static VALUE
-rb_digest_base_clone(self)
- VALUE self;
-{
- algo_t *algo;
- void *pctx1, *pctx2;
- VALUE class;
-
- class = CLASS_OF(self);
- algo = get_digest_base_metadata(class);
- Data_Get_Struct(self, void, pctx1);
-
- pctx2 = xmalloc(algo->ctx_size);
- memcpy(pctx2, pctx1, algo->ctx_size);
-
- return Data_Wrap_Struct(class, 0, free, pctx2);
-}
-
-static VALUE
-rb_digest_base_update(self, str)
- VALUE self, str;
-{
- algo_t *algo;
- void *pctx;
-
-#ifdef StringValue
- StringValue(str);
-#else
- Check_Type(str, T_STRING);
-#endif
-
- algo = get_digest_base_metadata(CLASS_OF(self));
- Data_Get_Struct(self, void, pctx);
-
- algo->update_func(pctx, RSTRING(str)->ptr, RSTRING(str)->len);
-
- return self;
-}
-
-static VALUE
-rb_digest_base_init(argc, argv, self)
- int argc;
- VALUE* argv;
- VALUE self;
-{
- VALUE arg;
-
- rb_scan_args(argc, argv, "01", &arg);
-
- if (!NIL_P(arg)) rb_digest_base_update(self, arg);
-
- return self;
-}
-
-static VALUE
-rb_digest_base_digest(self)
- VALUE self;
-{
- algo_t *algo;
- void *pctx1, *pctx2;
- unsigned char *digest;
- size_t len;
- VALUE str;
-
- algo = get_digest_base_metadata(CLASS_OF(self));
- Data_Get_Struct(self, void, pctx1);
-
- len = algo->ctx_size;
-
- pctx2 = xmalloc(len);
- memcpy(pctx2, pctx1, len);
-
- len = algo->digest_len;
-
- digest = xmalloc(len);
- algo->final_func(digest, pctx2);
-
- str = rb_str_new(digest, len);
-
- free(digest);
- free(pctx2);
-
- return str;
-}
-
-static VALUE
-rb_digest_base_hexdigest(self)
- VALUE self;
-{
- algo_t *algo;
- void *pctx1, *pctx2;
- unsigned char *hexdigest;
- size_t len;
- VALUE str;
-
- algo = get_digest_base_metadata(CLASS_OF(self));
- Data_Get_Struct(self, void, pctx1);
-
- len = algo->ctx_size;
-
- pctx2 = xmalloc(len);
- memcpy(pctx2, pctx1, len);
-
- len = algo->digest_len * 2;
-
- hexdigest = xmalloc(len + 1); /* +1 is for '\0' */
- algo->end_func(pctx2, hexdigest);
-
- str = rb_str_new(hexdigest, len);
-
- free(hexdigest);
- free(pctx2);
-
- return str;
-}
-
-static VALUE
-rb_digest_base_equal(self, other)
- VALUE self, other;
-{
- algo_t *algo;
- VALUE class;
- VALUE str1, str2;
-
- class = CLASS_OF(self);
- algo = get_digest_base_metadata(class);
-
- if (CLASS_OF(other) == class) {
- void *pctx1, *pctx2;
-
- Data_Get_Struct(self, void, pctx1);
- Data_Get_Struct(other, void, pctx2);
-
- return algo->equal_func(pctx1, pctx2) ? Qtrue : Qfalse;
- }
-
-#ifdef StringValue
- StringValue(other);
-#else
- Check_Type(other, T_STRING);
-#endif
- str2 = other;
-
- if (RSTRING(str2)->len == algo->digest_len)
- str1 = rb_digest_base_digest(self);
- else
- str1 = rb_digest_base_hexdigest(self);
-
- if (RSTRING(str1)->len == RSTRING(str2)->len
- && rb_str_cmp(str1, str2) == 0)
- return Qtrue;
-
- return Qfalse;
-}
-
-/*
- * Init
- */
-
-void
-Init_digest()
-{
- mDigest = rb_define_module("Digest");
-
- cDigest_Base = rb_define_class_under(mDigest, "Base", rb_cObject);
-
- rb_define_singleton_method(cDigest_Base, "new", rb_digest_base_s_new, -1);
- rb_define_singleton_method(cDigest_Base, "digest", rb_digest_base_s_digest, 1);
- rb_define_singleton_method(cDigest_Base, "hexdigest", rb_digest_base_s_hexdigest, 1);
-
- rb_define_method(cDigest_Base, "initialize", rb_digest_base_init, -1);
- rb_define_method(cDigest_Base, "clone", rb_digest_base_clone, 0);
- rb_define_method(cDigest_Base, "update", rb_digest_base_update, 1);
- rb_define_method(cDigest_Base, "<<", rb_digest_base_update, 1);
- rb_define_method(cDigest_Base, "digest", rb_digest_base_digest, 0);
- rb_define_method(cDigest_Base, "hexdigest", rb_digest_base_hexdigest, 0);
- rb_define_method(cDigest_Base, "to_s", rb_digest_base_hexdigest, 0);
- rb_define_method(cDigest_Base, "==", rb_digest_base_equal, 1);
-
- id_metadata = rb_intern("metadata");
-}
diff --git a/ext/digest/digest.h b/ext/digest/digest.h
deleted file mode 100644
index 5e846df040..0000000000
--- a/ext/digest/digest.h
+++ /dev/null
@@ -1,32 +0,0 @@
-/************************************************
-
- digest.c -
-
- $Author$
- created at: Fri May 25 08:54:56 JST 2001
-
-
- Copyright (C) 2001 Akinori MUSHA
-
- $RoughId: digest.h,v 1.3 2001/07/13 15:38:27 knu Exp $
- $Id$
-
-************************************************/
-
-#include "ruby.h"
-
-typedef void (*hash_init_func_t) _((void *));
-typedef void (*hash_update_func_t) _((void *, unsigned char *, size_t));
-typedef void (*hash_end_func_t) _((void *, unsigned char *));
-typedef void (*hash_final_func_t) _((unsigned char *, void *));
-typedef int (*hash_equal_func_t) _((void *, void *));
-
-typedef struct {
- size_t digest_len;
- size_t ctx_size;
- hash_init_func_t init_func;
- hash_update_func_t update_func;
- hash_end_func_t end_func;
- hash_final_func_t final_func;
- hash_equal_func_t equal_func;
-} algo_t;
diff --git a/ext/digest/digest.txt b/ext/digest/digest.txt
deleted file mode 100644
index 5797dd18f9..0000000000
--- a/ext/digest/digest.txt
+++ /dev/null
@@ -1,113 +0,0 @@
-.\" digest.txt - -*- Indented-Text -*- created at: Fri May 25 08:13:50 JST 2001
-$RoughId: digest.txt,v 1.9 2001/07/13 19:46:51 knu Exp $
-$Id$
-
-** MD5(Class)
-
-A class to implement the MD5 Message-Digest Algorithm by RSA Data
-Security, Inc., described in RFC1321.
-
-Superclass: Digest::Base
-
-require 'digest/md5'
-
-** SHA1(Class)
-
-A class to implement the SHA-1 Secure Hash Algorithm by NIST (the US'
-National Institute of Standards and Technology), described in FIPS PUB
-180-1.
-
-Superclass: Digest::Base
-
-require 'digest/sha1'
-
-** SHA256(Class)
-** SHA384(Class)
-** SHA512(Class)
-
-Classes to implement the SHA-256/384/512 Secure Hash Algorithm(s) by
-NIST (the US' National Institute of Standards and Technology),
-described in FIPS PUB 180-2.
-
-Superclass: Digest::Base
-
-require 'digest/sha2'
-
-** RMD160(Class)
-
-A class to implement the RIPEMD-160 cryptographic hash function,
-designed by Hans Dobbertin, Antoon Bosselaers, and Bart Preneel.
-
-Superclass: Digest::Base
-
-require 'digest/rmd160'
-
-
-Those above classes provide a common interface as shown below.
-
-
-Class Methods:
-
- new([str])
-
- Creates a new digest object. If a string argument is given,
- it is added to the object. (see update.)
-
- digest(str)
-
- Immediately calculates and return the hash of the given
- strings as a string. Equivalent to new(str).digest.
-
- hexdigest(str)
-
- Immediately calculates and return the hash of the given
- strings as a string of hexadecimal digits. Equivalent to
- new(str).hexdigest.
-
-Methods:
-
- clone
-
- Creates a copy of the digest object.
-
- digest
-
- Returns the hash of the added strings as a string of 16 bytes
- for MD5, 20 bytes for SHA1 and RMD160, 32 bytes for SHA256, 48
- bytes for SHA384, and 64 bytes for SHA512.
-
- hexdigest
- to_s
-
- Returns the hash of the added strings as a string of 32
- hexadecimal digits for MD5, 40 hexadecimal digits for SHA1 and
- RMD160, 64 hexadecimal digits for SHA256, 96 hexadecimal
- digits for SHA384, and 128 hexadecimal digits for SHA512.
- This method is equal to:
-
- def hexdigest
- digest.unpack("H*")[0]
- end
-
- update(str)
- << str
-
- Appends the string str to the digest object. Repeated calls
- are equivalent to a single call with the concatenation of all
- the arguments, i.e. m.update(a); m.update(b) is equivalent to
- m.update(a + b) and m << a << b is equivalent to m << a + b.
-
- == md
-
- Checks if the object is equal to the given digest object.
-
- == str
-
- Regards the value as either a digest value or a hexdigest
- value (depending on the length) and checks if the object is
- equal to the given string.
-
--------------------------------------------------------
-Local variables:
-fill-column: 70
-end:
diff --git a/ext/digest/digest.txt.ja b/ext/digest/digest.txt.ja
deleted file mode 100644
index 8997d25b9d..0000000000
--- a/ext/digest/digest.txt.ja
+++ /dev/null
@@ -1,111 +0,0 @@
-.\" digest.txt.ja - -*- Indented-Text -*- created at: Fri May 25 08:22:19 JST 2001
-$RoughId: digest.txt.jp,v 1.8 2001/07/13 15:38:27 knu Exp $
-$Id$
-
-** MD5(クラス)
-
-RFC1321に記述されているRSA Data Security, Inc. の MD5 Message-Digest
-Algorithmを実装するクラス。
-
-Superclass: Digest::Base
-
-require 'digest/md5'
-
-** SHA1(クラス)
-
-FIPS PUB 180-1に記述されているNIST (the US' National Institute of
-Standards and Technology) の SHA-1 Secure Hash Algorithmを実装するクラス。
-
-Superclass: Digest::Base
-
-require 'digest/sha1'
-
-** SHA256(クラス)
-** SHA384(クラス)
-** SHA512(クラス)
-
-FIPS PUB 180-2に記述されているNIST (the US' National Institute of
-Standards and Technology) の SHA-256/384/512 Secure Hash Algorithmを
-実装するクラス。
-
-Superclass: Digest::Base
-
-require 'digest/sha2'
-
-** RMD160(クラス)
-
-Hans Dobbertin, Antoon Bosselaers, Bart Preneel によって設計された
-RIPEMD-160 ハッシュ関数を実装するクラス。
-
-Superclass: Digest::Base
-
-require 'digest/rmd160'
-
-
-これらのクラスは以下のような共通のインターフェースを提供する。
-
-
-Class Methods:
-
- new([str])
-
- 新しいダイジェストオブジェクトを生成する.文字列引数が与えられる
- とそれを追加する(see update)。
-
- digest(str)
-
- 与えられた文字列に対するハッシュ値を文字列で返す。
- new(str).digest と等価。
-
- hexdigest(str)
-
- 与えられた文字列に対するハッシュ値を、ASCIIコードを使って
- 16進数の列を示す文字列にエンコードして返す。
- new(str).hexdigest と等価。
-
-Methods:
-
- clone
-
- ダイジェストオブジェクトの複製を作る。
-
- digest
-
- 今までに追加した文字列に対するハッシュ値を文字列で返す。MD5では
- 16バイト長、SHA1およびRMD160では20バイト長、SHA256では32バイト長、
- SHA384では48バイト長、SHA512では64バイト長となる。
-
- hexdigest
- to_s
-
- 今までに追加した文字列に対するハッシュ値を、ASCIIコードを使って
- 16進数の列を示す文字列にエンコードして返す。MD5では32バイト長、
- SHA1およびRMD160では40バイト長、SHA256では64バイト長、SHA384では
- 96バイト長、SHA512では128バイト長となる。Rubyで書くと以下と同じ。
-
- def hexdigest
- digest.unpack("H*")[0]
- end
-
- update(str)
- << str
-
- 文字列を追加する。複数回updateを呼ぶことは文字列を連結して
- updateを呼ぶことと等しい。すなわち m.update(a); m.update(b) は
- m.update(a + b) と、 m << a << b は m << a + b とそれぞれ等価
- である。
-
- == md
-
- 与えられたダイジェストオブジェクトと比較する。
-
- == str
-
- 与えられた文字列を digest 値、もしくは hexdigest 値と比較する。
- いずれの値と見るかは与えられた文字列の長さによって自動判別
- される。
-
--------------------------------------------------------
-Local variables:
-fill-column: 70
-end:
diff --git a/ext/digest/extconf.rb b/ext/digest/extconf.rb
deleted file mode 100644
index cd512622a4..0000000000
--- a/ext/digest/extconf.rb
+++ /dev/null
@@ -1,6 +0,0 @@
-# $RoughId: extconf.rb,v 1.6 2001/07/13 15:38:27 knu Exp $
-# $Id$
-
-require "mkmf"
-
-create_makefile("digest")
diff --git a/ext/digest/lib/md5.rb b/ext/digest/lib/md5.rb
deleted file mode 100644
index 1d05d7d04e..0000000000
--- a/ext/digest/lib/md5.rb
+++ /dev/null
@@ -1,14 +0,0 @@
-# just for compatibility; requiring "md5" is obsoleted
-#
-# $RoughId: md5.rb,v 1.4 2001/07/13 15:38:27 knu Exp $
-# $Id$
-
-require 'digest/md5'
-
-MD5 = Digest::MD5
-
-class MD5
- def self.md5(*args)
- new(*args)
- end
-end
diff --git a/ext/digest/lib/sha1.rb b/ext/digest/lib/sha1.rb
deleted file mode 100644
index c4ac6f66ea..0000000000
--- a/ext/digest/lib/sha1.rb
+++ /dev/null
@@ -1,14 +0,0 @@
-# just for compatibility; requiring "sha1" is obsoleted
-#
-# $RoughId: sha1.rb,v 1.4 2001/07/13 15:38:27 knu Exp $
-# $Id$
-
-require 'digest/sha1'
-
-SHA1 = Digest::SHA1
-
-class SHA1
- def self.sha1(*args)
- new(*args)
- end
-end
diff --git a/ext/digest/md5/.cvsignore b/ext/digest/md5/.cvsignore
deleted file mode 100644
index fc802ff1c2..0000000000
--- a/ext/digest/md5/.cvsignore
+++ /dev/null
@@ -1,2 +0,0 @@
-Makefile
-mkmf.log
diff --git a/ext/digest/md5/MANIFEST b/ext/digest/md5/MANIFEST
deleted file mode 100644
index 923af92ed2..0000000000
--- a/ext/digest/md5/MANIFEST
+++ /dev/null
@@ -1,5 +0,0 @@
-extconf.rb
-md5.c
-md5.h
-md5init.c
-depend
diff --git a/ext/digest/md5/depend b/ext/digest/md5/depend
deleted file mode 100644
index 30ad482101..0000000000
--- a/ext/digest/md5/depend
+++ /dev/null
@@ -1,5 +0,0 @@
-md5.o: md5.c md5.h $(srcdir)/../defs.h $(hdrdir)/ruby.h $(topdir)/config.h \
- $(hdrdir)/defines.h $(hdrdir)/intern.h
-md5init.o: md5init.c $(srcdir)/../digest.h $(hdrdir)/ruby.h \
- $(topdir)/config.h $(hdrdir)/defines.h $(hdrdir)/intern.h md5.h \
- $(srcdir)/../defs.h
diff --git a/ext/digest/md5/extconf.rb b/ext/digest/md5/extconf.rb
deleted file mode 100644
index 93a14025d0..0000000000
--- a/ext/digest/md5/extconf.rb
+++ /dev/null
@@ -1,19 +0,0 @@
-# $RoughId: extconf.rb,v 1.3 2001/08/14 19:54:51 knu Exp $
-# $Id$
-
-require "mkmf"
-
-$CFLAGS << " -DHAVE_CONFIG_H -I#{File.dirname(__FILE__)}/.."
-
-$objs = [
- "md5.#{$OBJEXT}",
- "md5init.#{$OBJEXT}",
-]
-
-have_header("sys/cdefs.h")
-
-have_header("inttypes.h")
-
-have_header("unistd.h")
-
-create_makefile("digest/md5")
diff --git a/ext/digest/md5/md5.c b/ext/digest/md5/md5.c
deleted file mode 100644
index 6b61f031c4..0000000000
--- a/ext/digest/md5/md5.c
+++ /dev/null
@@ -1,432 +0,0 @@
-/*
- Copyright (C) 1999, 2000 Aladdin Enterprises. All rights reserved.
-
- This software is provided 'as-is', without any express or implied
- warranty. In no event will the authors be held liable for any damages
- arising from the use of this software.
-
- Permission is granted to anyone to use this software for any purpose,
- including commercial applications, and to alter it and redistribute it
- freely, subject to the following restrictions:
-
- 1. The origin of this software must not be misrepresented; you must not
- claim that you wrote the original software. If you use this software
- in a product, an acknowledgment in the product documentation would be
- appreciated but is not required.
- 2. Altered source versions must be plainly marked as such, and must not be
- misrepresented as being the original software.
- 3. This notice may not be removed or altered from any source distribution.
-
- L. Peter Deutsch
- ghost@aladdin.com
-
- */
-
-/*
- Independent implementation of MD5 (RFC 1321).
-
- This code implements the MD5 Algorithm defined in RFC 1321.
- It is derived directly from the text of the RFC and not from the
- reference implementation.
-
- The original and principal author of md5.c is L. Peter Deutsch
- <ghost@aladdin.com>. Other authors are noted in the change history
- that follows (in reverse chronological order):
-
- 2000-07-03 lpd Patched to eliminate warnings about "constant is
- unsigned in ANSI C, signed in traditional";
- made test program self-checking.
- 1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
- 1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5).
- 1999-05-03 lpd Original version.
- */
-
-/*$OrigId: md5c.c,v 1.2 2001/03/26 08:57:14 matz Exp $ */
-/*$RoughId: md5.c,v 1.2 2001/07/13 19:48:41 knu Exp $ */
-/*$Id$ */
-
-#include "md5.h"
-
-#ifdef TEST
-/*
- * Compile with -DTEST to create a self-contained executable test program.
- * The test program should print out the same values as given in section
- * A.5 of RFC 1321, reproduced below.
- */
-#include <string.h>
-main()
-{
- static const char *const test[7*2] = {
- "", "d41d8cd98f00b204e9800998ecf8427e",
- "a", "0cc175b9c0f1b6a831c399e269772661",
- "abc", "900150983cd24fb0d6963f7d28e17f72",
- "message digest", "f96b697d7cb7938d525a2f31aaf161d0",
- "abcdefghijklmnopqrstuvwxyz", "c3fcd3d76192e4007dfb496cca67e13b",
- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
- "d174ab98d277d9f5a5611c2c9f419d9f",
- "12345678901234567890123456789012345678901234567890123456789012345678901234567890", "57edf4a22be3c955ac49da2e2107b67a"
- };
- int i;
-
- for (i = 0; i < 7*2; i += 2) {
- MD5_CTX state;
- uint8_t digest[16];
- char hex_output[16*2 + 1];
- int di;
-
- MD5_Init(&state);
- MD5_Update(&state, (const uint8_t *)test[i], strlen(test[i]));
- MD5_Final(digest, &state);
- printf("MD5 (\"%s\") = ", test[i]);
- for (di = 0; di < 16; ++di)
- sprintf(hex_output + di * 2, "%02x", digest[di]);
- puts(hex_output);
- if (strcmp(hex_output, test[i + 1]))
- printf("**** ERROR, should be: %s\n", test[i + 1]);
- }
- return 0;
-}
-#endif /* TEST */
-
-
-/*
- * For reference, here is the program that computed the T values.
- */
-#ifdef COMPUTE_T_VALUES
-#include <math.h>
-main()
-{
- int i;
- for (i = 1; i <= 64; ++i) {
- unsigned long v = (unsigned long)(4294967296.0 * fabs(sin((double)i)));
-
- /*
- * The following nonsense is only to avoid compiler warnings about
- * "integer constant is unsigned in ANSI C, signed with -traditional".
- */
- if (v >> 31) {
- printf("#define T%d /* 0x%08lx */ (T_MASK ^ 0x%08lx)\n", i,
- v, (unsigned long)(unsigned int)(~v));
- } else {
- printf("#define T%d 0x%08lx\n", i, v);
- }
- }
- return 0;
-}
-#endif /* COMPUTE_T_VALUES */
-/*
- * End of T computation program.
- */
-#ifdef T_MASK
-#undef T_MASK
-#endif
-#define T_MASK ((uint32_t)~0)
-#define T1 /* 0xd76aa478 */ (T_MASK ^ 0x28955b87)
-#define T2 /* 0xe8c7b756 */ (T_MASK ^ 0x173848a9)
-#define T3 0x242070db
-#define T4 /* 0xc1bdceee */ (T_MASK ^ 0x3e423111)
-#define T5 /* 0xf57c0faf */ (T_MASK ^ 0x0a83f050)
-#define T6 0x4787c62a
-#define T7 /* 0xa8304613 */ (T_MASK ^ 0x57cfb9ec)
-#define T8 /* 0xfd469501 */ (T_MASK ^ 0x02b96afe)
-#define T9 0x698098d8
-#define T10 /* 0x8b44f7af */ (T_MASK ^ 0x74bb0850)
-#define T11 /* 0xffff5bb1 */ (T_MASK ^ 0x0000a44e)
-#define T12 /* 0x895cd7be */ (T_MASK ^ 0x76a32841)
-#define T13 0x6b901122
-#define T14 /* 0xfd987193 */ (T_MASK ^ 0x02678e6c)
-#define T15 /* 0xa679438e */ (T_MASK ^ 0x5986bc71)
-#define T16 0x49b40821
-#define T17 /* 0xf61e2562 */ (T_MASK ^ 0x09e1da9d)
-#define T18 /* 0xc040b340 */ (T_MASK ^ 0x3fbf4cbf)
-#define T19 0x265e5a51
-#define T20 /* 0xe9b6c7aa */ (T_MASK ^ 0x16493855)
-#define T21 /* 0xd62f105d */ (T_MASK ^ 0x29d0efa2)
-#define T22 0x02441453
-#define T23 /* 0xd8a1e681 */ (T_MASK ^ 0x275e197e)
-#define T24 /* 0xe7d3fbc8 */ (T_MASK ^ 0x182c0437)
-#define T25 0x21e1cde6
-#define T26 /* 0xc33707d6 */ (T_MASK ^ 0x3cc8f829)
-#define T27 /* 0xf4d50d87 */ (T_MASK ^ 0x0b2af278)
-#define T28 0x455a14ed
-#define T29 /* 0xa9e3e905 */ (T_MASK ^ 0x561c16fa)
-#define T30 /* 0xfcefa3f8 */ (T_MASK ^ 0x03105c07)
-#define T31 0x676f02d9
-#define T32 /* 0x8d2a4c8a */ (T_MASK ^ 0x72d5b375)
-#define T33 /* 0xfffa3942 */ (T_MASK ^ 0x0005c6bd)
-#define T34 /* 0x8771f681 */ (T_MASK ^ 0x788e097e)
-#define T35 0x6d9d6122
-#define T36 /* 0xfde5380c */ (T_MASK ^ 0x021ac7f3)
-#define T37 /* 0xa4beea44 */ (T_MASK ^ 0x5b4115bb)
-#define T38 0x4bdecfa9
-#define T39 /* 0xf6bb4b60 */ (T_MASK ^ 0x0944b49f)
-#define T40 /* 0xbebfbc70 */ (T_MASK ^ 0x4140438f)
-#define T41 0x289b7ec6
-#define T42 /* 0xeaa127fa */ (T_MASK ^ 0x155ed805)
-#define T43 /* 0xd4ef3085 */ (T_MASK ^ 0x2b10cf7a)
-#define T44 0x04881d05
-#define T45 /* 0xd9d4d039 */ (T_MASK ^ 0x262b2fc6)
-#define T46 /* 0xe6db99e5 */ (T_MASK ^ 0x1924661a)
-#define T47 0x1fa27cf8
-#define T48 /* 0xc4ac5665 */ (T_MASK ^ 0x3b53a99a)
-#define T49 /* 0xf4292244 */ (T_MASK ^ 0x0bd6ddbb)
-#define T50 0x432aff97
-#define T51 /* 0xab9423a7 */ (T_MASK ^ 0x546bdc58)
-#define T52 /* 0xfc93a039 */ (T_MASK ^ 0x036c5fc6)
-#define T53 0x655b59c3
-#define T54 /* 0x8f0ccc92 */ (T_MASK ^ 0x70f3336d)
-#define T55 /* 0xffeff47d */ (T_MASK ^ 0x00100b82)
-#define T56 /* 0x85845dd1 */ (T_MASK ^ 0x7a7ba22e)
-#define T57 0x6fa87e4f
-#define T58 /* 0xfe2ce6e0 */ (T_MASK ^ 0x01d3191f)
-#define T59 /* 0xa3014314 */ (T_MASK ^ 0x5cfebceb)
-#define T60 0x4e0811a1
-#define T61 /* 0xf7537e82 */ (T_MASK ^ 0x08ac817d)
-#define T62 /* 0xbd3af235 */ (T_MASK ^ 0x42c50dca)
-#define T63 0x2ad7d2bb
-#define T64 /* 0xeb86d391 */ (T_MASK ^ 0x14792c6e)
-
-
-static void
-md5_process(MD5_CTX *pms, const uint8_t *data /*[64]*/)
-{
- uint32_t
- a = pms->state[0], b = pms->state[1],
- c = pms->state[2], d = pms->state[3];
- uint32_t t;
-
-#ifdef WORDS_BIGENDIAN
-
- /*
- * On big-endian machines, we must arrange the bytes in the right
- * order. (This also works on machines of unknown byte order.)
- */
- uint32_t X[16];
- const uint8_t *xp = data;
- int i;
-
- for (i = 0; i < 16; ++i, xp += 4)
- X[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24);
-
-#else
-
- /*
- * On little-endian machines, we can process properly aligned data
- * without copying it.
- */
- uint32_t xbuf[16];
- const uint32_t *X;
-
- if (!((data - (const uint8_t *)0) & 3)) {
- /* data are properly aligned */
- X = (const uint32_t *)data;
- } else {
- /* not aligned */
- memcpy(xbuf, data, 64);
- X = xbuf;
- }
-#endif
-
-#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
-
- /* Round 1. */
- /* Let [abcd k s i] denote the operation
- a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */
-#define F(x, y, z) (((x) & (y)) | (~(x) & (z)))
-#define SET(a, b, c, d, k, s, Ti)\
- t = a + F(b,c,d) + X[k] + Ti;\
- a = ROTATE_LEFT(t, s) + b
- /* Do the following 16 operations. */
- SET(a, b, c, d, 0, 7, T1);
- SET(d, a, b, c, 1, 12, T2);
- SET(c, d, a, b, 2, 17, T3);
- SET(b, c, d, a, 3, 22, T4);
- SET(a, b, c, d, 4, 7, T5);
- SET(d, a, b, c, 5, 12, T6);
- SET(c, d, a, b, 6, 17, T7);
- SET(b, c, d, a, 7, 22, T8);
- SET(a, b, c, d, 8, 7, T9);
- SET(d, a, b, c, 9, 12, T10);
- SET(c, d, a, b, 10, 17, T11);
- SET(b, c, d, a, 11, 22, T12);
- SET(a, b, c, d, 12, 7, T13);
- SET(d, a, b, c, 13, 12, T14);
- SET(c, d, a, b, 14, 17, T15);
- SET(b, c, d, a, 15, 22, T16);
-#undef SET
-
- /* Round 2. */
- /* Let [abcd k s i] denote the operation
- a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */
-#define G(x, y, z) (((x) & (z)) | ((y) & ~(z)))
-#define SET(a, b, c, d, k, s, Ti)\
- t = a + G(b,c,d) + X[k] + Ti;\
- a = ROTATE_LEFT(t, s) + b
- /* Do the following 16 operations. */
- SET(a, b, c, d, 1, 5, T17);
- SET(d, a, b, c, 6, 9, T18);
- SET(c, d, a, b, 11, 14, T19);
- SET(b, c, d, a, 0, 20, T20);
- SET(a, b, c, d, 5, 5, T21);
- SET(d, a, b, c, 10, 9, T22);
- SET(c, d, a, b, 15, 14, T23);
- SET(b, c, d, a, 4, 20, T24);
- SET(a, b, c, d, 9, 5, T25);
- SET(d, a, b, c, 14, 9, T26);
- SET(c, d, a, b, 3, 14, T27);
- SET(b, c, d, a, 8, 20, T28);
- SET(a, b, c, d, 13, 5, T29);
- SET(d, a, b, c, 2, 9, T30);
- SET(c, d, a, b, 7, 14, T31);
- SET(b, c, d, a, 12, 20, T32);
-#undef SET
-
- /* Round 3. */
- /* Let [abcd k s t] denote the operation
- a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */
-#define H(x, y, z) ((x) ^ (y) ^ (z))
-#define SET(a, b, c, d, k, s, Ti)\
- t = a + H(b,c,d) + X[k] + Ti;\
- a = ROTATE_LEFT(t, s) + b
- /* Do the following 16 operations. */
- SET(a, b, c, d, 5, 4, T33);
- SET(d, a, b, c, 8, 11, T34);
- SET(c, d, a, b, 11, 16, T35);
- SET(b, c, d, a, 14, 23, T36);
- SET(a, b, c, d, 1, 4, T37);
- SET(d, a, b, c, 4, 11, T38);
- SET(c, d, a, b, 7, 16, T39);
- SET(b, c, d, a, 10, 23, T40);
- SET(a, b, c, d, 13, 4, T41);
- SET(d, a, b, c, 0, 11, T42);
- SET(c, d, a, b, 3, 16, T43);
- SET(b, c, d, a, 6, 23, T44);
- SET(a, b, c, d, 9, 4, T45);
- SET(d, a, b, c, 12, 11, T46);
- SET(c, d, a, b, 15, 16, T47);
- SET(b, c, d, a, 2, 23, T48);
-#undef SET
-
- /* Round 4. */
- /* Let [abcd k s t] denote the operation
- a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */
-#define I(x, y, z) ((y) ^ ((x) | ~(z)))
-#define SET(a, b, c, d, k, s, Ti)\
- t = a + I(b,c,d) + X[k] + Ti;\
- a = ROTATE_LEFT(t, s) + b
- /* Do the following 16 operations. */
- SET(a, b, c, d, 0, 6, T49);
- SET(d, a, b, c, 7, 10, T50);
- SET(c, d, a, b, 14, 15, T51);
- SET(b, c, d, a, 5, 21, T52);
- SET(a, b, c, d, 12, 6, T53);
- SET(d, a, b, c, 3, 10, T54);
- SET(c, d, a, b, 10, 15, T55);
- SET(b, c, d, a, 1, 21, T56);
- SET(a, b, c, d, 8, 6, T57);
- SET(d, a, b, c, 15, 10, T58);
- SET(c, d, a, b, 6, 15, T59);
- SET(b, c, d, a, 13, 21, T60);
- SET(a, b, c, d, 4, 6, T61);
- SET(d, a, b, c, 11, 10, T62);
- SET(c, d, a, b, 2, 15, T63);
- SET(b, c, d, a, 9, 21, T64);
-#undef SET
-
- /* Then perform the following additions. (That is increment each
- of the four registers by the value it had before this block
- was started.) */
- pms->state[0] += a;
- pms->state[1] += b;
- pms->state[2] += c;
- pms->state[3] += d;
-}
-
-void
-MD5_Init(MD5_CTX *pms)
-{
- pms->count[0] = pms->count[1] = 0;
- pms->state[0] = 0x67452301;
- pms->state[1] = /*0xefcdab89*/ T_MASK ^ 0x10325476;
- pms->state[2] = /*0x98badcfe*/ T_MASK ^ 0x67452301;
- pms->state[3] = 0x10325476;
-}
-
-void
-MD5_Update(MD5_CTX *pms, const uint8_t *data, size_t nbytes)
-{
- const uint8_t *p = data;
- size_t left = nbytes;
- size_t offset = (pms->count[0] >> 3) & 63;
- uint32_t nbits = (uint32_t)(nbytes << 3);
-
- if (nbytes <= 0)
- return;
-
- /* Update the message length. */
- pms->count[1] += nbytes >> 29;
- pms->count[0] += nbits;
- if (pms->count[0] < nbits)
- pms->count[1]++;
-
- /* Process an initial partial block. */
- if (offset) {
- size_t copy = (offset + nbytes > 64 ? 64 - offset : nbytes);
-
- memcpy(pms->buffer + offset, p, copy);
- if (offset + copy < 64)
- return;
- p += copy;
- left -= copy;
- md5_process(pms, pms->buffer);
- }
-
- /* Process full blocks. */
- for (; left >= 64; p += 64, left -= 64)
- md5_process(pms, p);
-
- /* Process a final partial block. */
- if (left)
- memcpy(pms->buffer, p, left);
-}
-
-void
-MD5_Final(uint8_t *digest, MD5_CTX *pms)
-{
- static const uint8_t pad[64] = {
- 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
- };
- uint8_t data[8];
- size_t i;
-
- /* Save the length before padding. */
- for (i = 0; i < 8; ++i)
- data[i] = (uint8_t)(pms->count[i >> 2] >> ((i & 3) << 3));
- /* Pad to 56 bytes mod 64. */
- MD5_Update(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1);
- /* Append the length. */
- MD5_Update(pms, data, 8);
- for (i = 0; i < 16; ++i)
- digest[i] = (uint8_t)(pms->state[i >> 2] >> ((i & 3) << 3));
-}
-
-void
-MD5_End(MD5_CTX *pctx, uint8_t *hexdigest)
-{
- unsigned char digest[16];
- size_t i;
-
- MD5_Final(digest, pctx);
-
- for (i = 0; i < 16; i++)
- sprintf(hexdigest + i * 2, "%02x", digest[i]);
-}
-
-int MD5_Equal(MD5_CTX* pctx1, MD5_CTX* pctx2) {
- return memcmp(pctx1->count, pctx2->count, sizeof(pctx1->count)) == 0
- && memcmp(pctx1->state, pctx2->state, sizeof(pctx1->state)) == 0
- && memcmp(pctx1->buffer, pctx2->buffer, sizeof(pctx1->buffer)) == 0;
-}
diff --git a/ext/digest/md5/md5.h b/ext/digest/md5/md5.h
deleted file mode 100644
index fc41380d38..0000000000
--- a/ext/digest/md5/md5.h
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- Copyright (C) 1999 Aladdin Enterprises. All rights reserved.
-
- This software is provided 'as-is', without any express or implied
- warranty. In no event will the authors be held liable for any damages
- arising from the use of this software.
-
- Permission is granted to anyone to use this software for any purpose,
- including commercial applications, and to alter it and redistribute it
- freely, subject to the following restrictions:
-
- 1. The origin of this software must not be misrepresented; you must not
- claim that you wrote the original software. If you use this software
- in a product, an acknowledgment in the product documentation would be
- appreciated but is not required.
- 2. Altered source versions must be plainly marked as such, and must not be
- misrepresented as being the original software.
- 3. This notice may not be removed or altered from any source distribution.
-
- L. Peter Deutsch
- ghost@aladdin.com
-
- */
-/*
- Independent implementation of MD5 (RFC 1321).
-
- This code implements the MD5 Algorithm defined in RFC 1321.
- It is derived directly from the text of the RFC and not from the
- reference implementation.
-
- The original and principal author of md5.h is L. Peter Deutsch
- <ghost@aladdin.com>. Other authors are noted in the change history
- that follows (in reverse chronological order):
-
- 1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
- 1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5);
- added conditionalization for C++ compilation from Martin
- Purschke <purschke@bnl.gov>.
- 1999-05-03 lpd Original version.
- */
-
-/* $OrigId: md5.h,v 1.2 2001/03/26 08:57:14 matz Exp $ */
-/* $RoughId: md5.h,v 1.3 2002/02/24 08:14:31 knu Exp $ */
-/* $Id$ */
-
-#ifndef MD5_INCLUDED
-# define MD5_INCLUDED
-
-#include "defs.h"
-
-/*
- * This code has some adaptations for the Ghostscript environment, but it
- * will compile and run correctly in any environment with 8-bit chars and
- * 32-bit ints. Specifically, it assumes that if the following are
- * defined, they have the same meaning as in Ghostscript: P1, P2, P3.
- */
-
-/* Define the state of the MD5 Algorithm. */
-typedef struct md5_state_s {
- uint32_t count[2]; /* message length in bits, lsw first */
- uint32_t state[4]; /* digest buffer */
- uint8_t buffer[64]; /* accumulate block */
-} MD5_CTX;
-
-#ifdef RUBY
-#define MD5_Init rb_Digest_MD5_Init
-#define MD5_Update rb_Digest_MD5_Update
-#define MD5_Final rb_Digest_MD5_Final
-#define MD5_End rb_Digest_MD5_End
-#define MD5_Equal rb_Digest_MD5_Equal
-#endif
-
-void MD5_Init _((MD5_CTX *pms));
-void MD5_Update _((MD5_CTX *pms, const uint8_t *data, size_t nbytes));
-void MD5_Final _((uint8_t *digest, MD5_CTX *pms));
-void MD5_End _((MD5_CTX *pctx, uint8_t *hexdigest));
-int MD5_Equal _((MD5_CTX *pctx1, MD5_CTX *pctx2));
-
-#define MD5_BLOCK_LENGTH 64
-#define MD5_DIGEST_LENGTH 16
-#define MD5_DIGEST_STRING_LENGTH (MD5_DIGEST_LENGTH * 2 + 1)
-
-#endif /* MD5_INCLUDED */
diff --git a/ext/digest/md5/md5init.c b/ext/digest/md5/md5init.c
deleted file mode 100644
index 90ab707433..0000000000
--- a/ext/digest/md5/md5init.c
+++ /dev/null
@@ -1,34 +0,0 @@
-/* $RoughId: md5init.c,v 1.2 2001/07/13 19:49:10 knu Exp $ */
-/* $Id$ */
-
-#include "digest.h"
-#include "md5.h"
-
-static algo_t md5 = {
- MD5_DIGEST_LENGTH,
- sizeof(MD5_CTX),
- (hash_init_func_t)MD5_Init,
- (hash_update_func_t)MD5_Update,
- (hash_end_func_t)MD5_End,
- (hash_final_func_t)MD5_Final,
- (hash_equal_func_t)MD5_Equal,
-};
-
-void
-Init_md5()
-{
- VALUE mDigest, cDigest_Base, cDigest_MD5;
- ID id_metadata;
-
- rb_require("digest.so");
-
- mDigest = rb_path2class("Digest");
- cDigest_Base = rb_path2class("Digest::Base");
-
- cDigest_MD5 = rb_define_class_under(mDigest, "MD5", cDigest_Base);
-
- id_metadata = rb_intern("metadata");
-
- rb_cvar_set(cDigest_MD5, id_metadata,
- Data_Wrap_Struct(rb_cObject, 0, 0, &md5), Qtrue);
-}
diff --git a/ext/digest/rmd160/.cvsignore b/ext/digest/rmd160/.cvsignore
deleted file mode 100644
index fc802ff1c2..0000000000
--- a/ext/digest/rmd160/.cvsignore
+++ /dev/null
@@ -1,2 +0,0 @@
-Makefile
-mkmf.log
diff --git a/ext/digest/rmd160/MANIFEST b/ext/digest/rmd160/MANIFEST
deleted file mode 100644
index 017976de0d..0000000000
--- a/ext/digest/rmd160/MANIFEST
+++ /dev/null
@@ -1,6 +0,0 @@
-extconf.rb
-rmd160.c
-rmd160.h
-rmd160hl.c
-rmd160init.c
-depend
diff --git a/ext/digest/rmd160/depend b/ext/digest/rmd160/depend
deleted file mode 100644
index 7cf1d5e639..0000000000
--- a/ext/digest/rmd160/depend
+++ /dev/null
@@ -1,7 +0,0 @@
-rmd160.o: rmd160.c rmd160.h $(srcdir)/../defs.h $(hdrdir)/ruby.h \
- $(topdir)/config.h $(hdrdir)/defines.h $(hdrdir)/intern.h
-rmd160hl.o: rmd160hl.c rmd160.h $(srcdir)/../defs.h $(hdrdir)/ruby.h \
- $(topdir)/config.h $(hdrdir)/defines.h $(hdrdir)/intern.h
-rmd160init.o: rmd160init.c $(srcdir)/../digest.h $(hdrdir)/ruby.h \
- $(topdir)/config.h $(hdrdir)/defines.h $(hdrdir)/intern.h \
- rmd160.h $(srcdir)/../defs.h
diff --git a/ext/digest/rmd160/extconf.rb b/ext/digest/rmd160/extconf.rb
deleted file mode 100644
index ce53c77b55..0000000000
--- a/ext/digest/rmd160/extconf.rb
+++ /dev/null
@@ -1,20 +0,0 @@
-# $RoughId: extconf.rb,v 1.3 2001/08/14 19:54:51 knu Exp $
-# $Id$
-
-require "mkmf"
-
-$CFLAGS << " -DHAVE_CONFIG_H -I#{File.dirname(__FILE__)}/.."
-
-$objs = [
- "rmd160.#{$OBJEXT}",
- "rmd160hl.#{$OBJEXT}",
- "rmd160init.#{$OBJEXT}",
-]
-
-have_header("sys/cdefs.h")
-
-have_header("inttypes.h")
-
-have_header("unistd.h")
-
-create_makefile("digest/rmd160")
diff --git a/ext/digest/rmd160/rmd160.c b/ext/digest/rmd160/rmd160.c
deleted file mode 100644
index 2de3c99b29..0000000000
--- a/ext/digest/rmd160/rmd160.c
+++ /dev/null
@@ -1,464 +0,0 @@
-/* $NetBSD: rmd160.c,v 1.1.1.1 2001/03/06 11:21:05 agc Exp $ */
-/* $RoughId: rmd160.c,v 1.2 2001/07/13 19:49:10 knu Exp $ */
-/* $Id$ */
-
-/********************************************************************\
- *
- * FILE: rmd160.c
- *
- * CONTENTS: A sample C-implementation of the RIPEMD-160
- * hash-function.
- * TARGET: any computer with an ANSI C compiler
- *
- * AUTHOR: Antoon Bosselaers, ESAT-COSIC
- * (Arranged for libc by Todd C. Miller)
- * DATE: 1 March 1996
- * VERSION: 1.0
- *
- * Copyright (c) Katholieke Universiteit Leuven
- * 1996, All Rights Reserved
- *
-\********************************************************************/
-
-#include "rmd160.h"
-
-#ifndef lint
-/* __RCSID("$NetBSD: rmd160.c,v 1.1.1.1 2001/03/06 11:21:05 agc Exp $"); */
-#endif /* not lint */
-
-/* header files */
-
-#ifdef HAVE_SYS_ENDIAN_H_
-#include <sys/endian.h>
-#endif
-
-#ifdef HAVE_MACHINE_ENDIAN_H_
-#include <machine/endian.h>
-#endif
-
-/* #include "namespace.h" */
-
-#include <assert.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#ifndef _DIAGASSERT
-#define _DIAGASSERT(cond) assert(cond)
-#endif
-
-
-/********************************************************************/
-
-/* macro definitions */
-
-/* collect four bytes into one word: */
-#define BYTES_TO_DWORD(strptr) \
- (((uint32_t) *((strptr)+3) << 24) | \
- ((uint32_t) *((strptr)+2) << 16) | \
- ((uint32_t) *((strptr)+1) << 8) | \
- ((uint32_t) *(strptr)))
-
-/* ROL(x, n) cyclically rotates x over n bits to the left */
-/* x must be of an unsigned 32 bits type and 0 <= n < 32. */
-#define ROL(x, n) (((x) << (n)) | ((x) >> (32-(n))))
-
-/* the three basic functions F(), G() and H() */
-#define F(x, y, z) ((x) ^ (y) ^ (z))
-#define G(x, y, z) (((x) & (y)) | (~(x) & (z)))
-#define H(x, y, z) (((x) | ~(y)) ^ (z))
-#define I(x, y, z) (((x) & (z)) | ((y) & ~(z)))
-#define J(x, y, z) ((x) ^ ((y) | ~(z)))
-
-/* the eight basic operations FF() through III() */
-#define FF(a, b, c, d, e, x, s) { \
- (a) += F((b), (c), (d)) + (x); \
- (a) = ROL((a), (s)) + (e); \
- (c) = ROL((c), 10); \
-}
-#define GG(a, b, c, d, e, x, s) { \
- (a) += G((b), (c), (d)) + (x) + 0x5a827999U; \
- (a) = ROL((a), (s)) + (e); \
- (c) = ROL((c), 10); \
-}
-#define HH(a, b, c, d, e, x, s) { \
- (a) += H((b), (c), (d)) + (x) + 0x6ed9eba1U; \
- (a) = ROL((a), (s)) + (e); \
- (c) = ROL((c), 10); \
-}
-#define II(a, b, c, d, e, x, s) { \
- (a) += I((b), (c), (d)) + (x) + 0x8f1bbcdcU; \
- (a) = ROL((a), (s)) + (e); \
- (c) = ROL((c), 10); \
-}
-#define JJ(a, b, c, d, e, x, s) { \
- (a) += J((b), (c), (d)) + (x) + 0xa953fd4eU; \
- (a) = ROL((a), (s)) + (e); \
- (c) = ROL((c), 10); \
-}
-#define FFF(a, b, c, d, e, x, s) { \
- (a) += F((b), (c), (d)) + (x); \
- (a) = ROL((a), (s)) + (e); \
- (c) = ROL((c), 10); \
-}
-#define GGG(a, b, c, d, e, x, s) { \
- (a) += G((b), (c), (d)) + (x) + 0x7a6d76e9U; \
- (a) = ROL((a), (s)) + (e); \
- (c) = ROL((c), 10); \
-}
-#define HHH(a, b, c, d, e, x, s) { \
- (a) += H((b), (c), (d)) + (x) + 0x6d703ef3U; \
- (a) = ROL((a), (s)) + (e); \
- (c) = ROL((c), 10); \
-}
-#define III(a, b, c, d, e, x, s) { \
- (a) += I((b), (c), (d)) + (x) + 0x5c4dd124U; \
- (a) = ROL((a), (s)) + (e); \
- (c) = ROL((c), 10); \
-}
-#define JJJ(a, b, c, d, e, x, s) { \
- (a) += J((b), (c), (d)) + (x) + 0x50a28be6U; \
- (a) = ROL((a), (s)) + (e); \
- (c) = ROL((c), 10); \
-}
-
-/********************************************************************/
-
-void
-RMD160_Init(RMD160_CTX *context)
-{
-
- _DIAGASSERT(context != NULL);
-
- /* ripemd-160 initialization constants */
- context->state[0] = 0x67452301U;
- context->state[1] = 0xefcdab89U;
- context->state[2] = 0x98badcfeU;
- context->state[3] = 0x10325476U;
- context->state[4] = 0xc3d2e1f0U;
- context->length[0] = context->length[1] = 0;
- context->buflen = 0;
-}
-
-/********************************************************************/
-
-void
-RMD160_Transform(uint32_t state[5], const uint32_t block[16])
-{
- uint32_t aa, bb, cc, dd, ee;
- uint32_t aaa, bbb, ccc, ddd, eee;
-
- _DIAGASSERT(state != NULL);
- _DIAGASSERT(block != NULL);
-
- aa = aaa = state[0];
- bb = bbb = state[1];
- cc = ccc = state[2];
- dd = ddd = state[3];
- ee = eee = state[4];
-
- /* round 1 */
- FF(aa, bb, cc, dd, ee, block[ 0], 11);
- FF(ee, aa, bb, cc, dd, block[ 1], 14);
- FF(dd, ee, aa, bb, cc, block[ 2], 15);
- FF(cc, dd, ee, aa, bb, block[ 3], 12);
- FF(bb, cc, dd, ee, aa, block[ 4], 5);
- FF(aa, bb, cc, dd, ee, block[ 5], 8);
- FF(ee, aa, bb, cc, dd, block[ 6], 7);
- FF(dd, ee, aa, bb, cc, block[ 7], 9);
- FF(cc, dd, ee, aa, bb, block[ 8], 11);
- FF(bb, cc, dd, ee, aa, block[ 9], 13);
- FF(aa, bb, cc, dd, ee, block[10], 14);
- FF(ee, aa, bb, cc, dd, block[11], 15);
- FF(dd, ee, aa, bb, cc, block[12], 6);
- FF(cc, dd, ee, aa, bb, block[13], 7);
- FF(bb, cc, dd, ee, aa, block[14], 9);
- FF(aa, bb, cc, dd, ee, block[15], 8);
-
- /* round 2 */
- GG(ee, aa, bb, cc, dd, block[ 7], 7);
- GG(dd, ee, aa, bb, cc, block[ 4], 6);
- GG(cc, dd, ee, aa, bb, block[13], 8);
- GG(bb, cc, dd, ee, aa, block[ 1], 13);
- GG(aa, bb, cc, dd, ee, block[10], 11);
- GG(ee, aa, bb, cc, dd, block[ 6], 9);
- GG(dd, ee, aa, bb, cc, block[15], 7);
- GG(cc, dd, ee, aa, bb, block[ 3], 15);
- GG(bb, cc, dd, ee, aa, block[12], 7);
- GG(aa, bb, cc, dd, ee, block[ 0], 12);
- GG(ee, aa, bb, cc, dd, block[ 9], 15);
- GG(dd, ee, aa, bb, cc, block[ 5], 9);
- GG(cc, dd, ee, aa, bb, block[ 2], 11);
- GG(bb, cc, dd, ee, aa, block[14], 7);
- GG(aa, bb, cc, dd, ee, block[11], 13);
- GG(ee, aa, bb, cc, dd, block[ 8], 12);
-
- /* round 3 */
- HH(dd, ee, aa, bb, cc, block[ 3], 11);
- HH(cc, dd, ee, aa, bb, block[10], 13);
- HH(bb, cc, dd, ee, aa, block[14], 6);
- HH(aa, bb, cc, dd, ee, block[ 4], 7);
- HH(ee, aa, bb, cc, dd, block[ 9], 14);
- HH(dd, ee, aa, bb, cc, block[15], 9);
- HH(cc, dd, ee, aa, bb, block[ 8], 13);
- HH(bb, cc, dd, ee, aa, block[ 1], 15);
- HH(aa, bb, cc, dd, ee, block[ 2], 14);
- HH(ee, aa, bb, cc, dd, block[ 7], 8);
- HH(dd, ee, aa, bb, cc, block[ 0], 13);
- HH(cc, dd, ee, aa, bb, block[ 6], 6);
- HH(bb, cc, dd, ee, aa, block[13], 5);
- HH(aa, bb, cc, dd, ee, block[11], 12);
- HH(ee, aa, bb, cc, dd, block[ 5], 7);
- HH(dd, ee, aa, bb, cc, block[12], 5);
-
- /* round 4 */
- II(cc, dd, ee, aa, bb, block[ 1], 11);
- II(bb, cc, dd, ee, aa, block[ 9], 12);
- II(aa, bb, cc, dd, ee, block[11], 14);
- II(ee, aa, bb, cc, dd, block[10], 15);
- II(dd, ee, aa, bb, cc, block[ 0], 14);
- II(cc, dd, ee, aa, bb, block[ 8], 15);
- II(bb, cc, dd, ee, aa, block[12], 9);
- II(aa, bb, cc, dd, ee, block[ 4], 8);
- II(ee, aa, bb, cc, dd, block[13], 9);
- II(dd, ee, aa, bb, cc, block[ 3], 14);
- II(cc, dd, ee, aa, bb, block[ 7], 5);
- II(bb, cc, dd, ee, aa, block[15], 6);
- II(aa, bb, cc, dd, ee, block[14], 8);
- II(ee, aa, bb, cc, dd, block[ 5], 6);
- II(dd, ee, aa, bb, cc, block[ 6], 5);
- II(cc, dd, ee, aa, bb, block[ 2], 12);
-
- /* round 5 */
- JJ(bb, cc, dd, ee, aa, block[ 4], 9);
- JJ(aa, bb, cc, dd, ee, block[ 0], 15);
- JJ(ee, aa, bb, cc, dd, block[ 5], 5);
- JJ(dd, ee, aa, bb, cc, block[ 9], 11);
- JJ(cc, dd, ee, aa, bb, block[ 7], 6);
- JJ(bb, cc, dd, ee, aa, block[12], 8);
- JJ(aa, bb, cc, dd, ee, block[ 2], 13);
- JJ(ee, aa, bb, cc, dd, block[10], 12);
- JJ(dd, ee, aa, bb, cc, block[14], 5);
- JJ(cc, dd, ee, aa, bb, block[ 1], 12);
- JJ(bb, cc, dd, ee, aa, block[ 3], 13);
- JJ(aa, bb, cc, dd, ee, block[ 8], 14);
- JJ(ee, aa, bb, cc, dd, block[11], 11);
- JJ(dd, ee, aa, bb, cc, block[ 6], 8);
- JJ(cc, dd, ee, aa, bb, block[15], 5);
- JJ(bb, cc, dd, ee, aa, block[13], 6);
-
- /* parallel round 1 */
- JJJ(aaa, bbb, ccc, ddd, eee, block[ 5], 8);
- JJJ(eee, aaa, bbb, ccc, ddd, block[14], 9);
- JJJ(ddd, eee, aaa, bbb, ccc, block[ 7], 9);
- JJJ(ccc, ddd, eee, aaa, bbb, block[ 0], 11);
- JJJ(bbb, ccc, ddd, eee, aaa, block[ 9], 13);
- JJJ(aaa, bbb, ccc, ddd, eee, block[ 2], 15);
- JJJ(eee, aaa, bbb, ccc, ddd, block[11], 15);
- JJJ(ddd, eee, aaa, bbb, ccc, block[ 4], 5);
- JJJ(ccc, ddd, eee, aaa, bbb, block[13], 7);
- JJJ(bbb, ccc, ddd, eee, aaa, block[ 6], 7);
- JJJ(aaa, bbb, ccc, ddd, eee, block[15], 8);
- JJJ(eee, aaa, bbb, ccc, ddd, block[ 8], 11);
- JJJ(ddd, eee, aaa, bbb, ccc, block[ 1], 14);
- JJJ(ccc, ddd, eee, aaa, bbb, block[10], 14);
- JJJ(bbb, ccc, ddd, eee, aaa, block[ 3], 12);
- JJJ(aaa, bbb, ccc, ddd, eee, block[12], 6);
-
- /* parallel round 2 */
- III(eee, aaa, bbb, ccc, ddd, block[ 6], 9);
- III(ddd, eee, aaa, bbb, ccc, block[11], 13);
- III(ccc, ddd, eee, aaa, bbb, block[ 3], 15);
- III(bbb, ccc, ddd, eee, aaa, block[ 7], 7);
- III(aaa, bbb, ccc, ddd, eee, block[ 0], 12);
- III(eee, aaa, bbb, ccc, ddd, block[13], 8);
- III(ddd, eee, aaa, bbb, ccc, block[ 5], 9);
- III(ccc, ddd, eee, aaa, bbb, block[10], 11);
- III(bbb, ccc, ddd, eee, aaa, block[14], 7);
- III(aaa, bbb, ccc, ddd, eee, block[15], 7);
- III(eee, aaa, bbb, ccc, ddd, block[ 8], 12);
- III(ddd, eee, aaa, bbb, ccc, block[12], 7);
- III(ccc, ddd, eee, aaa, bbb, block[ 4], 6);
- III(bbb, ccc, ddd, eee, aaa, block[ 9], 15);
- III(aaa, bbb, ccc, ddd, eee, block[ 1], 13);
- III(eee, aaa, bbb, ccc, ddd, block[ 2], 11);
-
- /* parallel round 3 */
- HHH(ddd, eee, aaa, bbb, ccc, block[15], 9);
- HHH(ccc, ddd, eee, aaa, bbb, block[ 5], 7);
- HHH(bbb, ccc, ddd, eee, aaa, block[ 1], 15);
- HHH(aaa, bbb, ccc, ddd, eee, block[ 3], 11);
- HHH(eee, aaa, bbb, ccc, ddd, block[ 7], 8);
- HHH(ddd, eee, aaa, bbb, ccc, block[14], 6);
- HHH(ccc, ddd, eee, aaa, bbb, block[ 6], 6);
- HHH(bbb, ccc, ddd, eee, aaa, block[ 9], 14);
- HHH(aaa, bbb, ccc, ddd, eee, block[11], 12);
- HHH(eee, aaa, bbb, ccc, ddd, block[ 8], 13);
- HHH(ddd, eee, aaa, bbb, ccc, block[12], 5);
- HHH(ccc, ddd, eee, aaa, bbb, block[ 2], 14);
- HHH(bbb, ccc, ddd, eee, aaa, block[10], 13);
- HHH(aaa, bbb, ccc, ddd, eee, block[ 0], 13);
- HHH(eee, aaa, bbb, ccc, ddd, block[ 4], 7);
- HHH(ddd, eee, aaa, bbb, ccc, block[13], 5);
-
- /* parallel round 4 */
- GGG(ccc, ddd, eee, aaa, bbb, block[ 8], 15);
- GGG(bbb, ccc, ddd, eee, aaa, block[ 6], 5);
- GGG(aaa, bbb, ccc, ddd, eee, block[ 4], 8);
- GGG(eee, aaa, bbb, ccc, ddd, block[ 1], 11);
- GGG(ddd, eee, aaa, bbb, ccc, block[ 3], 14);
- GGG(ccc, ddd, eee, aaa, bbb, block[11], 14);
- GGG(bbb, ccc, ddd, eee, aaa, block[15], 6);
- GGG(aaa, bbb, ccc, ddd, eee, block[ 0], 14);
- GGG(eee, aaa, bbb, ccc, ddd, block[ 5], 6);
- GGG(ddd, eee, aaa, bbb, ccc, block[12], 9);
- GGG(ccc, ddd, eee, aaa, bbb, block[ 2], 12);
- GGG(bbb, ccc, ddd, eee, aaa, block[13], 9);
- GGG(aaa, bbb, ccc, ddd, eee, block[ 9], 12);
- GGG(eee, aaa, bbb, ccc, ddd, block[ 7], 5);
- GGG(ddd, eee, aaa, bbb, ccc, block[10], 15);
- GGG(ccc, ddd, eee, aaa, bbb, block[14], 8);
-
- /* parallel round 5 */
- FFF(bbb, ccc, ddd, eee, aaa, block[12] , 8);
- FFF(aaa, bbb, ccc, ddd, eee, block[15] , 5);
- FFF(eee, aaa, bbb, ccc, ddd, block[10] , 12);
- FFF(ddd, eee, aaa, bbb, ccc, block[ 4] , 9);
- FFF(ccc, ddd, eee, aaa, bbb, block[ 1] , 12);
- FFF(bbb, ccc, ddd, eee, aaa, block[ 5] , 5);
- FFF(aaa, bbb, ccc, ddd, eee, block[ 8] , 14);
- FFF(eee, aaa, bbb, ccc, ddd, block[ 7] , 6);
- FFF(ddd, eee, aaa, bbb, ccc, block[ 6] , 8);
- FFF(ccc, ddd, eee, aaa, bbb, block[ 2] , 13);
- FFF(bbb, ccc, ddd, eee, aaa, block[13] , 6);
- FFF(aaa, bbb, ccc, ddd, eee, block[14] , 5);
- FFF(eee, aaa, bbb, ccc, ddd, block[ 0] , 15);
- FFF(ddd, eee, aaa, bbb, ccc, block[ 3] , 13);
- FFF(ccc, ddd, eee, aaa, bbb, block[ 9] , 11);
- FFF(bbb, ccc, ddd, eee, aaa, block[11] , 11);
-
- /* combine results */
- ddd += cc + state[1]; /* final result for state[0] */
- state[1] = state[2] + dd + eee;
- state[2] = state[3] + ee + aaa;
- state[3] = state[4] + aa + bbb;
- state[4] = state[0] + bb + ccc;
- state[0] = ddd;
-}
-
-/********************************************************************/
-
-void
-RMD160_Update(RMD160_CTX *context, const uint8_t *data, size_t nbytes)
-{
- uint32_t X[16];
- uint32_t ofs = 0;
- uint32_t i;
-#ifdef WORDS_BIGENDIAN
- uint32_t j;
-#endif
-
- _DIAGASSERT(context != NULL);
- _DIAGASSERT(data != NULL);
-
- /* update length[] */
- if (context->length[0] + nbytes < context->length[0])
- context->length[1]++; /* overflow to msb of length */
- context->length[0] += nbytes;
-
- (void)memset(X, 0, sizeof(X));
-
- if ( context->buflen + nbytes < 64 )
- {
- (void)memcpy(context->bbuffer + context->buflen, data, nbytes);
- context->buflen += nbytes;
- }
- else
- {
- /* process first block */
- ofs = 64 - context->buflen;
- (void)memcpy(context->bbuffer + context->buflen, data, ofs);
-#ifndef WORDS_BIGENDIAN
- (void)memcpy(X, context->bbuffer, sizeof(X));
-#else
- for (j=0; j < 16; j++)
- X[j] = BYTES_TO_DWORD(context->bbuffer + (4 * j));
-#endif
- RMD160_Transform(context->state, X);
- nbytes -= ofs;
-
- /* process remaining complete blocks */
- for (i = 0; i < (nbytes >> 6); i++) {
-#ifndef WORDS_BIGENDIAN
- (void)memcpy(X, data + (64 * i) + ofs, sizeof(X));
-#else
- for (j=0; j < 16; j++)
- X[j] = BYTES_TO_DWORD(data + (64 * i) + (4 * j) + ofs);
-#endif
- RMD160_Transform(context->state, X);
- }
-
- /*
- * Put last bytes from data into context's buffer
- */
- context->buflen = nbytes & 63;
- memcpy(context->bbuffer, data + (64 * i) + ofs, context->buflen);
- }
-}
-
-/********************************************************************/
-
-void
-RMD160_Final(uint8_t digest[20], RMD160_CTX *context)
-{
- uint32_t i;
- uint32_t X[16];
-#ifdef WORDS_BIGENDIAN
- uint32_t j;
-#endif
-
- _DIAGASSERT(digest != NULL);
- _DIAGASSERT(context != NULL);
-
- /* append the bit m_n == 1 */
- context->bbuffer[context->buflen] = (uint8_t)'\200';
-
- (void)memset(context->bbuffer + context->buflen + 1, 0,
- 63 - context->buflen);
-#ifndef WORDS_BIGENDIAN
- (void)memcpy(X, context->bbuffer, sizeof(X));
-#else
- for (j=0; j < 16; j++)
- X[j] = BYTES_TO_DWORD(context->bbuffer + (4 * j));
-#endif
- if ((context->buflen) > 55) {
- /* length goes to next block */
- RMD160_Transform(context->state, X);
- (void)memset(X, 0, sizeof(X));
- }
-
- /* append length in bits */
- X[14] = context->length[0] << 3;
- X[15] = (context->length[0] >> 29) |
- (context->length[1] << 3);
- RMD160_Transform(context->state, X);
-
- if (digest != NULL) {
- for (i = 0; i < 20; i += 4) {
- /* extracts the 8 least significant bits. */
- digest[i] = context->state[i>>2];
- digest[i + 1] = (context->state[i>>2] >> 8);
- digest[i + 2] = (context->state[i>>2] >> 16);
- digest[i + 3] = (context->state[i>>2] >> 24);
- }
- }
-}
-
-int RMD160_Equal(RMD160_CTX* pctx1, RMD160_CTX* pctx2) {
- return pctx1->buflen == pctx2->buflen
- && memcmp(pctx1->length, pctx2->length, sizeof(pctx1->length)) == 0
- && memcmp(pctx1->state, pctx2->state, sizeof(pctx1->state)) == 0
- && memcmp(pctx1->bbuffer, pctx2->bbuffer, sizeof(pctx1->bbuffer)) == 0;
-}
-
-/************************ end of file rmd160.c **********************/
diff --git a/ext/digest/rmd160/rmd160.h b/ext/digest/rmd160/rmd160.h
deleted file mode 100644
index 24f9a025f0..0000000000
--- a/ext/digest/rmd160/rmd160.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/* $NetBSD: rmd160.h,v 1.2 2000/07/07 10:47:06 ad Exp $ */
-/* $RoughId: rmd160.h,v 1.3 2002/02/24 08:14:31 knu Exp $ */
-/* $Id$ */
-
-/********************************************************************\
- *
- * FILE: rmd160.h
- *
- * CONTENTS: Header file for a sample C-implementation of the
- * RIPEMD-160 hash-function.
- * TARGET: any computer with an ANSI C compiler
- *
- * AUTHOR: Antoon Bosselaers, ESAT-COSIC
- * DATE: 1 March 1996
- * VERSION: 1.0
- *
- * Copyright (c) Katholieke Universiteit Leuven
- * 1996, All Rights Reserved
- *
-\********************************************************************/
-
-/*
- * from OpenBSD: rmd160.h,v 1.4 1999/08/16 09:59:04 millert Exp
- */
-
-#ifndef _RMD160_H_
-#define _RMD160_H_
-
-#include "defs.h"
-
-typedef struct {
- uint32_t state[5]; /* state (ABCDE) */
- uint32_t length[2]; /* number of bits */
- uint8_t bbuffer[64]; /* overflow buffer */
- uint32_t buflen; /* number of chars in bbuffer */
-} RMD160_CTX;
-
-#ifdef RUBY
-#define RMD160_Init rb_Digest_RMD160_Init
-#define RMD160_Transform rb_Digest_RMD160_Transform
-#define RMD160_Update rb_Digest_RMD160_Update
-#define RMD160_Final rb_Digest_RMD160_Final
-#define RMD160_Equal rb_Digest_RMD160_Equal
-#ifndef _KERNEL
-#define RMD160_End rb_Digest_RMD160_End
-#define RMD160_File rb_Digest_RMD160_File
-#define RMD160_Data rb_Digest_RMD160_Data
-#endif /* _KERNEL */
-#endif
-
-__BEGIN_DECLS
-void RMD160_Init _((RMD160_CTX *));
-void RMD160_Transform _((uint32_t[5], const uint32_t[16]));
-void RMD160_Update _((RMD160_CTX *, const uint8_t *, size_t));
-void RMD160_Final _((uint8_t[20], RMD160_CTX *));
-int RMD160_Equal _((RMD160_CTX *, RMD160_CTX *));
-#ifndef _KERNEL
-char *RMD160_End _((RMD160_CTX *, char *));
-char *RMD160_File _((char *, char *));
-char *RMD160_Data _((const uint8_t *, size_t, char *));
-#endif /* _KERNEL */
-__END_DECLS
-
-#define RMD160_BLOCK_LENGTH 64
-#define RMD160_DIGEST_LENGTH 20
-#define RMD160_DIGEST_STRING_LENGTH (RMD160_DIGEST_LENGTH * 2 + 1)
-
-#endif /* !_RMD160_H_ */
diff --git a/ext/digest/rmd160/rmd160hl.c b/ext/digest/rmd160/rmd160hl.c
deleted file mode 100644
index 4c5e0217d9..0000000000
--- a/ext/digest/rmd160/rmd160hl.c
+++ /dev/null
@@ -1,96 +0,0 @@
-/* $NetBSD: rmd160hl.c,v 1.1.1.1 2001/03/06 11:21:05 agc Exp $ */
-/* $RoughId: rmd160hl.c,v 1.2 2001/07/13 19:49:10 knu Exp $ */
-/* $Id$ */
-
-/* rmd160hl.c
- * ----------------------------------------------------------------------------
- * "THE BEER-WARE LICENSE" (Revision 42):
- * <phk@login.dkuug.dk> wrote this file. As long as you retain this notice you
- * can do whatever you want with this stuff. If we meet some day, and you think
- * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp
- * ----------------------------------------------------------------------------
- *
- * from OpenBSD: rmd160hl.c,v 1.2 1999/08/17 09:13:12 millert Exp $
- */
-
-#include "rmd160.h"
-
-#ifndef lint
-/* __RCSID("$NetBSD: rmd160hl.c,v 1.1.1.1 2001/03/06 11:21:05 agc Exp $"); */
-#endif /* not lint */
-
-/* #include "namespace.h" */
-
-#include <assert.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <stdio.h>
-#include <stdlib.h>
-#if defined(HAVE_UNISTD_H)
-# include <unistd.h>
-#endif
-
-#ifndef _DIAGASSERT
-#define _DIAGASSERT(cond) assert(cond)
-#endif
-
-
-char *
-RMD160_End(RMD160_CTX *ctx, char *buf)
-{
- size_t i;
- char *p = buf;
- uint8_t digest[20];
- static const char hex[]="0123456789abcdef";
-
- _DIAGASSERT(ctx != NULL);
- /* buf may be NULL */
-
- if (p == NULL && (p = malloc(41)) == NULL)
- return 0;
-
- RMD160_Final(digest,ctx);
- for (i = 0; i < 20; i++) {
- p[i + i] = hex[(uint32_t)digest[i] >> 4];
- p[i + i + 1] = hex[digest[i] & 0x0f];
- }
- p[i + i] = '\0';
- return(p);
-}
-
-char *
-RMD160_File(char *filename, char *buf)
-{
- uint8_t buffer[BUFSIZ];
- RMD160_CTX ctx;
- int fd, num, oerrno;
-
- _DIAGASSERT(filename != NULL);
- /* XXX: buf may be NULL ? */
-
- RMD160_Init(&ctx);
-
- if ((fd = open(filename, O_RDONLY)) < 0)
- return(0);
-
- while ((num = read(fd, buffer, sizeof(buffer))) > 0)
- RMD160_Update(&ctx, buffer, (size_t)num);
-
- oerrno = errno;
- close(fd);
- errno = oerrno;
- return(num < 0 ? 0 : RMD160_End(&ctx, buf));
-}
-
-char *
-RMD160_Data(const uint8_t *data, size_t len, char *buf)
-{
- RMD160_CTX ctx;
-
- _DIAGASSERT(data != NULL);
- /* XXX: buf may be NULL ? */
-
- RMD160_Init(&ctx);
- RMD160_Update(&ctx, data, len);
- return(RMD160_End(&ctx, buf));
-}
diff --git a/ext/digest/rmd160/rmd160init.c b/ext/digest/rmd160/rmd160init.c
deleted file mode 100644
index 6955c2b64b..0000000000
--- a/ext/digest/rmd160/rmd160init.c
+++ /dev/null
@@ -1,34 +0,0 @@
-/* $RoughId: rmd160init.c,v 1.3 2001/07/13 20:00:43 knu Exp $ */
-/* $Id$ */
-
-#include "digest.h"
-#include "rmd160.h"
-
-static algo_t rmd160 = {
- RMD160_DIGEST_LENGTH,
- sizeof(RMD160_CTX),
- (hash_init_func_t)RMD160_Init,
- (hash_update_func_t)RMD160_Update,
- (hash_end_func_t)RMD160_End,
- (hash_final_func_t)RMD160_Final,
- (hash_equal_func_t)RMD160_Equal,
-};
-
-void
-Init_rmd160()
-{
- VALUE mDigest, cDigest_Base, cDigest_RMD160;
- ID id_metadata;
-
- rb_require("digest.so");
-
- mDigest = rb_path2class("Digest");
- cDigest_Base = rb_path2class("Digest::Base");
-
- cDigest_RMD160 = rb_define_class_under(mDigest, "RMD160", cDigest_Base);
-
- id_metadata = rb_intern("metadata");
-
- rb_cvar_set(cDigest_RMD160, id_metadata,
- Data_Wrap_Struct(rb_cObject, 0, 0, &rmd160), Qtrue);
-}
diff --git a/ext/digest/sha1/.cvsignore b/ext/digest/sha1/.cvsignore
deleted file mode 100644
index fc802ff1c2..0000000000
--- a/ext/digest/sha1/.cvsignore
+++ /dev/null
@@ -1,2 +0,0 @@
-Makefile
-mkmf.log
diff --git a/ext/digest/sha1/MANIFEST b/ext/digest/sha1/MANIFEST
deleted file mode 100644
index 99b83addfd..0000000000
--- a/ext/digest/sha1/MANIFEST
+++ /dev/null
@@ -1,6 +0,0 @@
-extconf.rb
-sha1.c
-sha1.h
-sha1hl.c
-sha1init.c
-depend
diff --git a/ext/digest/sha1/depend b/ext/digest/sha1/depend
deleted file mode 100644
index 31a5da06cf..0000000000
--- a/ext/digest/sha1/depend
+++ /dev/null
@@ -1,7 +0,0 @@
-sha1.o: sha1.c sha1.h $(srcdir)/../defs.h $(hdrdir)/ruby.h \
- $(topdir)/config.h $(hdrdir)/defines.h $(hdrdir)/intern.h
-sha1hl.o: sha1hl.c sha1.h $(srcdir)/../defs.h $(hdrdir)/ruby.h \
- $(topdir)/config.h $(hdrdir)/defines.h $(hdrdir)/intern.h
-sha1init.o: sha1init.c $(srcdir)/../digest.h $(hdrdir)/ruby.h \
- $(topdir)/config.h $(hdrdir)/defines.h $(hdrdir)/intern.h \
- sha1.h $(srcdir)/../defs.h
diff --git a/ext/digest/sha1/extconf.rb b/ext/digest/sha1/extconf.rb
deleted file mode 100644
index 45e374e369..0000000000
--- a/ext/digest/sha1/extconf.rb
+++ /dev/null
@@ -1,20 +0,0 @@
-# $RoughId: extconf.rb,v 1.3 2001/08/14 19:54:51 knu Exp $
-# $Id$
-
-require "mkmf"
-
-$CFLAGS << " -DHAVE_CONFIG_H -I#{File.dirname(__FILE__)}/.."
-
-$objs = [
- "sha1.#{$OBJEXT}",
- "sha1hl.#{$OBJEXT}",
- "sha1init.#{$OBJEXT}",
-]
-
-have_header("sys/cdefs.h")
-
-have_header("inttypes.h")
-
-have_header("unistd.h")
-
-create_makefile("digest/sha1")
diff --git a/ext/digest/sha1/sha1.c b/ext/digest/sha1/sha1.c
deleted file mode 100644
index 1012ef8751..0000000000
--- a/ext/digest/sha1/sha1.c
+++ /dev/null
@@ -1,283 +0,0 @@
-/* $NetBSD: sha1.c,v 1.2 2001/03/22 09:51:48 agc Exp $ */
-/* $OpenBSD: sha1.c,v 1.9 1997/07/23 21:12:32 kstailey Exp $ */
-/* $RoughId: sha1.c,v 1.2 2001/07/13 19:49:10 knu Exp $ */
-/* $Id$ */
-
-/*
- * SHA-1 in C
- * By Steve Reid <steve@edmweb.com>
- * 100% Public Domain
- *
- * Test Vectors (from FIPS PUB 180-1)
- * "abc"
- * A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D
- * "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
- * 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1
- * A million repetitions of "a"
- * 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F
- */
-
-#include "sha1.h"
-
-#define SHA1HANDSOFF /* Copies data before messing with it. */
-
-#if defined(_KERNEL) || defined(_STANDALONE)
-#include <sys/param.h>
-#include <sys/systm.h>
-#define _DIAGASSERT(x) (void)0
-#else
-/* #include "namespace.h" */
-#include <assert.h>
-#include <string.h>
-#endif
-
-#ifndef _DIAGASSERT
-#define _DIAGASSERT(cond) assert(cond)
-#endif
-
-/*
- * XXX Kludge until there is resolution regarding mem*() functions
- * XXX in the kernel.
- */
-#if defined(_KERNEL) || defined(_STANDALONE)
-#define memcpy(s, d, l) bcopy((d), (s), (l))
-#endif
-
-#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
-
-/*
- * blk0() and blk() perform the initial expand.
- * I got the idea of expanding during the round function from SSLeay
- */
-#ifndef WORDS_BIGENDIAN
-# define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \
- |(rol(block->l[i],8)&0x00FF00FF))
-#else
-# define blk0(i) block->l[i]
-#endif
-#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
- ^block->l[(i+2)&15]^block->l[i&15],1))
-
-/*
- * (R0+R1), R2, R3, R4 are the different operations (rounds) used in SHA1
- */
-#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30);
-#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
-#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
-#define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
-#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
-
-
-typedef union {
- uint8_t c[64];
- uint32_t l[16];
-} CHAR64LONG16;
-
-#ifdef __sparc_v9__
-void do_R01(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *);
-void do_R2(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *);
-void do_R3(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *);
-void do_R4(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *);
-
-#define nR0(v,w,x,y,z,i) R0(*v,*w,*x,*y,*z,i)
-#define nR1(v,w,x,y,z,i) R1(*v,*w,*x,*y,*z,i)
-#define nR2(v,w,x,y,z,i) R2(*v,*w,*x,*y,*z,i)
-#define nR3(v,w,x,y,z,i) R3(*v,*w,*x,*y,*z,i)
-#define nR4(v,w,x,y,z,i) R4(*v,*w,*x,*y,*z,i)
-
-void
-do_R01(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *block)
-{
- nR0(a,b,c,d,e, 0); nR0(e,a,b,c,d, 1); nR0(d,e,a,b,c, 2); nR0(c,d,e,a,b, 3);
- nR0(b,c,d,e,a, 4); nR0(a,b,c,d,e, 5); nR0(e,a,b,c,d, 6); nR0(d,e,a,b,c, 7);
- nR0(c,d,e,a,b, 8); nR0(b,c,d,e,a, 9); nR0(a,b,c,d,e,10); nR0(e,a,b,c,d,11);
- nR0(d,e,a,b,c,12); nR0(c,d,e,a,b,13); nR0(b,c,d,e,a,14); nR0(a,b,c,d,e,15);
- nR1(e,a,b,c,d,16); nR1(d,e,a,b,c,17); nR1(c,d,e,a,b,18); nR1(b,c,d,e,a,19);
-}
-
-void
-do_R2(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *block)
-{
- nR2(a,b,c,d,e,20); nR2(e,a,b,c,d,21); nR2(d,e,a,b,c,22); nR2(c,d,e,a,b,23);
- nR2(b,c,d,e,a,24); nR2(a,b,c,d,e,25); nR2(e,a,b,c,d,26); nR2(d,e,a,b,c,27);
- nR2(c,d,e,a,b,28); nR2(b,c,d,e,a,29); nR2(a,b,c,d,e,30); nR2(e,a,b,c,d,31);
- nR2(d,e,a,b,c,32); nR2(c,d,e,a,b,33); nR2(b,c,d,e,a,34); nR2(a,b,c,d,e,35);
- nR2(e,a,b,c,d,36); nR2(d,e,a,b,c,37); nR2(c,d,e,a,b,38); nR2(b,c,d,e,a,39);
-}
-
-void
-do_R3(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *block)
-{
- nR3(a,b,c,d,e,40); nR3(e,a,b,c,d,41); nR3(d,e,a,b,c,42); nR3(c,d,e,a,b,43);
- nR3(b,c,d,e,a,44); nR3(a,b,c,d,e,45); nR3(e,a,b,c,d,46); nR3(d,e,a,b,c,47);
- nR3(c,d,e,a,b,48); nR3(b,c,d,e,a,49); nR3(a,b,c,d,e,50); nR3(e,a,b,c,d,51);
- nR3(d,e,a,b,c,52); nR3(c,d,e,a,b,53); nR3(b,c,d,e,a,54); nR3(a,b,c,d,e,55);
- nR3(e,a,b,c,d,56); nR3(d,e,a,b,c,57); nR3(c,d,e,a,b,58); nR3(b,c,d,e,a,59);
-}
-
-void
-do_R4(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *block)
-{
- nR4(a,b,c,d,e,60); nR4(e,a,b,c,d,61); nR4(d,e,a,b,c,62); nR4(c,d,e,a,b,63);
- nR4(b,c,d,e,a,64); nR4(a,b,c,d,e,65); nR4(e,a,b,c,d,66); nR4(d,e,a,b,c,67);
- nR4(c,d,e,a,b,68); nR4(b,c,d,e,a,69); nR4(a,b,c,d,e,70); nR4(e,a,b,c,d,71);
- nR4(d,e,a,b,c,72); nR4(c,d,e,a,b,73); nR4(b,c,d,e,a,74); nR4(a,b,c,d,e,75);
- nR4(e,a,b,c,d,76); nR4(d,e,a,b,c,77); nR4(c,d,e,a,b,78); nR4(b,c,d,e,a,79);
-}
-#endif
-
-/*
- * Hash a single 512-bit block. This is the core of the algorithm.
- */
-void SHA1_Transform(state, buffer)
- uint32_t state[5];
- const uint8_t buffer[64];
-{
- uint32_t a, b, c, d, e;
- CHAR64LONG16 *block;
-
-#ifdef SHA1HANDSOFF
- CHAR64LONG16 workspace;
-#endif
-
- _DIAGASSERT(buffer != 0);
- _DIAGASSERT(state != 0);
-
-#ifdef SHA1HANDSOFF
- block = &workspace;
- (void)memcpy(block, buffer, 64);
-#else
- block = (CHAR64LONG16 *)(void *)buffer;
-#endif
-
- /* Copy context->state[] to working vars */
- a = state[0];
- b = state[1];
- c = state[2];
- d = state[3];
- e = state[4];
-
-#ifdef __sparc_v9__
- do_R01(&a, &b, &c, &d, &e, block);
- do_R2(&a, &b, &c, &d, &e, block);
- do_R3(&a, &b, &c, &d, &e, block);
- do_R4(&a, &b, &c, &d, &e, block);
-#else
- /* 4 rounds of 20 operations each. Loop unrolled. */
- R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3);
- R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7);
- R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11);
- R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15);
- R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19);
- R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23);
- R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27);
- R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31);
- R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35);
- R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39);
- R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43);
- R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47);
- R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51);
- R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55);
- R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59);
- R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63);
- R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67);
- R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71);
- R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75);
- R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79);
-#endif
-
- /* Add the working vars back into context.state[] */
- state[0] += a;
- state[1] += b;
- state[2] += c;
- state[3] += d;
- state[4] += e;
-
- /* Wipe variables */
- a = b = c = d = e = 0;
-}
-
-
-/*
- * SHA1_Init - Initialize new context
- */
-void SHA1_Init(context)
- SHA1_CTX *context;
-{
-
- _DIAGASSERT(context != 0);
-
- /* SHA1 initialization constants */
- context->state[0] = 0x67452301;
- context->state[1] = 0xEFCDAB89;
- context->state[2] = 0x98BADCFE;
- context->state[3] = 0x10325476;
- context->state[4] = 0xC3D2E1F0;
- context->count[0] = context->count[1] = 0;
-}
-
-
-/*
- * Run your data through this.
- */
-void SHA1_Update(context, data, len)
- SHA1_CTX *context;
- const uint8_t *data;
- size_t len;
-{
- uint32_t i, j;
-
- _DIAGASSERT(context != 0);
- _DIAGASSERT(data != 0);
-
- j = context->count[0];
- if ((context->count[0] += len << 3) < j)
- context->count[1] += (len>>29)+1;
- j = (j >> 3) & 63;
- if ((j + len) > 63) {
- (void)memcpy(&context->buffer[j], data, (i = 64-j));
- SHA1_Transform(context->state, context->buffer);
- for ( ; i + 63 < len; i += 64)
- SHA1_Transform(context->state, &data[i]);
- j = 0;
- } else {
- i = 0;
- }
- (void)memcpy(&context->buffer[j], &data[i], len - i);
-}
-
-
-/*
- * Add padding and return the message digest.
- */
-void SHA1_Final(digest, context)
- uint8_t digest[20];
- SHA1_CTX* context;
-{
- size_t i;
- uint8_t finalcount[8];
-
- _DIAGASSERT(digest != 0);
- _DIAGASSERT(context != 0);
-
- for (i = 0; i < 8; i++) {
- finalcount[i] = (uint8_t)((context->count[(i >= 4 ? 0 : 1)]
- >> ((3-(i & 3)) * 8) ) & 255); /* Endian independent */
- }
- SHA1_Update(context, (const uint8_t *)"\200", 1);
- while ((context->count[0] & 504) != 448)
- SHA1_Update(context, (const uint8_t *)"\0", 1);
- SHA1_Update(context, finalcount, 8); /* Should cause a SHA1_Transform() */
-
- if (digest) {
- for (i = 0; i < 20; i++)
- digest[i] = (uint8_t)
- ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
- }
-}
-
-int SHA1_Equal(SHA1_CTX* pctx1, SHA1_CTX* pctx2) {
- return memcmp(pctx1->count, pctx2->count, sizeof(pctx1->count)) == 0
- && memcmp(pctx1->state, pctx2->state, sizeof(pctx1->state)) == 0
- && memcmp(pctx1->buffer, pctx2->buffer, sizeof(pctx1->buffer)) == 0;
-}
diff --git a/ext/digest/sha1/sha1.h b/ext/digest/sha1/sha1.h
deleted file mode 100644
index 2303cecc2b..0000000000
--- a/ext/digest/sha1/sha1.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/* $NetBSD: sha1.h,v 1.2 1998/05/29 22:55:44 thorpej Exp $ */
-/* $RoughId: sha1.h,v 1.3 2002/02/24 08:14:32 knu Exp $ */
-/* $Id$ */
-
-/*
- * SHA-1 in C
- * By Steve Reid <steve@edmweb.com>
- * 100% Public Domain
- */
-
-#ifndef _SYS_SHA1_H_
-#define _SYS_SHA1_H_
-
-#include "defs.h"
-
-typedef struct {
- uint32_t state[5];
- uint32_t count[2];
- uint8_t buffer[64];
-} SHA1_CTX;
-
-#ifdef RUBY
-#define SHA1_Transform rb_Digest_SHA1_Transform
-#define SHA1_Init rb_Digest_SHA1_Init
-#define SHA1_Update rb_Digest_SHA1_Update
-#define SHA1_Final rb_Digest_SHA1_Final
-#define SHA1_Equal rb_Digest_SHA1_Equal
-#ifndef _KERNEL
-#define SHA1_End rb_Digest_SHA1_End
-#define SHA1_File rb_Digest_SHA1_File
-#define SHA1_Data rb_Digest_SHA1_Data
-#endif /* _KERNEL */
-#endif
-
-void SHA1_Transform _((uint32_t state[5], const uint8_t buffer[64]));
-void SHA1_Init _((SHA1_CTX *context));
-void SHA1_Update _((SHA1_CTX *context, const uint8_t *data, size_t len));
-void SHA1_Final _((uint8_t digest[20], SHA1_CTX *context));
-int SHA1_Equal _((SHA1_CTX *pctx1, SHA1_CTX *pctx2));
-#ifndef _KERNEL
-char *SHA1_End _((SHA1_CTX *, char *));
-char *SHA1_File _((char *, char *));
-char *SHA1_Data _((const uint8_t *, size_t, char *));
-#endif /* _KERNEL */
-
-#define SHA1_BLOCK_LENGTH 64
-#define SHA1_DIGEST_LENGTH 20
-#define SHA1_DIGEST_STRING_LENGTH (SHA1_DIGEST_LENGTH * 2 + 1)
-
-#endif /* _SYS_SHA1_H_ */
diff --git a/ext/digest/sha1/sha1hl.c b/ext/digest/sha1/sha1hl.c
deleted file mode 100644
index d1a236b22c..0000000000
--- a/ext/digest/sha1/sha1hl.c
+++ /dev/null
@@ -1,102 +0,0 @@
-/* $NetBSD: sha1hl.c,v 1.2 2001/03/10 15:55:14 tron Exp $ */
-/* $RoughId: sha1hl.c,v 1.2 2001/07/13 19:49:10 knu Exp $ */
-/* $Id$ */
-
-/* sha1hl.c
- * ----------------------------------------------------------------------------
- * "THE BEER-WARE LICENSE" (Revision 42):
- * <phk@login.dkuug.dk> wrote this file. As long as you retain this notice you
- * can do whatever you want with this stuff. If we meet some day, and you think
- * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp
- * ----------------------------------------------------------------------------
- */
-
-/* #include "namespace.h" */
-
-#include "sha1.h"
-#include <fcntl.h>
-
-#include <assert.h>
-#include <errno.h>
-#include <stdio.h>
-#include <stdlib.h>
-#if defined(HAVE_UNISTD_H)
-# include <unistd.h>
-#endif
-
-#if defined(LIBC_SCCS) && !defined(lint)
-/* __RCSID("$NetBSD: sha1hl.c,v 1.2 2001/03/10 15:55:14 tron Exp $"); */
-#endif /* LIBC_SCCS and not lint */
-
-#ifndef _DIAGASSERT
-#define _DIAGASSERT(cond) assert(cond)
-#endif
-
-
-/* ARGSUSED */
-char *
-SHA1_End(ctx, buf)
- SHA1_CTX *ctx;
- char *buf;
-{
- int i;
- char *p = buf;
- uint8_t digest[20];
- static const char hex[]="0123456789abcdef";
-
- _DIAGASSERT(ctx != NULL);
- /* buf may be NULL */
-
- if (p == NULL && (p = malloc(41)) == NULL)
- return 0;
-
- SHA1_Final(digest,ctx);
- for (i = 0; i < 20; i++) {
- p[i + i] = hex[((uint32_t)digest[i]) >> 4];
- p[i + i + 1] = hex[digest[i] & 0x0f];
- }
- p[i + i] = '\0';
- return(p);
-}
-
-char *
-SHA1_File (filename, buf)
- char *filename;
- char *buf;
-{
- uint8_t buffer[BUFSIZ];
- SHA1_CTX ctx;
- int fd, num, oerrno;
-
- _DIAGASSERT(filename != NULL);
- /* XXX: buf may be NULL ? */
-
- SHA1_Init(&ctx);
-
- if ((fd = open(filename,O_RDONLY)) < 0)
- return(0);
-
- while ((num = read(fd, buffer, sizeof(buffer))) > 0)
- SHA1_Update(&ctx, buffer, (size_t)num);
-
- oerrno = errno;
- close(fd);
- errno = oerrno;
- return(num < 0 ? 0 : SHA1_End(&ctx, buf));
-}
-
-char *
-SHA1_Data (data, len, buf)
- const uint8_t *data;
- size_t len;
- char *buf;
-{
- SHA1_CTX ctx;
-
- _DIAGASSERT(data != NULL);
- /* XXX: buf may be NULL ? */
-
- SHA1_Init(&ctx);
- SHA1_Update(&ctx, data, len);
- return(SHA1_End(&ctx, buf));
-}
diff --git a/ext/digest/sha1/sha1init.c b/ext/digest/sha1/sha1init.c
deleted file mode 100644
index 70bc4f9f52..0000000000
--- a/ext/digest/sha1/sha1init.c
+++ /dev/null
@@ -1,34 +0,0 @@
-/* $RoughId: sha1init.c,v 1.2 2001/07/13 19:49:10 knu Exp $ */
-/* $Id$ */
-
-#include "digest.h"
-#include "sha1.h"
-
-static algo_t sha1 = {
- SHA1_DIGEST_LENGTH,
- sizeof(SHA1_CTX),
- (hash_init_func_t)SHA1_Init,
- (hash_update_func_t)SHA1_Update,
- (hash_end_func_t)SHA1_End,
- (hash_final_func_t)SHA1_Final,
- (hash_equal_func_t)SHA1_Equal,
-};
-
-void
-Init_sha1()
-{
- VALUE mDigest, cDigest_Base, cDigest_SHA1;
- ID id_metadata;
-
- rb_require("digest.so");
-
- mDigest = rb_path2class("Digest");
- cDigest_Base = rb_path2class("Digest::Base");
-
- cDigest_SHA1 = rb_define_class_under(mDigest, "SHA1", cDigest_Base);
-
- id_metadata = rb_intern("metadata");
-
- rb_cvar_set(cDigest_SHA1, id_metadata,
- Data_Wrap_Struct(rb_cObject, 0, 0, &sha1), Qtrue);
-}
diff --git a/ext/digest/sha2/.cvsignore b/ext/digest/sha2/.cvsignore
deleted file mode 100644
index fc802ff1c2..0000000000
--- a/ext/digest/sha2/.cvsignore
+++ /dev/null
@@ -1,2 +0,0 @@
-Makefile
-mkmf.log
diff --git a/ext/digest/sha2/MANIFEST b/ext/digest/sha2/MANIFEST
deleted file mode 100644
index f117b94771..0000000000
--- a/ext/digest/sha2/MANIFEST
+++ /dev/null
@@ -1,6 +0,0 @@
-extconf.rb
-sha2.c
-sha2.h
-sha2hl.c
-sha2init.c
-depend
diff --git a/ext/digest/sha2/depend b/ext/digest/sha2/depend
deleted file mode 100644
index 2587415fdc..0000000000
--- a/ext/digest/sha2/depend
+++ /dev/null
@@ -1,7 +0,0 @@
-sha2.o: sha2.c sha2.h $(srcdir)/../defs.h $(hdrdir)/ruby.h \
- $(topdir)/config.h $(hdrdir)/defines.h $(hdrdir)/intern.h
-sha2hl.o: sha2hl.c sha2.h $(srcdir)/../defs.h $(hdrdir)/ruby.h \
- $(topdir)/config.h $(hdrdir)/defines.h $(hdrdir)/intern.h
-sha2init.o: sha2init.c $(srcdir)/../digest.h $(hdrdir)/ruby.h \
- $(topdir)/config.h $(hdrdir)/defines.h $(hdrdir)/intern.h \
- sha2.h $(srcdir)/../defs.h
diff --git a/ext/digest/sha2/extconf.rb b/ext/digest/sha2/extconf.rb
deleted file mode 100644
index c982aa64de..0000000000
--- a/ext/digest/sha2/extconf.rb
+++ /dev/null
@@ -1,28 +0,0 @@
-# $RoughId: extconf.rb,v 1.4 2001/08/14 19:54:51 knu Exp $
-# $Id$
-
-require "mkmf"
-
-$CFLAGS << " -DHAVE_CONFIG_H -I#{File.dirname(__FILE__)}/.."
-
-$objs = [
- "sha2.#{$OBJEXT}",
- "sha2hl.#{$OBJEXT}",
- "sha2init.#{$OBJEXT}",
-]
-
-have_header("sys/cdefs.h")
-
-have_header("inttypes.h")
-
-have_header("unistd.h")
-
-if try_cpp(<<SRC, $defs.join(' '))
-#include "defs.h"
-#ifdef NO_UINT64_T
- #error ** Cannot find a 64bit integer type - skipping the SHA2 module.
-#endif
-SRC
-then
- create_makefile("digest/sha2")
-end
diff --git a/ext/digest/sha2/sha2.c b/ext/digest/sha2/sha2.c
deleted file mode 100644
index a3c3258082..0000000000
--- a/ext/digest/sha2/sha2.c
+++ /dev/null
@@ -1,937 +0,0 @@
-/*
- * sha2.c
- *
- * Version 1.0.0beta1
- *
- * Written by Aaron D. Gifford <me@aarongifford.com>
- *
- * Copyright 2000 Aaron D. Gifford. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the copyright holder nor the names of contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) AND CONTRIBUTOR(S) ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) OR CONTRIBUTOR(S) BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- */
-
-/* $RoughId: sha2.c,v 1.3 2002/02/26 22:03:36 knu Exp $ */
-/* $Id$ */
-
-#include <stdio.h>
-#include <string.h> /* memcpy()/memset() or bcopy()/bzero() */
-#include <assert.h> /* assert() */
-#include "sha2.h"
-
-/*
- * ASSERT NOTE:
- * Some sanity checking code is included using assert(). On my FreeBSD
- * system, this additional code can be removed by compiling with NDEBUG
- * defined. Check your own systems manpage on assert() to see how to
- * compile WITHOUT the sanity checking code on your system.
- *
- * UNROLLED TRANSFORM LOOP NOTE:
- * You can define SHA2_UNROLL_TRANSFORM to use the unrolled transform
- * loop version for the hash transform rounds (defined using macros
- * later in this file). Either define on the command line, for example:
- *
- * cc -DSHA2_UNROLL_TRANSFORM -o sha2 sha2.c sha2prog.c
- *
- * or define below:
- *
- * #define SHA2_UNROLL_TRANSFORM
- *
- */
-
-
-/*** SHA-256/384/512 Machine Architecture Definitions *****************/
-typedef uint8_t sha2_byte; /* Exactly 1 byte */
-typedef uint32_t sha2_word32; /* Exactly 4 bytes */
-typedef uint64_t sha2_word64; /* Exactly 8 bytes */
-
-#if defined(__GNUC__)
-#define ULL(number) number##ULL
-#else
-#define ULL(number) (uint64_t)(number)
-#endif
-
-
-/*** SHA-256/384/512 Various Length Definitions ***********************/
-/* NOTE: Most of these are in sha2.h */
-#define SHA256_SHORT_BLOCK_LENGTH (SHA256_BLOCK_LENGTH - 8)
-#define SHA384_SHORT_BLOCK_LENGTH (SHA384_BLOCK_LENGTH - 16)
-#define SHA512_SHORT_BLOCK_LENGTH (SHA512_BLOCK_LENGTH - 16)
-
-
-/*** ENDIAN REVERSAL MACROS *******************************************/
-#ifndef WORDS_BIGENDIAN
-#define REVERSE32(w,x) { \
- sha2_word32 tmp = (w); \
- tmp = (tmp >> 16) | (tmp << 16); \
- (x) = ((tmp & 0xff00ff00UL) >> 8) | ((tmp & 0x00ff00ffUL) << 8); \
-}
-#define REVERSE64(w,x) { \
- sha2_word64 tmp = (w); \
- tmp = (tmp >> 32) | (tmp << 32); \
- tmp = ((tmp & ULL(0xff00ff00ff00ff00)) >> 8) | \
- ((tmp & ULL(0x00ff00ff00ff00ff)) << 8); \
- (x) = ((tmp & ULL(0xffff0000ffff0000)) >> 16) | \
- ((tmp & ULL(0x0000ffff0000ffff)) << 16); \
-}
-#endif
-
-/*
- * Macro for incrementally adding the unsigned 64-bit integer n to the
- * unsigned 128-bit integer (represented using a two-element array of
- * 64-bit words):
- */
-#define ADDINC128(w,n) { \
- (w)[0] += (sha2_word64)(n); \
- if ((w)[0] < (n)) { \
- (w)[1]++; \
- } \
-}
-
-/*
- * Macros for copying blocks of memory and for zeroing out ranges
- * of memory. Using these macros makes it easy to switch from
- * using memset()/memcpy() and using bzero()/bcopy().
- *
- * Please define either SHA2_USE_MEMSET_MEMCPY or define
- * SHA2_USE_BZERO_BCOPY depending on which function set you
- * choose to use:
- */
-#if !defined(SHA2_USE_MEMSET_MEMCPY) && !defined(SHA2_USE_BZERO_BCOPY)
-/* Default to memset()/memcpy() if no option is specified */
-#define SHA2_USE_MEMSET_MEMCPY 1
-#endif
-#if defined(SHA2_USE_MEMSET_MEMCPY) && defined(SHA2_USE_BZERO_BCOPY)
-/* Abort with an error if BOTH options are defined */
-#error Define either SHA2_USE_MEMSET_MEMCPY or SHA2_USE_BZERO_BCOPY, not both!
-#endif
-
-#ifdef SHA2_USE_MEMSET_MEMCPY
-#define MEMSET_BZERO(p,l) memset((p), 0, (l))
-#define MEMCPY_BCOPY(d,s,l) memcpy((d), (s), (l))
-#endif
-#ifdef SHA2_USE_BZERO_BCOPY
-#define MEMSET_BZERO(p,l) bzero((p), (l))
-#define MEMCPY_BCOPY(d,s,l) bcopy((s), (d), (l))
-#endif
-
-
-/*** THE SIX LOGICAL FUNCTIONS ****************************************/
-/*
- * Bit shifting and rotation (used by the six SHA-XYZ logical functions:
- *
- * NOTE: The naming of R and S appears backwards here (R is a SHIFT and
- * S is a ROTATION) because the SHA-256/384/512 description document
- * (see http://csrc.nist.gov/cryptval/shs/sha256-384-512.pdf) uses this
- * same "backwards" definition.
- */
-/* Shift-right (used in SHA-256, SHA-384, and SHA-512): */
-#define R(b,x) ((x) >> (b))
-/* 32-bit Rotate-right (used in SHA-256): */
-#define S32(b,x) (((x) >> (b)) | ((x) << (32 - (b))))
-/* 64-bit Rotate-right (used in SHA-384 and SHA-512): */
-#define S64(b,x) (((x) >> (b)) | ((x) << (64 - (b))))
-
-/* Two of six logical functions used in SHA-256, SHA-384, and SHA-512: */
-#define Ch(x,y,z) (((x) & (y)) ^ ((~(x)) & (z)))
-#define Maj(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
-
-/* Four of six logical functions used in SHA-256: */
-#define Sigma0_256(x) (S32(2, (x)) ^ S32(13, (x)) ^ S32(22, (x)))
-#define Sigma1_256(x) (S32(6, (x)) ^ S32(11, (x)) ^ S32(25, (x)))
-#define sigma0_256(x) (S32(7, (x)) ^ S32(18, (x)) ^ R(3 , (x)))
-#define sigma1_256(x) (S32(17, (x)) ^ S32(19, (x)) ^ R(10, (x)))
-
-/* Four of six logical functions used in SHA-384 and SHA-512: */
-#define Sigma0_512(x) (S64(28, (x)) ^ S64(34, (x)) ^ S64(39, (x)))
-#define Sigma1_512(x) (S64(14, (x)) ^ S64(18, (x)) ^ S64(41, (x)))
-#define sigma0_512(x) (S64( 1, (x)) ^ S64( 8, (x)) ^ R( 7, (x)))
-#define sigma1_512(x) (S64(19, (x)) ^ S64(61, (x)) ^ R( 6, (x)))
-
-/*** INTERNAL FUNCTION PROTOTYPES *************************************/
-/* NOTE: These should not be accessed directly from outside this
- * library -- they are intended for private internal visibility/use
- * only.
- */
-void SHA512_Last(SHA512_CTX*);
-void SHA256_Transform(SHA256_CTX*, const sha2_word32*);
-void SHA512_Transform(SHA512_CTX*, const sha2_word64*);
-
-
-/*** SHA-XYZ INITIAL HASH VALUES AND CONSTANTS ************************/
-/* Hash constant words K for SHA-256: */
-const static sha2_word32 K256[64] = {
- 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL,
- 0x3956c25bUL, 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL,
- 0xd807aa98UL, 0x12835b01UL, 0x243185beUL, 0x550c7dc3UL,
- 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, 0xc19bf174UL,
- 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL,
- 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL,
- 0x983e5152UL, 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL,
- 0xc6e00bf3UL, 0xd5a79147UL, 0x06ca6351UL, 0x14292967UL,
- 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, 0x53380d13UL,
- 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL,
- 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL,
- 0xd192e819UL, 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL,
- 0x19a4c116UL, 0x1e376c08UL, 0x2748774cUL, 0x34b0bcb5UL,
- 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, 0x682e6ff3UL,
- 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL,
- 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL
-};
-
-/* Initial hash value H for SHA-256: */
-const static sha2_word32 sha256_initial_hash_value[8] = {
- 0x6a09e667UL,
- 0xbb67ae85UL,
- 0x3c6ef372UL,
- 0xa54ff53aUL,
- 0x510e527fUL,
- 0x9b05688cUL,
- 0x1f83d9abUL,
- 0x5be0cd19UL
-};
-
-/* Hash constant words K for SHA-384 and SHA-512: */
-const static sha2_word64 K512[80] = {
- ULL(0x428a2f98d728ae22), ULL(0x7137449123ef65cd),
- ULL(0xb5c0fbcfec4d3b2f), ULL(0xe9b5dba58189dbbc),
- ULL(0x3956c25bf348b538), ULL(0x59f111f1b605d019),
- ULL(0x923f82a4af194f9b), ULL(0xab1c5ed5da6d8118),
- ULL(0xd807aa98a3030242), ULL(0x12835b0145706fbe),
- ULL(0x243185be4ee4b28c), ULL(0x550c7dc3d5ffb4e2),
- ULL(0x72be5d74f27b896f), ULL(0x80deb1fe3b1696b1),
- ULL(0x9bdc06a725c71235), ULL(0xc19bf174cf692694),
- ULL(0xe49b69c19ef14ad2), ULL(0xefbe4786384f25e3),
- ULL(0x0fc19dc68b8cd5b5), ULL(0x240ca1cc77ac9c65),
- ULL(0x2de92c6f592b0275), ULL(0x4a7484aa6ea6e483),
- ULL(0x5cb0a9dcbd41fbd4), ULL(0x76f988da831153b5),
- ULL(0x983e5152ee66dfab), ULL(0xa831c66d2db43210),
- ULL(0xb00327c898fb213f), ULL(0xbf597fc7beef0ee4),
- ULL(0xc6e00bf33da88fc2), ULL(0xd5a79147930aa725),
- ULL(0x06ca6351e003826f), ULL(0x142929670a0e6e70),
- ULL(0x27b70a8546d22ffc), ULL(0x2e1b21385c26c926),
- ULL(0x4d2c6dfc5ac42aed), ULL(0x53380d139d95b3df),
- ULL(0x650a73548baf63de), ULL(0x766a0abb3c77b2a8),
- ULL(0x81c2c92e47edaee6), ULL(0x92722c851482353b),
- ULL(0xa2bfe8a14cf10364), ULL(0xa81a664bbc423001),
- ULL(0xc24b8b70d0f89791), ULL(0xc76c51a30654be30),
- ULL(0xd192e819d6ef5218), ULL(0xd69906245565a910),
- ULL(0xf40e35855771202a), ULL(0x106aa07032bbd1b8),
- ULL(0x19a4c116b8d2d0c8), ULL(0x1e376c085141ab53),
- ULL(0x2748774cdf8eeb99), ULL(0x34b0bcb5e19b48a8),
- ULL(0x391c0cb3c5c95a63), ULL(0x4ed8aa4ae3418acb),
- ULL(0x5b9cca4f7763e373), ULL(0x682e6ff3d6b2b8a3),
- ULL(0x748f82ee5defb2fc), ULL(0x78a5636f43172f60),
- ULL(0x84c87814a1f0ab72), ULL(0x8cc702081a6439ec),
- ULL(0x90befffa23631e28), ULL(0xa4506cebde82bde9),
- ULL(0xbef9a3f7b2c67915), ULL(0xc67178f2e372532b),
- ULL(0xca273eceea26619c), ULL(0xd186b8c721c0c207),
- ULL(0xeada7dd6cde0eb1e), ULL(0xf57d4f7fee6ed178),
- ULL(0x06f067aa72176fba), ULL(0x0a637dc5a2c898a6),
- ULL(0x113f9804bef90dae), ULL(0x1b710b35131c471b),
- ULL(0x28db77f523047d84), ULL(0x32caab7b40c72493),
- ULL(0x3c9ebe0a15c9bebc), ULL(0x431d67c49c100d4c),
- ULL(0x4cc5d4becb3e42b6), ULL(0x597f299cfc657e2a),
- ULL(0x5fcb6fab3ad6faec), ULL(0x6c44198c4a475817)
-};
-
-/* Initial hash value H for SHA-384 */
-const static sha2_word64 sha384_initial_hash_value[8] = {
- ULL(0xcbbb9d5dc1059ed8),
- ULL(0x629a292a367cd507),
- ULL(0x9159015a3070dd17),
- ULL(0x152fecd8f70e5939),
- ULL(0x67332667ffc00b31),
- ULL(0x8eb44a8768581511),
- ULL(0xdb0c2e0d64f98fa7),
- ULL(0x47b5481dbefa4fa4)
-};
-
-/* Initial hash value H for SHA-512 */
-const static sha2_word64 sha512_initial_hash_value[8] = {
- ULL(0x6a09e667f3bcc908),
- ULL(0xbb67ae8584caa73b),
- ULL(0x3c6ef372fe94f82b),
- ULL(0xa54ff53a5f1d36f1),
- ULL(0x510e527fade682d1),
- ULL(0x9b05688c2b3e6c1f),
- ULL(0x1f83d9abfb41bd6b),
- ULL(0x5be0cd19137e2179)
-};
-
-
-/*** SHA-256: *********************************************************/
-void SHA256_Init(SHA256_CTX* context) {
- if (context == (SHA256_CTX*)0) {
- return;
- }
- MEMCPY_BCOPY(context->state, sha256_initial_hash_value, SHA256_DIGEST_LENGTH);
- MEMSET_BZERO(context->buffer, SHA256_BLOCK_LENGTH);
- context->bitcount = 0;
-}
-
-#ifdef SHA2_UNROLL_TRANSFORM
-
-/* Unrolled SHA-256 round macros: */
-
-#ifndef WORDS_BIGENDIAN
-
-#define ROUND256_0_TO_15(a,b,c,d,e,f,g,h) \
- REVERSE32(*data++, W256[j]); \
- T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + \
- K256[j] + W256[j]; \
- (d) += T1; \
- (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \
- j++
-
-
-#else
-
-#define ROUND256_0_TO_15(a,b,c,d,e,f,g,h) \
- T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + \
- K256[j] + (W256[j] = *data++); \
- (d) += T1; \
- (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \
- j++
-
-#endif
-
-#define ROUND256(a,b,c,d,e,f,g,h) \
- s0 = W256[(j+1)&0x0f]; \
- s0 = sigma0_256(s0); \
- s1 = W256[(j+14)&0x0f]; \
- s1 = sigma1_256(s1); \
- T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + K256[j] + \
- (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0); \
- (d) += T1; \
- (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \
- j++
-
-void SHA256_Transform(SHA256_CTX* context, const sha2_word32* data) {
- sha2_word32 a, b, c, d, e, f, g, h, s0, s1;
- sha2_word32 T1, *W256;
- int j;
-
- W256 = (sha2_word32*)context->buffer;
-
- /* Initialize registers with the prev. intermediate value */
- a = context->state[0];
- b = context->state[1];
- c = context->state[2];
- d = context->state[3];
- e = context->state[4];
- f = context->state[5];
- g = context->state[6];
- h = context->state[7];
-
- j = 0;
- do {
- /* Rounds 0 to 15 (unrolled): */
- ROUND256_0_TO_15(a,b,c,d,e,f,g,h);
- ROUND256_0_TO_15(h,a,b,c,d,e,f,g);
- ROUND256_0_TO_15(g,h,a,b,c,d,e,f);
- ROUND256_0_TO_15(f,g,h,a,b,c,d,e);
- ROUND256_0_TO_15(e,f,g,h,a,b,c,d);
- ROUND256_0_TO_15(d,e,f,g,h,a,b,c);
- ROUND256_0_TO_15(c,d,e,f,g,h,a,b);
- ROUND256_0_TO_15(b,c,d,e,f,g,h,a);
- } while (j < 16);
-
- /* Now for the remaining rounds to 64: */
- do {
- ROUND256(a,b,c,d,e,f,g,h);
- ROUND256(h,a,b,c,d,e,f,g);
- ROUND256(g,h,a,b,c,d,e,f);
- ROUND256(f,g,h,a,b,c,d,e);
- ROUND256(e,f,g,h,a,b,c,d);
- ROUND256(d,e,f,g,h,a,b,c);
- ROUND256(c,d,e,f,g,h,a,b);
- ROUND256(b,c,d,e,f,g,h,a);
- } while (j < 64);
-
- /* Compute the current intermediate hash value */
- context->state[0] += a;
- context->state[1] += b;
- context->state[2] += c;
- context->state[3] += d;
- context->state[4] += e;
- context->state[5] += f;
- context->state[6] += g;
- context->state[7] += h;
-
- /* Clean up */
- a = b = c = d = e = f = g = h = T1 = 0;
-}
-
-#else /* SHA2_UNROLL_TRANSFORM */
-
-void SHA256_Transform(SHA256_CTX* context, const sha2_word32* data) {
- sha2_word32 a, b, c, d, e, f, g, h, s0, s1;
- sha2_word32 T1, T2, *W256;
- int j;
-
- W256 = (sha2_word32*)context->buffer;
-
- /* Initialize registers with the prev. intermediate value */
- a = context->state[0];
- b = context->state[1];
- c = context->state[2];
- d = context->state[3];
- e = context->state[4];
- f = context->state[5];
- g = context->state[6];
- h = context->state[7];
-
- j = 0;
- do {
-#ifndef WORDS_BIGENDIAN
- /* Copy data while converting to host byte order */
- REVERSE32(*data++,W256[j]);
- /* Apply the SHA-256 compression function to update a..h */
- T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + W256[j];
-#else
- /* Apply the SHA-256 compression function to update a..h with copy */
- T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + (W256[j] = *data++);
-#endif
- T2 = Sigma0_256(a) + Maj(a, b, c);
- h = g;
- g = f;
- f = e;
- e = d + T1;
- d = c;
- c = b;
- b = a;
- a = T1 + T2;
-
- j++;
- } while (j < 16);
-
- do {
- /* Part of the message block expansion: */
- s0 = W256[(j+1)&0x0f];
- s0 = sigma0_256(s0);
- s1 = W256[(j+14)&0x0f];
- s1 = sigma1_256(s1);
-
- /* Apply the SHA-256 compression function to update a..h */
- T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] +
- (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0);
- T2 = Sigma0_256(a) + Maj(a, b, c);
- h = g;
- g = f;
- f = e;
- e = d + T1;
- d = c;
- c = b;
- b = a;
- a = T1 + T2;
-
- j++;
- } while (j < 64);
-
- /* Compute the current intermediate hash value */
- context->state[0] += a;
- context->state[1] += b;
- context->state[2] += c;
- context->state[3] += d;
- context->state[4] += e;
- context->state[5] += f;
- context->state[6] += g;
- context->state[7] += h;
-
- /* Clean up */
- a = b = c = d = e = f = g = h = T1 = T2 = 0;
-}
-
-#endif /* SHA2_UNROLL_TRANSFORM */
-
-void SHA256_Update(SHA256_CTX* context, const sha2_byte *data, size_t len) {
- unsigned int freespace, usedspace;
-
- if (len == 0) {
- /* Calling with no data is valid - we do nothing */
- return;
- }
-
- /* Sanity check: */
- assert(context != NULL && data != NULL);
-
- usedspace = (context->bitcount >> 3) % SHA256_BLOCK_LENGTH;
- if (usedspace > 0) {
- /* Calculate how much free space is available in the buffer */
- freespace = SHA256_BLOCK_LENGTH - usedspace;
-
- if (len >= freespace) {
- /* Fill the buffer completely and process it */
- MEMCPY_BCOPY(&context->buffer[usedspace], data, freespace);
- context->bitcount += freespace << 3;
- len -= freespace;
- data += freespace;
- SHA256_Transform(context, (sha2_word32*)context->buffer);
- } else {
- /* The buffer is not yet full */
- MEMCPY_BCOPY(&context->buffer[usedspace], data, len);
- context->bitcount += len << 3;
- /* Clean up: */
- usedspace = freespace = 0;
- return;
- }
- }
- while (len >= SHA256_BLOCK_LENGTH) {
- /* Process as many complete blocks as we can */
- SHA256_Transform(context, (const sha2_word32*)data);
- context->bitcount += SHA256_BLOCK_LENGTH << 3;
- len -= SHA256_BLOCK_LENGTH;
- data += SHA256_BLOCK_LENGTH;
- }
- if (len > 0) {
- /* There's left-overs, so save 'em */
- MEMCPY_BCOPY(context->buffer, data, len);
- context->bitcount += len << 3;
- }
- /* Clean up: */
- usedspace = freespace = 0;
-}
-
-void SHA256_Final(sha2_byte digest[], SHA256_CTX* context) {
- sha2_word32 *d = (sha2_word32*)digest;
- unsigned int usedspace;
-
- /* Sanity check: */
- assert(context != NULL);
-
- /* If no digest buffer is passed, we don't bother doing this: */
- if (digest != (sha2_byte*)0) {
- usedspace = (context->bitcount >> 3) % SHA256_BLOCK_LENGTH;
-#ifndef WORDS_BIGENDIAN
- /* Convert FROM host byte order */
- REVERSE64(context->bitcount,context->bitcount);
-#endif
- if (usedspace > 0) {
- /* Begin padding with a 1 bit: */
- context->buffer[usedspace++] = 0x80;
-
- if (usedspace <= SHA256_SHORT_BLOCK_LENGTH) {
- /* Set-up for the last transform: */
- MEMSET_BZERO(&context->buffer[usedspace], SHA256_SHORT_BLOCK_LENGTH - usedspace);
- } else {
- if (usedspace < SHA256_BLOCK_LENGTH) {
- MEMSET_BZERO(&context->buffer[usedspace], SHA256_BLOCK_LENGTH - usedspace);
- }
- /* Do second-to-last transform: */
- SHA256_Transform(context, (sha2_word32*)context->buffer);
-
- /* And set-up for the last transform: */
- MEMSET_BZERO(context->buffer, SHA256_SHORT_BLOCK_LENGTH);
- }
- } else {
- /* Set-up for the last transform: */
- MEMSET_BZERO(context->buffer, SHA256_SHORT_BLOCK_LENGTH);
-
- /* Begin padding with a 1 bit: */
- *context->buffer = 0x80;
- }
- /* Set the bit count: */
- *(sha2_word64*)&context->buffer[SHA256_SHORT_BLOCK_LENGTH] = context->bitcount;
-
- /* Final transform: */
- SHA256_Transform(context, (sha2_word32*)context->buffer);
-
-#ifndef WORDS_BIGENDIAN
- {
- /* Convert TO host byte order */
- int j;
- for (j = 0; j < 8; j++) {
- REVERSE32(context->state[j],context->state[j]);
- *d++ = context->state[j];
- }
- }
-#else
- MEMCPY_BCOPY(d, context->state, SHA256_DIGEST_LENGTH);
-#endif
- }
-
- /* Clean up state data: */
- MEMSET_BZERO(context, sizeof(SHA256_CTX));
- usedspace = 0;
-}
-
-int SHA256_Equal(SHA256_CTX* pctx1, SHA256_CTX* pctx2) {
- return pctx1->bitcount == pctx2->bitcount
- && memcmp(pctx1->state, pctx2->state, sizeof(pctx1->state)) == 0
- && memcmp(pctx1->buffer, pctx2->buffer, sizeof(pctx1->buffer)) == 0;
-}
-
-/*** SHA-512: *********************************************************/
-void SHA512_Init(SHA512_CTX* context) {
- if (context == (SHA512_CTX*)0) {
- return;
- }
- MEMCPY_BCOPY(context->state, sha512_initial_hash_value, SHA512_DIGEST_LENGTH);
- MEMSET_BZERO(context->buffer, SHA512_BLOCK_LENGTH);
- context->bitcount[0] = context->bitcount[1] = 0;
-}
-
-#ifdef SHA2_UNROLL_TRANSFORM
-
-/* Unrolled SHA-512 round macros: */
-#ifndef WORDS_BIGENDIAN
-
-#define ROUND512_0_TO_15(a,b,c,d,e,f,g,h) \
- REVERSE64(*data++, W512[j]); \
- T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + \
- K512[j] + W512[j]; \
- (d) += T1, \
- (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)), \
- j++
-
-
-#else
-
-#define ROUND512_0_TO_15(a,b,c,d,e,f,g,h) \
- T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + \
- K512[j] + (W512[j] = *data++); \
- (d) += T1; \
- (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \
- j++
-
-#endif
-
-#define ROUND512(a,b,c,d,e,f,g,h) \
- s0 = W512[(j+1)&0x0f]; \
- s0 = sigma0_512(s0); \
- s1 = W512[(j+14)&0x0f]; \
- s1 = sigma1_512(s1); \
- T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + K512[j] + \
- (W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0); \
- (d) += T1; \
- (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \
- j++
-
-void SHA512_Transform(SHA512_CTX* context, const sha2_word64* data) {
- sha2_word64 a, b, c, d, e, f, g, h, s0, s1;
- sha2_word64 T1, *W512 = (sha2_word64*)context->buffer;
- int j;
-
- /* Initialize registers with the prev. intermediate value */
- a = context->state[0];
- b = context->state[1];
- c = context->state[2];
- d = context->state[3];
- e = context->state[4];
- f = context->state[5];
- g = context->state[6];
- h = context->state[7];
-
- j = 0;
- do {
- ROUND512_0_TO_15(a,b,c,d,e,f,g,h);
- ROUND512_0_TO_15(h,a,b,c,d,e,f,g);
- ROUND512_0_TO_15(g,h,a,b,c,d,e,f);
- ROUND512_0_TO_15(f,g,h,a,b,c,d,e);
- ROUND512_0_TO_15(e,f,g,h,a,b,c,d);
- ROUND512_0_TO_15(d,e,f,g,h,a,b,c);
- ROUND512_0_TO_15(c,d,e,f,g,h,a,b);
- ROUND512_0_TO_15(b,c,d,e,f,g,h,a);
- } while (j < 16);
-
- /* Now for the remaining rounds up to 79: */
- do {
- ROUND512(a,b,c,d,e,f,g,h);
- ROUND512(h,a,b,c,d,e,f,g);
- ROUND512(g,h,a,b,c,d,e,f);
- ROUND512(f,g,h,a,b,c,d,e);
- ROUND512(e,f,g,h,a,b,c,d);
- ROUND512(d,e,f,g,h,a,b,c);
- ROUND512(c,d,e,f,g,h,a,b);
- ROUND512(b,c,d,e,f,g,h,a);
- } while (j < 80);
-
- /* Compute the current intermediate hash value */
- context->state[0] += a;
- context->state[1] += b;
- context->state[2] += c;
- context->state[3] += d;
- context->state[4] += e;
- context->state[5] += f;
- context->state[6] += g;
- context->state[7] += h;
-
- /* Clean up */
- a = b = c = d = e = f = g = h = T1 = 0;
-}
-
-#else /* SHA2_UNROLL_TRANSFORM */
-
-void SHA512_Transform(SHA512_CTX* context, const sha2_word64* data) {
- sha2_word64 a, b, c, d, e, f, g, h, s0, s1;
- sha2_word64 T1, T2, *W512 = (sha2_word64*)context->buffer;
- int j;
-
- /* Initialize registers with the prev. intermediate value */
- a = context->state[0];
- b = context->state[1];
- c = context->state[2];
- d = context->state[3];
- e = context->state[4];
- f = context->state[5];
- g = context->state[6];
- h = context->state[7];
-
- j = 0;
- do {
-#ifndef WORDS_BIGENDIAN
- /* Convert TO host byte order */
- REVERSE64(*data++, W512[j]);
- /* Apply the SHA-512 compression function to update a..h */
- T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + W512[j];
-#else
- /* Apply the SHA-512 compression function to update a..h with copy */
- T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + (W512[j] = *data++);
-#endif
- T2 = Sigma0_512(a) + Maj(a, b, c);
- h = g;
- g = f;
- f = e;
- e = d + T1;
- d = c;
- c = b;
- b = a;
- a = T1 + T2;
-
- j++;
- } while (j < 16);
-
- do {
- /* Part of the message block expansion: */
- s0 = W512[(j+1)&0x0f];
- s0 = sigma0_512(s0);
- s1 = W512[(j+14)&0x0f];
- s1 = sigma1_512(s1);
-
- /* Apply the SHA-512 compression function to update a..h */
- T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] +
- (W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0);
- T2 = Sigma0_512(a) + Maj(a, b, c);
- h = g;
- g = f;
- f = e;
- e = d + T1;
- d = c;
- c = b;
- b = a;
- a = T1 + T2;
-
- j++;
- } while (j < 80);
-
- /* Compute the current intermediate hash value */
- context->state[0] += a;
- context->state[1] += b;
- context->state[2] += c;
- context->state[3] += d;
- context->state[4] += e;
- context->state[5] += f;
- context->state[6] += g;
- context->state[7] += h;
-
- /* Clean up */
- a = b = c = d = e = f = g = h = T1 = T2 = 0;
-}
-
-#endif /* SHA2_UNROLL_TRANSFORM */
-
-void SHA512_Update(SHA512_CTX* context, const sha2_byte *data, size_t len) {
- unsigned int freespace, usedspace;
-
- if (len == 0) {
- /* Calling with no data is valid - we do nothing */
- return;
- }
-
- /* Sanity check: */
- assert(context != NULL && data != NULL);
-
- usedspace = (context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH;
- if (usedspace > 0) {
- /* Calculate how much free space is available in the buffer */
- freespace = SHA512_BLOCK_LENGTH - usedspace;
-
- if (len >= freespace) {
- /* Fill the buffer completely and process it */
- MEMCPY_BCOPY(&context->buffer[usedspace], data, freespace);
- ADDINC128(context->bitcount, freespace << 3);
- len -= freespace;
- data += freespace;
- SHA512_Transform(context, (const sha2_word64*)context->buffer);
- } else {
- /* The buffer is not yet full */
- MEMCPY_BCOPY(&context->buffer[usedspace], data, len);
- ADDINC128(context->bitcount, len << 3);
- /* Clean up: */
- usedspace = freespace = 0;
- return;
- }
- }
- while (len >= SHA512_BLOCK_LENGTH) {
- /* Process as many complete blocks as we can */
- SHA512_Transform(context, (const sha2_word64*)data);
- ADDINC128(context->bitcount, SHA512_BLOCK_LENGTH << 3);
- len -= SHA512_BLOCK_LENGTH;
- data += SHA512_BLOCK_LENGTH;
- }
- if (len > 0) {
- /* There's left-overs, so save 'em */
- MEMCPY_BCOPY(context->buffer, data, len);
- ADDINC128(context->bitcount, len << 3);
- }
- /* Clean up: */
- usedspace = freespace = 0;
-}
-
-void SHA512_Last(SHA512_CTX* context) {
- unsigned int usedspace;
-
- usedspace = (context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH;
-#ifndef WORDS_BIGENDIAN
- /* Convert FROM host byte order */
- REVERSE64(context->bitcount[0],context->bitcount[0]);
- REVERSE64(context->bitcount[1],context->bitcount[1]);
-#endif
- if (usedspace > 0) {
- /* Begin padding with a 1 bit: */
- context->buffer[usedspace++] = 0x80;
-
- if (usedspace <= SHA512_SHORT_BLOCK_LENGTH) {
- /* Set-up for the last transform: */
- MEMSET_BZERO(&context->buffer[usedspace], SHA512_SHORT_BLOCK_LENGTH - usedspace);
- } else {
- if (usedspace < SHA512_BLOCK_LENGTH) {
- MEMSET_BZERO(&context->buffer[usedspace], SHA512_BLOCK_LENGTH - usedspace);
- }
- /* Do second-to-last transform: */
- SHA512_Transform(context, (const sha2_word64*)context->buffer);
-
- /* And set-up for the last transform: */
- MEMSET_BZERO(context->buffer, SHA512_BLOCK_LENGTH - 2);
- }
- } else {
- /* Prepare for final transform: */
- MEMSET_BZERO(context->buffer, SHA512_SHORT_BLOCK_LENGTH);
-
- /* Begin padding with a 1 bit: */
- *context->buffer = 0x80;
- }
- /* Store the length of input data (in bits): */
- *(sha2_word64*)&context->buffer[SHA512_SHORT_BLOCK_LENGTH] = context->bitcount[1];
- *(sha2_word64*)&context->buffer[SHA512_SHORT_BLOCK_LENGTH+8] = context->bitcount[0];
-
- /* Final transform: */
- SHA512_Transform(context, (const sha2_word64*)context->buffer);
-}
-
-void SHA512_Final(sha2_byte digest[], SHA512_CTX* context) {
- sha2_word64 *d = (sha2_word64*)digest;
-
- /* Sanity check: */
- assert(context != NULL);
-
- /* If no digest buffer is passed, we don't bother doing this: */
- if (digest != (sha2_byte*)0) {
- SHA512_Last(context);
-
- /* Save the hash data for output: */
-#ifndef WORDS_BIGENDIAN
- {
- /* Convert TO host byte order */
- int j;
- for (j = 0; j < 8; j++) {
- REVERSE64(context->state[j],context->state[j]);
- *d++ = context->state[j];
- }
- }
-#else
- MEMCPY_BCOPY(d, context->state, SHA512_DIGEST_LENGTH);
-#endif
- }
-
- /* Zero out state data */
- MEMSET_BZERO(context, sizeof(SHA512_CTX));
-}
-
-int SHA512_Equal(SHA512_CTX* pctx1, SHA512_CTX* pctx2) {
- return memcmp(pctx1->bitcount, pctx2->bitcount, sizeof(pctx1->bitcount)) == 0
- && memcmp(pctx1->state, pctx2->state, sizeof(pctx1->state)) == 0
- && memcmp(pctx1->buffer, pctx2->buffer, sizeof(pctx1->buffer)) == 0;
-}
-
-/*** SHA-384: *********************************************************/
-void SHA384_Init(SHA384_CTX* context) {
- if (context == (SHA384_CTX*)0) {
- return;
- }
- MEMCPY_BCOPY(context->state, sha384_initial_hash_value, SHA512_DIGEST_LENGTH);
- MEMSET_BZERO(context->buffer, SHA384_BLOCK_LENGTH);
- context->bitcount[0] = context->bitcount[1] = 0;
-}
-
-void SHA384_Update(SHA384_CTX* context, const sha2_byte* data, size_t len) {
- SHA512_Update((SHA512_CTX*)context, data, len);
-}
-
-void SHA384_Final(sha2_byte digest[], SHA384_CTX* context) {
- sha2_word64 *d = (sha2_word64*)digest;
-
- /* Sanity check: */
- assert(context != NULL);
-
- /* If no digest buffer is passed, we don't bother doing this: */
- if (digest != (sha2_byte*)0) {
- SHA512_Last((SHA512_CTX*)context);
-
- /* Save the hash data for output: */
-#ifndef WORDS_BIGENDIAN
- {
- /* Convert TO host byte order */
- int j;
- for (j = 0; j < 6; j++) {
- REVERSE64(context->state[j],context->state[j]);
- *d++ = context->state[j];
- }
- }
-#else
- MEMCPY_BCOPY(d, context->state, SHA384_DIGEST_LENGTH);
-#endif
- }
-
- /* Zero out state data */
- MEMSET_BZERO(context, sizeof(SHA384_CTX));
-}
-
-int SHA384_Equal(SHA384_CTX* pctx1, SHA384_CTX* pctx2) {
- return memcmp(pctx1->bitcount, pctx2->bitcount, sizeof(pctx1->bitcount)) == 0
- && memcmp(pctx1->state, pctx2->state, sizeof(pctx1->state)) == 0
- && memcmp(pctx1->buffer, pctx2->buffer, sizeof(pctx1->buffer)) == 0;
-}
diff --git a/ext/digest/sha2/sha2.h b/ext/digest/sha2/sha2.h
deleted file mode 100644
index 4689ad93ce..0000000000
--- a/ext/digest/sha2/sha2.h
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * sha2.h
- *
- * Version 1.0.0beta1
- *
- * Written by Aaron D. Gifford <me@aarongifford.com>
- *
- * Copyright 2000 Aaron D. Gifford. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the copyright holder nor the names of contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) AND CONTRIBUTOR(S) ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) OR CONTRIBUTOR(S) BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- */
-
-/* $RoughId: sha2.h,v 1.3 2002/02/24 08:14:32 knu Exp $ */
-/* $Id$ */
-
-#ifndef __SHA2_H__
-#define __SHA2_H__
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include "defs.h"
-
-
-/*** SHA-256/384/512 Various Length Definitions ***********************/
-#define SHA256_BLOCK_LENGTH 64
-#define SHA256_DIGEST_LENGTH 32
-#define SHA256_DIGEST_STRING_LENGTH (SHA256_DIGEST_LENGTH * 2 + 1)
-#define SHA384_BLOCK_LENGTH 128
-#define SHA384_DIGEST_LENGTH 48
-#define SHA384_DIGEST_STRING_LENGTH (SHA384_DIGEST_LENGTH * 2 + 1)
-#define SHA512_BLOCK_LENGTH 128
-#define SHA512_DIGEST_LENGTH 64
-#define SHA512_DIGEST_STRING_LENGTH (SHA512_DIGEST_LENGTH * 2 + 1)
-
-
-/*** SHA-256/384/512 Context Structures *******************************/
-
-typedef struct _SHA256_CTX {
- uint32_t state[8];
- uint64_t bitcount;
- uint8_t buffer[SHA256_BLOCK_LENGTH];
-} SHA256_CTX;
-typedef struct _SHA512_CTX {
- uint64_t state[8];
- uint64_t bitcount[2];
- uint8_t buffer[SHA512_BLOCK_LENGTH];
-} SHA512_CTX;
-
-typedef SHA512_CTX SHA384_CTX;
-
-
-#ifdef RUBY
-#define SHA256_Init rb_Digest_SHA256_Init
-#define SHA256_Update rb_Digest_SHA256_Update
-#define SHA256_Final rb_Digest_SHA256_Final
-#define SHA256_End rb_Digest_SHA256_End
-#define SHA256_Data rb_Digest_SHA256_Data
-#define SHA256_File rb_Digest_SHA256_File
-#define SHA256_Equal rb_Digest_SHA256_Equal
-
-#define SHA384_Init rb_Digest_SHA384_Init
-#define SHA384_Update rb_Digest_SHA384_Update
-#define SHA384_Final rb_Digest_SHA384_Final
-#define SHA384_End rb_Digest_SHA384_End
-#define SHA384_Data rb_Digest_SHA384_Data
-#define SHA384_File rb_Digest_SHA384_File
-#define SHA384_Equal rb_Digest_SHA384_Equal
-
-#define SHA512_Init rb_Digest_SHA512_Init
-#define SHA512_Update rb_Digest_SHA512_Update
-#define SHA512_Final rb_Digest_SHA512_Final
-#define SHA512_End rb_Digest_SHA512_End
-#define SHA512_Data rb_Digest_SHA512_Data
-#define SHA512_File rb_Digest_SHA512_File
-#define SHA512_Equal rb_Digest_SHA512_Equal
-#endif
-
-/*** SHA-256/384/512 Function Prototypes ******************************/
-void SHA256_Init _((SHA256_CTX *));
-void SHA256_Update _((SHA256_CTX*, const uint8_t*, size_t));
-void SHA256_Final _((uint8_t[SHA256_DIGEST_LENGTH], SHA256_CTX*));
-char* SHA256_End _((SHA256_CTX*, char[SHA256_DIGEST_STRING_LENGTH]));
-char* SHA256_Data _((const uint8_t*, size_t, char[SHA256_DIGEST_STRING_LENGTH]));
-char *SHA256_File _((char *, char *));
-int SHA256_Equal _((SHA256_CTX*, SHA256_CTX*));
-
-void SHA384_Init _((SHA384_CTX*));
-void SHA384_Update _((SHA384_CTX*, const uint8_t*, size_t));
-void SHA384_Final _((uint8_t[SHA384_DIGEST_LENGTH], SHA384_CTX*));
-char* SHA384_End _((SHA384_CTX*, char[SHA384_DIGEST_STRING_LENGTH]));
-char* SHA384_Data _((const uint8_t*, size_t, char[SHA384_DIGEST_STRING_LENGTH]));
-char *SHA384_File _((char *, char *));
-int SHA384_Equal _((SHA384_CTX*, SHA384_CTX*));
-
-void SHA512_Init _((SHA512_CTX*));
-void SHA512_Update _((SHA512_CTX*, const uint8_t*, size_t));
-void SHA512_Final _((uint8_t[SHA512_DIGEST_LENGTH], SHA512_CTX*));
-char* SHA512_End _((SHA512_CTX*, char[SHA512_DIGEST_STRING_LENGTH]));
-char* SHA512_Data _((const uint8_t*, size_t, char[SHA512_DIGEST_STRING_LENGTH]));
-char *SHA512_File _((char *, char *));
-int SHA512_Equal _((SHA512_CTX*, SHA512_CTX*));
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif /* __SHA2_H__ */
-
diff --git a/ext/digest/sha2/sha2hl.c b/ext/digest/sha2/sha2hl.c
deleted file mode 100644
index 03fde538c3..0000000000
--- a/ext/digest/sha2/sha2hl.c
+++ /dev/null
@@ -1,252 +0,0 @@
-/* $NetBSD: sha2hl.c,v 1.1 2001/03/12 09:08:40 agc Exp $ */
-/* $RoughId: sha2hl.c,v 1.2 2001/07/13 19:49:10 knu Exp $ */
-/* $Id$ */
-
-/*
- * sha2hl.c
- * This code includes some functions taken from sha2.c, hence the
- * following licence reproduction.
- *
- * This code is not a verbatim copy, since some routines have been added,
- * and some bugs have been fixed.
- *
- * Version 1.0.0beta1
- *
- * Written by Aaron D. Gifford <me@aarongifford.com>
- *
- * Copyright 2000 Aaron D. Gifford. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the copyright holder nor the names of contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) AND CONTRIBUTOR(S) ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) OR CONTRIBUTOR(S) BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- */
-
-#include "sha2.h"
-
-#ifndef lint
-/* __RCSID("$NetBSD: sha2hl.c,v 1.1 2001/03/12 09:08:40 agc Exp $"); */
-#endif /* not lint */
-
-/* #include "namespace.h" */
-
-#include <assert.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#if defined(HAVE_UNISTD_H)
-# include <unistd.h>
-#endif
-
-#ifndef _DIAGASSERT
-#define _DIAGASSERT(cond) assert(cond)
-#endif
-
-/*
- * Constant used by SHA256/384/512_End() functions for converting the
- * digest to a readable hexadecimal character string:
- */
-static const char sha2_hex_digits[] = "0123456789abcdef";
-
-char *
-SHA256_File(char *filename, char *buf)
-{
- uint8_t buffer[BUFSIZ * 20];
- SHA256_CTX ctx;
- int fd, num, oerrno;
-
- _DIAGASSERT(filename != NULL);
- /* XXX: buf may be NULL ? */
-
- SHA256_Init(&ctx);
-
- if ((fd = open(filename, O_RDONLY)) < 0)
- return (0);
-
- while ((num = read(fd, buffer, sizeof(buffer))) > 0)
- SHA256_Update(&ctx, buffer, (size_t) num);
-
- oerrno = errno;
- close(fd);
- errno = oerrno;
- return (num < 0 ? 0 : SHA256_End(&ctx, buf));
-}
-
-
-char *
-SHA256_End(SHA256_CTX *ctx, char buffer[])
-{
- uint8_t digest[SHA256_DIGEST_LENGTH], *d = digest;
- uint8_t *ret;
- int i;
-
- /* Sanity check: */
- assert(ctx != NULL);
-
- if ((ret = buffer) != NULL) {
- SHA256_Final(digest, ctx);
-
- for (i = 0; i < SHA256_DIGEST_LENGTH; i++) {
- *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4];
- *buffer++ = sha2_hex_digits[*d & 0x0f];
- d++;
- }
- *buffer = (char) 0;
- } else {
- (void) memset(ctx, 0, sizeof(SHA256_CTX));
- }
- (void) memset(digest, 0, SHA256_DIGEST_LENGTH);
- return ret;
-}
-
-char *
-SHA256_Data(const uint8_t * data, size_t len, char *digest)
-{
- SHA256_CTX ctx;
-
- SHA256_Init(&ctx);
- SHA256_Update(&ctx, data, len);
- return SHA256_End(&ctx, digest);
-}
-
-char *
-SHA384_File(char *filename, char *buf)
-{
- SHA384_CTX ctx;
- uint8_t buffer[BUFSIZ * 20];
- int fd, num, oerrno;
-
- _DIAGASSERT(filename != NULL);
- /* XXX: buf may be NULL ? */
-
- SHA384_Init(&ctx);
-
- if ((fd = open(filename, O_RDONLY)) < 0)
- return (0);
-
- while ((num = read(fd, buffer, sizeof(buffer))) > 0)
- SHA384_Update(&ctx, buffer, (size_t) num);
-
- oerrno = errno;
- close(fd);
- errno = oerrno;
- return (num < 0 ? 0 : SHA384_End(&ctx, buf));
-}
-
-char *
-SHA384_End(SHA384_CTX * ctx, char buffer[])
-{
- uint8_t digest[SHA384_DIGEST_LENGTH], *d = digest;
- uint8_t *ret;
- int i;
-
- /* Sanity check: */
- assert(ctx != NULL);
-
- if ((ret = buffer) != NULL) {
- SHA384_Final(digest, ctx);
-
- for (i = 0; i < SHA384_DIGEST_LENGTH; i++) {
- *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4];
- *buffer++ = sha2_hex_digits[*d & 0x0f];
- d++;
- }
- *buffer = (char) 0;
- } else {
- (void) memset(ctx, 0, sizeof(SHA384_CTX));
- }
- (void) memset(digest, 0, SHA384_DIGEST_LENGTH);
- return ret;
-}
-
-char *
-SHA384_Data(const uint8_t * data, size_t len, char *digest)
-{
- SHA384_CTX ctx;
-
- SHA384_Init(&ctx);
- SHA384_Update(&ctx, data, len);
- return SHA384_End(&ctx, digest);
-}
-
-char *
-SHA512_File(char *filename, char *buf)
-{
- SHA512_CTX ctx;
- uint8_t buffer[BUFSIZ * 20];
- int fd, num, oerrno;
-
- _DIAGASSERT(filename != NULL);
- /* XXX: buf may be NULL ? */
-
- SHA512_Init(&ctx);
-
- if ((fd = open(filename, O_RDONLY)) < 0)
- return (0);
-
- while ((num = read(fd, buffer, sizeof(buffer))) > 0)
- SHA512_Update(&ctx, buffer, (size_t) num);
-
- oerrno = errno;
- close(fd);
- errno = oerrno;
- return (num < 0 ? 0 : SHA512_End(&ctx, buf));
-}
-
-char *
-SHA512_End(SHA512_CTX * ctx, char buffer[])
-{
- uint8_t digest[SHA512_DIGEST_LENGTH], *d = digest;
- uint8_t *ret;
- int i;
-
- /* Sanity check: */
- assert(ctx != NULL);
-
- if ((ret = buffer) != NULL) {
- SHA512_Final(digest, ctx);
-
- for (i = 0; i < SHA512_DIGEST_LENGTH; i++) {
- *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4];
- *buffer++ = sha2_hex_digits[*d & 0x0f];
- d++;
- }
- *buffer = (char) 0;
- } else {
- (void) memset(ctx, 0, sizeof(SHA512_CTX));
- }
- (void) memset(digest, 0, SHA512_DIGEST_LENGTH);
- return ret;
-}
-
-char *
-SHA512_Data(const uint8_t * data, size_t len, char *digest)
-{
- SHA512_CTX ctx;
-
- SHA512_Init(&ctx);
- SHA512_Update(&ctx, data, len);
- return SHA512_End(&ctx, digest);
-}
diff --git a/ext/digest/sha2/sha2init.c b/ext/digest/sha2/sha2init.c
deleted file mode 100644
index 4b14031811..0000000000
--- a/ext/digest/sha2/sha2init.c
+++ /dev/null
@@ -1,47 +0,0 @@
-/* $RoughId: sha2init.c,v 1.3 2001/07/13 20:00:43 knu Exp $ */
-/* $Id$ */
-
-#include "digest.h"
-#include "sha2.h"
-
-#define FOREACH_BITLEN(func) func(256) func(384) func(512)
-
-#define DEFINE_ALGO_METADATA(bitlen) \
-static algo_t sha##bitlen = { \
- SHA##bitlen##_DIGEST_LENGTH, \
- sizeof(SHA##bitlen##_CTX), \
- (hash_init_func_t)SHA##bitlen##_Init, \
- (hash_update_func_t)SHA##bitlen##_Update, \
- (hash_end_func_t)SHA##bitlen##_End, \
- (hash_final_func_t)SHA##bitlen##_Final, \
- (hash_equal_func_t)SHA##bitlen##_Equal, \
-};
-
-FOREACH_BITLEN(DEFINE_ALGO_METADATA)
-
-void
-Init_sha2()
-{
- VALUE mDigest, cDigest_Base;
- ID id_metadata;
-
-#define DECLARE_ALGO_CLASS(bitlen) \
- VALUE cDigest_SHA##bitlen;
-
- FOREACH_BITLEN(DECLARE_ALGO_CLASS)
-
- rb_require("digest.so");
-
- id_metadata = rb_intern("metadata");
-
- mDigest = rb_path2class("Digest");
- cDigest_Base = rb_path2class("Digest::Base");
-
-#define DEFINE_ALGO_CLASS(bitlen) \
- cDigest_SHA##bitlen = rb_define_class_under(mDigest, "SHA" #bitlen, cDigest_Base); \
-\
- rb_cvar_set(cDigest_SHA##bitlen, id_metadata, \
- Data_Wrap_Struct(rb_cObject, 0, 0, &sha##bitlen), Qtrue);
-
- FOREACH_BITLEN(DEFINE_ALGO_CLASS)
-}
diff --git a/ext/digest/test.rb b/ext/digest/test.rb
deleted file mode 100644
index 2f29948bb6..0000000000
--- a/ext/digest/test.rb
+++ /dev/null
@@ -1,100 +0,0 @@
-#!/usr/bin/env ruby
-#
-# $RoughId: test.rb,v 1.4 2001/07/13 15:38:27 knu Exp $
-# $Id$
-
-require 'runit/testcase'
-require 'runit/cui/testrunner'
-
-require 'digest/md5'
-require 'digest/rmd160'
-require 'digest/sha1'
-require 'digest/sha2'
-include Digest
-
-class TestDigest < RUNIT::TestCase
- ALGOS = [
- MD5,
- SHA1,
- SHA256,
- SHA384,
- SHA512,
- RMD160
- ]
-
- DATA = {
- "abc" => {
- MD5 => "900150983cd24fb0d6963f7d28e17f72",
- SHA1 => "a9993e364706816aba3e25717850c26c9cd0d89d",
- SHA256 => "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
- SHA384 => "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7",
- SHA512 => "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f",
- RMD160 => "8eb208f7e05d987a9b044a8e98c6b087f15a0bfc"
- },
-
- "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" => {
- MD5 => "8215ef0796a20bcaaae116d3876c664a",
- SHA1 => "84983e441c3bd26ebaae4aa1f95129e5e54670f1",
- SHA256 => "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1",
- SHA384 => "3391fdddfc8dc7393707a65b1b4709397cf8b1d162af05abfe8f450de5f36bc6b0455a8520bc4e6f5fe95b1fe3c8452b",
- SHA512 => "204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c33596fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445",
- RMD160 => "12a053384a9c0c88e405a06c27dcf49ada62eb2b"
- }
- }
-
- def test_s_hexdigest
- ALGOS.each do |algo|
- DATA.each do |str, table|
- assert_equal(table[algo], algo.hexdigest(str))
- end
- end
- end
-
- def test_s_digest
- ALGOS.each do |algo|
- DATA.each do |str, table|
- assert_equal([table[algo]].pack("H*"), algo.digest(str))
- end
- end
- end
-
- def test_update
- # This test is also for digest() and hexdigest()
-
- str = "ABC"
-
- ALGOS.each do |algo|
- md = algo.new
- md.update str
- assert_equal(algo.hexdigest(str), md.hexdigest)
- assert_equal(algo.digest(str), md.digest)
- end
- end
-
- def test_eq
- # This test is also for clone()
-
- ALGOS.each do |algo|
- md1 = algo.new("ABC")
-
- assert_equal(md1, md1.clone)
-
- md2 = algo.new
- md2 << "A"
-
- assert(md1 != md2)
-
- md2 << "BC"
-
- assert_equal(md1, md2)
- end
- end
-end
-
-if $0 == __FILE__
- suite = RUNIT::TestSuite.new
-
- suite.add_test(TestDigest.suite)
-
- RUNIT::CUI::TestRunner.run(suite)
-end
diff --git a/ext/digest/test.sh b/ext/digest/test.sh
deleted file mode 100644
index 88b34b04c5..0000000000
--- a/ext/digest/test.sh
+++ /dev/null
@@ -1,27 +0,0 @@
-#!/bin/sh
-#
-# $RoughId: test.sh,v 1.5 2001/07/13 15:38:27 knu Exp $
-# $Id$
-
-RUBY=${RUBY:=ruby}
-MAKE=${MAKE:=make}
-CFLAGS=${CFLAGS:=-Wall}
-
-${RUBY} extconf.rb --with-cflags="${CFLAGS}"
-${MAKE} clean
-${MAKE}
-
-mkdir -p lib/digest
-
-for algo in md5 rmd160 sha1 sha2; do
- (cd $algo &&
- ${RUBY} extconf.rb --with-cflags="${CFLAGS}";
- ${MAKE} clean;
- ${MAKE})
- ln -sf ../../$algo/$algo.so lib/digest/
-done
-
-${RUBY} -I. -I./lib test.rb
-
-rm lib/digest/*.so
-rmdir lib/digest
diff --git a/ext/etc/.cvsignore b/ext/etc/.cvsignore
deleted file mode 100644
index fc802ff1c2..0000000000
--- a/ext/etc/.cvsignore
+++ /dev/null
@@ -1,2 +0,0 @@
-Makefile
-mkmf.log
diff --git a/ext/etc/MANIFEST b/ext/etc/MANIFEST
deleted file mode 100644
index 62cf5be233..0000000000
--- a/ext/etc/MANIFEST
+++ /dev/null
@@ -1,6 +0,0 @@
-MANIFEST
-etc.c
-etc.txt
-etc.txt.ja
-depend
-extconf.rb
diff --git a/ext/etc/depend b/ext/etc/depend
deleted file mode 100644
index ac706477b0..0000000000
--- a/ext/etc/depend
+++ /dev/null
@@ -1 +0,0 @@
-etc.o : etc.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h
diff --git a/ext/etc/etc.c b/ext/etc/etc.c
deleted file mode 100644
index 5c54237b7a..0000000000
--- a/ext/etc/etc.c
+++ /dev/null
@@ -1,276 +0,0 @@
-/************************************************
-
- etc.c -
-
- $Author$
- $Date$
- created at: Tue Mar 22 18:39:19 JST 1994
-
-************************************************/
-
-#include "ruby.h"
-
-#include <sys/types.h>
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-
-#ifdef HAVE_GETPWENT
-#include <pwd.h>
-#endif
-
-#ifdef HAVE_GETGRENT
-#include <grp.h>
-#endif
-
-static VALUE sPasswd, sGroup;
-
-static VALUE
-etc_getlogin(obj)
- VALUE obj;
-{
- char *getenv();
- char *login;
-
-#ifdef HAVE_GETLOGIN
- char *getlogin();
-
- login = getlogin();
- if (!login) login = getenv("USER");
-#else
- login = getenv("USER");
-#endif
-
- if (login)
- return rb_tainted_str_new2(login);
- return Qnil;
-}
-
-#ifdef HAVE_GETPWENT
-static VALUE
-setup_passwd(pwd)
- struct passwd *pwd;
-{
- if (pwd == 0) rb_sys_fail("/etc/passwd");
- return rb_struct_new(sPasswd,
- rb_tainted_str_new2(pwd->pw_name),
- rb_tainted_str_new2(pwd->pw_passwd),
- INT2FIX(pwd->pw_uid),
- INT2FIX(pwd->pw_gid),
-#ifdef PW_GECOS
- rb_tainted_str_new2(pwd->pw_gecos),
-#endif
- rb_tainted_str_new2(pwd->pw_dir),
- rb_tainted_str_new2(pwd->pw_shell),
-#ifdef PW_CHANGE
- INT2FIX(pwd->pw_change),
-#endif
-#ifdef PW_QUOTA
- INT2FIX(pwd->pw_quota),
-#endif
-#ifdef PW_AGE
- INT2FIX(pwd->pw_age),
-#endif
-#ifdef PW_CLASS
- rb_tainted_str_new2(pwd->pw_class),
-#endif
-#ifdef PW_COMMENT
- rb_tainted_str_new2(pwd->pw_comment),
-#endif
-#ifdef PW_EXPIRE
- INT2FIX(pwd->pw_expire),
-#endif
- 0 /*dummy*/
- );
-}
-#endif
-
-static VALUE
-etc_getpwuid(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
-#ifdef HAVE_GETPWENT
- VALUE id;
- int uid;
- struct passwd *pwd;
-
- if (rb_scan_args(argc, argv, "01", &id) == 1) {
- uid = NUM2INT(id);
- }
- else {
- uid = getuid();
- }
- pwd = getpwuid(uid);
- if (pwd == 0) rb_raise(rb_eArgError, "can't find user for %d", uid);
- return setup_passwd(pwd);
-#else
- return Qnil;
-#endif
-}
-
-static VALUE
-etc_getpwnam(obj, nam)
- VALUE obj, nam;
-{
-#ifdef HAVE_GETPWENT
- struct passwd *pwd;
-
- StringValue(nam);
- pwd = getpwnam(RSTRING(nam)->ptr);
- if (pwd == 0) rb_raise(rb_eArgError, "can't find user for %s", RSTRING(nam)->ptr);
- return setup_passwd(pwd);
-#else
- return Qnil;
-#endif
-}
-
-static VALUE
-etc_passwd(obj)
- VALUE obj;
-{
-#ifdef HAVE_GETPWENT
- struct passwd *pw;
-
- if (rb_block_given_p()) {
- setpwent();
- while (pw = getpwent()) {
- rb_yield(setup_passwd(pw));
- }
- endpwent();
- return obj;
- }
- if (pw = getpwent()) {
- return setup_passwd(pw);
- }
-#endif
- return Qnil;
-}
-
-#ifdef HAVE_GETGRENT
-static VALUE
-setup_group(grp)
- struct group *grp;
-{
- VALUE mem;
- char **tbl;
-
- mem = rb_ary_new();
- tbl = grp->gr_mem;
- while (*tbl) {
- rb_ary_push(mem, rb_tainted_str_new2(*tbl));
- tbl++;
- }
- return rb_struct_new(sGroup,
- rb_tainted_str_new2(grp->gr_name),
- rb_tainted_str_new2(grp->gr_passwd),
- INT2FIX(grp->gr_gid),
- mem);
-}
-#endif
-
-static VALUE
-etc_getgrgid(obj, id)
- VALUE obj, id;
-{
-#ifdef HAVE_GETGRENT
- int gid;
- struct group *grp;
-
- gid = NUM2INT(id);
- grp = getgrgid(gid);
- if (grp == 0) rb_raise(rb_eArgError, "can't find group for %d", gid);
- return setup_group(grp);
-#else
- return Qnil;
-#endif
-}
-
-static VALUE
-etc_getgrnam(obj, nam)
- VALUE obj, nam;
-{
-#ifdef HAVE_GETGRENT
- struct group *grp;
-
- StringValue(nam);
- grp = getgrnam(RSTRING(nam)->ptr);
- if (grp == 0) rb_raise(rb_eArgError, "can't find group for %s", RSTRING(nam)->ptr);
- return setup_group(grp);
-#else
- return Qnil;
-#endif
-}
-
-static VALUE
-etc_group(obj)
- VALUE obj;
-{
-#ifdef HAVE_GETGRENT
- struct group *grp;
-
- if (rb_block_given_p()) {
- setgrent();
- while (grp = getgrent()) {
- rb_yield(setup_group(grp));
- }
- endgrent();
- return obj;
- }
- if (grp = getgrent()) {
- return setup_group(grp);
- }
-#endif
- return Qnil;
-}
-
-static VALUE mEtc;
-
-void
-Init_etc()
-{
- mEtc = rb_define_module("Etc");
-
- rb_define_module_function(mEtc, "getlogin", etc_getlogin, 0);
-
- rb_define_module_function(mEtc, "getpwuid", etc_getpwuid, -1);
- rb_define_module_function(mEtc, "getpwnam", etc_getpwnam, 1);
- rb_define_module_function(mEtc, "passwd", etc_passwd, 0);
-
- rb_define_module_function(mEtc, "getgrgid", etc_getgrgid, 1);
- rb_define_module_function(mEtc, "getgrnam", etc_getgrnam, 1);
- rb_define_module_function(mEtc, "group", etc_group, 0);
-
- sPasswd = rb_struct_define("Passwd",
- "name", "passwd", "uid", "gid",
-#ifdef PW_GECOS
- "gecos",
-#endif
- "dir", "shell",
-#ifdef PW_CHANGE
- "change",
-#endif
-#ifdef PW_QUOTA
- "quota",
-#endif
-#ifdef PW_AGE
- "age",
-#endif
-#ifdef PW_CLASS
- "class",
-#endif
-#ifdef PW_COMMENT
- "comment",
-#endif
-#ifdef PW_EXPIRE
- "expire",
-#endif
- 0);
- rb_global_variable(&sPasswd);
-
-#ifdef HAVE_GETGRENT
- sGroup = rb_struct_define("Group", "name", "passwd", "gid", "mem", 0);
- rb_global_variable(&sGroup);
-#endif
-}
diff --git a/ext/etc/etc.txt b/ext/etc/etc.txt
deleted file mode 100644
index 534790172c..0000000000
--- a/ext/etc/etc.txt
+++ /dev/null
@@ -1,72 +0,0 @@
-.\" etc.txt - -*- Indented-Text -*- created at: Fri Jul 14 00:47:15 JST 1995
-
-** Etc(Module)
-
-The module to retrieve information under /etc directory. Available
-only on UNIX platforms. All operations defined in this module are
-module functions, so that you can include Etc module into your class.
-
-Module Function:
-
- getlogin
-
- returns login name of the user. It this fails, try getpwuid().
-
- getpwnam(name)
-
- searches in /etc/passwd file (or equivalent database), and
- returns password entry for the user. The return value is an
- passwd structure, which has members described below.
-
- struct passwd
- name # user name(string)
- passwd # encrypted password(string)
- uid # user ID(integer)
- gid # group ID(integer)
- gecos # gecos field(string)
- dir # home directory(string)
- shell # login shell(string)
- # members below are optional
- change # password change time(integer)
- quota # quota value(integer)
- age # password age(integer)
- class # user access class(string)
- comment # comment(string)
- expire # account expiration time(integer)
- end
-
- See getpwnam(3) for detail.
-
- getpwuid([uid])
-
- returns passwd entry for the specified user id. If uid is
- ommitted, use the value from getuid(). See getpwuid(3) for
- detail.
-
- getgrgid(gid)
-
- searches in /etc/group file (or equivalent database), and
- returns group entry for the group id. The return value is an
- group structure, which has members described below.
-
- struct group
- name # group name(string)
- passwd # group password(string)
- gid # group ID(integer)
- mem # array of the group member names
- end
-
- See getgrgid(3) for detail.
-
- getgrnam(name)
-
- returns the group entry for the specified name. The return
- value is the group structure. See getgrnam(3) for detail.
-
- group
-
- iterates over all group entries.
-
- passwd
-
- iterates over all passwd entries.
diff --git a/ext/etc/etc.txt.ja b/ext/etc/etc.txt.ja
deleted file mode 100644
index 2dddcfb036..0000000000
--- a/ext/etc/etc.txt.ja
+++ /dev/null
@@ -1,72 +0,0 @@
-.\" etc.txt.ja - -*- Indented-Text -*- created at: Fri Jul 14 00:47:15 JST 1995
-
-** Etc(モジュール)
-
-/etcディレクトリ以下の情報を得るためのモジュール.クラスにインクルード
-して使うこともできる.
-
-Module Function:
-
- getlogin
-
- 自分のlogin名を返す.これが失敗した場合はgetpwuid()を用いると
- 良い.
-
- getpwnam(name)
-
- /etc/passwdファイル(あるいはDBMファイルやNISデータベース)を検
- 索し,nameの名前を持つpasswdエントリを返す.戻り値はpasswd構造
- 体で以下のメンバを持つ.
-
- struct passwd
- name # ユーザ名(文字列)
- passwd # パスワード(文字列)
- uid # ユーザID(整数)
- gid # グループID(整数)
- gecos # gecosフィールド(文字列)
- dir # ホームディレクトリ(文字列)
- shell # ログインシェル(文字列)
- # 以降のメンバはシステムによっては提供されない.
- change # パスワード変更時間(整数)
- quota # クォータ(整数)
- age # エージ(整数)
- class # ユーザアクセスクラス(文字列)
- comment # コメント(文字列)
- expire # アカウント有効期限(整数)
- end
-
- 詳細はgetpwnam(3)を参照のこと.
-
- getpwuid([uid])
-
- uidをユーザIDとするpasswdエントリを返す.戻り値はgetpwnam()と
- 同様である.引数を省略した場合にはgetuid()の値を用いる.詳細は
- getpwuid(3)を参照のこと.
-
- getgrgid(gid)
-
- /etc/groupファイル(あるいは…getpwnam参照)を検索し,gidをグルー
- プIDとするグループエントリを返す.戻り値はgroup構造体で以下の
- メンバを持つ.
-
- struct group
- name # グループ名(文字列)
- passwd # グループのパスワード(文字列)
- gid # グループID(整数)
- mem # グループメンバ名の配列
- end
-
- 詳細はgetgrgid(3)を参照のこと.
-
- getgrnam(name)
-
- nameという名前のグループエントリを返す.戻り値はgetgrgid()と同
- 様である.詳細はgetgrnam(3)を参照.
-
- group
-
- 全てのグループエントリを順にアクセスするためのイテレータ.
-
- passwd
-
- 全てのpasswdエントリを順にアクセスするためのイテレータ.
diff --git a/ext/etc/extconf.rb b/ext/etc/extconf.rb
deleted file mode 100644
index b920d91a95..0000000000
--- a/ext/etc/extconf.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-require 'mkmf'
-
-def etc_grep_header(field)
- if egrep_cpp(field, "#include <pwd.h>\n")
- $defs.push(format("-D%s", field.upcase))
- end
-end
-
-have_library("sun", "getpwnam") # NIS (== YP) interface for IRIX 4
-a = have_func("getlogin")
-b = have_func("getpwent")
-c = have_func("getgrent")
-if a or b or c
- etc_grep_header("pw_gecos")
- etc_grep_header("pw_change")
- etc_grep_header("pw_quota")
- etc_grep_header("pw_age")
- etc_grep_header("pw_class")
- etc_grep_header("pw_comment") unless /cygwin/ === RUBY_PLATFORM
- etc_grep_header("pw_expire")
- create_makefile("etc")
-end
diff --git a/ext/extmk.rb.in b/ext/extmk.rb.in
deleted file mode 100644
index dd7cabfc98..0000000000
--- a/ext/extmk.rb.in
+++ /dev/null
@@ -1,780 +0,0 @@
-#! /usr/local/bin/ruby
-# -*- ruby -*-
-
-$".push 'mkmf.rb' # "
-ORIG_LIBPATH = ENV['LIB']
-
-if ARGV[0] == 'static'
- $force_static = true
- ARGV.shift
-elsif ARGV[0] == 'install'
- $install = true
- $destdir = ARGV[1] || ''
- ARGV.shift
-elsif ARGV[0] == 'clean'
- $clean = "clean"
- ARGV.shift
-elsif ARGV[0] == 'distclean'
- $clean = "distclean"
- ARGV.shift
-elsif ARGV[0] == 'realclean'
- $clean = "realclean"
- ARGV.shift
-end
-
-SRC_EXT = ["c", "cc", "m", "cxx", "cpp", "C"]
-$extlist = []
-
-$includedir = "@includedir@"
-$libdir = "@libdir@"
-
-$top_srcdir = "@top_srcdir@"
-if $top_srcdir !~ "^/"
- # get absolute path
- $top_srcdir = File.expand_path($top_srcdir)
-end
-# get absolute path
-$topdir = File.expand_path("..")
-
-$:.replace [$topdir, $top_srcdir, $top_srcdir+"/lib", "."]
-
-require 'rbconfig.rb'
-require 'find'
-
-def rm_f(*files)
- targets = []
- for file in files
- targets.concat Dir[file]
- end
- if not targets.empty?
- File::chmod(0777, *targets)
- File::unlink(*targets)
- end
-end
-
-def older(file1, file2)
- if !File.exist?(file1) then
- return true
- end
- if !File.exist?(file2) then
- return false
- end
- if File.mtime(file1) < File.mtime(file2)
- return true
- end
- return false
-end
-
-CFLAGS = "@CFLAGS@"
-if RUBY_PLATFORM == "m68k-human"
- CFLAGS.gsub!(/-c..-stack=[0-9]+ */, '')
-end
-if /mswin32/ =~ RUBY_PLATFORM
- OUTFLAG = '-Fe'
-else
- OUTFLAG = '-o '
-end
-LINK = "@CC@ #{OUTFLAG}conftest -I#$topdir -I#$top_srcdir #{CFLAGS} -I#$includedir @LDFLAGS@ %s %s %s conftest.c %s %s @LIBS@"
-CPP = "@CPP@ @CPPFLAGS@ -I#$topdir -I#$top_srcdir #{CFLAGS} -I#$includedir %s %s %s conftest.c"
-
-$log = open('extmk.log', 'w')
-
-$orgerr = $stderr.dup
-$orgout = $stdout.dup
-def xsystem command
- if $DEBUG
- puts command
- return system(command)
- end
- $stderr.reopen($log)
- $stdout.reopen($log)
- puts command
- r = system(command)
- $stderr.reopen($orgerr)
- $stdout.reopen($orgout)
- return r
-end
-
-def try_link0(src, opt="")
- cfile = open("conftest.c", "w")
- cfile.print src
- cfile.close
- ldflags = $LDFLAGS
- if /mswin32/ =~ RUBY_PLATFORM and !$LIBPATH.empty?
- ENV['LIB'] = ($LIBPATH + [ORIG_LIBPATH]).compact.join(';')
- else
- ldflags = ldflags.dup
- $LIBPATH.each {|d| ldflags << " -L" + d}
- end
- begin
- xsystem(Config::expand(format(LINK, $CFLAGS, $CPPFLAGS, ldflags, opt, $LOCAL_LIBS)))
- ensure
- ENV['LIB'] = ORIG_LIBPATH if /mswin32/ =~ RUBY_PLATFORM
- end
-end
-
-def try_link(src, opt="")
- begin
- try_link0(src, opt)
- ensure
- rm_f "conftest*"
- end
-end
-
-def try_cpp(src, opt="")
- cfile = open("conftest.c", "w")
- cfile.print src
- cfile.close
- begin
- xsystem(Config::expand(format(CPP, $CFLAGS, $CPPFLAGS, opt)))
- ensure
- rm_f "conftest*"
- end
-end
-
-def egrep_cpp(pat, src, opt="")
- cfile = open("conftest.c", "w")
- cfile.print src
- cfile.close
- begin
- xsystem(Config::expand(format(CPP, $CFLAGS, $CPPFLAGS, opt))+"|egrep #{pat}")
- ensure
- rm_f "conftest*"
- end
-end
-
-def try_run(src, opt="")
- begin
- if try_link0(src, opt)
- if xsystem("./conftest")
- true
- else
- false
- end
- else
- nil
- end
- ensure
- rm_f "conftest*"
- end
-end
-
-def install_rb(mfile, srcdir = nil)
- libdir = "lib"
- libdir = srcdir + "/" + libdir if srcdir
- path = []
- dir = []
- if File.directory? libdir
- Find.find(libdir) do |f|
- next unless /\.rb$/ =~ f
- f = f[libdir.length+1..-1]
- path.push f
- dir |= [File.dirname(f)]
- end
- end
- for f in dir
- if f == "."
- mfile.print "\t@$(RUBY) -r ftools -e 'File::makedirs(*ARGV)' $(DESTDIR)$(pkglibdir)$(target_prefix)\n"
- else
- mfile.printf "\t@$(RUBY) -r ftools -e 'File::makedirs(*ARGV)' $(DESTDIR)$(pkglibdir)$(target_prefix)/%s\n", f
- end
- end
- for f in path
- mfile.printf "\t@$(RUBY) -r ftools -e 'File::install(ARGV[0], ARGV[1], 0644, true)' $(srcdir)/lib/%s $(DESTDIR)$(pkglibdir)$(target_prefix)/%s\n", f, f
- end
-end
-
-def append_library(libs, lib)
- if /mswin32/ =~ RUBY_PLATFORM
- lib + ".lib " + libs
- else
- "-l" + lib + " " + libs
- end
-end
-
-def have_library(lib, func="main")
- if func && func != ""
- libs = append_library($libs, lib)
- if /mswin32|mingw/ =~ RUBY_PLATFORM
- return true if lib == 'm'
- r = try_link(<<"SRC", libs)
-#include <windows.h>
-#include <winsock.h>
-int main() { return 0; }
-int t() { #{func}(); return 0; }
-SRC
- unless r
- r = try_link(<<"SRC", libs)
-#include <windows.h>
-#include <winsock.h>
-int main() { return 0; }
-int t() { void ((*p)()); p = (void ((*)()))#{func}; return 0; }
-SRC
- end
- else
- r = try_link(<<"SRC", libs)
-int main() { return 0; }
-int t() { #{func}(); return 0; }
-SRC
- end
- unless r
- return false
- end
- else
- libs = append_library($libs, lib)
- end
-
- $libs = libs
- return true
-end
-
-def find_library(lib, func, *paths)
- libpath = $LIBPATH
- libs = append_library($libs, lib)
- until try_link(<<"SRC", libs)
-int main() { return 0; }
-int t() { #{func}(); return 0; }
-SRC
- if paths.size == 0
- $LIBPATH = libpath
- return false
- end
- $LIBPATH = libpath | [paths.shift]
- end
- $libs = libs
- return true
-end
-
-def have_func(func, header=nil)
- libs = $libs
- src =
- if /mswin32|mingw/ =~ RUBY_PLATFORM
- r = <<"SRC"
-#include <windows.h>
-#include <winsock.h>
-SRC
- else
- ""
- end
- unless header.nil?
- src << <<"SRC"
-#include <#{header}>
-SRC
- end
- r = try_link(src + <<"SRC", libs)
-int main() { return 0; }
-int t() { #{func}(); return 0; }
-SRC
- unless r
- r = try_link(src + <<"SRC", libs)
-int main() { return 0; }
-int t() { void ((*p)()); p = (void ((*)()))#{func}; return 0; }
-SRC
- end
- unless r
- return false
- end
- $defs.push(format("-DHAVE_%s", func.upcase))
- return true
-end
-
-def have_header(header)
- unless try_cpp(<<"SRC")
-#include <#{header}>
-SRC
- return false
- end
- $defs.push(format("-DHAVE_%s", header.tr("a-z./\055", "A-Z___")))
- return true
-end
-
-def arg_config(config, default=nil)
- unless defined? $configure_args
- $configure_args = {}
- args = "@configure_args@"
- if /mswin32|mingw/ =~ RUBY_PLATFORM and ENV["CONFIGURE_ARGS"]
- args << " " << ENV["CONFIGURE_ARGS"]
- end
- for arg in args.split
- next unless /^--/ =~ arg
- arg, val = arg.split('=', 2)
- $configure_args[arg] = val || true
- end
- end
- $configure_args.fetch(config, default)
-end
-
-def with_config(config, default=nil)
- unless /^--with-/ =~ config
- config = '--with-' + config
- end
- arg_config(config, default)
-end
-
-def enable_config(config, default=nil)
- if arg_config("--enable-"+config, default)
- true
- elsif arg_config("--disable-"+config, false)
- false
- else
- default
- end
-end
-
-def create_header()
- if $defs.length > 0
- hfile = open("extconf.h", "w")
- for line in $defs
- line =~ /^-D(.*)/
- hfile.printf "#define %s 1\n", $1
- end
- hfile.close
- end
-end
-
-def dir_config(target, idefault=nil, ldefault=nil)
- if dir = with_config(target + "-dir", (idefault unless ldefault))
- idefault = dir + "/include"
- ldefault = dir + "/lib"
- end
-
- idir = with_config(target + "-include", idefault)
- ldir = with_config(target + "-lib", ldefault)
-
- if idir
- idircflag = "-I" + idir
- $CPPFLAGS += " " + idircflag unless $CPPFLAGS.split.include?(idircflag)
- end
-
- if ldir
- $LIBPATH << ldir unless $LIBPATH.include?(ldir)
- end
-
- [idir, ldir]
-end
-
-def create_makefile(target)
- $target = target
- if target.include?('/')
- target_prefix, target = File.split(target)
- target_prefix[0,0] = '/'
- else
- target_prefix = ""
- end
- rm_f "conftest*"
- if "@DLEXT@" == $OBJEXT
- libs = $libs.split
- for lib in libs
- lib.sub!(/-l(.*)/, %%"lib\\1.#{$LIBEXT}"%)
- end
- $defs.push(format("-DEXTLIB='%s'", libs.join(",")))
- end
-
- $DLDFLAGS = '@DLDFLAGS@'
-
- if $configure_args['--enable-shared'] or "@LIBRUBY@" != "@LIBRUBY_A@"
- $libs = "@LIBRUBYARG@ " + $libs
- $LIBPATH.unshift $topdir
- end
-
- defflag = ''
- if RUBY_PLATFORM =~ /cygwin|mingw/ and not $static
- if not File.exist? target + '.def'
- open(target + '.def', 'wb') do |f|
- f.print "EXPORTS\n", "Init_", target, "\n"
- end
- end
- defflag = "--def=" + target + ".def"
- end
-
- if RUBY_PLATFORM =~ /mswin32/
- libpath = $LIBPATH.join(';')
- else
- $LIBPATH.each {|d| $DLDFLAGS << " -L" << d}
- if /netbsdelf/ =~ RUBY_PLATFORM
- $LIBPATH.each {|d| $DLDFLAGS << " -Wl,-R" + d unless d == $topdir}
- end
- end
-
- $srcdir = $top_srcdir + "/ext/" + $mdir
- mfile = open("Makefile", "w")
- mfile.binmode if /mingw/ =~ RUBY_PLATFORM
- mfile.printf "\
-SHELL = /bin/sh
-
-#### Start of system configuration section. ####
-
-srcdir = #{$srcdir}
-VPATH = #{$srcdir}
-
-topdir = #{$topdir}
-hdrdir = #{$top_srcdir}
-
-CC = @CC@
-
-CFLAGS = %s #{CFLAGS} #$CFLAGS
-CPPFLAGS = -I$(topdir) -I$(hdrdir) -I@includedir@ %s #$CPPFLAGS
-DLDFLAGS = #$DLDFLAGS #$LDFLAGS
-LDSHARED = @LDSHARED@ #{defflag}
-", if $static then "" else "@CCDLFLAGS@" end, $defs.join(" ")
- mfile.puts "LIBPATH = #{libpath}" if libpath
-
- mfile.puts ".SUFFIXES: .@OBJEXT@" unless "@OBJEXT@" == "o"
-
- mfile.printf "\
-
-RUBY_INSTALL_NAME = @RUBY_INSTALL_NAME@
-RUBY_SO_NAME = @RUBY_SO_NAME@
-
-prefix = @prefix@
-exec_prefix = @exec_prefix@
-libdir = @libdir@
-#pkglibdir = $(libdir)/$(RUBY_INSTALL_NAME)/@MAJOR@.@MINOR@
-pkglibdir = $(libdir)/ruby/@MAJOR@.@MINOR@
-archdir = $(pkglibdir)/@arch@
-target_prefix = #{target_prefix}
-@SET_MAKE@
-
-#### End of system configuration section. ####
-
-"
- mfile.printf "LOCAL_LIBS = %s %s\n", $LOCAL_LIBS, $local_flags
- mfile.printf "LIBS = %s\n", $libs
- mfile.printf "OBJS = "
- if !$objs then
- $objs = []
- for f in Dir["#{$top_srcdir}/ext/#{$mdir}/*.{#{SRC_EXT.join(%q{,})}}"]
- f = File.basename(f)
- f.sub!(/(#{SRC_EXT.join(%q{|})})$/, $OBJEXT)
- $objs.push f
- end
- else
- for i in $objs
- i.sub!(/\.o\z/, ".#{$OBJEXT}")
- end
- end
- mfile.printf $objs.join(" ")
- mfile.printf "\n"
-
- ruby_interpreter = "$(topdir)/miniruby@EXEEXT@"
- if /nmake/i =~ $make
- ruby_interpreter = '$(topdir:/=\)\miniruby@EXEEXT@'
- end
- if defined? CROSS_COMPILING
- ruby_interpreter = "@MINIRUBY@"
- end
-
- mfile.printf <<EOS
-TARGET = #{target}
-DLLIB = $(TARGET).#{$static ? $LIBEXT : "@DLEXT@"}
-
-RUBY = #{ruby_interpreter} -I$(topdir) -I$(hdrdir)/lib
-RM = $(RUBY) -rftools -e "File::rm_f(*ARGV.map{|x|Dir[x]}.flatten.uniq)"
-
-EXEEXT = @EXEEXT@
-
-all: $(DLLIB)
-
-clean:; @$(RM) *.#{$OBJEXT} *.so *.sl *.#{$LIBEXT} $(DLLIB)
- @$(RM) *.ilk *.exp *.pdb *.bak $(CLEANFILES)
-
-distclean: clean
- @$(RM) Makefile extconf.h conftest.*
- @$(RM) core ruby$(EXEEXT) *~ $(DISTCLEANFILES)
-
-realclean: distclean
-EOS
-
- mfile.printf <<EOS
-
-install:
- @$(RUBY) -r ftools -e 'File::makedirs(*ARGV)' $(DESTDIR)$(libdir) $(DESTDIR)$(pkglibdir) $(DESTDIR)$(archdir)$(target_prefix)
-
-EOS
- unless $static
- mfile.printf "\
- @$(RUBY) -r ftools -e 'File::install(ARGV[0], ARGV[1], 0555, true)' $(DLLIB) $(DESTDIR)$(archdir)$(target_prefix)/$(DLLIB)
-"
- end
- install_rb(mfile, $srcdir)
- mfile.printf "\n"
-
- unless /mswin32/ =~ RUBY_PLATFORM
- src = '$<'
- copt = cxxopt = ''
- else
- if /nmake/i =~ $make
- src = '$(<:\\=/)'
- else
- src = '$(subst /,\\\\,$<)'
- end
- copt = '-Tc'
- cxxopt = '-Tp'
- end
- unless /nmake/i =~ $make
- mfile.puts "
-.cc.@OBJEXT@:
- $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c #{cxxopt}#{src}
-.cpp.@OBJEXT@:
- $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c #{cxxopt}#{src}
-.cxx.@OBJEXT@:
- $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c #{cxxopt}#{src}
-.C.@OBJEXT@:
- $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c #{cxxopt}#{src}
-.c.@OBJEXT@:
- $(CC) $(CFLAGS) $(CPPFLAGS) -c #{copt}#{src}
-"
- else
- mfile.print "
-{$(srcdir)}.c{}.@OBJEXT@:
- $(CC) -I. -I$(<D) $(CFLAGS) $(CPPFLAGS) -c #{copt}#{src}
-.c.@OBJEXT@:
- $(CC) $(CFLAGS) $(CPPFLAGS) -c #{copt}#{src}
-{$(srcdir)}.cc{}.@OBJEXT@:
- $(CXX) -I. -I$(<D) $(CXXFLAGS) $(CPPFLAGS) -c #{cxxopt}#{src}
-.cc.@OBJEXT@:
- $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c #{cxxopt}#{src}
-{$(srcdir)}.cpp{}.@OBJEXT@:
- $(CXX) -I. -I$(<D) $(CXXFLAGS) $(CPPFLAGS) -c #{cxxopt}#{src}
-.cpp.@OBJEXT@:
- $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c #{cxxopt}#{src}
-{$(srcdir)}.cxx{}.@OBJEXT@:
- $(CXX) -I. -I$(<D) $(CXXFLAGS) $(CPPFLAGS) -c #{cxxopt}#{src}
-.cxx.@OBJEXT@:
- $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c #{cxxopt}#{src}
-"
- end
-
- if $static
- if "@AR@" =~ /^lib\b/i
- mfile.printf "\
-$(DLLIB): $(OBJS)
- @AR@ /OUT:$(DLLIB) $(OBJS)
-"
- else
- mfile.printf "\
-$(DLLIB): $(OBJS)
- @AR@ cru $(DLLIB) $(OBJS)
- @-@RANLIB@ $(DLLIB) 2> /dev/null || true
-"
- end
- elsif "@DLEXT@" != $OBJEXT
- mfile.print "$(DLLIB): $(OBJS)\n"
- if /mswin32/ =~ RUBY_PLATFORM
- if /nmake/i =~ $make
- mfile.print "\tset LIB=$(LIBPATH:/=\\);$(LIB)\n"
- else
- mfile.print "\tenv LIB='$(subst /,\\\\,$(LIBPATH));$(LIB)' \\\n"
- end
- end
- mfile.print "\t$(LDSHARED) $(DLDFLAGS) #{OUTFLAG}$(DLLIB) $(OBJS) $(LIBS) $(LOCAL_LIBS)\n"
- elsif RUBY_PLATFORM == "m68k-human"
- mfile.printf "\
-$(DLLIB): $(OBJS)
- ar cru $(DLLIB) $(OBJS)
-"
- else
- mfile.printf "\
-$(DLLIB): $(OBJS)
- ld $(DLDFLAGS) -r -o $(DLLIB) $(OBJS)
-"
- end
-
- if File.exist?("#{$srcdir}/depend")
- dfile = open("#{$srcdir}/depend", "r")
- mfile.printf "###\n"
- while line = dfile.gets()
- line.gsub!(/\.o\b/, ".#{$OBJEXT}")
- line.gsub!(/(\s)([^\s\/]+\.[ch])/, '\1$(srcdir)/\2') if /nmake/i =~ $make
- mfile.printf "%s", line.gsub('\$\(hdrdir\)/config.h', '$(topdir)/config.h')
- end
- dfile.close
- end
- mfile.close
-end
-
-def extmake(target)
- if $force_static or $static_ext[target]
- $static = target
- else
- $static = false
- end
-
- unless $install or $clean
- return if $nodynamic and not $static
- end
-
- $OBJEXT = "@OBJEXT@"
- $LIBEXT = "a"
- $objs = nil
- $libs = "@DLDLIBS@"
- $local_flags = ""
- if /mswin32/ =~ RUBY_PLATFORM
- $LIBEXT = "lib"
- $local_flags = "-link /INCREMENTAL:no /EXPORT:Init_$(TARGET)"
- end
- $LOCAL_LIBS = "" # to be assigned in extconf.rb
- $CFLAGS = ""
- $CPPFLAGS = "@CPPFLAGS@"
- $LDFLAGS = ""
- $LIBPATH = [$libdir]
-
- dir_config("opt")
-
- begin
- dir = Dir.pwd
- Dir.mkdir target unless File.directory?(target)
- Dir.chdir target
- $target = target
- $mdir = target
- unless $install or $clean
- if $static_ext.size > 0 ||
- !File.exist?("./Makefile") ||
- older("./Makefile", "#{$top_srcdir}/ext/@setup@") ||
- older("./Makefile", "#{$topdir}/ext/extmk.rb") ||
- older("./Makefile", "#{$top_srcdir}/ext/#{target}/makefile.rb") ||
- older("./Makefile", "#{$top_srcdir}/ext/#{target}/extconf.rb")
- then
- $defs = []
- if File.exist?("#{$top_srcdir}/ext/#{target}/makefile.rb")
- load "#{$top_srcdir}/ext/#{target}/makefile.rb"
- elsif File.exist?("#{$top_srcdir}/ext/#{target}/extconf.rb")
- load "#{$top_srcdir}/ext/#{target}/extconf.rb"
- else
- create_makefile(target)
- end
- end
- end
- if File.exist?("./Makefile")
- if $static
- $extlist.push [$static, File.basename($target)]
- end
- if $install
- system "#{$make} install DESTDIR=#{$destdir}"
- elsif $clean
- system "#{$make} #{$clean}"
- else
- unless system "#{$make} all"
- if ENV["MAKEFLAGS"] != "k" and ENV["MFLAGS"] != "-k"
- exit
- end
- end
- end
- end
- if $static
- $extlibs ||= ""
- $extlibs += " " + $LDFLAGS unless $LDFLAGS == ""
- $extlibs += " " + $libs unless $libs == ""
- $extlibs += " " + $LOCAL_LIBS unless $LOCAL_LIBS == ""
- end
- ensure
- rm_f "conftest*"
- Dir.chdir dir
- end
-end
-
-$make = ENV["MAKE"]
-$make ||= with_config("make-prog", "make")
-
-# get static-link modules
-$static_ext = {}
-for setup in ["@setup@", "#{$top_srcdir}/ext/@setup@"]
- if File.file? setup
- f = open(setup)
- while line = f.gets()
- line.chomp!
- line.sub!(/#.*$/, '')
- next if /^\s*$/ =~ line
- if /^option +nodynamic/ =~ line
- $nodynamic = true
- next
- end
- target = line.split[0]
- target = target.downcase if /mswin32/ =~ RUBY_PLATFORM
- $static_ext[target] = true
- end
- f.close
- break
- end
-end
-
-ext_prefix = "#{$top_srcdir}/ext"
-for d in Dir["#{ext_prefix}/**/*"]
- File.directory?(d) || next
- File.file?(d + "/MANIFEST") || next
-
- d.slice!(0, ext_prefix.length + 1)
- if $install
- print "installing ", d, "\n"
- elsif $clean
- print "cleaning ", d, "\n"
- else
- print "compiling ", d, "\n"
- if RUBY_PLATFORM =~ /-aix/ and older("../ruby.imp", "../miniruby")
- load "#{$top_srcdir}/ext/aix_mksym.rb"
- end
- end
- extmake(d)
-end
-
-if $install or $clean
- Dir.chdir ".."
- exit
-end
-$extinit = "" unless $extinit
-
-ruby = "@RUBY_INSTALL_NAME@@EXEEXT@"
-miniruby = "miniruby@EXEEXT@"
-
-$extobjs = "" unless $extobjs
-if $extlist.size > 0
- for s,t in $extlist
- f = format("%s/%s.%s", s, t, $LIBEXT)
- if File.exist?(f)
- $extinit += format("\
-\tInit_%s();\n\
-\trb_provide(\"%s\");\n\
-", t, s)
- $extobjs += "ext/"
- $extobjs += f
- $extobjs += " "
- else
- false
- end
- end
-
- if older("extinit.c", "#{$top_srcdir}/ext/@setup@")
- f = open("extinit.c", "w")
- f.printf "void Init_ext() {\n"
- f.printf $extinit
- f.printf "}\n"
- f.close
- end
- if older("extinit.#{$OBJEXT}", "extinit.c")
- cmd = "@CC@ " + CFLAGS + " -c extinit.c"
- print cmd, "\n"
- system cmd or exit 1
- end
-
- Dir.chdir ".."
-
- if older(ruby, "#{$top_srcdir}/ext/@setup@") or older(ruby, miniruby)
- rm_f ruby
- end
-
- $extobjs = "ext/extinit.#{$OBJEXT} " + $extobjs
- if RUBY_PLATFORM =~ /m68k-human|beos/
- $extlibs.gsub!("-L/usr/local/lib", "") if $extlibs
- end
- system format(%[#{$make} #{ruby} EXTOBJS='%s' EXTLIBS='%s'], $extobjs, $extlibs)
-else
- Dir.chdir ".."
- if older(ruby, miniruby)
- rm_f ruby
- system("#{$make} #{ruby}")
- end
-end
-
-#Local variables:
-# mode: ruby
-#end:
diff --git a/ext/fcntl/.cvsignore b/ext/fcntl/.cvsignore
deleted file mode 100644
index fc802ff1c2..0000000000
--- a/ext/fcntl/.cvsignore
+++ /dev/null
@@ -1,2 +0,0 @@
-Makefile
-mkmf.log
diff --git a/ext/fcntl/MANIFEST b/ext/fcntl/MANIFEST
deleted file mode 100644
index aef7ad4ca0..0000000000
--- a/ext/fcntl/MANIFEST
+++ /dev/null
@@ -1,3 +0,0 @@
-MANIFEST
-depend
-fcntl.c
diff --git a/ext/fcntl/depend b/ext/fcntl/depend
deleted file mode 100644
index 10eab64a46..0000000000
--- a/ext/fcntl/depend
+++ /dev/null
@@ -1 +0,0 @@
-fcntl.o: fcntl.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h
diff --git a/ext/fcntl/fcntl.c b/ext/fcntl/fcntl.c
deleted file mode 100644
index de0b284b36..0000000000
--- a/ext/fcntl/fcntl.c
+++ /dev/null
@@ -1,107 +0,0 @@
-/************************************************
-
- fcntl.c -
-
- $Author$
- created at: Mon Apr 7 18:53:05 JST 1997
-
- Copyright (C) 1997-2001 Yukihiro Matsumoto
-
-************************************************/
-
-/************************************************
-= NAME
-
-fcntl - load the C fcntl.h defines
-
-= SYNOPSIS
-
- require "fcntl"
- m = s.fcntl(Fcntl::F_GETFL, 0)
- f.fcntl(Fcntl::F_SETFL, Fcntl::O_NONBLOCK|m)
-
-= DESCRIPTION
-
-This module is just a translation of the C <fnctl.h> file.
-
-= NOTE
-
-Only #define symbols get translated; you must still correctly
-pack up your own arguments to pass as args for locking functions, etc.
-
-************************************************/
-
-#include "ruby.h"
-#include <fcntl.h>
-
-void
-Init_fcntl()
-{
- VALUE mFcntl = rb_define_module("Fcntl");
-#ifdef F_DUPFD
- rb_define_const(mFcntl, "F_DUPFD", INT2NUM(F_DUPFD));
-#endif
-#ifdef F_GETFD
- rb_define_const(mFcntl, "F_GETFD", INT2NUM(F_GETFD));
-#endif
-#ifdef F_GETLK
- rb_define_const(mFcntl, "F_GETLK", INT2NUM(F_GETLK));
-#endif
-#ifdef F_SETFD
- rb_define_const(mFcntl, "F_SETFD", INT2NUM(F_SETFD));
-#endif
-#ifdef F_GETFL
- rb_define_const(mFcntl, "F_GETFL", INT2NUM(F_GETFL));
-#endif
-#ifdef F_SETFL
- rb_define_const(mFcntl, "F_SETFL", INT2NUM(F_SETFL));
-#endif
-#ifdef F_SETLK
- rb_define_const(mFcntl, "F_SETLK", INT2NUM(F_SETLK));
-#endif
-#ifdef F_SETLKW
- rb_define_const(mFcntl, "F_SETLKW", INT2NUM(F_SETLKW));
-#endif
-#ifdef FD_CLOEXEC
- rb_define_const(mFcntl, "FD_CLOEXEC", INT2NUM(FD_CLOEXEC));
-#endif
-#ifdef F_RDLCK
- rb_define_const(mFcntl, "F_RDLCK", INT2NUM(F_RDLCK));
-#endif
-#ifdef F_UNLCK
- rb_define_const(mFcntl, "F_UNLCK", INT2NUM(F_UNLCK));
-#endif
-#ifdef F_WRLCK
- rb_define_const(mFcntl, "F_WRLCK", INT2NUM(F_WRLCK));
-#endif
-#ifdef O_CREAT
- rb_define_const(mFcntl, "O_CREAT", INT2NUM(O_CREAT));
-#endif
-#ifdef O_EXCL
- rb_define_const(mFcntl, "O_EXCL", INT2NUM(O_EXCL));
-#endif
-#ifdef O_NOCTTY
- rb_define_const(mFcntl, "O_NOCTTY", INT2NUM(O_NOCTTY));
-#endif
-#ifdef O_TRUNC
- rb_define_const(mFcntl, "O_TRUNC", INT2NUM(O_TRUNC));
-#endif
-#ifdef O_APPEND
- rb_define_const(mFcntl, "O_APPEND", INT2NUM(O_APPEND));
-#endif
-#ifdef O_NONBLOCK
- rb_define_const(mFcntl, "O_NONBLOCK", INT2NUM(O_NONBLOCK));
-#endif
-#ifdef O_NDELAY
- rb_define_const(mFcntl, "O_NDELAY", INT2NUM(O_NDELAY));
-#endif
-#ifdef O_RDONLY
- rb_define_const(mFcntl, "O_RDONLY", INT2NUM(O_RDONLY));
-#endif
-#ifdef O_RDWR
- rb_define_const(mFcntl, "O_RDWR", INT2NUM(O_RDWR));
-#endif
-#ifdef O_WRONLY
- rb_define_const(mFcntl, "O_WRONLY", INT2NUM(O_WRONLY));
-#endif
-}
diff --git a/ext/gdbm/.cvsignore b/ext/gdbm/.cvsignore
deleted file mode 100644
index fc802ff1c2..0000000000
--- a/ext/gdbm/.cvsignore
+++ /dev/null
@@ -1,2 +0,0 @@
-Makefile
-mkmf.log
diff --git a/ext/gdbm/MANIFEST b/ext/gdbm/MANIFEST
deleted file mode 100644
index 1359b4fdaf..0000000000
--- a/ext/gdbm/MANIFEST
+++ /dev/null
@@ -1,6 +0,0 @@
-MANIFEST
-README
-depend
-extconf.rb
-gdbm.c
-testgdbm.rb
diff --git a/ext/gdbm/README b/ext/gdbm/README
deleted file mode 100644
index df7a261c68..0000000000
--- a/ext/gdbm/README
+++ /dev/null
@@ -1 +0,0 @@
-gdbm ext-library for Ruby 1.3 or later
diff --git a/ext/gdbm/depend b/ext/gdbm/depend
deleted file mode 100644
index c080a81619..0000000000
--- a/ext/gdbm/depend
+++ /dev/null
@@ -1 +0,0 @@
-gdbm.o: gdbm.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h
diff --git a/ext/gdbm/extconf.rb b/ext/gdbm/extconf.rb
deleted file mode 100644
index 5a09492e5e..0000000000
--- a/ext/gdbm/extconf.rb
+++ /dev/null
@@ -1,7 +0,0 @@
-require 'mkmf'
-
-dir_config("gdbm")
-if have_library("gdbm", "gdbm_open") and
- have_header("gdbm.h")
- create_makefile("gdbm")
-end
diff --git a/ext/gdbm/gdbm.c b/ext/gdbm/gdbm.c
deleted file mode 100644
index d30f5dec7a..0000000000
--- a/ext/gdbm/gdbm.c
+++ /dev/null
@@ -1,994 +0,0 @@
-/************************************************
-
- gdbm.c -
-
- $Author$
- $Date$
- modified at: Mon Jan 24 15:59:52 JST 1994
-
-************************************************/
-
-#include "ruby.h"
-
-#include <gdbm.h>
-#include <fcntl.h>
-#include <errno.h>
-
-static VALUE rb_cGDBM, rb_eGDBMError, rb_eGDBMFatalError;
-
-#define MY_BLOCK_SIZE (2048)
-#define MY_FATAL_FUNC rb_gdbm_fatal
-static void
-rb_gdbm_fatal(msg)
- char *msg;
-{
- rb_raise(rb_eGDBMFatalError, msg);
-}
-
-struct dbmdata {
- int di_size;
- GDBM_FILE di_dbm;
-};
-
-static void
-closed_dbm()
-{
- rb_raise(rb_eRuntimeError, "closed GDBM file");
-}
-
-#define GetDBM(obj, dbmp) {\
- Data_Get_Struct(obj, struct dbmdata, dbmp);\
- if (dbmp == 0) closed_dbm();\
- if (dbmp->di_dbm == 0) closed_dbm();\
-}
-
-static void
-free_dbm(dbmp)
- struct dbmdata *dbmp;
-{
- if (dbmp) {
- if (dbmp->di_dbm) gdbm_close(dbmp->di_dbm);
- free(dbmp);
- }
-}
-
-static VALUE
-fgdbm_close(obj)
- VALUE obj;
-{
- struct dbmdata *dbmp;
-
- GetDBM(obj, dbmp);
- gdbm_close(dbmp->di_dbm);
- dbmp->di_dbm = 0;
-
- return Qnil;
-}
-
-static VALUE
-fgdbm_s_new(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- VALUE obj = Data_Wrap_Struct(klass, 0, free_dbm, 0);
- rb_obj_call_init(obj, argc, argv);
- return obj;
-}
-
-static VALUE
-fgdbm_initialize(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- VALUE file, vmode, vflags;
- GDBM_FILE dbm;
- struct dbmdata *dbmp;
- int mode, flags = 0;
-
- if (rb_scan_args(argc, argv, "12", &file, &vmode, &vflags) == 1) {
- mode = 0666; /* default value */
- }
- else if (NIL_P(vmode)) {
- mode = -1; /* return nil if DB not exist */
- }
- else {
- mode = NUM2INT(vmode);
- }
-
- if (!NIL_P(vflags))
- flags = NUM2INT(vflags);
-
- SafeStringValue(file);
-
- dbm = 0;
- if (mode >= 0)
- dbm = gdbm_open(RSTRING(file)->ptr, MY_BLOCK_SIZE,
- GDBM_WRCREAT|flags, mode, MY_FATAL_FUNC);
- if (!dbm)
- dbm = gdbm_open(RSTRING(file)->ptr, MY_BLOCK_SIZE,
- GDBM_WRITER|flags, 0, MY_FATAL_FUNC);
- if (!dbm)
- dbm = gdbm_open(RSTRING(file)->ptr, MY_BLOCK_SIZE,
- GDBM_READER|flags, 0, MY_FATAL_FUNC);
-
- if (!dbm) {
- if (mode == -1) return Qnil;
-
- if (gdbm_errno == GDBM_FILE_OPEN_ERROR ||
- gdbm_errno == GDBM_CANT_BE_READER ||
- gdbm_errno == GDBM_CANT_BE_WRITER)
- rb_sys_fail(RSTRING(file)->ptr);
- else
- rb_raise(rb_eGDBMError, "%s", gdbm_strerror(gdbm_errno));
- }
-
- dbmp = ALLOC(struct dbmdata);
- DATA_PTR(obj) = dbmp;
- dbmp->di_dbm = dbm;
- dbmp->di_size = -1;
-
- return obj;
-}
-
-static VALUE
-fgdbm_s_open(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- VALUE obj = Data_Wrap_Struct(klass, 0, free_dbm, 0);
-
- if (NIL_P(fgdbm_initialize(argc, argv, obj))) {
- return Qnil;
- }
-
- if (rb_block_given_p()) {
- return rb_ensure(rb_yield, obj, fgdbm_close, obj);
- }
-
- return obj;
-}
-
-static VALUE
-rb_gdbm_fetch(dbm, key)
- GDBM_FILE dbm;
- datum key;
-{
- datum val;
- VALUE str;
-
- val = gdbm_fetch(dbm, key);
- if (val.dptr == 0)
- return Qnil;
-
- str = rb_obj_alloc(rb_cString);
- RSTRING(str)->len = val.dsize;
- RSTRING(str)->aux.capa = val.dsize;
- RSTRING(str)->ptr = REALLOC_N(val.dptr,char,val.dsize+1);
- RSTRING(str)->ptr[val.dsize] = '\0';
-
- OBJ_TAINT(str);
- return (VALUE)str;
-}
-
-static VALUE
-rb_gdbm_fetch2(dbm, keystr)
- GDBM_FILE dbm;
- VALUE keystr;
-{
- datum key;
-
- StringValue(keystr);
- key.dptr = RSTRING(keystr)->ptr;
- key.dsize = RSTRING(keystr)->len;
-
- return rb_gdbm_fetch(dbm, key);
-}
-
-static VALUE
-rb_gdbm_fetch3(obj, keystr)
- VALUE obj, keystr;
-{
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- return rb_gdbm_fetch2(dbm, keystr);
-}
-
-static VALUE
-rb_gdbm_firstkey(dbm)
- GDBM_FILE dbm;
-{
- datum key;
- VALUE str;
-
- key = gdbm_firstkey(dbm);
- if (key.dptr == 0)
- return Qnil;
-
- str = rb_obj_alloc(rb_cString);
- RSTRING(str)->len = key.dsize;
- RSTRING(str)->aux.capa = key.dsize;
- RSTRING(str)->ptr = REALLOC_N(key.dptr,char,key.dsize+1);
- RSTRING(str)->ptr[RSTRING(str)->len] = '\0';
-
- OBJ_TAINT(str);
- return str;
-}
-
-static VALUE
-rb_gdbm_nextkey(dbm, keystr)
- GDBM_FILE dbm;
- VALUE keystr;
-{
- datum key, key2;
- VALUE str;
-
- key.dptr = RSTRING(keystr)->ptr;
- key.dsize = RSTRING(keystr)->len;
- key2 = gdbm_nextkey(dbm, key);
- if (key2.dptr == 0)
- return Qnil;
-
- str = rb_obj_alloc(rb_cString);
- RSTRING(str)->len = key2.dsize;
- RSTRING(str)->aux.capa = key2.dsize;
- RSTRING(str)->ptr = REALLOC_N(key2.dptr,char,key2.dsize+1);
- RSTRING(str)->ptr[RSTRING(str)->len] = '\0';
-
- OBJ_TAINT(str);
- return str;
-}
-
-static VALUE
-fgdbm_fetch(obj, keystr, ifnone)
- VALUE obj, keystr, ifnone;
-{
- VALUE valstr;
-
- valstr = rb_gdbm_fetch3(obj, keystr);
- if (NIL_P(valstr)) {
- if (ifnone == Qnil && rb_block_given_p())
- return rb_yield(keystr);
- return ifnone;
- }
- return valstr;
-}
-
-static VALUE
-fgdbm_aref(obj, keystr)
- VALUE obj, keystr;
-{
- return rb_gdbm_fetch3(obj, keystr);
-}
-
-static VALUE
-fgdbm_fetch_m(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- VALUE keystr, valstr, ifnone;
-
- rb_scan_args(argc, argv, "11", &keystr, &ifnone);
- valstr = fgdbm_fetch(obj, keystr, ifnone);
- if (argc == 1 && !rb_block_given_p() && NIL_P(valstr))
- rb_raise(rb_eIndexError, "key not found");
-
- return valstr;
-}
-
-static VALUE
-fgdbm_index(obj, valstr)
- VALUE obj, valstr;
-{
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
- VALUE keystr, valstr2;
-
- StringValue(valstr);
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr);
- keystr = rb_gdbm_nextkey(dbm, keystr)) {
-
- valstr2 = rb_gdbm_fetch2(dbm, keystr);
- if (!NIL_P(valstr2) &&
- RSTRING(valstr)->len == RSTRING(valstr2)->len &&
- memcmp(RSTRING(valstr)->ptr, RSTRING(valstr2)->ptr,
- RSTRING(valstr)->len) == 0) {
- return keystr;
- }
- }
- return Qnil;
-}
-
-static VALUE
-fgdbm_indexes(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- VALUE new;
- int i;
-
- new = rb_ary_new2(argc);
- for (i=0; i<argc; i++) {
- rb_ary_push(new, rb_gdbm_fetch3(obj, argv[i]));
- }
-
- return new;
-}
-
-static VALUE
-fgdbm_select(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- VALUE new = rb_ary_new2(argc);
- int i;
-
- if (rb_block_given_p()) {
- GDBM_FILE dbm;
- struct dbmdata *dbmp;
- VALUE keystr;
-
- if (argc > 0) {
- rb_raise(rb_eArgError, "wrong number arguments(%d for 0)", argc);
- }
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr);
- keystr = rb_gdbm_nextkey(dbm, keystr)) {
- VALUE assoc = rb_assoc_new(keystr, rb_gdbm_fetch2(dbm, keystr));
-
- if (RTEST(rb_yield(assoc)))
- rb_ary_push(new, assoc);
- }
- }
- else {
- for (i=0; i<argc; i++) {
- rb_ary_push(new, rb_gdbm_fetch3(obj, argv[i]));
- }
- }
-
- return new;
-}
-
-static VALUE
-rb_gdbm_delete(obj, keystr)
- VALUE obj, keystr;
-{
- datum key;
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
-
- rb_secure(4);
- StringValue(keystr);
- key.dptr = RSTRING(keystr)->ptr;
- key.dsize = RSTRING(keystr)->len;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- if (!gdbm_exists(dbm, key)) {
- return Qnil;
- }
-
- if (gdbm_delete(dbm, key)) {
- dbmp->di_size = -1;
- rb_raise(rb_eGDBMError, "%s", gdbm_strerror(gdbm_errno));
- }
- else if (dbmp->di_size >= 0) {
- dbmp->di_size--;
- }
- return obj;
-}
-
-static VALUE
-fgdbm_delete(obj, keystr)
- VALUE obj, keystr;
-{
- VALUE valstr;
-
- valstr = fgdbm_fetch(obj, keystr, Qnil);
- rb_gdbm_delete(obj, keystr);
- return valstr;
-}
-
-static VALUE
-fgdbm_shift(obj)
- VALUE obj;
-{
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
- VALUE keystr, valstr;
-
- rb_secure(4);
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- keystr = rb_gdbm_firstkey(dbm);
- if (NIL_P(keystr)) return Qnil;
- valstr = rb_gdbm_fetch2(dbm, keystr);
- rb_gdbm_delete(obj, keystr);
-
- return rb_assoc_new(keystr, valstr);
-}
-
-static VALUE
-fgdbm_delete_if(obj)
- VALUE obj;
-{
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
- VALUE keystr, valstr;
- VALUE ret, ary = rb_ary_new();
- int i, status = 0, n;
-
- rb_secure(4);
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- n = dbmp->di_size;
- dbmp->di_size = -1;
-
- for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr);
- keystr = rb_gdbm_nextkey(dbm, keystr)) {
-
- valstr = rb_gdbm_fetch2(dbm, keystr);
- ret = rb_protect(rb_yield, rb_assoc_new(keystr, valstr), &status);
- if (status != 0) break;
- if (RTEST(ret)) rb_ary_push(ary, keystr);
- }
-
- for (i = 0; i < RARRAY(ary)->len; i++)
- rb_gdbm_delete(obj, RARRAY(ary)->ptr[i]);
- if (status) rb_jump_tag(status);
- if (n > 0) dbmp->di_size = n - RARRAY(ary)->len;
-
- return obj;
-}
-
-static VALUE
-fgdbm_clear(obj)
- VALUE obj;
-{
- datum key, nextkey;
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
-
- rb_secure(4);
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- dbmp->di_size = -1;
-
-#if 0
- while (key = gdbm_firstkey(dbm), key.dptr) {
- if (gdbm_delete(dbm, key)) {
- free(key.dptr);
- rb_raise(rb_eGDBMError, "%s", gdbm_strerror(gdbm_errno));
- }
- free(key.dptr);
- }
-#else
- while (key = gdbm_firstkey(dbm), key.dptr) {
- for (; key.dptr; key = nextkey) {
- nextkey = gdbm_nextkey(dbm, key);
- if (gdbm_delete(dbm, key)) {
- free(key.dptr);
- if (nextkey.dptr) free(nextkey.dptr);
- rb_raise(rb_eGDBMError, "%s", gdbm_strerror(gdbm_errno));
- }
- free(key.dptr);
- }
- }
-#endif
- dbmp->di_size = 0;
-
- return obj;
-}
-
-static VALUE
-fgdbm_invert(obj)
- VALUE obj;
-{
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
- VALUE keystr, valstr;
- VALUE hash = rb_hash_new();
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr);
- keystr = rb_gdbm_nextkey(dbm, keystr)) {
- valstr = rb_gdbm_fetch2(dbm, keystr);
-
- rb_hash_aset(hash, valstr, keystr);
- }
- return hash;
-}
-
-static VALUE
-each_pair(obj)
- VALUE obj;
-{
- return rb_funcall(obj, rb_intern("each_pair"), 0, 0);
-}
-
-static VALUE fgdbm_store _((VALUE,VALUE,VALUE));
-
-static VALUE
-update_i(pair, dbm)
- VALUE pair, dbm;
-{
- Check_Type(pair, T_ARRAY);
- if (RARRAY(pair)->len < 2) {
- rb_raise(rb_eArgError, "pair must be [key, value]");
- }
- fgdbm_store(dbm, RARRAY(pair)->ptr[0], RARRAY(pair)->ptr[1]);
- return Qnil;
-}
-
-static VALUE
-fgdbm_update(obj, other)
- VALUE obj, other;
-{
- rb_iterate(each_pair, other, update_i, obj);
- return obj;
-}
-
-static VALUE
-fgdbm_replace(obj, other)
- VALUE obj, other;
-{
- fgdbm_clear(obj);
- rb_iterate(each_pair, other, update_i, obj);
- return obj;
-}
-
-static VALUE
-fgdbm_store(obj, keystr, valstr)
- VALUE obj, keystr, valstr;
-{
- datum key, val;
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
-
- rb_secure(4);
- StringValue(keystr);
- key.dptr = RSTRING(keystr)->ptr;
- key.dsize = RSTRING(keystr)->len;
-
- StringValue(valstr);
- val.dptr = RSTRING(valstr)->ptr;
- val.dsize = RSTRING(valstr)->len;
-
- GetDBM(obj, dbmp);
- dbmp->di_size = -1;
- dbm = dbmp->di_dbm;
- if (gdbm_store(dbm, key, val, GDBM_REPLACE)) {
- if (errno == EPERM) rb_sys_fail(0);
- rb_raise(rb_eGDBMError, "%s", gdbm_strerror(gdbm_errno));
- }
-
- return valstr;
-}
-
-static VALUE
-fgdbm_length(obj)
- VALUE obj;
-{
- datum key, nextkey;
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
- int i = 0;
-
- GetDBM(obj, dbmp);
- if (dbmp->di_size > 0) return INT2FIX(dbmp->di_size);
- dbm = dbmp->di_dbm;
-
- for (key = gdbm_firstkey(dbm); key.dptr; key = nextkey) {
- nextkey = gdbm_nextkey(dbm, key);
- free(key.dptr);
- i++;
- }
- dbmp->di_size = i;
-
- return INT2FIX(i);
-}
-
-static VALUE
-fgdbm_empty_p(obj)
- VALUE obj;
-{
- datum key;
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
-
- GetDBM(obj, dbmp);
- if (dbmp->di_size < 0) {
- dbm = dbmp->di_dbm;
-
- key = gdbm_firstkey(dbm);
- if (key.dptr) {
- free(key.dptr);
- return Qfalse;
- }
- return Qtrue;
- }
-
- if (dbmp->di_size == 0) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-fgdbm_each_value(obj)
- VALUE obj;
-{
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
- VALUE keystr;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr);
- keystr = rb_gdbm_nextkey(dbm, keystr)) {
-
- rb_yield(rb_gdbm_fetch2(dbm, keystr));
- }
- return obj;
-}
-
-static VALUE
-fgdbm_each_key(obj)
- VALUE obj;
-{
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
- VALUE keystr;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr);
- keystr = rb_gdbm_nextkey(dbm, keystr)) {
-
- rb_yield(keystr);
- }
- return obj;
-}
-
-static VALUE
-fgdbm_each_pair(obj)
- VALUE obj;
-{
- GDBM_FILE dbm;
- struct dbmdata *dbmp;
- VALUE keystr;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr);
- keystr = rb_gdbm_nextkey(dbm, keystr)) {
-
- rb_yield(rb_assoc_new(keystr, rb_gdbm_fetch2(dbm, keystr)));
- }
-
- return obj;
-}
-
-static VALUE
-fgdbm_keys(obj)
- VALUE obj;
-{
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
- VALUE keystr, ary;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- ary = rb_ary_new();
- for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr);
- keystr = rb_gdbm_nextkey(dbm, keystr)) {
-
- rb_ary_push(ary, keystr);
- }
-
- return ary;
-}
-
-static VALUE
-fgdbm_values(obj)
- VALUE obj;
-{
- datum key, nextkey;
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
- VALUE valstr, ary;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- ary = rb_ary_new();
- for (key = gdbm_firstkey(dbm); key.dptr; key = nextkey) {
- nextkey = gdbm_nextkey(dbm, key);
- valstr = rb_gdbm_fetch(dbm, key);
- free(key.dptr);
- rb_ary_push(ary, valstr);
- }
-
- return ary;
-}
-
-static VALUE
-fgdbm_has_key(obj, keystr)
- VALUE obj, keystr;
-{
- datum key;
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
-
- StringValue(keystr);
- key.dptr = RSTRING(keystr)->ptr;
- key.dsize = RSTRING(keystr)->len;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- if (gdbm_exists(dbm, key))
- return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-fgdbm_has_value(obj, valstr)
- VALUE obj, valstr;
-{
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
- VALUE keystr, valstr2;
-
- StringValue(valstr);
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr);
- keystr = rb_gdbm_nextkey(dbm, keystr)) {
-
- valstr2 = rb_gdbm_fetch2(dbm, keystr);
-
- if (!NIL_P(valstr2) &&
- RSTRING(valstr)->len == RSTRING(valstr2)->len &&
- memcmp(RSTRING(valstr)->ptr, RSTRING(valstr2)->ptr,
- RSTRING(valstr)->len) == 0) {
- return Qtrue;
- }
- }
- return Qfalse;
-}
-
-static VALUE
-fgdbm_to_a(obj)
- VALUE obj;
-{
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
- VALUE keystr, ary;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- ary = rb_ary_new();
- for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr);
- keystr = rb_gdbm_nextkey(dbm, keystr)) {
-
- rb_ary_push(ary, rb_assoc_new(keystr, rb_gdbm_fetch2(dbm, keystr)));
- }
-
- return ary;
-}
-
-static VALUE
-fgdbm_reorganize(obj)
- VALUE obj;
-{
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
-
- rb_secure(4);
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- gdbm_reorganize(dbm);
- return obj;
-}
-
-static VALUE
-fgdbm_sync(obj)
- VALUE obj;
-{
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
-
- rb_secure(4);
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- gdbm_sync(dbm);
- return obj;
-}
-
-static VALUE
-fgdbm_set_cachesize(obj, val)
- VALUE obj, val;
-{
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
- int optval;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- optval = FIX2INT(val);
- if (gdbm_setopt(dbm, GDBM_CACHESIZE, &optval, sizeof(optval)) == -1) {
- rb_raise(rb_eGDBMError, "%s", gdbm_strerror(gdbm_errno));
- }
- return val;
-}
-
-static VALUE
-fgdbm_set_fastmode(obj, val)
- VALUE obj, val;
-{
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
- int optval;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- optval = 0;
- if (RTEST(val))
- optval = 1;
-
- if (gdbm_setopt(dbm, GDBM_FASTMODE, &optval, sizeof(optval)) == -1) {
- rb_raise(rb_eGDBMError, "%s", gdbm_strerror(gdbm_errno));
- }
- return val;
-}
-
-static VALUE
-fgdbm_set_syncmode(obj, val)
- VALUE obj, val;
-{
-#if !defined(GDBM_SYNCMODE)
- fgdbm_set_fastmode(obj, RTEST(val) ? Qfalse : Qtrue);
- return val;
-#else
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
- int optval;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- optval = 0;
- if (RTEST(val))
- optval = 1;
-
- if (gdbm_setopt(dbm, GDBM_FASTMODE, &optval, sizeof(optval)) == -1) {
- rb_raise(rb_eGDBMError, "%s", gdbm_strerror(gdbm_errno));
- }
- return val;
-#endif
-}
-
-static VALUE
-fgdbm_to_hash(obj)
- VALUE obj;
-{
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
- VALUE keystr, hash;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- hash = rb_hash_new();
- for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr);
- keystr = rb_gdbm_nextkey(dbm, keystr)) {
-
- rb_hash_aset(hash, keystr, rb_gdbm_fetch2(dbm, keystr));
- }
-
- return hash;
-}
-
-static VALUE
-fgdbm_reject(obj)
- VALUE obj;
-{
- return rb_hash_delete_if(fgdbm_to_hash(obj));
-}
-
-void
-Init_gdbm()
-{
- rb_cGDBM = rb_define_class("GDBM", rb_cObject);
- rb_eGDBMError = rb_define_class("GDBMError", rb_eStandardError);
- rb_eGDBMFatalError = rb_define_class("GDBMFatalError", rb_eException);
- rb_include_module(rb_cGDBM, rb_mEnumerable);
-
- rb_define_singleton_method(rb_cGDBM, "new", fgdbm_s_new, -1);
- rb_define_singleton_method(rb_cGDBM, "open", fgdbm_s_open, -1);
-
- rb_define_method(rb_cGDBM, "initialize", fgdbm_initialize, -1);
- rb_define_method(rb_cGDBM, "close", fgdbm_close, 0);
- rb_define_method(rb_cGDBM, "[]", fgdbm_aref, 1);
- rb_define_method(rb_cGDBM, "fetch", fgdbm_fetch_m, -1);
- rb_define_method(rb_cGDBM, "[]=", fgdbm_store, 2);
- rb_define_method(rb_cGDBM, "store", fgdbm_store, 2);
- rb_define_method(rb_cGDBM, "index", fgdbm_index, 1);
- rb_define_method(rb_cGDBM, "indexes", fgdbm_indexes, -1);
- rb_define_method(rb_cGDBM, "indices", fgdbm_indexes, -1);
- rb_define_method(rb_cGDBM, "select", fgdbm_select, -1);
- rb_define_method(rb_cGDBM, "length", fgdbm_length, 0);
- rb_define_method(rb_cGDBM, "size", fgdbm_length, 0);
- rb_define_method(rb_cGDBM, "empty?", fgdbm_empty_p, 0);
- rb_define_method(rb_cGDBM, "each", fgdbm_each_pair, 0);
- rb_define_method(rb_cGDBM, "each_value", fgdbm_each_value, 0);
- rb_define_method(rb_cGDBM, "each_key", fgdbm_each_key, 0);
- rb_define_method(rb_cGDBM, "each_pair", fgdbm_each_pair, 0);
- rb_define_method(rb_cGDBM, "keys", fgdbm_keys, 0);
- rb_define_method(rb_cGDBM, "values", fgdbm_values, 0);
- rb_define_method(rb_cGDBM, "shift", fgdbm_shift, 0);
- rb_define_method(rb_cGDBM, "delete", fgdbm_delete, 1);
- rb_define_method(rb_cGDBM, "delete_if", fgdbm_delete_if, 0);
- rb_define_method(rb_cGDBM, "reject!", fgdbm_delete_if, 0);
- rb_define_method(rb_cGDBM, "reject", fgdbm_reject, 0);
- rb_define_method(rb_cGDBM, "clear", fgdbm_clear, 0);
- rb_define_method(rb_cGDBM,"invert", fgdbm_invert, 0);
- rb_define_method(rb_cGDBM,"update", fgdbm_update, 1);
- rb_define_method(rb_cGDBM,"replace", fgdbm_replace, 1);
- rb_define_method(rb_cGDBM,"reorganize", fgdbm_reorganize, 0);
- rb_define_method(rb_cGDBM,"sync", fgdbm_sync, 0);
- /* rb_define_method(rb_cGDBM,"setopt", fgdbm_setopt, 2); */
- rb_define_method(rb_cGDBM,"cachesize=", fgdbm_set_cachesize, 1);
- rb_define_method(rb_cGDBM,"fastmode=", fgdbm_set_fastmode, 1);
- rb_define_method(rb_cGDBM,"syncmode=", fgdbm_set_syncmode, 1);
-
- rb_define_method(rb_cGDBM, "include?", fgdbm_has_key, 1);
- rb_define_method(rb_cGDBM, "has_key?", fgdbm_has_key, 1);
- rb_define_method(rb_cGDBM, "member?", fgdbm_has_key, 1);
- rb_define_method(rb_cGDBM, "has_value?", fgdbm_has_value, 1);
- rb_define_method(rb_cGDBM, "key?", fgdbm_has_key, 1);
- rb_define_method(rb_cGDBM, "value?", fgdbm_has_value, 1);
-
- rb_define_method(rb_cGDBM, "to_a", fgdbm_to_a, 0);
- rb_define_method(rb_cGDBM, "to_hash", fgdbm_to_hash, 0);
-
- /* flags for gdbm_opn() */
- /*
- rb_define_const(rb_cGDBM, "READER", INT2FIX(GDBM_READER));
- rb_define_const(rb_cGDBM, "WRITER", INT2FIX(GDBM_WRITER));
- rb_define_const(rb_cGDBM, "WRCREAT", INT2FIX(GDBM_WRCREAT));
- rb_define_const(rb_cGDBM, "NEWDB", INT2FIX(GDBM_NEWDB));
- */
- rb_define_const(rb_cGDBM, "FAST", INT2FIX(GDBM_FAST));
- /* this flag is obsolete in gdbm 1.8.
- On gdbm 1.8, fast mode is default behavior. */
-
- /* gdbm version 1.8 specific */
-#if defined(GDBM_SYNC)
- rb_define_const(rb_cGDBM, "SYNC", INT2FIX(GDBM_SYNC));
-#endif
-#if defined(GDBM_NOLOCK)
- rb_define_const(rb_cGDBM, "NOLOCK", INT2FIX(GDBM_NOLOCK));
-#endif
- rb_define_const(rb_cGDBM, "VERSION", rb_str_new2(gdbm_version));
-}
diff --git a/ext/gdbm/testgdbm.rb b/ext/gdbm/testgdbm.rb
deleted file mode 100644
index 524d3f8ca3..0000000000
--- a/ext/gdbm/testgdbm.rb
+++ /dev/null
@@ -1,663 +0,0 @@
-require 'runit/testcase'
-require 'runit/cui/testrunner'
-
-if $".grep(/\bgdbm.so\b/).empty?
- begin
- require './gdbm'
- rescue LoadError
- require 'gdbm'
- end
-end
-
-def uname_s
- require 'rbconfig'
- case Config::CONFIG['host_os']
- when 'cygwin'
- require 'Win32API'
- uname = Win32API.new 'cygwin1', 'uname', 'P', 'I'
- utsname = ' ' * 100
- raise 'cannot get system name' if uname.call(utsname) == -1
-
- utsname.unpack('A20' * 5)[0]
- else
- Config::CONFIG['host_os']
- end
-end
-
-SYSTEM = uname_s
-
-class TestGDBM < RUNIT::TestCase
- def setup
- @path = "tmptest_gdbm_"
- assert_instance_of(GDBM, @gdbm = GDBM.new(@path))
-
- # prepare to make readonly GDBM file
- GDBM.open("tmptest_gdbm_rdonly", 0400) {|gdbm|
- gdbm['foo'] = 'FOO'
- }
- assert_instance_of(GDBM, @gdbm_rdonly = GDBM.new("tmptest_gdbm_rdonly", nil))
- end
- def teardown
- assert_nil(@gdbm.close)
- assert_nil(@gdbm_rdonly.close)
- GC.start
- File.delete *Dir.glob("tmptest_gdbm*").to_a
- p Dir.glob("tmptest_gdbm*") if $DEBUG
- end
-
- def check_size(expect, gdbm=@gdbm)
- assert_equals(expect, gdbm.size)
- n = 0
- gdbm.each { n+=1 }
- assert_equals(expect, n)
- if expect == 0
- assert_equals(true, gdbm.empty?)
- else
- assert_equals(false, gdbm.empty?)
- end
- end
-
- def test_version
- STDERR.print GDBM::VERSION
- end
-
- def test_s_new_has_no_block
- # GDBM.new ignore the block
- foo = true
- assert_instance_of(GDBM, gdbm = GDBM.new("tmptest_gdbm") { foo = false })
- assert_equals(foo, true)
- assert_nil(gdbm.close)
- end
- def test_s_open_create_new
- return if /^CYGWIN_9/ =~ SYSTEM
-
- save_mask = File.umask(0)
- begin
- assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm"))
- gdbm.close
- assert_equals(File.stat("tmptest_gdbm").mode & 0777, 0666)
- assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm2", 0644))
- gdbm.close
- assert_equals(File.stat("tmptest_gdbm2").mode & 0777, 0644)
- ensure
- File.umask save_mask
- end
- end
- def test_s_open_no_create
- # this test is failed on libgdbm 1.8.0
- assert_nil(gdbm = GDBM.open("tmptest_gdbm", nil))
- ensure
- gdbm.close if gdbm
- end
- def test_s_open_3rd_arg
- assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644,
- GDBM::FAST))
- gdbm.close
-
- # gdbm 1.8.0 specific
- if defined? GDBM::SYNC
- assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644,
- GDBM::SYNC))
- gdbm.close
- end
- # gdbm 1.8.0 specific
- if defined? GDBM::NOLOCK
- assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644,
- GDBM::NOLOCK))
- gdbm.close
- end
- end
- def test_s_open_with_block
- assert_equals(GDBM.open("tmptest_gdbm") { :foo }, :foo)
- end
- def test_s_open_lock
- fork() {
- assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644))
- sleep 2
- }
- begin
- sleep 1
- assert_exception(Errno::EWOULDBLOCK) {
- begin
- assert_instance_of(GDBM, gdbm2 = GDBM.open("tmptest_gdbm", 0644))
- rescue Errno::EAGAIN, Errno::EACCES
- raise Errno::EWOULDBLOCK
- end
- }
- ensure
- Process.wait
- end
- end
-
-=begin
- # Is it guaranteed on many OS?
- def test_s_open_lock_one_process
- # locking on one process
- assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644))
- assert_exception(Errno::EWOULDBLOCK) {
- begin
- GDBM.open("tmptest_gdbm", 0644)
- rescue Errno::EAGAIN
- raise Errno::EWOULDBLOCK
- end
- }
- end
-=end
-
- def test_s_open_nolock
- # gdbm 1.8.0 specific
- if not defined? GDBM::NOLOCK
- return
- end
-
- fork() {
- assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644,
- GDBM::NOLOCK))
- sleep 2
- }
- sleep 1
- begin
- gdbm2 = nil
- assert_no_exception(Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EACCES) {
- assert_instance_of(GDBM, gdbm2 = GDBM.open("tmptest_gdbm", 0644))
- }
- ensure
- Process.wait
- gdbm2.close if gdbm2
- end
-
- p Dir.glob("tmptest_gdbm*") if $DEBUG
-
- fork() {
- assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644))
- sleep 2
- }
- begin
- sleep 1
- gdbm2 = nil
- assert_no_exception(Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EACCES) {
- # this test is failed on Cygwin98 (???)
- assert_instance_of(GDBM, gdbm2 = GDBM.open("tmptest_gdbm", 0644,
- GDBM::NOLOCK))
- }
- ensure
- Process.wait
- gdbm2.close if gdbm2
- end
- end
-
- def test_s_open_error
- assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0))
- assert_exception(Errno::EACCES) {
- GDBM.open("tmptest_gdbm", 0)
- }
- gdbm.close
- end
-
- def test_close
- assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm"))
- assert_nil(gdbm.close)
-
- # closed GDBM file
- assert_exception(RuntimeError) { gdbm.close }
- end
-
- def test_aref
- assert_equals('bar', @gdbm['foo'] = 'bar')
- assert_equals('bar', @gdbm['foo'])
-
- assert_nil(@gdbm['bar'])
- end
-
- def test_fetch
- assert_equals('bar', @gdbm['foo']='bar')
- assert_equals('bar', @gdbm.fetch('foo'))
-
- # key not found
- assert_exception(IndexError) {
- @gdbm.fetch('bar')
- }
-
- # test for `ifnone' arg
- assert_equals('baz', @gdbm.fetch('bar', 'baz'))
-
- # test for `ifnone' block
- assert_equals('foobar', @gdbm.fetch('bar') {|key| 'foo' + key })
- end
-
- def test_aset
- num = 0
- 2.times {|i|
- assert_equals('foo', @gdbm['foo'] = 'foo')
- assert_equals('foo', @gdbm['foo'])
- assert_equals('bar', @gdbm['foo'] = 'bar')
- assert_equals('bar', @gdbm['foo'])
-
- num += 1 if i == 0
- assert_equals(num, @gdbm.size)
-
- # assign nil
- assert_equals('', @gdbm['bar'] = '')
- assert_equals('', @gdbm['bar'])
-
- num += 1 if i == 0
- assert_equals(num, @gdbm.size)
-
- # empty string
- assert_equals('', @gdbm[''] = '')
- assert_equals('', @gdbm[''])
-
- num += 1 if i == 0
- assert_equals(num, @gdbm.size)
-
- # Fixnum
- assert_equals('200', @gdbm['100'] = '200')
- assert_equals('200', @gdbm['100'])
-
- num += 1 if i == 0
- assert_equals(num, @gdbm.size)
-
- # Big key and value
- assert_equals('y' * 100, @gdbm['x' * 100] = 'y' * 100)
- assert_equals('y' * 100, @gdbm['x' * 100])
-
- num += 1 if i == 0
- assert_equals(num, @gdbm.size)
- }
- end
-
- def test_index
- assert_equals('bar', @gdbm['foo'] = 'bar')
- assert_equals('foo', @gdbm.index('bar'))
- assert_nil(@gdbm['bar'])
- end
-
- def test_indexes
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
- @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
- assert_equals(values.reverse, @gdbm.indexes(*keys.reverse))
- end
-
- def test_select
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
- @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
- assert_equals(values.reverse, @gdbm.select(*keys.reverse))
- end
-
- def test_select_with_block
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
- @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
- ret = @gdbm.select {|k,v|
- assert_equals(k.upcase, v)
- k != "bar"
- }
- assert_equals([['baz', 'BAZ'], ['foo', 'FOO']],
- ret.sort)
- end
-
- def test_length
- num = 10
- assert_equals(0, @gdbm.size)
- num.times {|i|
- i = i.to_s
- @gdbm[i] = i
- }
- assert_equals(num, @gdbm.size)
-
- @gdbm.shift
-
- assert_equals(num - 1, @gdbm.size)
- end
-
- def test_empty?
- assert_equals(true, @gdbm.empty?)
- @gdbm['foo'] = 'FOO'
- assert_equals(false, @gdbm.empty?)
- end
-
- def test_each_pair
- n = 0
- @gdbm.each_pair { n += 1 }
- assert_equals(0, n)
-
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
-
- @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
-
- n = 0
- ret = @gdbm.each_pair {|key, val|
- assert_not_nil(i = keys.index(key))
- assert_equals(val, values[i])
-
- n += 1
- }
- assert_equals(keys.size, n)
- assert_equals(@gdbm, ret)
- end
-
- def test_each_value
- n = 0
- @gdbm.each_value { n += 1 }
- assert_equals(0, n)
-
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
-
- @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
-
- n = 0
- ret = @gdbm.each_value {|val|
- assert_not_nil(key = @gdbm.index(val))
- assert_not_nil(i = keys.index(key))
- assert_equals(val, values[i])
-
- n += 1
- }
- assert_equals(keys.size, n)
- assert_equals(@gdbm, ret)
- end
-
- def test_each_key
- n = 0
- @gdbm.each_key { n += 1 }
- assert_equals(0, n)
-
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
-
- @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
-
- n = 0
- ret = @gdbm.each_key {|key|
- assert_not_nil(i = keys.index(key))
- assert_equals(@gdbm[key], values[i])
-
- n += 1
- }
- assert_equals(keys.size, n)
- assert_equals(@gdbm, ret)
- end
-
- def test_keys
- assert_equals([], @gdbm.keys)
-
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
-
- @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
-
- assert_equals(keys.sort, @gdbm.keys.sort)
- assert_equals(values.sort, @gdbm.values.sort)
- end
-
- def test_values
- test_keys
- end
-
- def test_shift
- assert_nil(@gdbm.shift)
- assert_equals(0, @gdbm.size)
-
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
-
- @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
-
- ret_keys = []
- ret_values = []
- while ret = @gdbm.shift
- ret_keys.push ret[0]
- ret_values.push ret[1]
-
- assert_equals(keys.size - ret_keys.size, @gdbm.size)
- end
-
- assert_equals(keys.sort, ret_keys.sort)
- assert_equals(values.sort, ret_values.sort)
- end
-
- def test_delete
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
- key = keys[1]
-
- assert_nil(@gdbm.delete(key))
- assert_equals(0, @gdbm.size)
-
- @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
-
- assert_equals('BAR', @gdbm.delete(key))
- assert_nil(@gdbm[key])
- assert_equals(2, @gdbm.size)
-
- assert_nil(@gdbm.delete(key))
-
- if /^CYGWIN_9/ !~ SYSTEM
- assert_exception(GDBMError) {
- @gdbm_rdonly.delete("foo")
- }
-
- assert_nil(@gdbm_rdonly.delete("bar"))
- end
- end
- def test_delete_with_block
- key = 'no called block'
- @gdbm[key] = 'foo'
- assert_equals('foo', @gdbm.delete(key) {|k| k.replace 'called block'})
- assert_equals('no called block', key)
- assert_equals(0, @gdbm.size)
-
- key = 'no called block'
- assert_equals(:blockval,
- @gdbm.delete(key) {|k| k.replace 'called block'; :blockval})
- assert_equals('called block', key)
- assert_equals(0, @gdbm.size)
- end
-
- def test_delete_if
- v = "0"
- 100.times {@gdbm[v] = v; v = v.next}
-
- ret = @gdbm.delete_if {|key, val| key.to_i < 50}
- assert_equals(@gdbm, ret)
- check_size(50, @gdbm)
-
- ret = @gdbm.delete_if {|key, val| key.to_i >= 50}
- assert_equals(@gdbm, ret)
- check_size(0, @gdbm)
-
- # break
- v = "0"
- 100.times {@gdbm[v] = v; v = v.next}
- check_size(100, @gdbm)
- n = 0;
- @gdbm.delete_if {|key, val|
- break if n > 50
- n+=1
- true
- }
- assert_equals(51, n)
- check_size(49, @gdbm)
-
- @gdbm.clear
-
- # raise
- v = "0"
- 100.times {@gdbm[v] = v; v = v.next}
- check_size(100, @gdbm)
- n = 0;
- begin
- @gdbm.delete_if {|key, val|
- raise "runtime error" if n > 50
- n+=1
- true
- }
- rescue
- end
- assert_equals(51, n)
- check_size(49, @gdbm)
- end
-
- def test_reject
- v = "0"
- 100.times {@gdbm[v] = v; v = v.next}
-
- hash = @gdbm.reject {|key, val| key.to_i < 50}
- assert_instance_of(Hash, hash)
- assert_equals(100, @gdbm.size)
-
- assert_equals(50, hash.size)
- hash.each_pair {|key,val|
- assert_equals(false, key.to_i < 50)
- assert_equals(key, val)
- }
-
- hash = @gdbm.reject {|key, val| key.to_i < 100}
- assert_instance_of(Hash, hash)
- assert_equals(true, hash.empty?)
- end
-
- def test_clear
- v = "1"
- 100.times {v = v.next; @gdbm[v] = v}
-
- assert_equals(@gdbm, @gdbm.clear)
-
- # validate GDBM#size
- i = 0
- @gdbm.each { i += 1 }
- assert_equals(@gdbm.size, i)
- assert_equals(0, i)
- end
-
- def test_invert
- v = "0"
- 100.times {@gdbm[v] = v; v = v.next}
-
- hash = @gdbm.invert
- assert_instance_of(Hash, hash)
- assert_equals(100, hash.size)
- hash.each_pair {|key, val|
- assert_equals(key.to_i, val.to_i)
- }
- end
-
- def test_update
- hash = {}
- v = "0"
- 100.times {v = v.next; hash[v] = v}
-
- @gdbm["101"] = "101"
- @gdbm.update hash
- assert_equals(101, @gdbm.size)
- @gdbm.each_pair {|key, val|
- assert_equals(key.to_i, val.to_i)
- }
- end
-
- def test_replace
- hash = {}
- v = "0"
- 100.times {v = v.next; hash[v] = v}
-
- @gdbm["101"] = "101"
- @gdbm.replace hash
- assert_equals(100, @gdbm.size)
- @gdbm.each_pair {|key, val|
- assert_equals(key.to_i, val.to_i)
- }
- end
-
- def test_reorganize
- size1 = File.size(@path)
- i = "1"
- 1000.times {i = i.next; @gdbm[i] = i}
- @gdbm.clear
- @gdbm.sync
-
- size2 = File.size(@path)
- @gdbm.reorganize
- size3 = File.size(@path)
-
- # p [size1, size2, size3]
- assert_equals(true, size1 < size2)
- # this test is failed on Cygwin98. `GDBM version 1.8.0, as of May 19, 1999'
- assert_equals(true, size3 < size2)
- assert_equals(size1, size3)
- end
-
- def test_sync
- assert_instance_of(GDBM, gdbm = GDBM.open('tmptest_gdbm', 0666, GDBM::FAST))
- assert_equals(gdbm.sync, gdbm)
- gdbm.close
- assert_instance_of(GDBM, gdbm = GDBM.open('tmptest_gdbm', 0666))
- assert_equals(gdbm.sync, gdbm)
- gdbm.close
- end
-
- def test_cachesize=
- assert_equals(@gdbm.cachesize = 1024, 1024)
- end
-
- def test_fastmode=
- assert_equals(@gdbm.fastmode = true, true)
- end
-
- def test_syncmode=
- assert_equals(@gdbm.syncmode = true, true)
- end
-
- def test_haskey?
- assert_equals('bar', @gdbm['foo']='bar')
- assert_equals(true, @gdbm.has_key?('foo'))
- assert_equals(false, @gdbm.has_key?('bar'))
- end
-
- def test_has_value?
- assert_equals('bar', @gdbm['foo']='bar')
- assert_equals(true, @gdbm.has_value?('bar'))
- assert_equals(false, @gdbm.has_value?('foo'))
- end
-
- def test_to_a
- v = "0"
- 100.times {v = v.next; @gdbm[v] = v}
-
- ary = @gdbm.to_a
- assert_instance_of(Array, ary)
- assert_equals(100, ary.size)
- ary.each {|key,val|
- assert_equals(key.to_i, val.to_i)
- }
- end
-
- def test_to_hash
- v = "0"
- 100.times {v = v.next; @gdbm[v] = v}
-
- hash = @gdbm.to_hash
- assert_instance_of(Hash, hash)
- assert_equals(100, hash.size)
- hash.each {|key,val|
- assert_equals(key.to_i, val.to_i)
- }
- end
-end
-
-if $0 == __FILE__
- if ARGV.size == 0
- suite = RUNIT::TestSuite.new
- suite.add_test(TestGDBM.suite)
- else
- suite = RUNIT::TestSuite.new
- ARGV.each do |testmethod|
- suite.add_test(TestGDBM.new(testmethod))
- end
- end
-
- RUNIT::CUI::TestRunner.run(suite)
-end
diff --git a/ext/iconv/MANIFEST b/ext/iconv/MANIFEST
deleted file mode 100644
index 643f3b7f4d..0000000000
--- a/ext/iconv/MANIFEST
+++ /dev/null
@@ -1,4 +0,0 @@
-MANIFEST
-extconf.rb
-iconv.c
-depend
diff --git a/ext/iconv/depend b/ext/iconv/depend
deleted file mode 100644
index 688ddd97b7..0000000000
--- a/ext/iconv/depend
+++ /dev/null
@@ -1,2 +0,0 @@
-iconv.o: iconv.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h \
- $(hdrdir)/intern.h
diff --git a/ext/iconv/extconf.rb b/ext/iconv/extconf.rb
deleted file mode 100644
index 55d9c5da5f..0000000000
--- a/ext/iconv/extconf.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-require 'mkmf'
-
-dir_config("iconv")
-
-if have_header("iconv.h")
- have_library("iconv")
- create_makefile("iconv")
-end
diff --git a/ext/iconv/iconv.c b/ext/iconv/iconv.c
deleted file mode 100644
index bf1528d21a..0000000000
--- a/ext/iconv/iconv.c
+++ /dev/null
@@ -1,735 +0,0 @@
-/* -*- mode:c; c-file-style:"ruby" -*- */
-/**********************************************************************
-
- iconv.c -
-
- $Author$
- $Date$
- created at: Wed Dec 1 20:28:09 JST 1999
-
- All the files in this distribution are covered under the Ruby's
- license (see the file COPYING).
-
-**********************************************************************/
-
-/*
-=begin
-= Summary
-Ruby extension for codeset conversion.
-
-= Abstract
-Iconv is a wrapper class for UNIX 95 (({iconv()})) function family, which
-translates string between various coding systems.
-
-See ((<Open Group|URL:http://www.opengroup.org/>))'s on-line documents for more details.
-* ((<iconv.h|URL:http://www.opengroup.org/onlinepubs/007908799/xsh/iconv.h.html>))
-* ((<iconv_open()|URL:http://www.opengroup.org/onlinepubs/007908799/xsh/iconv_open.html>))
-* ((<iconv()|URL:http://www.opengroup.org/onlinepubs/007908799/xsh/iconv.html>))
-* ((<iconv_close()|URL:http://www.opengroup.org/onlinepubs/007908799/xsh/iconv_close.html>))
-
-Which coding systems are available, it depends on the platform.
-
-=end
-*/
-
-#include <errno.h>
-#include <iconv.h>
-#include <assert.h>
-#include "ruby.h"
-#include "intern.h"
-
-/* Invalid value for iconv_t is -1 but 0 for VALUE, I hope VALUE is
- big enough to keep iconv_t */
-#define VALUE2ICONV(v) ((iconv_t)((VALUE)(v) ^ -1))
-#define ICONV2VALUE(c) ((VALUE)(c) ^ -1)
-
-struct iconv_env_t
-{
- iconv_t cd;
- int argc;
- VALUE *argv;
- VALUE ret;
-};
-
-static VALUE rb_eIconvFailure;
-static VALUE rb_eIconvIllegalSeq;
-static VALUE rb_eIconvInvalidChar;
-static VALUE rb_eIconvOutOfRange;
-static ID rb_inserter;
-
-static ID rb_success, rb_failed, rb_mesg;
-static VALUE iconv_failure_initialize _((VALUE error, VALUE success, VALUE failed, struct iconv_env_t* env));
-static VALUE iconv_failure_success _((VALUE self));
-static VALUE iconv_failure_failed _((VALUE self));
-
-static iconv_t iconv_create _((VALUE to, VALUE from));
-static VALUE iconv_free _((VALUE cd));
-static VALUE iconv_try _((iconv_t cd, const char **inptr, size_t *inlen, char **outptr, size_t *outlen));
-static VALUE rb_str_derive _((VALUE str, const char* ptr, int len));
-static VALUE iconv_convert _((iconv_t cd, VALUE str, int start, int length, struct iconv_env_t* env));
-static VALUE iconv_s_allocate _((VALUE klass));
-static VALUE iconv_initialize _((VALUE self, VALUE to, VALUE from));
-static VALUE iconv_s_open _((VALUE self, VALUE to, VALUE from));
-static VALUE iconv_s_convert _((struct iconv_env_t* env));
-static VALUE iconv_s_iconv _((int argc, VALUE *argv, VALUE self));
-static VALUE iconv_init_state _((VALUE cd));
-static VALUE iconv_finish _((VALUE self));
-static VALUE iconv_iconv _((int argc, VALUE *argv, VALUE self));
-
-
-/*
-=begin
-= Classes & Modules
-=end
-*/
-
-/*
-=begin
-== Iconv
-=end
-*/
-static iconv_t
-iconv_create
-#ifdef HAVE_PROTOTYPES
-(VALUE to, VALUE from)
-#else /* HAVE_PROTOTYPES */
- (to, from)
- VALUE to;
- VALUE from;
-#endif /* HAVE_PROTOTYPES */
-{
- const char* tocode = StringValuePtr(to);
- const char* fromcode = StringValuePtr(from);
-
- iconv_t cd = iconv_open(tocode, fromcode);
-
- if (cd == (iconv_t)-1) {
- switch (errno) {
- case EMFILE:
- case ENFILE:
- case ENOMEM:
- rb_gc();
- cd = iconv_open(tocode, fromcode);
- }
- if (cd == (iconv_t)-1) {
- volatile VALUE msg = rb_str_new2("iconv(\"");
- rb_str_buf_cat2(rb_str_buf_append(msg, to), "\", \"");
- rb_str_buf_cat2(rb_str_buf_append(msg, from), "\")");
- rb_sys_fail(StringValuePtr(msg));
- }
- }
-
- return cd;
-}
-
-static VALUE
-iconv_free
-#ifdef HAVE_PROTOTYPES
-(VALUE cd)
-#else /* HAVE_PROTOTYPES */
- (cd)
- VALUE cd;
-#endif /* HAVE_PROTOTYPES */
-{
- if (cd && iconv_close(VALUE2ICONV(cd)) == -1)
- rb_sys_fail("iconv_close");
- return Qnil;
-}
-
-#define ICONV_FREE (RUBY_DATA_FUNC)iconv_free
-
-static VALUE
-iconv_try
-#ifdef HAVE_PROTOTYPES
-(iconv_t cd, const char **inptr, size_t *inlen, char **outptr, size_t *outlen)
-#else /* HAVE_PROTOTYPES */
- (cd, inptr, inlen, outptr, outlen)
- iconv_t cd;
- const char **inptr;
- size_t *inlen;
- char **outptr;
- size_t *outlen;
-#endif /* HAVE_PROTOTYPES */
-{
- if (iconv(cd, (char **)inptr, inlen, outptr, outlen) == (size_t)-1) {
- if (!*inlen)
- return Qfalse;
- switch (errno) {
- case E2BIG:
- /* try the left in next loop */
- break;
- case EILSEQ:
- return rb_obj_alloc(rb_eIconvIllegalSeq);
- case EINVAL:
- return rb_obj_alloc(rb_eIconvInvalidChar);
- default:
- rb_sys_fail("iconv");
- }
- }
- else if (*inlen > 0) {
- /* something goes wrong */
- return rb_obj_alloc(rb_eIconvIllegalSeq);
- }
- return Qfalse;
-}
-
-#define iconv_fail(error, success, failed, env) \
- rb_exc_raise(iconv_failure_initialize(error, success, failed, env))
-
-static VALUE
-iconv_failure_initialize
-#ifdef HAVE_PROTOTYPES
-(VALUE error, VALUE success, VALUE failed, struct iconv_env_t* env)
-#else /* HAVE_PROTOTYPES */
- (error, success, failed, env)
- VALUE error;
- VALUE success;
- VALUE failed;
- struct iconv_env_t *env;
-#endif /* HAVE_PROTOTYPES */
-{
- if (NIL_P(rb_ivar_get(error, rb_mesg)))
- rb_ivar_set(error, rb_mesg, rb_inspect(failed));
- if (env) {
- success = rb_funcall3(env->ret, rb_inserter, 1, &success);
- if (env->argc > 0) {
- *(env->argv) = failed;
- failed = rb_ary_new4(env->argc, env->argv);
- }
- }
- rb_ivar_set(error, rb_success, success);
- rb_ivar_set(error, rb_failed, failed);
- return error;
-}
-
-static VALUE
-rb_str_derive
-#ifdef HAVE_PROTOTYPES
-(VALUE str, const char* ptr, int len)
-#else /* HAVE_PROTOTYPES */
- (str, ptr, len)
- VALUE str;
- const char *ptr;
- int len;
-#endif /* HAVE_PROTOTYPES */
-{
- VALUE ret;
-
- if (NIL_P(str))
- return rb_str_new(ptr, len);
- if (RSTRING(str)->ptr == ptr && RSTRING(str)->len == len)
- return str;
- ret = rb_str_new(ptr, len);
- OBJ_INFECT(ret, str);
- return ret;
-}
-
-static VALUE
-iconv_convert
-#ifdef HAVE_PROTOTYPES
-(iconv_t cd, VALUE str, int start, int length, struct iconv_env_t* env)
-#else /* HAVE_PROTOTYPES */
- (cd, str, start, length, env)
- iconv_t cd;
- VALUE str;
- int start;
- int length;
- struct iconv_env_t *env;
-#endif /* HAVE_PROTOTYPES */
-{
- VALUE ret = Qfalse;
- VALUE error = Qfalse;
- const char *inptr, *instart;
- size_t inlen;
- /* I believe ONE CHARACTER never exceed this. */
- char buffer[BUFSIZ];
- char *outptr;
- size_t outlen;
-
- if (cd == (iconv_t)-1)
- rb_raise(rb_eArgError, "closed iconv");
-
- if (NIL_P(str)) {
- /* Reset output pointer or something. */
- inptr = "";
- inlen = 0;
- outptr = buffer;
- outlen = sizeof(buffer);
- error = iconv_try(cd, &inptr, &inlen, &outptr, &outlen);
- if (error)
- iconv_fail(error, Qnil, Qnil, env);
-
- inptr = NULL;
- length = 0;
- }
- else {
- int slen;
-
- Check_Type(str, T_STRING);
- slen = RSTRING(str)->len;
- inptr = RSTRING(str)->ptr;
-
- if (start < 0 ? (start += slen) < 0 : start >= slen)
- length = 0;
- else if (length < 0 && (length += slen + 1) < 0)
- length = 0;
- else if ((length -= start) < 0)
- length = 0;
- else
- inptr += start;
- }
- instart = inptr;
- inlen = length;
-
- do {
- const char *tmpstart = inptr;
- outptr = buffer;
- outlen = sizeof(buffer);
-
- error = iconv_try(cd, &inptr, &inlen, &outptr, &outlen);
-
- if (0 <= outlen && outlen <= sizeof(buffer)) {
- outlen = sizeof(buffer) - outlen;
- if (outlen > inptr - tmpstart || /* input can't contain output */
- (outlen < inptr - tmpstart && inlen > 0) || /* something skipped */
- memcmp(buffer, tmpstart, outlen)) /* something differs */
- {
- if (NIL_P(str)) {
- ret = rb_str_new(buffer, outlen);
- }
- else {
- if (ret) {
- ret = rb_str_buf_cat(ret, instart, tmpstart - instart);
- }
- else {
- ret = rb_str_new(instart, tmpstart - instart);
- OBJ_INFECT(ret, str);
- }
- ret = rb_str_buf_cat(ret, buffer, outlen);
- instart = inptr;
- }
- }
- else if (!inlen) {
- inptr = tmpstart + outlen;
- }
- }
- else {
- /* Some iconv() have a bug, return *outlen out of range */
- char errmsg[50];
- sprintf(errmsg, "bug?(output length = %d)", sizeof(buffer) - outlen);
- error = rb_exc_new2(rb_eIconvOutOfRange, errmsg);
- }
-
- if (error) {
- if (!ret)
- ret = rb_str_derive(str, instart, inptr - instart);
- str = rb_str_derive(str, inptr, inlen);
- iconv_fail(error, ret, str, env);
- }
- } while (inlen > 0);
-
- if (!ret)
- ret = rb_str_derive(str, instart, inptr - instart);
- return ret;
-}
-
-
-/*
-=begin
-=== Class methods
-=end
-*/
-/*
-=begin
---- Iconv.new(to, from)
- Creates new code converter from a coding-system designated with ((|from|))
- to another one designated with ((|to|)).
- :Parameters
- :((|to|))
- coding-system name for destination.
- :((|from|))
- coding-system name for source.
- :Exceptions
- :(({TypeError}))
- if ((|to|)) or ((|from|)) aren't String
- :(({ArgumentError}))
- if designated converter couldn't find out.
- :(({SystemCallError}))
- when (({iconv_open(3)})) failed.
-
---- Iconv.open(to, from)
- Equivalents to ((<Iconv.new>)) except with in the case of called
- with a block, yields with the new instance and closes it, and
- returns the result which returned from the block.
-=end
-*/
-static VALUE
-iconv_s_allocate
-#ifdef HAVE_PROTOTYPES
-(VALUE klass)
-#else /* HAVE_PROTOTYPES */
- (klass)
- VALUE klass;
-#endif /* HAVE_PROTOTYPES */
-{
- return Data_Wrap_Struct(klass, 0, ICONV_FREE, 0);
-}
-
-static VALUE
-iconv_initialize
-#ifdef HAVE_PROTOTYPES
-(VALUE self, VALUE to, VALUE from)
-#else /* HAVE_PROTOTYPES */
- (self, to, from)
- VALUE self;
- VALUE to;
- VALUE from;
-#endif /* HAVE_PROTOTYPES */
-{
- iconv_free((VALUE)(DATA_PTR(self)));
- DATA_PTR(self) = NULL;
- DATA_PTR(self) = (void *)ICONV2VALUE(iconv_create(to, from));
- return self;
-}
-
-static VALUE
-iconv_s_open
-#ifdef HAVE_PROTOTYPES
-(VALUE self, VALUE to, VALUE from)
-#else /* HAVE_PROTOTYPES */
- (self, to, from)
- VALUE self;
- VALUE to;
- VALUE from;
-#endif /* HAVE_PROTOTYPES */
-{
- VALUE cd = ICONV2VALUE(iconv_create(to, from));
-
- if (rb_block_given_p()) {
- self = Data_Wrap_Struct(self, NULL, NULL, (void *)cd);
- return rb_ensure(rb_yield, self, (VALUE(*)())iconv_finish, self);
- }
- else {
- return Data_Wrap_Struct(self, NULL, ICONV_FREE, (void *)cd);
- }
-}
-
-/*
-=begin
---- Iconv.iconv(to, from, *strs)
- Shorthand for
- Iconv.open(to, from) {|cd| (strs + nil).collect {|s| cd.iconv(s)}}
- :Parameters
- :((|to|)), ((|from|))
- see ((<Iconv.new>)).
- :((|strs|))
- strings to be converted.
- :Exceptions
- exceptions thrown by ((<Iconv.new>)), ((<Iconv.open>)) and
- ((<Iconv#iconv>)).
-=end
-*/
-
-static VALUE
-iconv_s_convert
-#ifdef HAVE_PROTOTYPES
-(struct iconv_env_t* env)
-#else /* HAVE_PROTOTYPES */
- (env)
- struct iconv_env_t *env;
-#endif /* HAVE_PROTOTYPES */
-{
- VALUE last = 0;
-
- for (; env->argc > 0; --env->argc, ++env->argv) {
- VALUE s = iconv_convert(env->cd, last = *(env->argv), 0, -1, env);
- rb_funcall3(env->ret, rb_inserter, 1, &s);
- }
-
- if (!NIL_P(last)) {
- VALUE s = iconv_convert(env->cd, Qnil, 0, 0, env);
- if (RSTRING(s)->len)
- rb_funcall3(env->ret, rb_inserter, 1, &s);
- }
-
- return env->ret;
-}
-
-static VALUE
-iconv_s_iconv
-#ifdef HAVE_PROTOTYPES
-(int argc, VALUE *argv, VALUE self)
-#else /* HAVE_PROTOTYPES */
- (argc, argv, self)
- int argc;
- VALUE *argv;
- VALUE self;
-#endif /* HAVE_PROTOTYPES */
-{
- struct iconv_env_t arg;
-
- if (argc < 2) /* needs `to' and `from' arguments at least */
- rb_raise(rb_eArgError, "wrong # of arguments (%d for %d)", argc, 2);
-
- arg.argc = argc -= 2;
- arg.argv = argv + 2;
- arg.ret = rb_ary_new2(argc);
- arg.cd = iconv_create(argv[0], argv[1]);
- return rb_ensure(iconv_s_convert, (VALUE)&arg, iconv_free, ICONV2VALUE(arg.cd));
-}
-
-
-/*
-=begin
-=== Instance methods
-=end
-*/
-/*
-=begin
---- Iconv#close
- Finishes conversion.
- * After calling this, invoking method ((<Iconv#iconv>)) will cause
- exception, but multiple calls of (({close})) are guaranteed to
- end successfully.
- * Returns a string contains the byte sequence to change the
- output buffer to its initial shift state.
-=end
-*/
-static VALUE
-iconv_init_state
-#ifdef HAVE_PROTOTYPES
-(VALUE cd)
-#else /* HAVE_PROTOTYPES */
- (cd)
- VALUE cd;
-#endif /* HAVE_PROTOTYPES */
-{
- return iconv_convert(VALUE2ICONV(cd), Qnil, 0, 0, NULL);
-}
-
-static VALUE
-iconv_finish
-#ifdef HAVE_PROTOTYPES
-(VALUE self)
-#else /* HAVE_PROTOTYPES */
- (self)
- VALUE self;
-#endif /* HAVE_PROTOTYPES */
-{
- VALUE cd;
-
- Check_Type(self, T_DATA);
-
- cd = (VALUE)DATA_PTR(self);
- if (!cd) return Qnil;
- DATA_PTR(self) = NULL;
-
- return rb_ensure(iconv_init_state, cd, iconv_free, cd);
-}
-
-/*
-=begin
---- Iconv#iconv(str, [ start = 0, [ length = -1 ] ])
- Converts string and returns converted one.
- * In the case of ((|str|)) is (({String})), converts (({str[start, length]})).
- Returns converted string.
- * In the case of ((|str|)) is (({nil})), places ((|converter|))
- itself into initial shift state and just returns a string contains
- the byte sequence to change the output buffer to its initial shift
- state.
- * Otherwise, causes exception.
- :Parameters
- :((|str|))
- string to be converted or (({nil})).
- :((|start|))
- starting offset.
- :((|length|))
- conversion length,
- (({nil})) or (({-1})) means whole string from (({start})).
- :Exceptions
- * ((<Iconv::IllegalSequence>))
- * ((<Iconv::InvalidCharacter>))
- * ((<Iconv::OutOfRange>))
-=end
-*/
-static VALUE
-iconv_iconv
-#ifdef HAVE_PROTOTYPES
-(int argc, VALUE *argv, VALUE self)
-#else /* HAVE_PROTOTYPES */
- (argc, argv, self)
- int argc;
- VALUE *argv;
- VALUE self;
-#endif /* HAVE_PROTOTYPES */
-{
- VALUE str, n1, n2;
-
- Check_Type(self, T_DATA);
-
- n1 = n2 = Qnil;
- rb_scan_args(argc, argv, "12", &str, &n1, &n2);
-
- return iconv_convert(VALUE2ICONV(DATA_PTR(self)), str,
- NIL_P(n1) ? 0 : NUM2INT(n1),
- NIL_P(n2) ? -1 : NUM2INT(n1),
- NULL);
-}
-
-
-/*
-=begin
-= Exceptions
-=end
-*/
-/*
-=begin
-== Iconv::Failure
-Base exceptional attributes from ((<Iconv>)).
-
-=== Instance methods
-=end
-*/
-/*
-=begin
---- Iconv::Failure#success
- Returns string(s) translated successfully until the exception occurred.
- * In the case of failure occurred within ((<Iconv.iconv>)), returned
- value is an array of strings translated successfully preceding
- failure and the last element is string on the way.
-=end
-*/
-static VALUE
-iconv_failure_success
-#ifdef HAVE_PROTOTYPES
-(VALUE self)
-#else /* HAVE_PROTOTYPES */
- (self)
- VALUE self;
-#endif /* HAVE_PROTOTYPES */
-{
- return rb_ivar_get(self, rb_success);
-}
-
-/*
-=begin
---- Iconv::Failure#failed
- Returns substring of the original string passed to ((<Iconv>)) that
- starts at the character caused the exception.
-=end
-*/
-static VALUE
-iconv_failure_failed
-#ifdef HAVE_PROTOTYPES
-(VALUE self)
-#else /* HAVE_PROTOTYPES */
- (self)
- VALUE self;
-#endif /* HAVE_PROTOTYPES */
-{
- return rb_ivar_get(self, rb_failed);
-}
-
-/*
-=begin
---- Iconv::Failure#inspect
- Returns inspected string like as: #<(({type})): "(({success}))", "(({failed}))">
-=end
-*/
-static VALUE
-iconv_failure_inspect
-#ifdef HAVE_PROTOTYPES
-(VALUE self)
-#else /* HAVE_PROTOTYPES */
- (self)
- VALUE self;
-#endif /* HAVE_PROTOTYPES */
-{
- char *cname = rb_class2name(CLASS_OF(self));
- VALUE success = iconv_failure_success(self);
- VALUE failed = iconv_failure_failed(self);
- VALUE str = rb_str_buf_cat2(rb_str_new2("#<"), cname);
- str = rb_str_buf_cat(str, ": ", 2);
- str = rb_str_buf_append(str, rb_inspect(success));
- str = rb_str_buf_cat(str, ", ", 2);
- str = rb_str_buf_append(str, rb_inspect(failed));
- return rb_str_buf_cat(str, ">", 1);
-}
-
-/*
- Hmmm, I don't like to write RD inside of function :-<.
-
-=begin
-== Iconv::IllegalSequence
-Exception in the case of any illegal sequence detected.
-=== Superclass
-(({ArgumentError}))
-=== Included Modules
-((<Iconv::Failure>))
-
-== Iconv::InvalidCharacter
-Exception in the case of output coding system can't express the character.
-=== Superclass
-(({ArgumentError}))
-=== Included Modules
-((<Iconv::Failure>))
-
-== Iconv::OutOfRange
-Iconv library internal error. Must not occur.
-=== Superclass
-(({RuntimeError}))
-=== Included Modules
-((<Iconv::Failure>))
-=end
-*/
-
-void
-Init_iconv _((void))
-{
- VALUE rb_cIconv = rb_define_class("Iconv", rb_cData);
- rb_define_singleton_method(rb_cIconv, "allocate", iconv_s_allocate, 0);
- rb_define_singleton_method(rb_cIconv, "open", iconv_s_open, 2);
- rb_define_singleton_method(rb_cIconv, "iconv", iconv_s_iconv, -1);
- rb_define_method(rb_cIconv, "initialize", iconv_initialize, 2);
- rb_define_method(rb_cIconv, "close", iconv_finish, 0);
- rb_define_method(rb_cIconv, "iconv", iconv_iconv, -1);
-
- rb_eIconvFailure = rb_define_module_under(rb_cIconv, "Failure");
- rb_define_method(rb_eIconvFailure, "success", iconv_failure_success, 0);
- rb_define_method(rb_eIconvFailure, "failed", iconv_failure_failed, 0);
- rb_define_method(rb_eIconvFailure, "inspect", iconv_failure_inspect, 0);
-
- rb_eIconvIllegalSeq = rb_define_class_under(rb_cIconv, "IllegalSequence", rb_eArgError);
- rb_eIconvInvalidChar = rb_define_class_under(rb_cIconv, "InvalidCharacter", rb_eArgError);
- rb_eIconvOutOfRange = rb_define_class_under(rb_cIconv, "OutOfRange", rb_eRuntimeError);
- rb_include_module(rb_eIconvIllegalSeq, rb_eIconvFailure);
- rb_include_module(rb_eIconvInvalidChar, rb_eIconvFailure);
- rb_include_module(rb_eIconvOutOfRange, rb_eIconvFailure);
-
- rb_inserter = rb_intern("<<");
- rb_success = rb_intern("success");
- rb_failed = rb_intern("failed");
- rb_mesg = rb_intern("mesg");
-}
-
-
-/*
-=begin
-== Example
-(1) Instantiate a new ((<Iconv>)), use method ((<Iconv#iconv>)).
- cd = Iconv.new(to, from)
- begin
- input.each {|s| output << cd.iconv(s)}
- output << cd.iconv(nil) # don't forget this
- ensure
- cd.close
- end
-(2) Invoke ((<Iconv.open>)) with a block.
- Iconv.open(to, from) do |cd|
- input.each {|s| output << cd.iconv(s)}
- output << cd.iconv(nil)
- end
-(3) Shorthand for (2).
- Iconv.iconv(to, from, *input.to_a)
-=end
-*/
diff --git a/ext/nkf/.cvsignore b/ext/nkf/.cvsignore
deleted file mode 100644
index fc802ff1c2..0000000000
--- a/ext/nkf/.cvsignore
+++ /dev/null
@@ -1,2 +0,0 @@
-Makefile
-mkmf.log
diff --git a/ext/nkf/MANIFEST b/ext/nkf/MANIFEST
deleted file mode 100644
index 5114a3762a..0000000000
--- a/ext/nkf/MANIFEST
+++ /dev/null
@@ -1,7 +0,0 @@
-MANIFEST
-depend
-extconf.rb
-lib/kconv.rb
-nkf.c
-nkf1.7/nkf.c
-test.rb
diff --git a/ext/nkf/depend b/ext/nkf/depend
deleted file mode 100644
index 13e32e6074..0000000000
--- a/ext/nkf/depend
+++ /dev/null
@@ -1 +0,0 @@
-nkf.o : nkf.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h $(srcdir)/nkf1.7/nkf.c
diff --git a/ext/nkf/extconf.rb b/ext/nkf/extconf.rb
deleted file mode 100644
index 710662f19c..0000000000
--- a/ext/nkf/extconf.rb
+++ /dev/null
@@ -1,2 +0,0 @@
-require 'mkmf'
-create_makefile('nkf')
diff --git a/ext/nkf/lib/kconv.rb b/ext/nkf/lib/kconv.rb
deleted file mode 100644
index af6d82275f..0000000000
--- a/ext/nkf/lib/kconv.rb
+++ /dev/null
@@ -1,73 +0,0 @@
-require 'nkf'
-
-module Kconv
- AUTO = NKF::AUTO
- JIS = NKF::JIS
- EUC = NKF::EUC
- SJIS = NKF::SJIS
- BINARY = NKF::BINARY
- NOCONV = NKF::NOCONV
- UNKNOWN = NKF::UNKNOWN
- def kconv(str, out_code, in_code = AUTO)
- opt = '-'
- case in_code
- when NKF::JIS
- opt << 'J'
- when NKF::EUC
- opt << 'E'
- when NKF::SJIS
- opt << 'S'
- end
-
- case out_code
- when NKF::JIS
- opt << 'j'
- when NKF::EUC
- opt << 'e'
- when NKF::SJIS
- opt << 's'
- when NKF::NOCONV
- return str
- end
-
- opt = '' if opt == '-'
-
- NKF::nkf(opt, str)
- end
- module_function :kconv
-
- def tojis(str)
- NKF::nkf('-j', str)
- end
- module_function :tojis
-
- def toeuc(str)
- NKF::nkf('-e', str)
- end
- module_function :toeuc
-
- def tosjis(str)
- NKF::nkf('-s', str)
- end
- module_function :tosjis
-
- def guess(str)
- NKF::guess(str)
- end
- module_function :guess
-end
-
-class String
- def kconv(out_code, in_code=Kconv::AUTO)
- Kconv::kconv(self, out_code, in_code)
- end
- def tojis
- NKF::nkf('-j', self)
- end
- def toeuc
- NKF::nkf('-e', self)
- end
- def tosjis
- NKF::nkf('-s', self)
- end
-end
diff --git a/ext/nkf/nkf.c b/ext/nkf/nkf.c
deleted file mode 100644
index 50723467cd..0000000000
--- a/ext/nkf/nkf.c
+++ /dev/null
@@ -1,197 +0,0 @@
-#include "ruby.h"
-
-#define _AUTO 0
-#define _JIS 1
-#define _EUC 2
-#define _SJIS 3
-#define _BINARY 4
-#define _NOCONV 4
-#define _UNKNOWN _AUTO
-
-#undef getc
-#undef ungetc
-#define getc(f) (input_ctr<i_len?input[input_ctr++]:-1)
-#define ungetc(c,f) input_ctr--
-
-#undef putchar
-#define putchar(c) rb_nkf_putchar(c)
-
-#define INCSIZE 32
-static int incsize;
-
-static unsigned char *input, *output;
-static int input_ctr, i_len;
-static int output_ctr, o_len;
-
-static VALUE dst;
-
-static int
-rb_nkf_putchar(c)
- unsigned int c;
-{
- if (output_ctr >= o_len) {
- o_len += incsize;
- rb_str_cat(dst, 0, incsize);
- output = RSTRING(dst)->ptr;
- incsize *= 2;
- }
- output[output_ctr++] = c;
-
- return c;
-}
-
-#define PERL_XS 1
-#include "nkf1.7/nkf.c"
-
-static VALUE
-rb_nkf_kconv(obj, opt, src)
- VALUE obj, opt, src;
-{
- char *opt_ptr, *opt_end;
- volatile VALUE v;
-
- reinit();
- StringValue(opt);
- opt_ptr = RSTRING(opt)->ptr;
- opt_end = opt_ptr + RSTRING(opt)->len;
- for (; opt_ptr < opt_end; opt_ptr++) {
- if (*opt_ptr != '-') {
- continue;
- }
- arguments(opt_ptr);
- }
-
- incsize = INCSIZE;
-
- input_ctr = 0;
- StringValue(src);
- input = RSTRING(src)->ptr;
- i_len = RSTRING(src)->len;
- dst = rb_str_new(0, i_len*3 + 10);
- v = dst;
-
- output_ctr = 0;
- output = RSTRING(dst)->ptr;
- o_len = RSTRING(dst)->len;
- *output = '\0';
-
- if(iso8859_f && (oconv != j_oconv || !x0201_f )) {
- iso8859_f = FALSE;
- }
-
- kanji_convert(NULL);
- RSTRING(dst)->ptr[output_ctr] = '\0';
- RSTRING(dst)->len = output_ctr;
- OBJ_INFECT(dst, src);
-
- return dst;
-}
-
-/*
- * Character code detection - Algorithm described in:
- * Ken Lunde. `Understanding Japanese Information Processing'
- * Sebastopol, CA: O'Reilly & Associates.
- */
-
-static VALUE
-rb_nkf_guess(obj, src)
- VALUE obj, src;
-{
- unsigned char *p;
- unsigned char *pend;
- int sequence_counter = 0;
-
- StringValue(src);
- p = RSTRING(src)->ptr;
- pend = p + RSTRING(src)->len;
-
-#define INCR do {\
- p++;\
- if (p==pend) return INT2FIX(_UNKNOWN);\
- sequence_counter++;\
- if (sequence_counter % 2 == 1 && *p != 0xa4)\
- sequence_counter = 0;\
- if (6 <= sequence_counter) {\
- sequence_counter = 0;\
- return INT2FIX(_EUC);\
- }\
-} while (0)
-
- if (*p == 0xa4)
- sequence_counter = 1;
-
- while (p<pend) {
- if (*p == '\033') {
- return INT2FIX(_JIS);
- }
- if (*p < '\006' || *p == 0x7f || *p == 0xff) {
- return INT2FIX(_BINARY);
- }
- if (0x81 <= *p && *p <= 0x8d) {
- return INT2FIX(_SJIS);
- }
- if (0x8f <= *p && *p <= 0x9f) {
- return INT2FIX(_SJIS);
- }
- if (*p == 0x8e) { /* SS2 */
- INCR;
- if ((0x40 <= *p && *p <= 0x7e) ||
- (0x80 <= *p && *p <= 0xa0) ||
- (0xe0 <= *p && *p <= 0xfc))
- return INT2FIX(_SJIS);
- }
- else if (0xa1 <= *p && *p <= 0xdf) {
- INCR;
- if (0xf0 <= *p && *p <= 0xfe)
- return INT2FIX(_EUC);
- if (0xe0 <= *p && *p <= 0xef) {
- while (p < pend && *p >= 0x40) {
- if (*p >= 0x81) {
- if (*p <= 0x8d || (0x8f <= *p && *p <= 0x9f)) {
- return INT2FIX(_SJIS);
- }
- else if (0xfd <= *p && *p <= 0xfe) {
- return INT2FIX(_EUC);
- }
- }
- INCR;
- }
- }
- else if (*p <= 0x9f) {
- return INT2FIX(_SJIS);
- }
- }
- else if (0xf0 <= *p && *p <= 0xfe) {
- return INT2FIX(_EUC);
- }
- else if (0xe0 <= *p && *p <= 0xef) {
- INCR;
- if ((0x40 <= *p && *p <= 0x7e) ||
- (0x80 <= *p && *p <= 0xa0)) {
- return INT2FIX(_SJIS);
- }
- if (0xfd <= *p && *p <= 0xfe) {
- return INT2FIX(_EUC);
- }
- }
- INCR;
- }
- return INT2FIX(_UNKNOWN);
-}
-
-void
-Init_nkf()
-{
- VALUE mKconv = rb_define_module("NKF");
-
- rb_define_module_function(mKconv, "nkf", rb_nkf_kconv, 2);
- rb_define_module_function(mKconv, "guess", rb_nkf_guess, 1);
-
- rb_define_const(mKconv, "AUTO", INT2FIX(_AUTO));
- rb_define_const(mKconv, "JIS", INT2FIX(_JIS));
- rb_define_const(mKconv, "EUC", INT2FIX(_EUC));
- rb_define_const(mKconv, "SJIS", INT2FIX(_SJIS));
- rb_define_const(mKconv, "BINARY", INT2FIX(_BINARY));
- rb_define_const(mKconv, "NOCONV", INT2FIX(_NOCONV));
- rb_define_const(mKconv, "UNKNOWN", INT2FIX(_UNKNOWN));
-}
diff --git a/ext/nkf/nkf1.7/nkf.c b/ext/nkf/nkf1.7/nkf.c
deleted file mode 100644
index 09419f40a7..0000000000
--- a/ext/nkf/nkf1.7/nkf.c
+++ /dev/null
@@ -1,1900 +0,0 @@
-/** Network Kanji Filter. (PDS Version)
-************************************************************************
-** Copyright (C) 1987, Fujitsu LTD. (Itaru ICHIKAWA)
-** $BO"Mm@h!'(B $B!J3t!KIY;NDL8&5f=j!!%=%U%H#38&!!;T@n!!;j(B
-** $B!J(BE-Mail Address: ichikawa@flab.fujitsu.co.jp$B!K(B
-** Copyright (C) 1996,1998
-** $BO"Mm@h!'(B $BN05eBg3X>pJs9)3X2J(B $B2OLn(B $B??<#(B mine/X0208 support
-** $B!J(BE-Mail Address: kono@ie.u-ryukyu.ac.jp$B!K(B
-** $BO"Mm@h!'(B COW for DOS & Win16 & Win32 & OS/2
-** $B!J(BE-Mail Address: GHG00637@niftyserve.or.p$B!K(B
-** $B$3$N%=!<%9$N$$$+$J$kJ#<L!$2~JQ!$=$@5$b5vBz$7$^$9!#$?$@$7!"(B
-** $B$=$N:]$K$O!"C/$,9W8%$7$?$r<($9$3$NItJ,$r;D$9$3$H!#(B
-** $B:FG[I[$d;(;o$NIUO?$J$I$NLd$$9g$o$;$bI,MW$"$j$^$;$s!#(B
-** $B$3$N%W%m%0%i%`$K$D$$$F$OFC$K2?$NJ]>Z$b$7$J$$!"0-$7$+$i$:!#(B
-** Everyone is permitted to do anything on this program
-** including copying, modifying, improving.
-** as long as you don't try to pretend that you wrote it.
-** i.e., the above copyright notice has to appear in all copies.
-** You don't have to ask before copying or publishing.
-** THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE.
-***********************************************************************/
-
-static char *CopyRight =
- "Copyright (C) 1987, FUJITSU LTD. (I.Ichikawa),1998 S. Kono, COW";
-static char *Version =
- "1.7";
-static char *Patchlevel =
- "0/9711/Shinji Kono";
-
-/*
-**
-**
-**
-** USAGE: nkf [flags] [file]
-**
-** Flags:
-** b Output is bufferred (DEFAULT)
-** u Output is unbufferred
-**
-** t no operation
-**
-** j Outout code is JIS 7 bit (DEFAULT SELECT)
-** s Output code is MS Kanji (DEFAULT SELECT)
-** e Output code is AT&T JIS (DEFAULT SELECT)
-** l Output code is JIS 7bit and ISO8859-1 Latin-1
-**
-** m MIME conversion for ISO-2022-JP
-** i_ Output sequence to designate JIS-kanji (DEFAULT_J)
-** o_ Output sequence to designate single-byte roman characters (DEFAULT_R)
-**
-** r {de/en}crypt ROT13/47
-**
-** v display Version
-**
-** T Text mode output (for MS-DOS)
-**
-** x Do not convert X0201 kana into X0208
-** Z Convert X0208 alphabet to ASCII
-**
-** f60 fold option
-**
-** m MIME decode
-** B try to fix broken JIS, missing Escape
-** B[1-9] broken level
-**
-** O Output to 'nkf.out' file
-** d Delete \r in line feed
-** c Add \r in line feed
-**/
-/******************************/
-/* $B%G%U%)%k%H$N=PNO%3!<%IA*Br(B */
-/* Select DEFAULT_CODE */
-#define DEFAULT_CODE_JIS
-/* #define DEFAULT_CODE_SJIS */
-/* #define DEFAULT_CODE_EUC */
-/******************************/
-
-#if (defined(__TURBOC__) || defined(LSI_C)) && !defined(MSDOS)
-#define MSDOS
-#endif
-
-#ifndef PERL_XS
-#include <stdio.h>
-#endif
-
-#if defined(MSDOS) || defined(__OS2__)
-#include <stdlib.h>
-#include <fcntl.h>
-#include <io.h>
-#endif
-
-#ifdef MSDOS
-#ifdef LSI_C
-#define setbinmode(fp) fsetbin(fp)
-#else /* Microsoft C, Turbo C */
-#define setbinmode(fp) setmode(fileno(fp), O_BINARY)
-#endif
-#else /* UNIX,OS/2 */
-#define setbinmode(fp)
-#endif
-
-#ifdef _IOFBF /* SysV and MSDOS */
-#define setvbuffer(fp, buf, size) setvbuf(fp, buf, _IOFBF, size)
-#else /* BSD */
-#define setvbuffer(fp, buf, size) setbuffer(fp, buf, size)
-#endif
-
-/*Borland C++ 4.5 EasyWin*/
-#if defined(__TURBOC__) && defined(_Windows) && !defined(__WIN32__) /*Easy Win */
-#define EASYWIN
-#include <windows.h>
-#endif
-
-#define FALSE 0
-#define TRUE 1
-
-/* state of output_mode and input_mode */
-
-#define ASCII 0
-#define X0208 1
-#define X0201 2
-#define NO_X0201 3
-#define JIS_INPUT 4
-#define SJIS_INPUT 5
-#define LATIN1_INPUT 6
-#define FIXED_MIME 7
-#define DOUBLE_SPACE -2
-
-#define NL 0x0a
-#define ESC 0x1b
-#define SPACE 0x20
-#define AT 0x40
-#define SSP 0xa0
-#define DEL 0x7f
-#define SI 0x0f
-#define SO 0x0e
-#define SSO 0x8e
-
-#define HOLD_SIZE 32
-#define IOBUF_SIZE 16384
-
-#define DEFAULT_J 'B'
-#define DEFAULT_R 'B'
-
-#define SJ0162 0x00e1 /* 01 - 62 ku offset */
-#define SJ6394 0x0161 /* 63 - 94 ku offset */
-
-
-/* MIME preprocessor */
-
-#undef STRICT_MIME /* do stupid strict mime integrity check */
-#define GETC(p) ((!mime_mode)?getc(p):mime_getc(p))
-#define UNGETC(c,p) ((!mime_mode)?ungetc(c,p):mime_ungetc(c))
-
-
-#ifdef EASYWIN /*Easy Win */
-extern POINT _BufferSize;
-#endif
-
-/* function prototype */
-
-#ifndef _
-# ifdef __STDC__
-# define _(args) args
-# else
-# define _(args) ()
-# endif
-#endif
-
-#ifndef PERL_XS
-static void noconvert _((FILE *f));
-static int mime_integrity _((FILE *f,unsigned char *p));
-static int usage _((void));
-static char stdibuf[IOBUF_SIZE];
-static char stdobuf[IOBUF_SIZE];
-static unsigned int mime_input = 0; /* undecoded */
-static int end_check;
-#endif
-
-static void kanji_convert _((FILE *f));
-static void h_conv _((FILE *f,int c2,int c1));
-static int push_hold_buf _((int c2,int c1));
-static void s_iconv _((int c2,int c1));
-static void e_oconv _((int c2,int c1));
-static void s_oconv _((int c2,int c1));
-static void j_oconv _((int c2,int c1));
-static int line_fold _((int c2,int c1));
-static int pre_convert _((int c1,int c2));
-static int mime_begin _((FILE *f));
-static int mime_getc _((FILE *f));
-static int mime_ungetc _((unsigned int c));
-static int base64decode _((int c));
-static void arguments _((char *c));
-static void reinit _((void));
-
-/* buffers */
-
-static unsigned char hold_buf[HOLD_SIZE*2];
-static int hold_count;
-
-/* MIME preprocessor fifo */
-
-#define MIME_BUF_SIZE (1024) /* 2^n ring buffer */
-#define MIME_BUF_MASK (MIME_BUF_SIZE-1)
-#define Fifo(n) mime_buf[(n)&MIME_BUF_MASK]
-static unsigned char mime_buf[MIME_BUF_SIZE];
-static unsigned int mime_top = 0;
-static unsigned int mime_last = 0; /* decoded */
-
-/* flags */
-static int unbuf_f = FALSE;
-static int estab_f = FALSE;
-static int nop_f = FALSE;
-static int binmode_f = TRUE; /* binary mode */
-static int rot_f = FALSE; /* rot14/43 mode */
-static int input_f = FALSE; /* non fixed input code */
-static int alpha_f = FALSE; /* convert JIx0208 alphbet to ASCII */
-static int mime_f = TRUE; /* convert MIME B base64 or Q */
-static int mimebuf_f = FALSE; /* MIME buffered input */
-static int broken_f = FALSE; /* convert ESC-less broken JIS */
-static int iso8859_f = FALSE; /* ISO8859 through */
-#if defined(MSDOS) || defined(__OS2__)
-static int x0201_f = TRUE; /* Assume JISX0201 kana */
-#else
-static int x0201_f = NO_X0201; /* Assume NO JISX0201 */
-#endif
-
-/* X0208 -> ASCII converter */
-
-static int c1_return;
-
-/* fold parameter */
-static int line = 0; /* chars in line */
-static int prev = 0;
-static int fold_f = FALSE;
-static int fold_len = 0;
-
-/* options */
-static char kanji_intro = DEFAULT_J,
- ascii_intro = DEFAULT_R;
-
-/* Folding */
-
-int line_fold();
-#define FOLD_MARGIN 10
-#define DEFAULT_FOLD 60
-
-/* converters */
-
-#ifdef DEFAULT_CODE_JIS
-# define DEFAULT_CONV j_oconv
-#endif
-#ifdef DEFAULT_CODE_SJIS
-# define DEFAULT_CONV s_oconv
-#endif
-#ifdef DEFAULT_CODE_EUC
-# define DEFAULT_CONV e_oconv
-#endif
-
-static void (*iconv) _((int c2,int c1));
- /* s_iconv or oconv */
-static void (*oconv) _((int c2,int c1)) = DEFAULT_CONV;
- /* [ejs]_oconv */
-
-/* Global states */
-static int output_mode = ASCII, /* output kanji mode */
- input_mode = ASCII, /* input kanji mode */
- shift_mode = FALSE; /* TRUE shift out, or X0201 */
-static int mime_mode = FALSE; /* MIME mode B base64, Q hex */
-
-/* X0201 / X0208 conversion tables */
-
-/* X0201 kana conversion table */
-/* 90-9F A0-DF */
-unsigned char cv[]= {
-0x21,0x21,0x21,0x23,0x21,0x56,0x21,0x57,
-0x21,0x22,0x21,0x26,0x25,0x72,0x25,0x21,
-0x25,0x23,0x25,0x25,0x25,0x27,0x25,0x29,
-0x25,0x63,0x25,0x65,0x25,0x67,0x25,0x43,
-0x21,0x3c,0x25,0x22,0x25,0x24,0x25,0x26,
-0x25,0x28,0x25,0x2a,0x25,0x2b,0x25,0x2d,
-0x25,0x2f,0x25,0x31,0x25,0x33,0x25,0x35,
-0x25,0x37,0x25,0x39,0x25,0x3b,0x25,0x3d,
-0x25,0x3f,0x25,0x41,0x25,0x44,0x25,0x46,
-0x25,0x48,0x25,0x4a,0x25,0x4b,0x25,0x4c,
-0x25,0x4d,0x25,0x4e,0x25,0x4f,0x25,0x52,
-0x25,0x55,0x25,0x58,0x25,0x5b,0x25,0x5e,
-0x25,0x5f,0x25,0x60,0x25,0x61,0x25,0x62,
-0x25,0x64,0x25,0x66,0x25,0x68,0x25,0x69,
-0x25,0x6a,0x25,0x6b,0x25,0x6c,0x25,0x6d,
-0x25,0x6f,0x25,0x73,0x21,0x2b,0x21,0x2c,
-0x00,0x00};
-
-
-/* X0201 kana conversion table for daguten */
-/* 90-9F A0-DF */
-unsigned char dv[]= {
-0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
-0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
-0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
-0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
-0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
-0x00,0x00,0x00,0x00,0x25,0x2c,0x25,0x2e,
-0x25,0x30,0x25,0x32,0x25,0x34,0x25,0x36,
-0x25,0x38,0x25,0x3a,0x25,0x3c,0x25,0x3e,
-0x25,0x40,0x25,0x42,0x25,0x45,0x25,0x47,
-0x25,0x49,0x00,0x00,0x00,0x00,0x00,0x00,
-0x00,0x00,0x00,0x00,0x25,0x50,0x25,0x53,
-0x25,0x56,0x25,0x59,0x25,0x5c,0x00,0x00,
-0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
-0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
-0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
-0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
-0x00,0x00};
-
-/* X0201 kana conversion table for han-daguten */
-/* 90-9F A0-DF */
-unsigned char ev[]= {
-0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
-0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
-0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
-0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
-0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
-0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
-0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
-0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
-0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
-0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
-0x00,0x00,0x00,0x00,0x25,0x51,0x25,0x54,
-0x25,0x57,0x25,0x5a,0x25,0x5d,0x00,0x00,
-0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
-0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
-0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
-0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
-0x00,0x00};
-
-
-/* X0208 kigou conversion table */
-/* 0x8140 - 0x819e */
-unsigned char fv[] = {
-
-0x00,0x00,0x00,0x00,0x2c,0x2e,0x00,0x3a,
-0x3b,0x3f,0x21,0x00,0x00,0x27,0x60,0x00,
-0x5e,0x00,0x5f,0x00,0x00,0x00,0x00,0x00,
-0x00,0x00,0x00,0x00,0x00,0x2d,0x00,0x2f,
-0x5c,0x00,0x00,0x7c,0x00,0x00,0x60,0x27,
-0x22,0x22,0x28,0x29,0x00,0x00,0x5b,0x5d,
-0x7b,0x7d,0x3c,0x3e,0x00,0x00,0x00,0x00,
-0x00,0x00,0x00,0x00,0x2b,0x2d,0x00,0x00,
-0x00,0x3d,0x00,0x3c,0x3e,0x00,0x00,0x00,
-0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
-0x24,0x00,0x00,0x25,0x23,0x26,0x2a,0x40,
-0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
-} ;
-
-
-static int file_out = FALSE;
-static int add_cr = FALSE;
-static int del_cr = FALSE;
-
-#ifndef PERL_XS
-int
-main(argc, argv)
- int argc;
- char **argv;
-{
- FILE *fin;
- char *cp;
-
-#ifdef EASYWIN /*Easy Win */
- _BufferSize.y = 400;/*Set Scroll Buffer Size*/
-#endif
-
- for (argc--,argv++; (argc > 0) && **argv == '-'; argc--, argv++) {
- cp = *argv;
- arguments(cp);
- }
-
- if(iso8859_f && (oconv != j_oconv || !x0201_f )) {
- fprintf(stderr,"Mixed ISO8859/JISX0201/SJIS/EUC output is not allowed.\n");
- exit(1);
- }
-
- if(binmode_f == TRUE)
-#ifdef __OS2__
- if(freopen("","wb",stdout) == NULL)
- return (-1);
-#else
- setbinmode(stdout);
-#endif
-
- if(unbuf_f)
- setbuf(stdout, (char *) NULL);
- else
- setvbuffer(stdout, stdobuf, IOBUF_SIZE);
-
- if(argc == 0) {
- if(binmode_f == TRUE)
-#ifdef __OS2__
- if(freopen("","rb",stdin) == NULL) return (-1);
-#else
- setbinmode(stdin);
-#endif
- setvbuffer(stdin, stdibuf, IOBUF_SIZE);
- if(nop_f)
- noconvert(stdin);
- else
- kanji_convert(stdin);
- } else {
- while (argc--) {
- if((fin = fopen(*argv++, "r")) == NULL) {
- perror(*--argv);
- return(-1);
- } else {
-/* reopen file for stdout */
- if(file_out == TRUE){
- if(argc == 1 ) {
- if(freopen(*argv++, "w", stdout) == NULL) {
- perror(*--argv);
- return (-1);
- }
- argc--;
- } else {
- if(freopen("nkf.out", "w", stdout) == NULL) {
- perror(*--argv);
- return (-1);
- }
- }
- if(binmode_f == TRUE) {
-#ifdef __OS2__
- if(freopen("","wb",stdout) == NULL)
- return (-1);
-#else
- setbinmode(stdout);
-#endif
- }
- }
- if(binmode_f == TRUE)
-#ifdef __OS2__
- if(freopen("","rb",fin) == NULL)
- return (-1);
-#else
- setbinmode(fin);
-#endif
- setvbuffer(fin, stdibuf, IOBUF_SIZE);
- if(nop_f)
- noconvert(fin);
- else
- kanji_convert(fin);
- fclose(fin);
- }
- }
- }
-#ifdef EASYWIN /*Easy Win */
- if(file_out == FALSE)
- scanf("%d",&end_check);
- else
- fclose(stdout);
-#else /* for Other OS */
- if(file_out == TRUE)
- fclose(stdout);
-#endif
- return (0);
-}
-#endif
-
-static void
-arguments(cp)
- char *cp;
-{
- while (*cp) {
- switch (*cp++) {
- case 'b': /* buffered mode */
- unbuf_f = FALSE;
- continue;
- case 'u': /* non bufferd mode */
- unbuf_f = TRUE;
- continue;
- case 't': /* transparent mode */
- nop_f = TRUE;
- continue;
- case 'j': /* JIS output */
- case 'n':
- oconv = j_oconv;
- continue;
- case 'e': /* AT&T EUC output */
- oconv = e_oconv;
- continue;
- case 's': /* SJIS output */
- oconv = s_oconv;
- continue;
- case 'l': /* ISO8859 Latin-1 support, no conversion */
- iso8859_f = TRUE; /* Only compatible with ISO-2022-JP */
- input_f = LATIN1_INPUT;
- continue;
- case 'i': /* Kanji IN ESC-$-@/B */
- if(*cp=='@'||*cp=='B')
- kanji_intro = *cp++;
- continue;
- case 'o': /* ASCII IN ESC-(-J/B */
- if(*cp=='J'||*cp=='B'||*cp=='H')
- ascii_intro = *cp++;
- continue;
- case 'r':
- rot_f = TRUE;
- continue;
-#if defined(MSDOS) || defined(__OS2__)
- case 'T':
- binmode_f = FALSE;
- continue;
-#endif
-#ifndef PERL_XS
- case 'v':
- usage();
- exit(1);
- break;
-#endif
- /* Input code assumption */
- case 'J': /* JIS input */
- case 'E': /* AT&T EUC input */
- input_f = JIS_INPUT;
- continue;
- case 'S': /* MS Kanji input */
- input_f = SJIS_INPUT;
- if(x0201_f==NO_X0201) x0201_f=TRUE;
- continue;
- case 'Z': /* Convert X0208 alphabet to asii */
- /* bit:0 Convert X0208
- bit:1 Convert Kankaku to one space
- bit:2 Convert Kankaku to two spaces
- */
- if('9'>= *cp && *cp>='0')
- alpha_f |= 1<<(*cp++ -'0');
- else
- alpha_f |= TRUE;
- continue;
- case 'x': /* Convert X0201 kana to X0208 or X0201 Conversion */
- x0201_f = FALSE; /* No X0201->X0208 conversion */
- /* accept X0201
- ESC-(-I in JIS, EUC, MS Kanji
- SI/SO in JIS, EUC, MS Kanji
- SSO in EUC, JIS, not in MS Kanji
- MS Kanji (0xa0-0xdf)
- output X0201
- ESC-(-I in JIS (0x20-0x5f)
- SSO in EUC (0xa0-0xdf)
- 0xa0-0xd in MS Kanji (0xa0-0xdf)
- */
- continue;
- case 'X': /* Assume X0201 kana */
- /* Default value is NO_X0201 for EUC/MS-Kanji mix */
- x0201_f = TRUE;
- continue;
- case 'f': /* folding -f60 or -f */
- fold_f = TRUE;
- fold_len = atoi(cp);
- if(!(0<fold_len && fold_len<BUFSIZ))
- fold_len = DEFAULT_FOLD;
- while('0'<= *cp && *cp <='9') cp++;
- continue;
- case 'm': /* MIME support */
- mime_f = TRUE;
- if(*cp=='B'||*cp=='Q') {
- mime_mode = *cp++;
- mimebuf_f = FIXED_MIME;
- } else if (*cp=='0') {
- mime_f = FALSE;
- }
- continue;
- case 'M': /* MIME output */
- oconv = j_oconv; /* sorry... not yet done.. */
- continue;
- case 'B': /* Broken JIS support */
- /* bit:0 no ESC JIS
- bit:1 allow any x on ESC-(-x or ESC-$-x
- bit:2 reset to ascii on NL
- */
- if('9'>= *cp && *cp>='0')
- broken_f |= 1<<(*cp++ -'0');
- else
- broken_f |= TRUE;
- continue;
-#ifndef PERL_XS
- case 'O':/* for Output file */
- file_out = TRUE;
- continue;
-#endif
- case 'c':/* add cr code */
- add_cr = TRUE;
- continue;
- case 'd':/* delete cr code */
- del_cr = TRUE;
- continue;
- default:
- /* bogus option but ignored */
- continue;
- }
- }
-}
-
-#ifndef PERL_XS
-static void
-noconvert(f)
- FILE *f;
-{
- int c;
-
- while ((c = getc(f)) != EOF)
- putchar(c);
-}
-#endif
-
-
-static void
-kanji_convert(f)
- FILE *f;
-{
- int c1, c2;
-
- c2 = 0;
-
- if(input_f == JIS_INPUT || input_f == LATIN1_INPUT) {
- estab_f = TRUE; iconv = oconv;
- } else if(input_f == SJIS_INPUT) {
- estab_f = TRUE; iconv = s_iconv;
- } else {
- estab_f = FALSE; iconv = oconv;
- }
- input_mode = ASCII;
- output_mode = ASCII;
- shift_mode = FALSE;
-
-#define NEXT continue /* no output, get next */
-#define SEND ; /* output c1 and c2, get next */
-#define LAST break /* end of loop, go closing */
-
- while ((c1 = GETC(f)) != EOF) {
- if(c2) {
- /* second byte */
- if(c2 > DEL) {
- /* in case of 8th bit is on */
- if(!estab_f) {
- /* in case of not established yet */
- if(c1 > SSP) {
- /* It is still ambiguious */
- h_conv(f, c2, c1);
- c2 = 0;
- NEXT;
- } else if(c1 < AT) {
- /* ignore bogus code */
- c2 = 0;
- NEXT;
- } else {
- /* established */
- /* it seems to be MS Kanji */
- estab_f = TRUE;
- iconv = s_iconv;
- SEND;
- }
- } else
- /* in case of already established */
- if(c1 < AT) {
- /* ignore bogus code */
- c2 = 0;
- NEXT;
- } else
- SEND;
- } else
- /* 7 bit code */
- /* it might be kanji shitfted */
- if((c1 == DEL) || (c1 <= SPACE)) {
- /* ignore bogus first code */
- c2 = 0;
- NEXT;
- } else
- SEND;
- } else {
- /* first byte */
- if(c1 > DEL) {
- /* 8 bit code */
- if(!estab_f && !iso8859_f) {
- /* not established yet */
- if(c1 < SSP) {
- /* it seems to be MS Kanji */
- estab_f = TRUE;
- iconv = s_iconv;
- } else if(c1 < 0xe0) {
- /* it seems to be EUC */
- estab_f = TRUE;
- iconv = oconv;
- } else {
- /* still ambiguious */
- }
- c2 = c1;
- NEXT;
- } else { /* estab_f==TRUE */
- if(iso8859_f) {
- SEND;
- } else if(SSP<=c1 && c1<0xe0 && iconv == s_iconv) {
- /* SJIS X0201 Case... */
- /* This is too arrogant, but ... */
- if(x0201_f==NO_X0201) {
- iconv = oconv;
- c2 = c1;
- NEXT;
- } else
- if(x0201_f) {
- if(dv[(c1-SSP)*2]||ev[(c1-SSP)*2]) {
- /* look ahead for X0201/X0208conversion */
- if((c2 = GETC(f)) == EOF) {
- (*oconv)(cv[(c1-SSP)*2],cv[(c1-SSP)*2+1]);
- LAST;
- } else if(c2==(0xde)) { /* $BByE@(B */
- (*oconv)(dv[(c1-SSP)*2],dv[(c1-SSP)*2+1]);
- c2=0;
- NEXT;
- } else if(c2==(0xdf)&&ev[(c1-SSP)*2]) {
- /* $BH>ByE@(B */
- (*oconv)(ev[(c1-SSP)*2],ev[(c1-SSP)*2+1]);
- c2=0;
- NEXT;
- }
- UNGETC(c2,f); c2 = 0;
- }
- (*oconv)(cv[(c1-SSP)*2],cv[(c1-SSP)*2+1]);
- NEXT;
- } else
- SEND;
- } else if(c1==SSO && iconv != s_iconv) {
- /* EUC X0201 Case */
- /* This is too arrogant
- if(x0201_f == NO_X0201) {
- estab_f = FALSE;
- c2 = 0;
- NEXT;
- } */
- c1 = GETC(f); /* skip SSO */
- euc_1byte_check:
- if(x0201_f && SSP<=c1 && c1<0xe0) {
- if(dv[(c1-SSP)*2]||ev[(c1-SSP)*2]) {
- if((c2 = GETC(f)) == EOF) {
- (*oconv)(cv[(c1-SSP)*2],cv[(c1-SSP)*2+1]);
- LAST;
- }
- /* forward lookup $BByE@(B/$BH>ByE@(B */
- if(c2 != SSO) {
- UNGETC(c2,f); c2 = 0;
- (*oconv)(cv[(c1-SSP)*2],cv[(c1-SSP)*2+1]);
- NEXT;
- } else if((c2 = GETC(f)) == EOF) {
- (*oconv)(cv[(c1-SSP)*2],cv[(c1-SSP)*2+1]);
- (*oconv)(0,SSO);
- LAST;
- } else if(c2==(0xde)) { /* $BByE@(B */
- (*oconv)(dv[(c1-SSP)*2],dv[(c1-SSP)*2+1]);
- c2=0;
- NEXT;
- } else if(c2==(0xdf)&&ev[(c1-SSP)*2]) {
- /* $BH>ByE@(B */
- (*oconv)(ev[(c1-SSP)*2],ev[(c1-SSP)*2+1]);
- c2=0;
- NEXT;
- } else {
- (*oconv)(cv[(c1-SSP)*2],cv[(c1-SSP)*2+1]);
- /* we have to check this c2 */
- /* and no way to push back SSO */
- c1 = c2; c2 = 0;
- goto euc_1byte_check;
- }
- }
- (*oconv)(cv[(c1-SSP)*2],cv[(c1-SSP)*2+1]);
- NEXT;
- } else
- SEND;
- } else if(c1 < SSP && iconv != s_iconv) {
- /* strange code in EUC */
- iconv = s_iconv; /* try SJIS */
- c2 = c1;
- NEXT;
- } else {
- /* already established */
- c2 = c1;
- NEXT;
- }
- }
- } else if((c1 > SPACE) && (c1 != DEL)) {
- /* in case of Roman characters */
- if(shift_mode) {
- c1 |= 0x80;
- /* output 1 shifted byte */
- if(x0201_f && (!iso8859_f||input_mode==X0201) &&
- SSP<=c1 && c1<0xe0 ) {
- if(dv[(c1-SSP)*2]||ev[(c1-SSP)*2]) {
- if((c2 = GETC(f)) == EOF) {
- (*oconv)(cv[(c1-SSP)*2],cv[(c1-SSP)*2+1]);
- LAST;
- } else if(c2==(0xde&0x7f)) { /* $BByE@(B */
- (*oconv)(dv[(c1-SSP)*2],dv[(c1-SSP)*2+1]);
- c2=0;
- NEXT;
- } else if(c2==(0xdf&0x7f)&&ev[(c1-SSP)*2]) {
- /* $BH>ByE@(B */
- (*oconv)(ev[(c1-SSP)*2],ev[(c1-SSP)*2+1]);
- c2=0;
- NEXT;
- }
- UNGETC(c2,f); c2 = 0;
- }
- (*oconv)(cv[(c1-SSP)*2],cv[(c1-SSP)*2+1]);
- NEXT;
- } else
- SEND;
- } else if(c1 == '(' && broken_f && input_mode == X0208
- && !mime_mode ) {
- /* Try to recover missing escape */
- if((c1 = GETC(f)) == EOF) {
- (*oconv)(0, '(');
- LAST;
- } else {
- if(c1 == 'B' || c1 == 'J' || c1 == 'H') {
- input_mode = ASCII; shift_mode = FALSE;
- NEXT;
- } else {
- (*oconv)(0, '(');
- /* do not modify various input_mode */
- /* It can be vt100 sequence */
- SEND;
- }
- }
- } else if(input_mode == X0208) {
- /* in case of Kanji shifted */
- c2 = c1;
- NEXT;
- /* goto next_byte */
- } else if(c1 == '=' && mime_f && !mime_mode ) {
- if((c1 = getc(f)) == EOF) {
- (*oconv)(0, '=');
- LAST;
- } else if(c1 == '?') {
- /* =? is mime conversiooon start sequence */
- if(mime_begin(f) == EOF) /* check in detail */
- LAST;
- else
- NEXT;
- } else {
- (*oconv)(0, '=');
- ungetc(c1,f);
- NEXT;
- }
- } else if(c1 == '$' && broken_f && !mime_mode) {
- /* try to recover missing escape */
- if((c1 = GETC(f)) == EOF) {
- (*oconv)(0, '$');
- LAST;
- } else if(c1 == '@'|| c1 == 'B') {
- /* in case of Kanji in ESC sequence */
- input_mode = X0208;
- shift_mode = FALSE;
- NEXT;
- } else {
- /* sorry */
- (*oconv)(0, '$');
- (*oconv)(0, c1);
- NEXT;
- }
- } else
- SEND;
- } else if(c1 == SI) {
- shift_mode = FALSE;
- NEXT;
- } else if(c1 == SO) {
- shift_mode = TRUE;
- NEXT;
- } else if(c1 == ESC) {
- if((c1 = GETC(f)) == EOF) {
- (*oconv)(0, ESC);
- LAST;
- } else if(c1 == '$') {
- if((c1 = GETC(f)) == EOF) {
- (*oconv)(0, ESC);
- (*oconv)(0, '$');
- LAST;
- } else if(c1 == '@'|| c1 == 'B') {
- /* This is kanji introduction */
- input_mode = X0208;
- shift_mode = FALSE;
- NEXT;
- } else if(c1 == '(') {
- if((c1 = GETC(f)) == EOF) {
- (*oconv)(0, ESC);
- (*oconv)(0, '$');
- (*oconv)(0, '(');
- LAST;
- } else if(c1 == '@'|| c1 == 'B') {
- /* This is kanji introduction */
- input_mode = X0208;
- shift_mode = FALSE;
- NEXT;
- } else {
- (*oconv)(0, ESC);
- (*oconv)(0, '$');
- (*oconv)(0, '(');
- (*oconv)(0, c1);
- NEXT;
- }
- } else if(broken_f&0x2) {
- input_mode = X0208;
- shift_mode = FALSE;
- NEXT;
- } else {
- (*oconv)(0, ESC);
- (*oconv)(0, '$');
- (*oconv)(0, c1);
- NEXT;
- }
- } else if(c1 == '(') {
- if((c1 = GETC(f)) == EOF) {
- (*oconv)(0, ESC);
- (*oconv)(0, '(');
- LAST;
- } else {
- if(c1 == 'I') {
- /* This is X0201 kana introduction */
- input_mode = X0201; shift_mode = X0201;
- NEXT;
- } else if(c1 == 'B' || c1 == 'J' || c1 == 'H') {
- /* This is X0208 kanji introduction */
- input_mode = ASCII; shift_mode = FALSE;
- NEXT;
- } else if(broken_f&0x2) {
- input_mode = ASCII; shift_mode = FALSE;
- NEXT;
- } else {
- (*oconv)(0, ESC);
- (*oconv)(0, '(');
- /* maintain various input_mode here */
- SEND;
- }
- }
- } else {
- /* lonely ESC */
- (*oconv)(0, ESC);
- SEND;
- }
- } else if(c1 == NL && broken_f&4) {
- input_mode = ASCII;
- SEND;
- } else
- SEND;
- }
- /* send: */
- if(input_mode == X0208)
- (*oconv)(c2, c1); /* this is JIS, not SJIS/EUC case */
- else
- (*iconv)(c2, c1); /* can be EUC/SJIS */
- c2 = 0;
- continue;
- /* goto next_word */
- }
-
- /* epilogue */
- (*iconv)(EOF, 0);
-}
-
-
-
-
-static void
-h_conv(f, c2, c1)
- FILE *f;
- int c1, c2;
-{
- int wc;
-
-
- /** it must NOT be in the kanji shifte sequence */
- /** it must NOT be written in JIS7 */
- /** and it must be after 2 byte 8bit code */
-
- hold_count = 0;
- push_hold_buf(c2, c1);
- c2 = 0;
-
- while ((c1 = GETC(f)) != EOF) {
- if(c2) {
- /* second byte */
- if(!estab_f) {
- /* not established */
- if(c1 > SSP) {
- /* it is still ambiguious yet */
- SEND;
- } else if(c1 < AT) {
- /* ignore bogus first byte */
- c2 = 0;
- SEND;
- } else {
- /* now established */
- /* it seems to be MS Kanji */
- estab_f = TRUE;
- iconv = s_iconv;
- SEND;
- }
- } else
- SEND;
- } else {
- /* First byte */
- if(c1 > DEL) {
- /* 8th bit is on */
- if(c1 < SSP) {
- /* it seems to be MS Kanji */
- estab_f = TRUE;
- iconv = s_iconv;
- } else if(c1 < 0xe0) {
- /* it seems to be EUC */
- estab_f = TRUE;
- iconv = oconv;
- } else {
- /* still ambiguious */
- }
- c2 = c1;
- NEXT;
- } else
- /* 7 bit code , then send without any process */
- SEND;
- }
- /* send: */
- if((push_hold_buf(c2, c1) == EOF) || estab_f)
- break;
- c2 = 0;
- continue;
- }
-
- /** now,
- ** 1) EOF is detected, or
- ** 2) Code is established, or
- ** 3) Buffer is FULL (but last word is pushed)
- **
- ** in 1) and 3) cases, we continue to use
- ** Kanji codes by oconv and leave estab_f unchanged.
- **/
-
- for (wc = 0; wc < hold_count; wc += 2) {
- c2 = hold_buf[wc];
- c1 = hold_buf[wc+1];
- (*iconv)(c2, c1);
- }
- return;
-}
-
-
-
-static int
-push_hold_buf(c2, c1)
- int c2, c1;
-{
- if(hold_count >= HOLD_SIZE*2)
- return (EOF);
- hold_buf[hold_count++] = c2;
- hold_buf[hold_count++] = c1;
- return ((hold_count >= HOLD_SIZE*2) ? EOF : hold_count);
-}
-
-
-static void
-s_iconv(c2, c1)
- int c2,
- c1;
-{
- if((c2 == EOF) || (c2 == 0)) {
- /* NOP */
- } else {
- c2 = c2 + c2 - ((c2 <= 0x9f) ? SJ0162 : SJ6394);
- if(c1 < 0x9f)
- c1 = c1 - ((c1 > DEL) ? SPACE : 0x1f);
- else {
- c1 = c1 - 0x7e;
- c2++;
- }
- }
- (*oconv)(c2, c1);
-}
-
-
-static void
-e_oconv(c2, c1)
- int c2, c1;
-{
- c2 = pre_convert(c1,c2); c1 = c1_return;
- if(fold_f) {
- switch(line_fold(c2,c1)) {
- case '\n':
- if(add_cr == TRUE) {
- putchar('\r');
- c1 = '\n';
- }
- putchar('\n');
- break;
- case 0: return;
- case '\r':
- c1 = '\n'; c2 = 0;
- break;
- case '\t':
- case ' ':
- c1 = ' '; c2 = 0;
- break;
- }
- }
- if(c2==DOUBLE_SPACE) {
- putchar(' '); putchar(' ');
- return;
- }
- if(c2 == EOF)
- return;
- else if(c2 == 0 && (c1&0x80)) {
- putchar(SSO); putchar(c1);
- } else if(c2 == 0) {
- if(c1 == '\n' && add_cr == TRUE)
- putchar('\r');
- if(c1 != '\r')
- putchar(c1);
- else if(del_cr == FALSE)
- putchar(c1);
- } else {
- if((c1<0x20 || 0x7e<c1) ||
- (c2<0x20 || 0x7e<c2)) {
- estab_f = FALSE;
- return; /* too late to rescue this char */
- }
- putchar(c2 | 0x080);
- putchar(c1 | 0x080);
- }
- return;
-}
-
-
-static void
-s_oconv(c2, c1)
- int c2, c1;
-{
- c2 = pre_convert(c1,c2); c1 = c1_return;
- if(fold_f) {
- switch(line_fold(c2,c1)) {
- case '\n':
- if(add_cr == TRUE) {
- putchar('\r');
- c1 = '\n';
- }
- putchar('\n');
- break;
- case '\r':
- c1 = '\n'; c2 = 0;
- break;
- case 0: return;
- case '\t':
- case ' ':
- c1 = ' '; c2 = 0;
- break;
- }
- }
- if(c2==DOUBLE_SPACE) {
- putchar(' '); putchar(' ');
- return;
- }
- if(c2 == EOF)
- return;
- else if(c2 == 0) {
- if(c1 == '\n' && add_cr == TRUE)
- putchar('\r');
- if(c1 != '\r')
- putchar(c1);
- else if(del_cr == FALSE)
- putchar(c1);
- } else {
- if((c1<0x20 || 0x7e<c1) ||
- (c2<0x20 || 0x7e<c2)) {
- estab_f = FALSE;
- return; /* too late to rescue this char */
- }
- putchar((((c2 - 1) >> 1) + ((c2 <= 0x5e) ? 0x71 : 0xb1)));
- putchar((c1 + ((c2 & 1) ? ((c1 < 0x60) ? 0x1f : 0x20) : 0x7e)));
- }
- return;
-}
-
-
-static void
-j_oconv(c2, c1)
- int c2, c1;
-{
- c2 = pre_convert(c1,c2); c1 = c1_return;
- if(fold_f) {
- switch(line_fold(c2,c1)) {
- case '\n':
- if(output_mode) {
- putchar(ESC);
- putchar('(');
- putchar(ascii_intro);
- }
- if(add_cr == TRUE) {
- putchar('\r');
- c1 = '\n';
- }
- putchar('\n');
- output_mode = ASCII;
- break;
- case '\r':
- c1 = '\n'; c2 = 0;
- break;
- case '\t':
- case ' ':
- c1 = ' '; c2 = 0;
- break;
- case 0: return;
- }
- }
- if(c2 == EOF) {
- if(output_mode) {
- putchar(ESC);
- putchar('(');
- putchar(ascii_intro);
- }
- } else if(c2 == 0 && (c1 & 0x80)) {
- if(input_mode==X0201 || !iso8859_f) {
- if(output_mode!=X0201) {
- putchar(ESC);
- putchar('(');
- putchar('I');
- output_mode = X0201;
- }
- c1 &= 0x7f;
- } else {
- /* iso8859 introduction, or 8th bit on */
- /* Can we convert in 7bit form using ESC-'-'-A ?
- Is this popular? */
- }
- putchar(c1);
- } else if(c2 == 0) {
- if(output_mode) {
- putchar(ESC);
- putchar('(');
- putchar(ascii_intro);
- output_mode = ASCII;
- }
- if(c1 == '\n' && add_cr == TRUE)
- putchar('\r');
- if(c1 != '\r')
- putchar(c1);
- else if(del_cr == FALSE)
- putchar(c1);
- } else if(c2 == DOUBLE_SPACE) {
- if(output_mode) {
- putchar(ESC);
- putchar('(');
- putchar(ascii_intro);
- output_mode = ASCII;
- }
- putchar(' ');
- if(c1 == '\n' && add_cr == TRUE)
- putchar('\r');
- if(c1 != '\r')
- putchar(c1);
- else if(del_cr == FALSE)
- putchar(c1);
- } else {
- if(output_mode != X0208) {
- putchar(ESC);
- putchar('$');
- putchar(kanji_intro);
- output_mode = X0208;
- }
- if(c1<0x20 || 0x7e<c1)
- return;
- if(c2<0x20 || 0x7e<c2)
- return;
- putchar(c2);
- if(c1 == '\n' && add_cr == TRUE)
- putchar('\r');
- if(c1 != '\r')
- putchar(c1);
- else if(del_cr == FALSE)
- putchar(c1);
- }
- return;
-}
-
-
-
-#define rot13(c) ( \
- ( c < 'A' ) ? c: \
- (c <= 'M') ? (c + 13): \
- (c <= 'Z') ? (c - 13): \
- (c < 'a') ? (c): \
- (c <= 'm') ? (c + 13): \
- (c <= 'z') ? (c - 13): \
- (c) \
-)
-
-#define rot47(c) ( \
- ( c < '!' ) ? c: \
- ( c <= 'O' ) ? (c + 47) : \
- ( c <= '~' ) ? (c - 47) : \
- c \
-)
-
-
-/*
- Return value of line_fold()
-
- \n add newline and output char
- \r add newline and output nothing
- ' ' space
- 0 skip
- 1 (or else) normal output
-
- fold state in prev (previous character)
-
- >0x80 Japanese (X0208/X0201)
- <0x80 ASCII
- \n new line
- ' ' space
-
- This fold algorthm does not preserve heading space in a line.
- This is the main difference from fmt.
-*/
-
-static int
-line_fold(c2,c1)
-int c2,c1;
-{
- int prev0;
- if(c1=='\r')
- return 0; /* ignore cr */
- if(c1== 8) {
- if(line>0) line--;
- return 1;
- }
- if(c2==EOF && line != 0) /* close open last line */
- return '\n';
- /* new line */
- if(c1=='\n') {
- if(prev == c1) { /* duplicate newline */
- if(line) {
- line = 0;
- return '\n'; /* output two newline */
- } else {
- line = 0;
- return 1;
- }
- } else {
- if(prev&0x80) { /* Japanese? */
- prev = c1;
- return 0; /* ignore given single newline */
- } else if(prev==' ') {
- return 0;
- } else {
- prev = c1;
- if(++line<=fold_len)
- return ' ';
- else {
- line = 0;
- return '\r'; /* fold and output nothing */
- }
- }
- }
- }
- if(c1=='\f') {
- prev = '\n';
- if(line==0)
- return 1;
- line = 0;
- return '\n'; /* output newline and clear */
- }
- /* X0208 kankaku or ascii space */
- if( (c2==0&&c1==' ')||
- (c2==0&&c1=='\t')||
- (c2==DOUBLE_SPACE)||
- (c2=='!'&& c1=='!')) {
- if(prev == ' ') {
- return 0; /* remove duplicate spaces */
- }
- prev = ' ';
- if(++line<=fold_len)
- return ' '; /* output ASCII space only */
- else {
- prev = ' '; line = 0;
- return '\r'; /* fold and output nothing */
- }
- }
- prev0 = prev; /* we still need this one... , but almost done */
- prev = c1;
- if(c2 || (SSP<=c1 && c1<=0xdf))
- prev |= 0x80; /* this is Japanese */
- line += (c2==0)?1:2;
- if(line<=fold_len) { /* normal case */
- return 1;
- }
- if(line>=fold_len+FOLD_MARGIN) { /* too many kinsou suspension */
- line = (c2==0)?1:2;
- return '\n'; /* We can't wait, do fold now */
- }
- /* simple kinsoku rules return 1 means no folding */
- if(c2==0) {
- if(c1==0xde) return 1; /* $B!+(B*/
- if(c1==0xdf) return 1; /* $B!,(B*/
- if(c1==0xa4) return 1; /* $B!#(B*/
- if(c1==0xa3) return 1; /* $B!$(B*/
- if(c1==0xa1) return 1; /* $B!W(B*/
- if(c1==0xb0) return 1; /* - */
- if(SSP<=c1 && c1<=0xdf) { /* X0201 */
- line = 1;
- return '\n';/* add one new line before this character */
- }
- /* fold point in ASCII { [ ( */
- if(( c1!=')'&&
- c1!=']'&&
- c1!='}'&&
- c1!='.'&&
- c1!=','&&
- c1!='!'&&
- c1!='?'&&
- c1!='/'&&
- c1!=':'&&
- c1!=';')&&
- ((prev0=='\n')|| (prev0==' ')|| /* ignored new line */
- (prev0&0x80)) /* X0208 - ASCII */
- ) {
- line = 1;
- return '\n';/* add one new line before this character */
- }
- return 1; /* default no fold in ASCII */
- } else {
- if(c2=='!') {
- if(c1=='"') return 1; /* $B!"(B */
- if(c1=='#') return 1; /* $B!#(B */
- if(c1=='$') return 1; /* $B!$(B */
- if(c1=='%') return 1; /* $B!%(B */
- if(c1=='\'') return 1; /* $B!\(B */
- if(c1=='(') return 1; /* $B!((B */
- if(c1==')') return 1; /* $B!)(B */
- if(c1=='*') return 1; /* $B!*(B */
- if(c1=='+') return 1; /* $B!+(B */
- if(c1==',') return 1; /* $B!,(B */
- }
- line = 2;
- return '\n'; /* add one new line before this character */
- }
-}
-
-static int
-pre_convert(c1,c2)
- int c1,c2;
-{
- if(c2) c1 &= 0x7f;
- c1_return = c1;
- if(c2==EOF) return c2;
- c2 &= 0x7f;
- if(rot_f) {
- if(c2) {
- c1 = rot47(c1);
- c2 = rot47(c2);
- } else {
- if(!(c1 & 0x80))
- c1 = rot13(c1);
- }
- c1_return = c1;
- }
- /* JISX0208 Alphabet */
- if(alpha_f && c2 == 0x23 ) return 0;
- /* JISX0208 Kigou */
- if(alpha_f && c2 == 0x21 ) {
- if(0x21==c1) {
- if(alpha_f&0x2) {
- c1_return = ' ';
- return 0;
- } else if(alpha_f&0x4) {
- c1_return = ' ';
- return DOUBLE_SPACE;
- } else {
- return c2;
- }
- } else if(0x20<c1 && c1<0x7f && fv[c1-0x20]) {
- c1_return = fv[c1-0x20];
- return 0;
- }
- }
- return c2;
-}
-
-
-#ifdef STRICT_MIME
-/* This converts */
-
-unsigned char *mime_pattern[] = {
- (unsigned char *)"\075?ISO-8859-1?Q?",
- (unsigned char *)"\075?ISO-2022-JP?B?",
- (unsigned char *)"\075?ISO-2022-JP?Q?",
- (unsigned char *)"\075?JAPANESE_EUC?B?",
- (unsigned char *)"\075?SHIFT_JIS?B?",
- NULL
-};
-
-int mime_encode[] = {
- 'Q', 'B', 'Q',
- 0
-};
-#endif
-
-#define MAXRECOVER 20
-int iso8859_f_save;
-
-#ifdef STRICT_MIME
-
-#define nkf_toupper(c) (('a'<=c && c<='z')?(c-('a'-'A')):c)
-/* I don't trust portablity of toupper */
-
-static int
-mime_begin(f)
- FILE *f;
-{
- int c1;
- int i,j,k;
- unsigned char *p,*q;
- int r[MAXRECOVER]; /* recovery buffer, max mime pattern lenght */
-
- mime_mode = FALSE;
- /* =? has been checked */
- j = 0;
- p = mime_pattern[j];
- r[0]='='; r[1]='?';
-
- for(i=2;p[i]>' ';i++) { /* start at =? */
- if( ((((r[i] = c1 = getc(f))==EOF) || nkf_toupper(c1) != p[i] ) {
- /* pattern fails, try next one */
- q = p;
- while (p = mime_pattern[++j]) {
- for(k=2;k<i;k++) /* assume length(p) > i */
- if(p[k]!=q[k]) break;
- if(k==i && nkf_toupper(c1)==p[k]) break;
- }
- if(p) continue; /* found next one, continue */
- /* all fails, output from recovery buffer */
- ungetc(c1,f);
- for(j=0;j<i;j++) {
- (*oconv)(0,r[j]);
- }
- return c1;
- }
- }
- mime_mode = mime_encode[j];
- iso8859_f_save = iso8859_f;
- if(j==0) {
- iso8859_f = TRUE;
- }
- if(mime_mode=='B') {
- mimebuf_f = unbuf_f;
- if(!unbuf_f) {
- /* do MIME integrity check */
- return mime_integrity(f,mime_pattern[j]);
- }
- }
- mimebuf_f = TRUE;
- return c1;
-}
-
-#define mime_getc0(f) (mimebuf_f?getc(f):Fifo(mime_input++))
-#define mime_ungetc0(c,f) (mimebuf_f?ungetc(c,f):mime_input--)
-
-#else
-static int
-mime_begin(f)
-FILE *f;
-{
- int c1;
- int i,j;
- int r[MAXRECOVER]; /* recovery buffer, max mime pattern lenght */
-
- mime_mode = FALSE;
- /* =? has been checked */
- j = 0;
- r[0]='='; r[1]='?';
- for(i=2;i<MAXRECOVER;i++) { /* start at =? */
- /* We accept any charcter type even if it is breaked by new lines */
- if( (r[i] = c1 = getc(f))==EOF) break;
- if(c1=='=') break;
- if(c1<' '&& c1!='\r' && c1!='\n') break;
- if(c1=='?') {
- i++;
- if(!(i<MAXRECOVER) || (r[i] = c1 = getc(f))==EOF) break;
- if(c1=='b'||c1=='B') {
- mime_mode = 'B';
- } else if(c1=='q'||c1=='Q') {
- mime_mode = 'Q';
- } else {
- break;
- }
- i++;
- if(!(i<MAXRECOVER) || (r[i] = c1 = getc(f))==EOF) break;
- if(c1=='?') {
- break;
- } else {
- mime_mode = FALSE;
- }
- break;
- }
- }
- if(!mime_mode || c1==EOF || i==MAXRECOVER) {
- ungetc(c1,f);
- if (i == MAXRECOVER)
- i--;
- for(j=0;j<i;j++) {
- (*oconv)(0,r[j]);
- }
- return c1;
- }
- iso8859_f_save = iso8859_f;
- /* do no MIME integrity check */
- return c1; /* used only for checking EOF */
-}
-
-#define mime_getc0(f) getc(f)
-#define mime_ungetc0(c,f) ungetc(c,f)
-
-#endif
-
-static int
-mime_getc(f)
- FILE *f;
-{
- int c1, c2, c3, c4, cc;
- int t1, t2, t3, t4, mode, exit_mode;
-
- if(mime_top != mime_last) { /* Something is in FIFO */
- return Fifo(mime_top++);
- }
-
- if(mimebuf_f == FIXED_MIME)
- exit_mode = mime_mode;
- else
- exit_mode = FALSE;
- if(mime_mode == 'Q') {
- if((c1 = mime_getc0(f)) == EOF) return (EOF);
- if(c1=='_') return ' ';
- if(c1!='=' && c1!='?')
- return c1;
- mime_mode = exit_mode; /* prepare for quit */
- if(c1<=' ') return c1;
- if((c2 = mime_getc0(f)) == EOF) return (EOF);
- if(c2<=' ') return c2;
- if(c1=='?'&&c2=='=') {
- /* end Q encoding */
- input_mode = exit_mode;
- iso8859_f = iso8859_f_save;
- return getc(f);
- }
- if(c1=='?') {
- mime_mode = 'Q'; /* still in MIME */
- mime_ungetc0(c2,f);
- return c1;
- }
- if((c3 = mime_getc0(f)) == EOF) return (EOF);
- if(c2<=' ') return c2;
- mime_mode = 'Q'; /* still in MIME */
-#define hex(c) (('0'<=c&&c<='9')?(c-'0'):\
- ('A'<=c&&c<='F')?(c-'A'+10):('a'<=c&&c<='f')?(c-'a'+10):0)
- return ((hex(c2)<<4) + hex(c3));
- }
-
- if(mime_mode != 'B') {
- mime_mode = FALSE;
- return getc(f);
- }
-
-
- /* Base64 encoding */
- /*
- MIME allows line break in the middle of
- Base64, but we are very pessimistic in decoding
- in unbuf mode because MIME encoded code may broken by
- less or editor's control sequence (such as ESC-[-K in unbuffered
- mode. ignore incomplete MIME.
- */
- mode = mime_mode;
- mime_mode = exit_mode; /* prepare for quit */
-
- while ((c1 = mime_getc0(f))<=' ') {
- if(c1==EOF)
- return (EOF);
- }
- if((c2 = mime_getc0(f))<=' ') {
- if(c2==EOF)
- return (EOF);
- if(mimebuf_f!=FIXED_MIME) input_mode = ASCII;
- return c2;
- }
- if((c1 == '?') && (c2 == '=')) {
- input_mode = ASCII;
- while((c1 = getc(f))==' ' /* || c1=='\n' || c1=='\r' */);
- return c1;
- }
- if((c3 = mime_getc0(f))<=' ') {
- if(c3==EOF)
- return (EOF);
- if(mimebuf_f!=FIXED_MIME) input_mode = ASCII;
- return c3;
- }
- if((c4 = mime_getc0(f))<=' ') {
- if(c4==EOF)
- return (EOF);
- if(mimebuf_f!=FIXED_MIME) input_mode = ASCII;
- return c4;
- }
-
- mime_mode = mode; /* still in MIME sigh... */
-
- /* BASE 64 decoding */
-
- t1 = 0x3f & base64decode(c1);
- t2 = 0x3f & base64decode(c2);
- t3 = 0x3f & base64decode(c3);
- t4 = 0x3f & base64decode(c4);
- cc = ((t1 << 2) & 0x0fc) | ((t2 >> 4) & 0x03);
- if(c2 != '=') {
- Fifo(mime_last++) = cc;
- cc = ((t2 << 4) & 0x0f0) | ((t3 >> 2) & 0x0f);
- if(c3 != '=') {
- Fifo(mime_last++) = cc;
- cc = ((t3 << 6) & 0x0c0) | (t4 & 0x3f);
- if(c4 != '=')
- Fifo(mime_last++) = cc;
- }
- } else {
- return c1;
- }
- return Fifo(mime_top++);
-}
-
-static int
-mime_ungetc(c)
- unsigned int c;
-{
- Fifo(mime_last++) = c;
- return c;
-}
-
-#ifdef STRICT_MIME
-int
-mime_integrity(f,p)
- FILE *f;
- unsigned char *p;
-{
- int c,d;
- unsigned int q;
- /* In buffered mode, read until =? or NL or buffer fffull
- */
- mime_input = mime_top;
- mime_last = mime_top;
- while(*p) Fifo(mime_input++) = *p++;
- d = 0;
- q = mime_input;
- while((c=getc(f))!=EOF) {
- if(((mime_input-mime_top)&MIME_BUF_MASK)==0) break;
- if(c=='=' && d=='?') {
- /* checked. skip header, start decode */
- Fifo(mime_input++) = c;
- mime_input = q;
- return 1;
- }
- if(!( (c=='+'||c=='/'|| c=='=' || c=='?' ||
- ('a'<=c && c<='z')||('A'<= c && c<='Z')||('0'<=c && c<='9'))))
- break;
- /* Should we check length mod 4? */
- Fifo(mime_input++) = c;
- d=c;
- }
- /* In case of Incomplete MIME, no MIME decode */
- Fifo(mime_input++) = c;
- mime_last = mime_input; /* point undecoded buffer */
- mime_mode = 1; /* no decode on Fifo last in mime_getc */
- return 1;
-}
-#endif
-
-static int
-base64decode(c)
- int c;
-{
- int i;
- if(c > '@')
- if(c < '[')
- i = c - 'A'; /* A..Z 0-25 */
- else
- i = c - 'G' /* - 'a' + 26 */ ; /* a..z 26-51 */
- else if(c > '/')
- i = c - '0' + '4' /* - '0' + 52 */ ; /* 0..9 52-61 */
- else if(c == '+')
- i = '>' /* 62 */ ; /* + 62 */
- else
- i = '?' /* 63 */ ; /* / 63 */
- return (i);
-}
-
-static void
-reinit()
-{
- unbuf_f = FALSE;
- estab_f = FALSE;
- nop_f = FALSE;
- binmode_f = TRUE;
- rot_f = FALSE;
- input_f = FALSE;
- alpha_f = FALSE;
- mime_f = TRUE;
- mimebuf_f = FALSE;
- broken_f = FALSE;
- iso8859_f = FALSE;
- x0201_f = TRUE;
- x0201_f = NO_X0201;
- fold_f = FALSE;
- kanji_intro = DEFAULT_J;
- ascii_intro = DEFAULT_R;
- oconv = DEFAULT_CONV;
- output_mode = ASCII;
- input_mode = ASCII;
- shift_mode = FALSE;
- mime_mode = FALSE;
- file_out = FALSE;
- add_cr = FALSE;
- del_cr = FALSE;
- line = 0;
-}
-
-#ifndef PERL_XS
-int
-usage()
-{
- fprintf(stderr,"USAGE: nkf(nkf32,wnkf,nkf2) -[flags] [in file] .. [out file for -O flag]\n");
- fprintf(stderr,"Flags:\n");
- fprintf(stderr,"b,u Output is bufferred (DEFAULT),Output is unbufferred\n");
-#ifdef DEFAULT_CODE_SJIS
- fprintf(stderr,"j,s,e Outout code is JIS 7 bit, Shift JIS (DEFAULT), AT&T JIS (EUC)\n");
-#endif
-#ifdef DEFAULT_CODE_JIS
- fprintf(stderr,"j,s,e Outout code is JIS 7 bit (DEFAULT), Shift JIS, AT&T JIS (EUC)\n");
-#endif
-#ifdef DEFAULT_CODE_EUC
- fprintf(stderr,"j,s,e Outout code is JIS 7 bit, Shift JIS, AT&T JIS (EUC) (DEFAULT)\n");
-#endif
- fprintf(stderr,"J,S,E Input assumption is JIS 7 bit , Shift JIS, AT&T JIS (EUC)\n");
- fprintf(stderr,"t no conversion\n");
- fprintf(stderr,"i_ Output sequence to designate JIS-kanji (DEFAULT B)\n");
- fprintf(stderr,"o_ Output sequence to designate ASCII (DEFAULT B)\n");
- fprintf(stderr,"r {de/en}crypt ROT13/47\n");
- fprintf(stderr,"v Show this usage\n");
- fprintf(stderr,"m[BQ0] MIME decode [B:base64,Q:quoted,0:no decode]\n");
- fprintf(stderr,"l ISO8859-1 (Latin-1) support\n");
- fprintf(stderr,"f Folding: -f60 or -f\n");
- fprintf(stderr,"Z[0-2] Convert X0208 alphabet to ASCII 1: Kankaku to space,2: 2 spaces\n");
- fprintf(stderr,"X,x Assume X0201 kana in MS-Kanji, -x preserves X0201\n");
- fprintf(stderr,"B[0-2] Broken input 0: missing ESC,1: any X on ESC-[($]-X,2: ASCII on NL\n");
-#ifdef MSDOS
- fprintf(stderr,"T Text mode output\n");
-#endif
- fprintf(stderr,"O Output to File (DEFAULT 'nkf.out')\n");
- fprintf(stderr,"d,c Delete \\r in line feed, Add \\r in line feed\n");
- fprintf(stderr,"Network Kanji Filter Version %s (%s) "
-#if defined(MSDOS) && !defined(_Windows)
- "for DOS"
-#endif
-#if !defined(__WIN32__) && defined(_Windows)
- "for Win16"
-#endif
-#if defined(__WIN32__) && defined(_Windows)
- "for Win32"
-#endif
-#ifdef __OS2__
- "for OS/2"
-#endif
- ,Version,Patchlevel);
- fprintf(stderr,"\n%s\n",CopyRight);
- return 0;
-}
-#endif
-
-/**
- ** $B%Q%C%A@):n<T(B
- ** void@merope.pleiades.or.jp (Kusakabe Youichi)
- ** NIDE Naoyuki <nide@ics.nara-wu.ac.jp>
- ** ohta@src.ricoh.co.jp (Junn Ohta)
- ** inouet@strl.nhk.or.jp (Tomoyuki Inoue)
- ** kiri@pulser.win.or.jp (Tetsuaki Kiriyama)
- ** Kimihiko Sato <sato@sail.t.u-tokyo.ac.jp>
- ** a_kuroe@kuroe.aoba.yokohama.jp (Akihiko Kuroe)
- ** kono@ie.u-ryukyu.ac.jp (Shinji Kono)
- ** GHG00637@nifty-serve.or.jp (COW)
- **
- ** $B:G=*99?7F|(B
- ** 1998.11.7
- **/
-
-/* end */
diff --git a/ext/nkf/test.rb b/ext/nkf/test.rb
deleted file mode 100644
index 4519f8ba7e..0000000000
--- a/ext/nkf/test.rb
+++ /dev/null
@@ -1,318 +0,0 @@
-$counter = 0
-def result(result, message = nil)
- $counter += 1
- printf("%s %d%s\n",
- result ? 'ok' : 'no',
- $counter,
- message ? ' ... ' + message : '')
-end
-
-begin
- require 'nkf'
- include NKF
-rescue LoadError
- result(false)
-end
-result(true)
-
-if nkf('-me', '1')
- result(true);
-else
- result(false);
-end
-
-output = nkf('-e', "\033\$@#1#3#2%B")
-if output
- # print output, "\n"
- result(true, output)
-else
- result(false)
-end
-
-output = nkf('-Zj', "\033\$@#1#3#2%B")
-if output
- # print output, "\n"
- result(true, output)
-else
- result(false)
-end
-
-output = "\244\306 " * 1024
-old = output.length
-output = nkf("-j", output)
-if output
- # print output, "\n"
- result(true, "#{old} #{output.length}")
-else
- result(false)
-end
-
-
-$detail = false
-def test(opt, input, expect)
- print "\nINPUT:\n", input if $detail
- print "\nEXPECT:\n", expect if $detail
- result = nkf(opt, input)
- print "\nGOT:\n", result if $detail
-
- print result == expect ? "Ok\n" : "Fail\n"
- return result
-end
-
-# Basic Conversion
-print "\nBasic Conversion test\n\n"
-
-example = {}
-example['jis'] = <<'eofeof'.unpack('u')[0]
-M1FER<W0@4W1A9V4@&R1"(3DQ(3%^2R%+?D]3&RA"(%-E8V]N9"!3=&%G92`;
-M)$)0)TU:&RA"($AI<F%G86YA(!LD0B0B)"0D)B0H)"HD;R1R)',;*$(*2V%T
-M86MA;F$@&R1")2(E)"4F)2@E*B5O)7(E<QLH0B!+:6=O=2`;)$(A)B%G(S`C
-/029!)E@G(B=!*$`;*$(*
-eofeof
-#'
-
-example['sjis'] = <<'eofeof'.unpack('u')[0]
-M1FER<W0@4W1A9V4@@5B)0(F>ED"6GIAR(%-E8V]N9"!3=&%G92"8I9=Y($AI
-M<F%G86YA((*@@J*"I(*F@JB"[8+P@O$*2V%T86MA;F$@@T&#0X-%@T>#28./
->@Y*#DR!+:6=O=2"!18&'@D^"8(._@]:$081@A+X*
-eofeof
-#'
-
-example['euc'] = <<'eofeof'.unpack('u')[0]
-M1FER<W0@4W1A9V4@H;FQH;'^RZ'+_L_3(%-E8V]N9"!3=&%G92#0I\W:($AI
-M<F%G86YA(*2BI*2DIJ2HI*JD[Z3RI/,*2V%T86MA;F$@I:*EI*6FI:BEJJ7O
->I?*E\R!+:6=O=2"AIJ'GH["CP:;!IMBGHJ?!J,`*
-eofeof
-#'
-
-example['amb'] = <<'eofeof'.unpack('u')[0]
-MI<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"QI<*PL:7"L+&E
-MPK"QI<*PL:7"L+&EPK"QI<(*I<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"QI<*P
-ML:7"L+&EPK"QI<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"QI<(*I<*PL:7"L+&E
-MPK"QI<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"QI<*PL:7"
-ML+&EPK"QI<(*I<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"Q
-MI<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"QI<(*I<*PL:7"L+&EPK"QI<*PL:7"
-ML+&EPK"QI<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"QI<(*
-eofeof
-
-example['amb.euc'] = <<'eofeof'.unpack('u')[0]
-M&R1")4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25"
-M,#$E0C`Q)4(P,25",#$E0C`Q)4(;*$(*&R1")4(P,25",#$E0C`Q)4(P,25"
-M,#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(;
-M*$(*&R1")4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P
-M,25",#$E0C`Q)4(P,25",#$E0C`Q)4(;*$(*&R1")4(P,25",#$E0C`Q)4(P
-M,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q
-M)4(;*$(*&R1")4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q
->)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(;*$(*
-eofeof
-
-example['amb.sjis'] = <<'eofeof'.unpack('u')[0]
-M&RA))4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25"
-M,#$E0C`Q)4(P,25",#$E0C`Q)4(;*$(*&RA))4(P,25",#$E0C`Q)4(P,25"
-M,#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(;
-M*$(*&RA))4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P
-M,25",#$E0C`Q)4(P,25",#$E0C`Q)4(;*$(*&RA))4(P,25",#$E0C`Q)4(P
-M,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q
-M)4(;*$(*&RA))4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q
->)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(;*$(*
-eofeof
-
-example['x0201.sjis'] = <<'eofeof'.unpack('u')[0]
-MD5.*<(-*@TR#3H-0@U*#2X--@T^#48-3"I%3B7""8()A@F*"8X)D@F6"9H*!
-M@H*"@X*$@H6"AH*'"I%3BTR-AH%)@9>!E(&0@9.!3X&5@9:!:8%J@7R!>X&!
-M@6V!;H%O@7"!CPJ4O(IPMK>X/;FZMMZWWKC>N=ZZWH+&"I2\BG#*W\O?S-_-
-MW\[?M]^QW@K*W\O?S`IH86YK86MU(,K?R]_,I`K*W\O?S-VA"I2\BG""S(SC
-!"@!"
-eofeof
-#'
-
-example['x0201.euc'] = <<'eofeof'.unpack('u')[0]
-MP;2ST:6KI:VEKZ6QI;.EK*6NI;"ELJ6T"L&TL=&CP:/"H\.CQ*/%H\:CQZ/A
-MH^*CXZ/DH^6CYJ/G"L&TM:VYYJ&JH?>A]*'PH?.AL*'UH?:ARJ'+H=VAW*'A
-MH<ZASZ'0H=&A[PK(OK/1CK:.MXZX/8ZYCKJ.MH[>CK>.WHZXCMZ.N8[>CKJ.
-MWJ3("LB^L]&.RH[?CLN.WX[,CM^.S8[?CLZ.WXZWCM^.L8[>"H[*CM^.RX[?
-MCLP*:&%N:V%K=2".RH[?CLN.WX[,CJ0*CLJ.WX[+CM^.S([=CJ$*R+ZST:3.
-#N.4*
-eofeof
-#'
-
-example['x0201.jis'] = <<'eofeof'.unpack('u')[0]
-M&R1"030S424K)2TE+R4Q)3,E+"4N)3`E,B4T&RA""ALD0D$T,5$C02-"(T,C
-M1"-%(T8C1R-A(V(C8R-D(V4C9B-G&RA""ALD0D$T-2TY9B$J(7<A="%P(7,A
-M,"%U(78A2B%+(5TA7"%A(4XA3R%0(5$A;QLH0@H;)$)(/C-1&RA)-C<X&RA"
-M/1LH23DZ-EXW7CA>.5XZ7ALD0B1(&RA""ALD0D@^,U$;*$E*7TM?3%]-7TY?
-M-U\Q7ALH0@H;*$E*7TM?3!LH0@IH86YK86MU(!LH24I?2U],)!LH0@H;*$E*
-97TM?3%TA&RA""ALD0D@^,U$D3CAE&RA""@``
-eofeof
-#`
-
-example['x0201.sosi'] = <<'eofeof'.unpack('u')[0]
-M&R1"030S424K)2TE+R4Q)3,E+"4N)3`E,B4T&RA*"ALD0D$T,5$C02-"(T,C
-M1"-%(T8C1R-A(V(C8R-D(V4C9B-G&RA*"ALD0D$T-2TY9B$J(7<A="%P(7,A
-M,"%U(78A2B%+(5TA7"%A(4XA3R%0(5$A;QLH2@H;)$)(/C-1&RA*#C8W.`\;
-M*$H]#CDZ-EXW7CA>.5XZ7@\;)$(D2!LH2@H;)$)(/C-1&RA*#DI?2U],7TU?
-M3E\W7S%>#PH.2E]+7TP/&RA*"FAA;FMA:W4@#DI?2U],)`\;*$H*#DI?2U],
-672$/&RA*"ALD0D@^,U$D3CAE&RA""@``
-eofeof
-#"
-
-example['x0201.x0208'] = <<'eofeof'.unpack('u')[0]
-M&R1"030S424K)2TE+R4Q)3,E+"4N)3`E,B4T&RA""ALD0D$T,5$;*$)!0D-$
-M149'86)C9&5F9PH;)$)!-#4M.68;*$(A0",D)5XF*B@I+2L]6UU[?1LD0B%O
-M&RA""ALD0D@^,U$E*R4M)2\;*$(]&R1")3$E,R4L)2XE,"4R)30D2!LH0@H;
-M)$)(/C-1)5$E5"57)5HE724M(2PE(B$K&RA""ALD0B51)50E51LH0@IH86YK
-M86MU(!LD0B51)50E52$B&RA""ALD0B51)50E525S(2,;*$(*&R1"2#XS421.
-&.&4;*$(*
-eofeof
-#`
-
-example['mime.iso2022'] = <<'eofeof'.unpack('u')[0]
-M/3])4T\M,C`R,BU*4#]"/T=Y4D%.144W96E23TI566Q/4U9)1WEH2S\]"CT_
-M:7-O+3(P,C(M2E`_0C]'>5)!3D5%-V5I4D]*55EL3U-624=Y:$L_/0H]/VES
-M;RTR,#(R+4I0/U$_/3%")$(D1B11/3%"*$)?96YD/ST*&R1`)#TD)B0K)$H;
-M*$H@/3])4T\M,C`R,BU*4#]"/T=Y4D%.144W96E23U!Y:S=D:'-O4V<]/3\]
-M(&5N9"!O9B!L:6YE"CT_25-/+3(P,C(M2E`_0C]'>5)!3D5%-V5I4D]0>6LW
-M9&AS;U-G/3T_/2`]/TE33RTR,#(R+4I0/T(_1WE204Y%13=E:5)/4'EK-V1H
-M<V]39ST]/ST*0G)O:V5N(&-A<V4*/3])4T\M,C`R,BU*4#]"/T=Y4D%.144W
-M96E23U!Y:S=D"FAS;U-G/3T_/2`]/TE33RTR,`HR,BU*4#]"/T=Y4D%.144W
-M96E23U!Y:S=D:'-O4V<]/3\]"CT_25-/+3(P,C(M2E`_0C]'>5)!3D5%-V5I
-44D]*55EL3QM;2U-624=Y:$L_/0H_
-eofeof
-#'
-
-example['mime.ans.strict'] = <<'eofeof'.unpack('u')[0]
-M&R1"-$$[>B1.)48E.25(&RA""ALD0C1!.WHD3B5&)3DE2!LH0@H;)$(D1B11
-M&RA"(&5N9`H;)$(D/20F)"LD2ALH0B`;)$(T03MZ)$X_*3MV&RA"96YD(&]F
-M(&QI;F4*&R1"-$$[>B1./RD[=C1!.WHD3C\I.W8;*$(*0G)O:V5N(&-A<V4*
-M/3])4T\M,C`R,BU*4#]"/T=Y4D%.144W96E23U!Y:S=D"FAS;U-G/3T_/2`]
-M/TE33RTR,`HR,BU*4#]"/T=Y4D%.144W96E23U!Y:S=D:'-O4V<]/3\]"CT_
-L25-/+3(P,C(M2E`_0C]'>5)!3D5%-V5I4D]*55EL3QM;2U-624=Y:$L_/0H_
-eofeof
-#'
-
-example['mime.unbuf.strict'] = <<'eofeof'.unpack('u')[0]
-M&R1"-$$[>B1.)48E.25(&RA""ALD0C1!.WHD3B5&)3DE2!LH0@H;)$(D1B11
-M&RA"(&5N9`H;)$(D/20F)"LD2ALH0B`;)$(T03MZ)$X_*3MV&RA"96YD(&]F
-M(&QI;F4*&R1"-$$[>B1./RD[=C1!.WHD3C\I.W8;*$(*0G)O:V5N(&-A<V4*
-M&R1"-$$[>B1./RD;*$)H<V]39ST]/ST@/3])4T\M,C`*,C(M2E`_0C]'>5)!
-M3D5%-V5I4D]0>6LW9&AS;U-G/3T_/0H;)$(T03MZ)$XE1ALH0EM+4U9)1WEH
-$2S\]"F5I
-eofeof
-
-example['mime.ans'] = <<'eofeof'.unpack('u')[0]
-M&R1"-$$[>B1.)48E.25(&RA""ALD0C1!.WHD3B5&)3DE2!LH0@H;)$(D1B11
-M&RA"(&5N9`H;)$(D/20F)"LD2ALH0B`;)$(T03MZ)$X_*3MV&RA"96YD(&]F
-M(&QI;F4*&R1"-$$[>B1./RD[=C1!.WHD3C\I.W8;*$(*0G)O:V5N(&-A<V4*
-M&R1"-$$[>B1./RD;*$)H<V]39ST]/ST@&R1"-$$[>B1./RD[=ALH0@H;)$(T
-603MZ)$XE1ALH0EM+4U9)1WEH2S\]"@`*
-eofeof
-#"
-
-example['mime.unbuf'] = <<'eofeof'.unpack('u')[0]
-M&R1"-$$[>B1.)48E.25(&RA""ALD0C1!.WHD3B5&)3DE2!LH0@H;)$(D1B11
-M&RA"(&5N9`H;)$(D/20F)"LD2ALH0B`;)$(T03MZ)$X_*3MV&RA"96YD(&]F
-M(&QI;F4*&R1"-$$[>B1./RD[=C1!.WHD3C\I.W8;*$(*0G)O:V5N(&-A<V4*
-M&R1"-$$[>B1./RD;*$)H<V]39ST]/ST@&R1"-$$[>B1./RD[=ALH0@H;)$(T
-603MZ)$XE1ALH0EM+4U9)1WEH2S\]"@`*
-eofeof
-#"
-
-example['mime.base64'] = <<'eofeof'.unpack('u')[0]
-M9W-M5"])3&YG<FU#>$I+-&=Q=4,S24LS9W%Q0E%:3TUI-39,,S0Q-&=S5T)1
-M43!+9VUA1%9O3T@*9S)+1%1O3'=K8C)1;$E+;V=Q2T-X24MG9W5M0W%*3EEG
-<<T=#>$E+9V=U;4,X64Q&9W)70S592VMG<6U""F=Q
-eofeof
-#"
-
-example['mime.base64.ans'] = <<'eofeof'.unpack('u')[0]
-M&R1")$M&?B1I)#LD1D0Z)"TD7B0Y)"PA(D5L-7XV83E9)$<A(ALH0@T*&R1"
-M(T<E-R5G)4,E+R1R0C\_="0J)"0D1B0B)&LD*D4Y)$,D1B0B)&LD<R1')#<D
-(9R0F)"L;*$(E
-eofeof
-#'
-
-example['mime.is8859'] = <<'eofeof'.unpack('u')[0]
-M/3])4T\M.#@U.2TQ/U$_*CU#-V%V83\_/2`*4&5E<B!4]G)N9W)E;@I,87-S
-M92!(:6QL97+X92!0971E<G-E;B`@7"`B36EN(&MA97!H97-T(&AA<B!F86%E
-M="!E="!F;V5L(2(*06%R:'5S(%5N:79E<G-I='DL($1%3DU!4DL@(%P@(DUI
-<;B!KYG!H97-T(&AA<B!FY65T(&5T(&;X;"$B"@!K
-eofeof
-
-example['mime.is8859.ans'] = <<'eofeof'.unpack('u')[0]
-M*L=A=F$_(`I0965R(%3V<FYG<F5N"DQA<W-E($AI;&QE<OAE(%!E=&5R<V5N
-M("!<(")-:6X@:V%E<&AE<W0@:&%R(&9A865T(&5T(&9O96PA(@I!87)H=7,@
-M56YI=F5R<VET>2P@1$5.34%22R`@7"`B36EN(&OF<&AE<W0@:&%R(&;E970@
-)970@9OAL(2(*
-eofeof
-#"
-
-print 'JIS to JIS ... '; test(' ', example['jis'], example['jis'])
-print 'JIS to SJIS... '; test('-s', example['jis'], example['sjis'])
-print 'JIS to EUC ... '; test('-e', example['jis'], example['euc'])
-
-print 'SJIS to JIS ... '; test('-j', example['sjis'], example['jis'])
-print 'SJIS to SJIS... '; test('-s', example['sjis'], example['sjis'])
-print 'SJIS to EUC ... '; test('-e', example['sjis'], example['euc'])
-
-print 'EUC to JIS ... '; test(' ', example['euc'], example['jis'])
-print 'EUC to SJIS... '; test('-s', example['euc'], example['sjis'])
-print 'EUC to EUC ... '; test('-e', example['euc'], example['euc'])
-
-
-# Ambigous Case
-print 'Ambiguous Case. '; test('' , example['amb'], example['amb.euc'])
-
-# Input assumption
-print 'SJIS Input assumption '
-test('-Sx', example['amb'], example['amb.sjis'])
-
-# X0201 仮名
-# X0201->X0208 conversion
-# X0208 aphabet -> ASCII
-# X0201 相互変換
-
-print "\nX0201 test\n\n"
-
-# -X is necessary to allow X0201 in SJIS
-# -Z convert X0208 alphabet to ASCII
-print 'X0201 conversion: SJIS '
-test('-XZ', example['x0201.sjis'], example['x0201.x0208'])
-print 'X0201 conversion: JIS '
-test('-Z', example['x0201.jis'], example['x0201.x0208'])
-print 'X0201 conversion:SI/SO '
-test('-Z', example['x0201.sosi'], example['x0201.x0208'])
-print 'X0201 conversion: EUC '
-test('-Z', example['x0201.euc'], example['x0201.x0208'])
-# -x means X0201 output
-print 'X0201 output: SJIS '
-test('-xs', example['x0201.euc'], example['x0201.sjis'])
-print 'X0201 output: JIS '
-test('-xj', example['x0201.sjis'], example['x0201.jis'])
-print 'X0201 output: EUC '
-test('-xe', example['x0201.jis'], example['x0201.euc'])
-
-# MIME decode
-
-print "\nMIME test\n\n"
-
-# MIME ISO-2022-JP
-
-print "Next test is expeced to Fail.\n"
-
-print 'MIME decode (strict) '
-tmp = test('-m', example['mime.iso2022'], example['mime.ans.strict'])
-print 'MIME decode (nonstrict)'
-tmp = test('-m', example['mime.iso2022'], example['mime.ans'])
-# open(OUT,'>tmp1');print OUT pack('u',$tmp);close(OUT);
-# unbuf mode implies more pessimistic decode
-print 'MIME decode (unbuf) '
-test('-mu', example['mime.iso2022'], example['mime.unbuf'])
-print 'MIME decode (base64) '
-t = test('-mB', example['mime.base64'], example['mime.base64.ans'])
-
-# MIME ISO-8859-1
-
-# Without -l, ISO-8859-1 was handled as X0201.
-
-print 'MIME ISO-8859-1 (Q) '
-test('-ml', example['mime.is8859'], example['mime.is8859.ans'])
diff --git a/ext/pty/.cvsignore b/ext/pty/.cvsignore
deleted file mode 100644
index fc802ff1c2..0000000000
--- a/ext/pty/.cvsignore
+++ /dev/null
@@ -1,2 +0,0 @@
-Makefile
-mkmf.log
diff --git a/ext/pty/MANIFEST b/ext/pty/MANIFEST
deleted file mode 100644
index 0535a5b7ef..0000000000
--- a/ext/pty/MANIFEST
+++ /dev/null
@@ -1,12 +0,0 @@
-MANIFEST
-README
-README.expect
-README.expect.ja
-README.ja
-depend
-expect_sample.rb
-extconf.rb
-lib/expect.rb
-pty.c
-script.rb
-shl.rb
diff --git a/ext/pty/README b/ext/pty/README
deleted file mode 100644
index a09469d39c..0000000000
--- a/ext/pty/README
+++ /dev/null
@@ -1,93 +0,0 @@
-pty extension version 0.3 by A.ito
-
-1. Introduction
-
-This extension module adds ruby a functionality to execute an
-arbitrary command through pseudo tty (pty).
-
-2. Install
-
-Follow the instruction below.
-
-(1) Execute
-
- ruby extconf.rb
-
- then Makefile is generated.
-
-(3) Do make; make install.
-
-3. What you can do
-
-This extension module defines a module named PTY, which contains
-following module fungtions:
-
- getpty(command)
- spawn(command)
-
- This function reserves a pty, executes command over the pty
- and returns an array. The return value is an array with three
- elements. The first element in the array is for reading and the
- second for writing. The third element is the process ID of the
- child process. If this function is called with an iterator block,
- the array is passed to the block as block parameters, and the
- function itself returns nil.
-
- While the process spawned by this function is active, SIGCHLD
- is captured to handle the change of the child process. When the
- child process is suspended or finished, an exception is raised.
- As all SIGCHLD signal is captured and processed by PTY module,
- you can't use other function or method which spawns subprosesses
- (including signal() and IO.popen()) while the PTY subprocesses
- are active. Otherwise, unexpected exception will occur. To avoid
- this problem, see protect_signal() below.
-
- If this function is called with an iterator block, SIGCHLD signal
- is captured only within the block. Therefore, it is risky to use
- File objects for PTY subprocess outside the iterator block.
-
-
- protect_signal
-
- This function takes an iterator block. Within the iterator block,
- no exception is raised even if any subprocess is terminated.
- This function is used to enable functions like system() or IO.popen()
- while PTY subprocess is active. For example,
-
- PTY.spawn("command_foo") do |r,w|
- ...
- ...
- PTY.protect_signal do
- system "some other commands"
- end
- ...
- end
-
- disables to send exception when "some other commands" is
- terminated.
-
- reset_signal
-
- Disables to handle SIGCHLD while PTY subprocess is active.
-
-
-4. License
-
-(C) Copyright 1998 by Akinori Ito.
-
-This software may be redistributed freely for this purpose, in full
-or in part, provided that this entire copyright notice is included
-on any copies of this software and applications and derivations thereof.
-
-This software is provided on an "as is" basis, without warranty of any
-kind, either expressed or implied, as to any matter including, but not
-limited to warranty of fitness of purpose, or merchantability, or
-results obtained from use of this software.
-
-5. Bug report
-
-Please feel free to send E-mail to
-
- aito@ei5sun.yz.yamagata-u.ac.jp
-
-for any bug report, opinion, contribution, etc.
diff --git a/ext/pty/README.expect b/ext/pty/README.expect
deleted file mode 100644
index fddbb6fdad..0000000000
--- a/ext/pty/README.expect
+++ /dev/null
@@ -1,22 +0,0 @@
- README for expect
- by A. Ito, 28 October, 1998
-
- Expect library adds IO class a method called expect(), which
-does similar act to tcl's expect extension.
-
-The usage of the method is:
-
- IO#expect(pattern,timeout=9999999)
-
-where `pattern' is an instance of String or Regexp and `timeout'
-is Fixnum, which can be omitted.
- When the method is called without block, it waits until the
-input which matches the pattern is obtained from the IO or the time
-specified as the timeout passes. When the pattern is obtained from the
-IO, the method returns an array. The first element of the array is the
-entire string obtained from the IO until the pattern matches. The
-following elements indicates the specific pattern which matched to the
-anchor in the regular expression. If the method ends because of
-timeout, it returns nil.
- When the method is called with block, the array is passed as
-the block parameter.
diff --git a/ext/pty/README.expect.ja b/ext/pty/README.expect.ja
deleted file mode 100644
index db84695ee5..0000000000
--- a/ext/pty/README.expect.ja
+++ /dev/null
@@ -1,21 +0,0 @@
- README for expect
- by A. Ito, 28 October, 1998
-
- Expectライブラリは,tcl の expect パッケージと似たような機能を
-IOクラスに追加します.
-
- 追加されるメソッドの使い方は次の通りです.
-
- IO#expect(pattern,timeout=9999999)
-
-pattern は String か Regexp のインスタンス,timeout は Fixnum
-のインスタンスです.timeout は省略できます.
- このメソッドがブロックなしで呼ばれた場合,まずレシーバである
-IOオブジェクトから pattern にマッチするパターンが読みこまれる
-まで待ちます.パターンが得られたら,そのパターンに関する配列を
-返します.配列の最初の要素は,pattern にマッチするまでに読みこ
-まれた内容の文字列です.2番目以降の要素は,pattern の正規表現
-の中にアンカーがあった場合に,そのアンカーにマッチする部分です.
-もしタイムアウトが起きた場合は,このメソッドはnilを返します.
- このメソッドがブロック付きで呼ばれた場合には,マッチした要素の
-配列がブロック引数として渡され,ブロックが評価されます.
diff --git a/ext/pty/README.ja b/ext/pty/README.ja
deleted file mode 100644
index 5ae4fb06a0..0000000000
--- a/ext/pty/README.ja
+++ /dev/null
@@ -1,89 +0,0 @@
-pty 拡張モジュール version 0.3 by A.ito
-
-1. はじめに
-
-この拡張モジュールは,仮想tty (pty) を通して適当なコマンドを
-実行する機能を ruby に提供します.
-
-2. インストール
-
-次のようにしてインストールしてください.
-
-(1) ruby extconf.rb
-
- を実行すると Makefile が生成されます.
-
-(2) make; make install を実行してください.
-
-3. 何ができるか
-
-この拡張モジュールは,PTY というモジュールを定義します.その中
-には,次のようなモジュール関数が含まれています.
-
- getpty(command)
- spawn(command)
-
- この関数は,仮想ttyを確保し,指定されたコマンドをその仮想tty
- の向こうで実行し,配列を返します.戻り値は3つの要素からなる
- 配列です.最初の要素は仮想ttyから読み出すためのIOオブジェクト,
- 2番目は書きこむためのIOオブジェクト,3番目は子プロセスのプロ
- セスIDです.この関数がイテレータとして呼ばれた場合,これらの
- 要素はブロックパラメータとして渡され,関数自体はnilを返します.
-
- この関数によって作られたサブプロセスが動いている間,子プロセス
- の状態を監視するために SIGCHLD シグナルを捕捉します.子プロセス
- が終了したり停止した場合には,例外が発生します.この間,すべての
- SIGCHLD が PTY モジュールのシグナルハンドラに捕捉されるので,
- サブプロセスを生成する他の関数(system() とか IO.popen()など)を
- 使うと,予期しない例外が発生することがあります.これを防ぐため
- には,下記のprotect_signal()を参照してください.
-
- この関数がブロックパラメータ付きで呼ばれた場合には,そのブロック
- の中でのみ SIGCHLD が捕捉されます.したがって,ブロックパラメータ
- として渡されたIOオブジェクトを,ブロックの外に持ち出して使うの
- は勧められません.
-
-
- protect_signal
-
- この関数はイテレータです.ここで指定されたブロックの中では,
- 子プロセスが終了しても例外を発生しません.この関数を使うことで,
- PTYの子プロセスが動いている間でも,system()や IO.popen()などの
- 関数を安全に使うことができます.例えば,
-
- PTY.spawn("command_foo") do |r,w|
- ...
- ...
- PTY.protect_signal do
- system "some other commands"
- end
- ...
- end
-
- このような記述により,"some other commands" が終了したときに
- 例外が発生するのを防げます.
-
- reset_signal
-
- PTY の子プロセスが動いていても,そのプロセスの終了時に例外が発生
- しないようにします.
-
-4. 利用について
-
-伊藤彰則が著作権を保有します.
-
-ソースプログラムまたはドキュメントに元の著作権表示が改変されずに
-表示されている場合に限り,誰でも,このソフトウェアを無償かつ著作
-権者に無断で利用・配布・改変できます.利用目的は限定されていませ
-ん.
-
-このプログラムの利用・配布その他このプログラムに関係する行為によ
-って生じたいかなる損害に対しても,作者は一切責任を負いません.
-
-5. バグ報告等
-
-バグレポートは歓迎します.
-
- aito@ei5sun.yz.yamagata-u.ac.jp
-
-まで電子メールでバグレポートをお送りください.
diff --git a/ext/pty/depend b/ext/pty/depend
deleted file mode 100644
index 888be6c301..0000000000
--- a/ext/pty/depend
+++ /dev/null
@@ -1 +0,0 @@
-pty.o: pty.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h
diff --git a/ext/pty/expect_sample.rb b/ext/pty/expect_sample.rb
deleted file mode 100644
index 1311476c5d..0000000000
--- a/ext/pty/expect_sample.rb
+++ /dev/null
@@ -1,56 +0,0 @@
-#
-# sample program of expect.rb
-#
-# by A. Ito
-#
-# This program reports the latest version of ruby interpreter
-# by connecting to ftp server at netlab.co.jp.
-#
-require 'pty'
-require 'expect'
-
-fnames = []
-PTY.spawn("ftp ftp.netlab.co.jp") do
- |r_f,w_f,pid|
- w_f.sync = true
-
- $expect_verbose = true
-
- r_f.expect(/^Name.*: /) do
- w_f.print "ftp\n"
- end
-
- if !ENV['USER'].nil?
- username = ENV['USER']
- elsif !ENV['LOGNAME'].nil?
- username = ENV['LOGNAME']
- else
- username = 'guest'
- end
-
- r_f.expect('word:') do
- w_f.print username+"@\n"
- end
- r_f.expect("ftp> ") do
- w_f.print "cd pub/lang/ruby\n"
- end
- r_f.expect("ftp> ") do
- w_f.print "dir\n"
- end
-
- r_f.expect("ftp> ") do |output|
- for x in output[0].split("\n")
- if x =~ /(ruby.*\.tar\.gz)/ then
- fnames.push $1
- end
- end
- end
- begin
- w_f.print "quit\n"
- rescue
- end
-end
-
-print "The latest ruby interpreter is "
-print fnames.sort.pop
-print "\n"
diff --git a/ext/pty/extconf.rb b/ext/pty/extconf.rb
deleted file mode 100644
index ec35879a33..0000000000
--- a/ext/pty/extconf.rb
+++ /dev/null
@@ -1,15 +0,0 @@
-require 'mkmf'
-
-if /mswin32|mingw/ !~ RUBY_PLATFORM
- have_header("sys/stropts.h")
- have_func("setresuid")
- have_header("libutil.h")
- have_header("pty.h")
- have_library("util", "openpty")
- if have_func("openpty") or
- have_func("_getpty") or
- have_func("ptsname") or
- have_func("ioctl")
- create_makefile('pty')
- end
-end
diff --git a/ext/pty/lib/expect.rb b/ext/pty/lib/expect.rb
deleted file mode 100644
index 5b5619e6b2..0000000000
--- a/ext/pty/lib/expect.rb
+++ /dev/null
@@ -1,36 +0,0 @@
-$expect_verbose = false
-
-class IO
- def expect(pat,timeout=9999999)
- buf = ''
- case pat
- when String
- e_pat = Regexp.new(Regexp.quote(pat))
- when Regexp
- e_pat = pat
- end
- while true
- if IO.select([self],nil,nil,timeout).nil? then
- result = nil
- break
- end
- c = getc.chr
- buf << c
- if $expect_verbose
- STDOUT.print c
- STDOUT.flush
- end
- if buf =~ e_pat then
- result = [buf,$1,$2,$3,$4,$5,$6,$7,$8,$9]
- break
- end
- end
- if block_given? then
- yield result
- else
- return result
- end
- nil
- end
-end
-
diff --git a/ext/pty/pty.c b/ext/pty/pty.c
deleted file mode 100644
index b7c69fe400..0000000000
--- a/ext/pty/pty.c
+++ /dev/null
@@ -1,488 +0,0 @@
-#include "config.h"
-#include <stdio.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <sys/file.h>
-#include <fcntl.h>
-#include <errno.h>
-#include <pwd.h>
-#if !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
-#include <sys/ioctl.h>
-#endif
-#ifdef HAVE_LIBUTIL_H
-#include <libutil.h>
-#endif
-#ifdef HAVE_PTY_H
-#include <pty.h>
-#endif
-#ifdef HAVE_SYS_WAIT_H
-#include <sys/wait.h>
-#else
-#define WIFSTOPPED(status) (((status) & 0xff) == 0x7f)
-#endif
-#include <ctype.h>
-
-#include "ruby.h"
-#include "rubyio.h"
-
-#include <signal.h>
-#ifdef HAVE_SYS_STROPTS_H
-#include <sys/stropts.h>
-#endif
-
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-
-#define DEVICELEN 16
-
-#if !defined(HAVE_OPENPTY)
-#ifdef __hpux
-static
-char *MasterDevice = "/dev/ptym/pty%s",
- *SlaveDevice = "/dev/pty/tty%s",
- *deviceNo[] = {
- "p0","p1","p2","p3","p4","p5","p6","p7",
- "p8","p9","pa","pb","pc","pd","pe","pf",
- "q0","q1","q2","q3","q4","q5","q6","q7",
- "q8","q9","qa","qb","qc","qd","qe","qf",
- "r0","r1","r2","r3","r4","r5","r6","r7",
- "r8","r9","ra","rb","rc","rd","re","rf",
- "s0","s1","s2","s3","s4","s5","s6","s7",
- "s8","s9","sa","sb","sc","sd","se","sf",
- "t0","t1","t2","t3","t4","t5","t6","t7",
- "t8","t9","ta","tb","tc","td","te","tf",
- "u0","u1","u2","u3","u4","u5","u6","u7",
- "u8","u9","ua","ub","uc","ud","ue","uf",
- "v0","v1","v2","v3","v4","v5","v6","v7",
- "v8","v9","va","vb","vc","vd","ve","vf",
- "w0","w1","w2","w3","w4","w5","w6","w7",
- "w8","w9","wa","wb","wc","wd","we","wf",
- 0,
- };
-#else /* NOT HPUX */
-#ifdef _IBMESA /* AIX/ESA */
-static
-char *MasterDevice = "/dev/ptyp%s",
- *SlaveDevice = "/dev/ttyp%s",
- *deviceNo[] = {
-"00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f",
-"10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f",
-"20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f",
-"30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f",
-"40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f",
-"50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f",
-"60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f",
-"70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f",
-"80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f",
-"90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f",
-"a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af",
-"b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf",
-"c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf",
-"d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df",
-"e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef",
-"f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff",
- };
-#else
-static
-char *MasterDevice = "/dev/pty%s",
- *SlaveDevice = "/dev/tty%s",
- *deviceNo[] = {
- "p0","p1","p2","p3","p4","p5","p6","p7",
- "p8","p9","pa","pb","pc","pd","pe","pf",
- "q0","q1","q2","q3","q4","q5","q6","q7",
- "q8","q9","qa","qb","qc","qd","qe","qf",
- "r0","r1","r2","r3","r4","r5","r6","r7",
- "r8","r9","ra","rb","rc","rd","re","rf",
- "s0","s1","s2","s3","s4","s5","s6","s7",
- "s8","s9","sa","sb","sc","sd","se","sf",
- 0,
- };
-#endif /* _IBMESA */
-#endif /* HPUX */
-#endif /* !defined(HAVE_OPENPTY) */
-
-static char SlaveName[DEVICELEN];
-
-extern int errno;
-
-#ifndef HAVE_SETEUID
-# ifdef HAVE_SETREUID
-# define seteuid(e) setreuid(-1, (e))
-# else /* NOT HAVE_SETREUID */
-# ifdef HAVE_SETRESUID
-# define seteuid(e) setresuid(-1, (e), -1)
-# else /* NOT HAVE_SETRESUID */
- /* I can't set euid. (;_;) */
-# endif /* HAVE_SETRESUID */
-# endif /* HAVE_SETREUID */
-#endif /* NO_SETEUID */
-
-static VALUE eChildExited;
-
-static VALUE
-echild_status(self)
- VALUE self;
-{
- return rb_ivar_get(self, rb_intern("status"));
-}
-
-struct pty_info {
- int fd;
- pid_t child_pid;
- VALUE thread;
-};
-
-static VALUE
-pty_syswait(info)
- struct pty_info *info;
-{
- extern VALUE rb_last_status;
- int cpid, status;
- char buf[1024];
- VALUE exc, st;
- char *state = "changed";
-
- cpid = rb_waitpid(info->child_pid, &status, WUNTRACED);
- st = rb_last_status;
-
- if (cpid == 0 || cpid == -1)
- return Qnil;
-
-#ifdef IF_STOPPED
- if (IF_STOPPED(status)) { /* suspend */
- state = "stopped";
- }
-#else
-#ifdef WIFSTOPPED
- if (WIFSTOPPED(status)) { /* suspend */
- state = "stopped";
- }
-#else
----->> Either IF_STOPPED or WIFSTOPPED is needed <<----
-#endif /* WIFSTOPPED */
-#endif /* IF_STOPPED */
- if (WIFEXITED(status)) {
- state = "exit";
- }
-
- snprintf(buf, sizeof(buf), "pty - %s: %d", state, cpid);
- exc = rb_exc_new2(eChildExited, buf);
- rb_iv_set(exc, "status", st);
- rb_funcall(info->thread, rb_intern("raise"), 1, exc);
- return Qnil;
-}
-
-static void getDevice _((int*, int*));
-
-struct exec_info {
- int argc;
- VALUE *argv;
-};
-
-static VALUE
-pty_exec(arg)
- struct exec_info *arg;
-{
- return rb_f_exec(arg->argc, arg->argv);
-}
-
-static void
-establishShell(argc, argv, info)
- int argc;
- VALUE *argv;
- struct pty_info *info;
-{
- static int i,master,slave,currentPid;
- char *p,*getenv();
- struct passwd *pwent;
- VALUE v;
- struct exec_info arg;
- int status;
-
- if (argc == 0) {
- char *shellname;
-
- if ((p = getenv("SHELL")) != NULL) {
- shellname = p;
- }
- else {
- pwent = getpwuid(getuid());
- if (pwent && pwent->pw_shell)
- shellname = pwent->pw_shell;
- else
- shellname = "/bin/sh";
- }
- v = rb_str_new2(shellname);
- argc = 1;
- argv = &v;
- }
- getDevice(&master,&slave);
-
- info->thread = rb_thread_current();
- currentPid = getpid();
- if((i = fork()) < 0) {
- rb_sys_fail("fork failed");
- }
-
- if(i == 0) { /* child */
- currentPid = getpid();
-
- /*
- * Set free from process group and controlling terminal
- */
-#ifdef HAVE_SETSID
- (void) setsid();
-#else /* HAS_SETSID */
-# ifdef HAVE_SETPGRP
-# ifdef SETGRP_VOID
- if (setpgrp() == -1)
- perror("setpgrp()");
-# else /* SETGRP_VOID */
- if (setpgrp(0, currentPid) == -1)
- rb_sys_fail("setpgrp()");
- if ((i = open("/dev/tty", O_RDONLY)) < 0)
- rb_sys_fail("/dev/tty");
- else {
- if (ioctl(i, TIOCNOTTY, (char *)0))
- perror("ioctl(TIOCNOTTY)");
- close(i);
- }
-# endif /* SETGRP_VOID */
-# endif /* HAVE_SETPGRP */
-#endif /* HAS_SETSID */
-
- /*
- * obtain new controlling terminal
- */
-#if defined(TIOCSCTTY)
- close(master);
- (void) ioctl(slave, TIOCSCTTY, (char *)0);
- /* errors ignored for sun */
-#else
- close(slave);
- slave = open(SlaveName, O_RDWR);
- if (slave < 0) {
- perror("open: pty slave");
- _exit(1);
- }
- close(master);
-#endif
- dup2(slave,0);
- dup2(slave,1);
- dup2(slave,2);
- close(slave);
-#if defined(HAVE_SETEUID) || defined(HAVE_SETREUID) || defined(HAVE_SETRESUID)
- seteuid(getuid());
-#endif
-
- arg.argc = argc;
- arg.argv = argv;
- rb_protect(pty_exec, (VALUE)&arg, &status);
- sleep(1);
- _exit(1);
- }
-
- close(slave);
-
- info->child_pid = i;
- info->fd = master;
-}
-
-static VALUE
-pty_kill_child(info)
- struct pty_info *info;
-{
- if (rb_funcall(info->thread, rb_intern("alive?"), 0, 0) == Qtrue &&
- kill(info->child_pid, 0) == 0) {
- rb_thread_schedule();
- if (kill(info->child_pid, SIGTERM) == 0) {
- rb_thread_schedule();
- if (kill(info->child_pid, 0) == 0) {
- kill(info->child_pid, SIGINT);
- rb_thread_schedule();
- if (kill(info->child_pid, 0) == 0)
- kill(info->child_pid, SIGKILL);
- }
- }
- }
- rb_funcall(info->thread, rb_intern("join"), 0, 0);
- return Qnil;
-}
-
-
-#ifdef HAVE_OPENPTY
-/*
- * Use openpty(3) of 4.3BSD Reno and later,
- * or the same interface function.
- */
-static void
-getDevice(master,slave)
- int *master,*slave;
-{
- if (openpty(master, slave, SlaveName,
- (struct termios *)0, (struct winsize *)0) == -1) {
- rb_raise(rb_eRuntimeError, "openpty() failed");
- }
-}
-#else /* HAVE_OPENPTY */
-#ifdef HAVE__GETPTY
-static void
-getDevice(master,slave)
- int *master,*slave;
-{
- char *name;
-
- if (!(name = _getpty(master, O_RDWR, 0622, 0))) {
- rb_raise(rb_eRuntimeError, "_getpty() failed");
- }
-
- *slave = open(name, O_RDWR);
- strcpy(SlaveName, name);
-}
-#else /* HAVE__GETPTY */
-static void
-getDevice(master,slave)
- int *master,*slave;
-{
- char **p;
- int i,j;
- char MasterName[DEVICELEN];
-
-#ifdef HAVE_PTSNAME
- char *pn;
- void (*s)();
-
- extern char *ptsname(int);
- extern int unlockpt(int);
- extern int grantpt(int);
-
- if((i = open("/dev/ptmx", O_RDWR, 0)) != -1) {
- s = signal(SIGCHLD, SIG_DFL);
- if(grantpt(i) != -1) {
- signal(SIGCHLD, s);
- if(unlockpt(i) != -1) {
- if((pn = ptsname(i)) != NULL) {
- if((j = open(pn, O_RDWR, 0)) != -1) {
-#if defined I_PUSH && !defined linux
- if(ioctl(j, I_PUSH, "ptem") != -1) {
- if(ioctl(j, I_PUSH, "ldterm") != -1) {
-#endif
- *master = i;
- *slave = j;
- strcpy(SlaveName, pn);
- return;
-#if defined I_PUSH && !defined linux
- }
- }
-#endif
- }
- }
- }
- }
- close(i);
- }
- rb_raise(rb_eRuntimeError, "Cannot get Master/Slave device");
-#else
- for (p = deviceNo; *p != NULL; p++) {
- sprintf(MasterName,MasterDevice,*p);
- if ((i = open(MasterName,O_RDWR,0)) >= 0) {
- *master = i;
- sprintf(SlaveName,SlaveDevice,*p);
- if ((j = open(SlaveName,O_RDWR,0)) >= 0) {
- *slave = j;
- chown(SlaveName, getuid(), getgid());
- chmod(SlaveName, 0622);
- return;
- }
- close(i);
- }
- }
- rb_raise(rb_eRuntimeError, "Cannot get %s", SlaveName);
-#endif
-}
-#endif /* HAVE__GETPTY */
-#endif /* HAVE_OPENPTY */
-
-static void
-freeDevice()
-{
- chmod(SlaveName, 0666);
- chown(SlaveName, 0, 0);
-}
-
-/* ruby function: getpty */
-static VALUE
-pty_getpty(argc, argv, self)
- int argc;
- VALUE *argv;
- VALUE self;
-{
- VALUE res, th;
- struct pty_info info, thinfo;
- OpenFile *wfptr,*rfptr;
- VALUE rport = rb_obj_alloc(rb_cFile);
- VALUE wport = rb_obj_alloc(rb_cFile);
-
- MakeOpenFile(rport, rfptr);
- MakeOpenFile(wport, wfptr);
-
- establishShell(argc, argv, &info);
-
- rfptr->mode = rb_io_mode_flags("r");
- rfptr->f = fdopen(info.fd, "r");
- rfptr->path = strdup(SlaveName);
-
- wfptr->mode = rb_io_mode_flags("w") | FMODE_SYNC;
- wfptr->f = fdopen(dup(info.fd), "w");
- wfptr->path = strdup(SlaveName);
-
- res = rb_ary_new2(3);
- rb_ary_store(res,0,(VALUE)rport);
- rb_ary_store(res,1,(VALUE)wport);
- rb_ary_store(res,2,INT2FIX(info.child_pid));
-
- th = rb_thread_create(pty_syswait, (void*)&info);
- thinfo.thread = th;
- thinfo.child_pid = info.child_pid;
-
- if (rb_block_given_p()) {
- rb_ensure(rb_yield, res, pty_kill_child, (VALUE)&thinfo);
- return Qnil;
- }
- return res;
-}
-
-/* ruby function: protect_signal - obsolete */
-static VALUE
-pty_protect(self)
- VALUE self;
-{
- rb_warn("PTY::protect_signal is no longer needed");
- rb_yield(Qnil);
- return self;
-}
-
-/* ruby function: reset_signal - obsolete */
-static VALUE
-pty_reset_signal(self)
- VALUE self;
-{
- rb_warn("PTY::reset_signal is no longer needed");
- return self;
-}
-
-static VALUE cPTY;
-
-void
-Init_pty()
-{
- cPTY = rb_define_module("PTY");
- rb_define_module_function(cPTY,"getpty",pty_getpty,-1);
- rb_define_module_function(cPTY,"spawn",pty_getpty,-1);
- rb_define_module_function(cPTY,"protect_signal",pty_protect,0);
- rb_define_module_function(cPTY,"reset_signal",pty_reset_signal,0);
-
- eChildExited = rb_define_class_under(cPTY,"ChildExited",rb_eRuntimeError);
- rb_define_method(eChildExited,"status",echild_status,0);
-}
diff --git a/ext/pty/script.rb b/ext/pty/script.rb
deleted file mode 100644
index 3084935637..0000000000
--- a/ext/pty/script.rb
+++ /dev/null
@@ -1,38 +0,0 @@
-require 'pty'
-
-if ARGV.size == 0 then
- ofile = "typescript"
-else
- ofile = ARGV[0]
-end
-
-logfile = File.open(ofile,"a")
-
-system "stty -echo raw lnext ^_"
-
-PTY.spawn("/bin/csh") do
- |r_pty,w_pty,pid|
-
- Thread.new do
- while true
- w_pty.print STDIN.getc.chr
- w_pty.flush
- end
- end
-
- begin
- while true
- c = r_pty.sysread(512)
- break if c.nil?
- print c
- STDOUT.flush
- logfile.print c
- end
- rescue
- # print $@,':',$!,"\n"
- logfile.close
- end
-end
-
-system "stty echo -raw lnext ^v"
-
diff --git a/ext/pty/shl.rb b/ext/pty/shl.rb
deleted file mode 100644
index cdaf8d7398..0000000000
--- a/ext/pty/shl.rb
+++ /dev/null
@@ -1,92 +0,0 @@
-#
-# old-fashioned 'shl' like program
-# by A. Ito
-#
-# commands:
-# c creates new shell
-# C-z suspends shell
-# p lists all shell
-# 0,1,... choose shell
-# q quit
-
-require 'pty'
-
-$shells = []
-$n_shells = 0
-
-$r_pty = nil
-$w_pty = nil
-
-def writer
- system "stty -echo raw"
- begin
- while true
- c = STDIN.getc
- if c == 26 then # C-z
- $reader.raise(nil)
- return 'Suspend'
- end
- $w_pty.print c.chr
- $w_pty.flush
- end
- rescue
- $reader.raise(nil)
- return 'Exit'
- ensure
- system "stty echo -raw"
- end
-end
-
-$reader = Thread.new {
- while true
- begin
- next if $r_pty.nil?
- c = $r_pty.getc
- if c.nil? then
- Thread.stop
- end
- print c.chr
- STDOUT.flush
- rescue
- Thread.stop
- end
- end
-}
-
-# $reader.raise(nil)
-
-
-while true
- print ">> "
- STDOUT.flush
- case gets
- when /^c/i
- $shells[$n_shells] = PTY.spawn("/bin/csh")
- $r_pty,$w_pty = $shells[$n_shells]
- $n_shells += 1
- $reader.run
- if writer == 'Exit'
- $n_shells -= 1
- $shells[$n_shells] = nil
- end
- when /^p/i
- for i in 0..$n_shells
- unless $shells[i].nil?
- print i,"\n"
- end
- end
- when /^([0-9]+)/
- n = $1.to_i
- if $shells[n].nil?
- print "\##{i} doesn't exist\n"
- else
- $r_pty,$w_pty = $shells[n]
- $reader.run
- if writer == 'Exit' then
- $shells[n] = nil
- end
- end
- when /^q/i
- exit
- end
-end
diff --git a/ext/readline/.cvsignore b/ext/readline/.cvsignore
deleted file mode 100644
index fc802ff1c2..0000000000
--- a/ext/readline/.cvsignore
+++ /dev/null
@@ -1,2 +0,0 @@
-Makefile
-mkmf.log
diff --git a/ext/readline/MANIFEST b/ext/readline/MANIFEST
deleted file mode 100644
index 4dd1d9e1a1..0000000000
--- a/ext/readline/MANIFEST
+++ /dev/null
@@ -1,6 +0,0 @@
-MANIFEST
-README
-README.ja
-depend
-extconf.rb
-readline.c
diff --git a/ext/readline/README b/ext/readline/README
deleted file mode 100644
index 9bbf325c99..0000000000
--- a/ext/readline/README
+++ /dev/null
@@ -1,62 +0,0 @@
-Extension for GNU Readline Library
-
-Example:
-
- require "readline"
- include Readline
-
- line = readline("Prompt> ", true)
-
-[Readline]
-
-<module function>
-
-readline(prompt, add_history=nil)
-
- Reads one line with line editing. The inputted line is added to the
- history if add_history is true.
-
-<class methods>
-
-completion_proc = proc
-
- Specifies a Proc object to determine completion behavior. It
- should take input-string, and return an array of completion
- candidates.
-
-completion_proc
-
- Returns the completion Proc object.
-
-completion_case_fold = bool
-
- Sets whether or not to ignore case on completion.
-
-completion_case_fold
-
- Returns true if completion ignores case.
-
-completion_append_character = char
-
- Specifies a character to be appended on completion.
- Nothing will be appended if an empty string ("") or nil is
- specified.
-
-completion_append_character
-
- Returns a string containing a character to be appended on
- completion. The default is a space (" ").
-
-vi_editing_mode
-
- Specifies VI editing mode.
-
-emacs_editing_mode
-
- Specifies Emacs editing mode.
-
-<class constants>
-
-HISTORY
-
-The history buffer. It behaves just like an array.
diff --git a/ext/readline/README.ja b/ext/readline/README.ja
deleted file mode 100644
index beb951fbf0..0000000000
--- a/ext/readline/README.ja
+++ /dev/null
@@ -1,63 +0,0 @@
-GNU Readline Libraryを利用するための拡張モジュールです。
-
-require "readline"
-include Readline
-
-line = readline("Prompt> ", true)
-
-のように使用してください。
-
-[Readline]
-
-<モジュール関数>
-
-readline(prompt, add_history=nil)
-
- 一行入力を読み込みます。
- add_historyがtrueの場合、ヒストリに読み込んだ文字列を追加します。
-
-<クラスメソッド>
-
-completion_proc = proc
-
- 補完時の動作を決定するProcオブジェクトを指定します。
- procは引数に入力文字列を取り、候補文字列の配列を返すように
- してください。
-
-completion_proc
-
- 補完時の動作を決定するProcオブジェクトを返します。
-
-completion_case_fold = case_fold
-
- 補完時に大文字小文字を区別しない場合、trueを指定します。
-
-completion_case_fold
-
- 補完時に大文字小文字を区別しない場合、trueを返します。
-
-completion_append_character = char
-
- 補完時に付加される文字を文字列で指定します。先頭の一文字が
- 設定され、空文字列 ("") または nil を指定すると何も付加
- されなくなります。
-
-completion_append_character
-
- 補完時に付加される文字を文字列で返します。デフォルトは
- 空白 (" ") です。
-
-vi_editing_mode
-
- VIモードになります。
-
-emacs_editing_mode
-
- Emacsモードになります。
-
-<クラス定数>
-
-HISTORY
-
-ヒストリに対する操作はこの定数を通して行ってください。
-配列と同じように扱えるようになっています。
diff --git a/ext/readline/depend b/ext/readline/depend
deleted file mode 100644
index 6570c5a036..0000000000
--- a/ext/readline/depend
+++ /dev/null
@@ -1 +0,0 @@
-readline.o: readline.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h
diff --git a/ext/readline/extconf.rb b/ext/readline/extconf.rb
deleted file mode 100644
index b883de3e01..0000000000
--- a/ext/readline/extconf.rb
+++ /dev/null
@@ -1,27 +0,0 @@
-require "mkmf"
-
-dir_config("readline")
-have_library("user32", nil) if /cygwin/ === RUBY_PLATFORM
-have_library("ncurses", "tgetnum") or
- have_library("termcap", "tgetnum") or
- have_library("curses", "tgetnum")
-
-if have_header("readline/readline.h") and
- have_header("readline/history.h") and
- have_library("readline", "readline")
- if have_func("rl_filename_completion_function")
- $CFLAGS += " -DREADLINE_42_OR_LATER"
- end
- if have_func("rl_cleanup_after_signal")
- $CFLAGS += " -DREADLINE_40_OR_LATER"
- end
- if try_link(<<EOF, $libs)
-#include <stdio.h>
-#include <readline/readline.h>
-main() {rl_completion_append_character = 1;}
-EOF
- # this feature is implemented in readline-2.1 or later.
- $CFLAGS += " -DREADLINE_21_OR_LATER"
- end
- create_makefile("readline")
-end
diff --git a/ext/readline/readline.c b/ext/readline/readline.c
deleted file mode 100644
index a6554a5b57..0000000000
--- a/ext/readline/readline.c
+++ /dev/null
@@ -1,737 +0,0 @@
-/* readline.c -- GNU Readline module
- Copyright (C) 1997-2001 Shugo Maeda */
-
-#include <stdio.h>
-#include <readline/readline.h>
-#include <readline/history.h>
-
-#include "ruby.h"
-#include "rubysig.h"
-
-static VALUE mReadline;
-
-#define TOLOWER(c) (isupper(c) ? tolower(c) : c)
-
-#define COMPLETION_PROC "completion_proc"
-#define COMPLETION_CASE_FOLD "completion_case_fold"
-
-#ifndef READLINE_42_OR_LATER
-# define rl_filename_completion_function filename_completion_function
-# define rl_username_completion_function username_completion_function
-# define rl_completion_matches completion_matches
-#endif
-
-static int
-readline_event()
-{
- CHECK_INTS;
- rb_thread_schedule();
- return 0;
-}
-
-static VALUE
-readline_readline(argc, argv, self)
- int argc;
- VALUE *argv;
- VALUE self;
-{
- VALUE tmp, add_hist, result;
- char *prompt = NULL;
- char *buff;
- int status;
-
- if (rb_scan_args(argc, argv, "02", &tmp, &add_hist) > 0) {
- prompt = StringValuePtr(tmp);
- }
-
- buff = (char*)rb_protect((VALUE(*)_((VALUE)))readline, (VALUE)prompt,
- &status);
- if (status) {
-#if READLINE_40_OR_LATER
- /* restore terminal mode and signal handler*/
- rl_cleanup_after_signal();
-#elif READLINE_21_OR_LATER
- /* restore terminal mode */
- (*rl_deprep_term_function)();
-#else
- rl_deprep_terminal();
-#endif
- rb_jump_tag(status);
- }
-
- if (RTEST(add_hist) && buff) {
- add_history(buff);
- }
- if (buff)
- result = rb_tainted_str_new2(buff);
- else
- result = Qnil;
- if (buff) free(buff);
- return result;
-}
-
-static VALUE
-readline_s_set_completion_proc(self, proc)
- VALUE self;
- VALUE proc;
-{
- if (!rb_respond_to(proc, rb_intern("call")))
- rb_raise(rb_eArgError, "argument have to respond to `call'");
- return rb_iv_set(mReadline, COMPLETION_PROC, proc);
-}
-
-static VALUE
-readline_s_get_completion_proc(self)
- VALUE self;
-{
- return rb_iv_get(mReadline, COMPLETION_PROC);
-}
-
-static VALUE
-readline_s_set_completion_case_fold(self, val)
- VALUE self;
- VALUE val;
-{
- return rb_iv_set(mReadline, COMPLETION_CASE_FOLD, val);
-}
-
-static VALUE
-readline_s_get_completion_case_fold(self)
- VALUE self;
-{
- return rb_iv_get(mReadline, COMPLETION_CASE_FOLD);
-}
-
-static char **
-readline_attempted_completion_function(text, start, end)
- char *text;
- int start;
- int end;
-{
- VALUE proc, ary, temp;
- char **result;
- int case_fold;
- int i, matches;
-
- proc = rb_iv_get(mReadline, COMPLETION_PROC);
- if (NIL_P(proc))
- return NULL;
- rl_attempted_completion_over = 1;
- case_fold = RTEST(rb_iv_get(mReadline, COMPLETION_CASE_FOLD));
- ary = rb_funcall(proc, rb_intern("call"), 1, rb_tainted_str_new2(text));
- if (TYPE(ary) != T_ARRAY)
- ary = rb_Array(ary);
- matches = RARRAY(ary)->len;
- if (matches == 0)
- return NULL;
- result = ALLOC_N(char *, matches + 2);
- for (i = 0; i < matches; i++) {
- temp = rb_obj_as_string(RARRAY(ary)->ptr[i]);
- result[i + 1] = ALLOC_N(char, RSTRING(temp)->len + 1);
- strcpy(result[i + 1], RSTRING(temp)->ptr);
- }
- result[matches + 1] = NULL;
-
- if (matches == 1) {
- result[0] = result[1];
- result[1] = NULL;
- } else {
- register int i = 1;
- int low = 100000;
-
- while (i < matches) {
- register int c1, c2, si;
-
- if (case_fold) {
- for (si = 0;
- (c1 = TOLOWER(result[i][si])) &&
- (c2 = TOLOWER(result[i + 1][si]));
- si++)
- if (c1 != c2) break;
- } else {
- for (si = 0;
- (c1 = result[i][si]) &&
- (c2 = result[i + 1][si]);
- si++)
- if (c1 != c2) break;
- }
-
- if (low > si) low = si;
- i++;
- }
- result[0] = ALLOC_N(char, low + 1);
- strncpy(result[0], result[1], low);
- result[0][low] = '\0';
- }
-
- return result;
-}
-
-static VALUE
-readline_s_vi_editing_mode(self)
- VALUE self;
-{
- rl_vi_editing_mode(1,0);
- return Qnil;
-}
-
-static VALUE
-readline_s_emacs_editing_mode(self)
- VALUE self;
-{
- rl_emacs_editing_mode(1,0);
- return Qnil;
-}
-
-static VALUE
-readline_s_set_completion_append_character(self, str)
- VALUE self, str;
-{
-#ifdef READLINE_21_OR_LATER
- if (NIL_P(str)) {
- rl_completion_append_character = '\0';
- } else {
- StringValue(str);
-
- rl_completion_append_character = RSTRING(str)->ptr[0];
- }
-
- return self;
-#else
- rb_notimplement();
-#endif /* READLINE_21_OR_LATER */
-}
-
-static VALUE
-readline_s_get_completion_append_character(self)
- VALUE self;
-{
-#ifdef READLINE_21_OR_LATER
- VALUE str;
-
- if (rl_completion_append_character == '\0')
- return Qnil;
-
- str = rb_str_new("", 1);
- RSTRING(str)->ptr[0] = rl_completion_append_character;
-
- return str;
-#else
- rb_notimplement();
-#endif /* READLINE_21_OR_LATER */
-}
-
-static VALUE
-readline_s_set_basic_word_break_characters(self, str)
- VALUE self, str;
-{
-#ifdef READLINE_21_OR_LATER
- static char *basic_word_break_characters = NULL;
- char *s;
-
- StringValue(str);
- if (basic_word_break_characters == NULL) {
- basic_word_break_characters =
- ALLOC_N(char, RSTRING(str)->len + 1);
- }
- else {
- REALLOC_N(basic_word_break_characters, char, RSTRING(str)->len + 1);
- }
- strncpy(basic_word_break_characters,
- RSTRING(str)->ptr, RSTRING(str)->len);
- basic_word_break_characters[RSTRING(str)->len] = '\0';
- rl_basic_word_break_characters = basic_word_break_characters;
-
- return self;
-#else
- rb_notimplement();
-#endif /* READLINE_21_OR_LATER */
-}
-
-static VALUE
-readline_s_get_basic_word_break_characters(self, str)
- VALUE self, str;
-{
-#ifdef READLINE_21_OR_LATER
- if (rl_basic_word_break_characters == NULL)
- return Qnil;
- return rb_str_new2(rl_basic_word_break_characters);
-#else
- rb_notimplement();
-#endif /* READLINE_21_OR_LATER */
-}
-
-static VALUE
-readline_s_set_completer_word_break_characters(self, str)
- VALUE self, str;
-{
-#ifdef READLINE_21_OR_LATER
- static char *completer_word_break_characters = NULL;
- char *s;
-
- StringValue(str);
- if (completer_word_break_characters == NULL) {
- completer_word_break_characters =
- ALLOC_N(char, RSTRING(str)->len + 1);
- }
- else {
- REALLOC_N(completer_word_break_characters, char, RSTRING(str)->len + 1);
- }
- strncpy(completer_word_break_characters,
- RSTRING(str)->ptr, RSTRING(str)->len);
- completer_word_break_characters[RSTRING(str)->len] = '\0';
- rl_completer_word_break_characters = completer_word_break_characters;
-
- return self;
-#else
- rb_notimplement();
-#endif /* READLINE_21_OR_LATER */
-}
-
-static VALUE
-readline_s_get_completer_word_break_characters(self, str)
- VALUE self, str;
-{
-#ifdef READLINE_21_OR_LATER
- if (rl_completer_word_break_characters == NULL)
- return Qnil;
- return rb_str_new2(rl_completer_word_break_characters);
-#else
- rb_notimplement();
-#endif /* READLINE_21_OR_LATER */
-}
-
-static VALUE
-readline_s_set_basic_quote_characters(self, str)
- VALUE self, str;
-{
-#ifdef READLINE_21_OR_LATER
- static char *basic_quote_characters = NULL;
- char *s;
-
- StringValue(str);
- if (basic_quote_characters == NULL) {
- basic_quote_characters =
- ALLOC_N(char, RSTRING(str)->len + 1);
- }
- else {
- REALLOC_N(basic_quote_characters, char, RSTRING(str)->len + 1);
- }
- strncpy(basic_quote_characters,
- RSTRING(str)->ptr, RSTRING(str)->len);
- basic_quote_characters[RSTRING(str)->len] = '\0';
- rl_basic_quote_characters = basic_quote_characters;
-
- return self;
-#else
- rb_notimplement();
-#endif /* READLINE_21_OR_LATER */
-}
-
-static VALUE
-readline_s_get_basic_quote_characters(self, str)
- VALUE self, str;
-{
-#ifdef READLINE_21_OR_LATER
- if (rl_basic_quote_characters == NULL)
- return Qnil;
- return rb_str_new2(rl_basic_quote_characters);
-#else
- rb_notimplement();
-#endif /* READLINE_21_OR_LATER */
-}
-
-static VALUE
-readline_s_set_completer_quote_characters(self, str)
- VALUE self, str;
-{
-#ifdef READLINE_21_OR_LATER
- static char *completer_quote_characters = NULL;
- char *s;
-
- StringValue(str);
- if (completer_quote_characters == NULL) {
- completer_quote_characters =
- ALLOC_N(char, RSTRING(str)->len + 1);
- }
- else {
- REALLOC_N(completer_quote_characters, char, RSTRING(str)->len + 1);
- }
- strncpy(completer_quote_characters,
- RSTRING(str)->ptr, RSTRING(str)->len);
- completer_quote_characters[RSTRING(str)->len] = '\0';
- rl_completer_quote_characters = completer_quote_characters;
-
- return self;
-#else
- rb_notimplement();
-#endif /* READLINE_21_OR_LATER */
-}
-
-static VALUE
-readline_s_get_completer_quote_characters(self, str)
- VALUE self, str;
-{
-#ifdef READLINE_21_OR_LATER
- if (rl_completer_quote_characters == NULL)
- return Qnil;
- return rb_str_new2(rl_completer_quote_characters);
-#else
- rb_notimplement();
-#endif /* READLINE_21_OR_LATER */
-}
-
-static VALUE
-readline_s_set_filename_quote_characters(self, str)
- VALUE self, str;
-{
-#ifdef READLINE_21_OR_LATER
- static char *filename_quote_characters = NULL;
- char *s;
-
- StringValue(str);
- if (filename_quote_characters == NULL) {
- filename_quote_characters =
- ALLOC_N(char, RSTRING(str)->len + 1);
- }
- else {
- REALLOC_N(filename_quote_characters, char, RSTRING(str)->len + 1);
- }
- strncpy(filename_quote_characters,
- RSTRING(str)->ptr, RSTRING(str)->len);
- filename_quote_characters[RSTRING(str)->len] = '\0';
- rl_filename_quote_characters = filename_quote_characters;
-
- return self;
-#else
- rb_notimplement();
-#endif /* READLINE_21_OR_LATER */
-}
-
-static VALUE
-readline_s_get_filename_quote_characters(self, str)
- VALUE self, str;
-{
-#ifdef READLINE_21_OR_LATER
- if (rl_filename_quote_characters == NULL)
- return Qnil;
- return rb_str_new2(rl_filename_quote_characters);
-#else
- rb_notimplement();
-#endif /* READLINE_21_OR_LATER */
-}
-
-static VALUE
-rb_remove_history(index)
- int index;
-{
- HIST_ENTRY *entry;
- VALUE val;
-
- entry = remove_history(index);
- if (entry) {
- val = rb_tainted_str_new2(entry->line);
- free(entry->line);
- free(entry);
- return val;
- }
- return Qnil;
-}
-
-static VALUE
-hist_to_s(self)
- VALUE self;
-{
- return rb_str_new2("HISTORY");
-}
-
-static VALUE
-hist_get(self, index)
- VALUE self;
- VALUE index;
-{
- HISTORY_STATE *state;
- int i;
-
- state = history_get_history_state();
- i = NUM2INT(index);
- if (i < 0) {
- i += state->length;
- }
- if (i < 0 || i > state->length - 1) {
- rb_raise(rb_eIndexError, "Invalid index");
- }
- return rb_tainted_str_new2(state->entries[i]->line);
-}
-
-static VALUE
-hist_set(self, index, str)
- VALUE self;
- VALUE index;
- VALUE str;
-{
- HISTORY_STATE *state;
- VALUE s = str;
- int i;
-
- state = history_get_history_state();
- i = NUM2INT(index);
- if (i < 0) {
- i += state->length;
- }
- if (i < 0 || i > state->length - 1) {
- rb_raise(rb_eIndexError, "Invalid index");
- }
- replace_history_entry(i, StringValuePtr(s), NULL);
- return str;
-}
-
-static VALUE
-hist_push(self, str)
- VALUE self;
- VALUE str;
-{
- add_history(StringValuePtr(str));
- return self;
-}
-
-static VALUE
-hist_push_method(argc, argv, self)
- int argc;
- VALUE *argv;
- VALUE self;
-{
- VALUE str;
-
- while (argc--) {
- str = *argv++;
- add_history(StringValuePtr(str));
- }
- return self;
-}
-
-static VALUE
-hist_pop(self)
- VALUE self;
-{
- HISTORY_STATE *state;
-
- state = history_get_history_state();
- if (state->length > 0) {
- return rb_remove_history(state->length - 1);
- } else {
- return Qnil;
- }
-}
-
-static VALUE
-hist_shift(self)
- VALUE self;
-{
- HISTORY_STATE *state;
-
- state = history_get_history_state();
- if (state->length > 0) {
- return rb_remove_history(0);
- } else {
- return Qnil;
- }
-}
-
-static VALUE
-hist_each(self)
- VALUE self;
-{
- HISTORY_STATE *state;
- int i;
-
- state = history_get_history_state();
- for (i = 0; i < state->length; i++) {
- rb_yield(rb_tainted_str_new2(state->entries[i]->line));
- }
- return self;
-}
-
-static VALUE
-hist_length(self)
- VALUE self;
-{
- HISTORY_STATE *state;
-
- state = history_get_history_state();
- return INT2NUM(state->length);
-}
-
-static VALUE
-hist_empty_p(self)
- VALUE self;
-{
- HISTORY_STATE *state;
-
- state = history_get_history_state();
- if (state->length == 0)
- return Qtrue;
- else
- return Qfalse;
-}
-
-static VALUE
-hist_delete_at(self, index)
- VALUE self;
- VALUE index;
-{
- HISTORY_STATE *state;
- int i;
-
- state = history_get_history_state();
- i = NUM2INT(index);
- if (i < 0)
- i += state->length;
- if (i < 0 || i > state->length - 1) {
- rb_raise(rb_eIndexError, "Invalid index");
- }
- return rb_remove_history(i);
-}
-
-static VALUE
-filename_completion_proc_call(self, str)
- VALUE self;
- VALUE str;
-{
- VALUE result;
- char **matches;
- int i;
-
- matches = rl_completion_matches(StringValuePtr(str),
- rl_filename_completion_function);
- if (matches) {
- result = rb_ary_new();
- for (i = 0; matches[i]; i++) {
- rb_ary_push(result, rb_tainted_str_new2(matches[i]));
- free(matches[i]);
- }
- free(matches);
- if (RARRAY(result)->len >= 2)
- rb_ary_shift(result);
- }
- else {
- result = Qnil;
- }
- return result;
-}
-
-static VALUE
-username_completion_proc_call(self, str)
- VALUE self;
- VALUE str;
-{
- VALUE result;
- char **matches;
- int i;
-
- matches = rl_completion_matches(StringValuePtr(str),
- rl_username_completion_function);
- if (matches) {
- result = rb_ary_new();
- for (i = 0; matches[i]; i++) {
- rb_ary_push(result, rb_tainted_str_new2(matches[i]));
- free(matches[i]);
- }
- free(matches);
- if (RARRAY(result)->len >= 2)
- rb_ary_shift(result);
- }
- else {
- result = Qnil;
- }
- return result;
-}
-
-void
-Init_readline()
-{
- VALUE histary, fcomp, ucomp;
-
- /* Allow conditional parsing of the ~/.inputrc file. */
- rl_readline_name = "Ruby";
-
- using_history();
-
- mReadline = rb_define_module("Readline");
- rb_define_module_function(mReadline, "readline",
- readline_readline, -1);
- rb_define_singleton_method(mReadline, "completion_proc=",
- readline_s_set_completion_proc, 1);
- rb_define_singleton_method(mReadline, "completion_proc",
- readline_s_get_completion_proc, 0);
- rb_define_singleton_method(mReadline, "completion_case_fold=",
- readline_s_set_completion_case_fold, 1);
- rb_define_singleton_method(mReadline, "completion_case_fold",
- readline_s_get_completion_case_fold, 0);
- rb_define_singleton_method(mReadline, "vi_editing_mode",
- readline_s_vi_editing_mode, 0);
- rb_define_singleton_method(mReadline, "emacs_editing_mode",
- readline_s_emacs_editing_mode, 0);
- rb_define_singleton_method(mReadline, "completion_append_character=",
- readline_s_set_completion_append_character, 1);
- rb_define_singleton_method(mReadline, "completion_append_character",
- readline_s_get_completion_append_character, 0);
- rb_define_singleton_method(mReadline, "basic_word_break_characters=",
- readline_s_set_basic_word_break_characters, 1);
- rb_define_singleton_method(mReadline, "basic_word_break_characters",
- readline_s_get_basic_word_break_characters, 0);
- rb_define_singleton_method(mReadline, "completer_word_break_characters=",
- readline_s_set_completer_word_break_characters, 1);
- rb_define_singleton_method(mReadline, "completer_word_break_characters",
- readline_s_get_completer_word_break_characters, 0);
- rb_define_singleton_method(mReadline, "basic_quote_characters=",
- readline_s_set_basic_quote_characters, 1);
- rb_define_singleton_method(mReadline, "basic_quote_characters",
- readline_s_get_basic_quote_characters, 0);
- rb_define_singleton_method(mReadline, "completer_quote_characters=",
- readline_s_set_completer_quote_characters, 1);
- rb_define_singleton_method(mReadline, "completer_quote_characters",
- readline_s_get_completer_quote_characters, 0);
- rb_define_singleton_method(mReadline, "filename_quote_characters=",
- readline_s_set_filename_quote_characters, 1);
- rb_define_singleton_method(mReadline, "filename_quote_characters",
- readline_s_get_filename_quote_characters, 0);
-
- histary = rb_obj_alloc(rb_cObject);
- rb_extend_object(histary, rb_mEnumerable);
- rb_define_singleton_method(histary,"to_s", hist_to_s, 0);
- rb_define_singleton_method(histary,"[]", hist_get, 1);
- rb_define_singleton_method(histary,"[]=", hist_set, 2);
- rb_define_singleton_method(histary,"<<", hist_push, 1);
- rb_define_singleton_method(histary,"push", hist_push_method, -1);
- rb_define_singleton_method(histary,"pop", hist_pop, 0);
- rb_define_singleton_method(histary,"shift", hist_shift, 0);
- rb_define_singleton_method(histary,"each", hist_each, 0);
- rb_define_singleton_method(histary,"length", hist_length, 0);
- rb_define_singleton_method(histary,"size", hist_length, 0);
-
- rb_define_singleton_method(histary,"empty?", hist_empty_p, 0);
- rb_define_singleton_method(histary,"delete_at", hist_delete_at, 1);
- rb_define_const(mReadline, "HISTORY", histary);
-
- fcomp = rb_obj_alloc(rb_cObject);
- rb_define_singleton_method(fcomp, "call",
- filename_completion_proc_call, 1);
- rb_define_const(mReadline, "FILENAME_COMPLETION_PROC", fcomp);
-
- ucomp = rb_obj_alloc(rb_cObject);
- rb_define_singleton_method(ucomp, "call",
- username_completion_proc_call, 1);
- rb_define_const(mReadline, "USERNAME_COMPLETION_PROC", ucomp);
-#if READLINE_21_OR_LATER
- rb_define_const(mReadline, "VERSION", rb_str_new2(rl_library_version));
-#else
- rb_define_const(mReadline, "VERSION",
- rb_str_new2("2.0 or before version"));
-#endif
-
- rl_attempted_completion_function
- = (CPPFunction *) readline_attempted_completion_function;
- rl_event_hook = readline_event;
- rl_clear_signals();
-}
diff --git a/ext/sdbm/.cvsignore b/ext/sdbm/.cvsignore
deleted file mode 100644
index fc802ff1c2..0000000000
--- a/ext/sdbm/.cvsignore
+++ /dev/null
@@ -1,2 +0,0 @@
-Makefile
-mkmf.log
diff --git a/ext/sdbm/MANIFEST b/ext/sdbm/MANIFEST
deleted file mode 100644
index 8888e69ad4..0000000000
--- a/ext/sdbm/MANIFEST
+++ /dev/null
@@ -1,6 +0,0 @@
-MANIFEST
-_sdbm.c
-depend
-extconf.rb
-init.c
-sdbm.h
diff --git a/ext/sdbm/_sdbm.c b/ext/sdbm/_sdbm.c
deleted file mode 100644
index d8bfae80b2..0000000000
--- a/ext/sdbm/_sdbm.c
+++ /dev/null
@@ -1,973 +0,0 @@
-/*
- * sdbm - ndbm work-alike hashed database library
- * based on Per-Aake Larson's Dynamic Hashing algorithms. BIT 18 (1978).
- * author: oz@nexus.yorku.ca
- * status: public domain.
- *
- * core routines
- */
-
-#ifndef lint
-/*char sdbm_rcsid[] = "$Id$";*/
-#endif
-
-#include "sdbm.h"
-#include "config.h"
-
-/*
- * sdbm - ndbm work-alike hashed database library
- * tuning and portability constructs [not nearly enough]
- * author: oz@nexus.yorku.ca
- */
-
-#define BYTESIZ 8
-
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-
-#ifdef BSD42
-#define SEEK_SET L_SET
-#define memset(s,c,n) bzero(s, n) /* only when c is zero */
-#define memcpy(s1,s2,n) bcopy(s2, s1, n)
-#define memcmp(s1,s2,n) bcmp(s1,s2,n)
-#endif
-
-/*
- * important tuning parms (hah)
- */
-
-#define SEEDUPS /* always detect duplicates */
-#define BADMESS /* generate a message for worst case:
- cannot make room after SPLTMAX splits */
-/*
- * misc
- */
-#ifdef DEBUG
-#define debug(x) printf x
-#else
-#define debug(x)
-#endif
-
-#ifdef BIG_E
-#define GET_SHORT(p, i) (((unsigned)((unsigned char *)(p))[(i)*2] << 8) + (((unsigned char *)(p))[(i)*2 + 1]))
-#define PUT_SHORT(p, i, s) (((unsigned char *)(p))[(i)*2] = (unsigned char)((s) >> 8), ((unsigned char *)(p))[(i)*2 + 1] = (unsigned char)(s))
-#else
-#define GET_SHORT(p, i) ((p)[i])
-#define PUT_SHORT(p, i, s) ((p)[i] = (s))
-#endif
-
-/*#include "pair.h"*/
-static int fitpair proto((char *, int));
-static void putpair proto((char *, datum, datum));
-static datum getpair proto((char *, datum));
-static int delpair proto((char *, datum));
-static int chkpage proto((char *));
-static datum getnkey proto((char *, int));
-static void splpage proto((char *, char *, long));
-#ifdef SEEDUPS
-static int duppair proto((char *, datum));
-#endif
-
-#include <stdio.h>
-#include <stdlib.h>
-#ifdef MSDOS
-#include <io.h>
-#endif
-#include <sys/types.h>
-#include <sys/stat.h>
-#ifdef BSD42
-#include <sys/file.h>
-#else
-#include <fcntl.h>
-/*#include <memory.h>*/
-#endif
-#ifndef O_BINARY
-#define O_BINARY 0
-#endif
-
-#include <errno.h>
-#ifndef EPERM
-#define EPERM EACCES
-#endif
-#include <string.h>
-
-#ifdef __STDC__
-#include <stddef.h>
-#endif
-
-#ifndef NULL
-#define NULL 0
-#endif
-
-/*
- * externals
- */
-#if !defined sun && !defined MSDOS && !defined _WIN32 && !defined __CYGWIN__
-extern int errno;
-#endif
-
-/*
- * forward
- */
-static int getdbit proto((DBM *, long));
-static int setdbit proto((DBM *, long));
-static int getpage proto((DBM *, long));
-static datum getnext proto((DBM *));
-static int makroom proto((DBM *, long, int));
-
-/*
- * useful macros
- */
-#define bad(x) ((x).dptr == NULL || (x).dsize < 0)
-#define exhash(item) sdbm_hash((item).dptr, (item).dsize)
-#define ioerr(db) ((db)->flags |= DBM_IOERR)
-
-#define OFF_PAG(off) (long) (off) * PBLKSIZ
-#define OFF_DIR(off) (long) (off) * DBLKSIZ
-
-static long masks[] = {
- 000000000000L, 000000000001L, 000000000003L,
- 000000000007L, 000000000017L, 000000000037L,
- 000000000077L, 000000000177L, 000000000377L,
- 000000000777L, 000000001777L, 000000003777L,
- 000000007777L, 000000017777L, 000000037777L,
- 000000077777L, 000000177777L, 000000377777L,
- 000000777777L, 000001777777L, 000003777777L,
- 000007777777L, 000017777777L, 000037777777L,
- 000077777777L, 000177777777L, 000377777777L,
- 000777777777L, 001777777777L, 003777777777L,
- 007777777777L, 017777777777L
-};
-
-datum nullitem = {NULL, 0};
-
-DBM *
-sdbm_open(file, flags, mode)
-register char *file;
-register int flags;
-register int mode;
-{
- register DBM *db;
- register char *dirname;
- register char *pagname;
- register int n;
-
- if (file == NULL || !*file)
- return errno = EINVAL, (DBM *) NULL;
-/*
- * need space for two seperate filenames
- */
- n = strlen(file) * 2 + strlen(DIRFEXT) + strlen(PAGFEXT) + 2;
-
- if ((dirname = malloc((unsigned) n)) == NULL)
- return errno = ENOMEM, (DBM *) NULL;
-/*
- * build the file names
- */
- dirname = strcat(strcpy(dirname, file), DIRFEXT);
- pagname = strcpy(dirname + strlen(dirname) + 1, file);
- pagname = strcat(pagname, PAGFEXT);
-
- db = sdbm_prep(dirname, pagname, flags, mode);
- free((char *) dirname);
- return db;
-}
-
-DBM *
-sdbm_prep(dirname, pagname, flags, mode)
-char *dirname;
-char *pagname;
-int flags;
-int mode;
-{
- register DBM *db;
- struct stat dstat;
-
- if ((db = (DBM *) malloc(sizeof(DBM))) == NULL)
- return errno = ENOMEM, (DBM *) NULL;
-
- db->flags = 0;
- db->hmask = 0;
- db->blkptr = 0;
- db->keyptr = 0;
-/*
- * adjust user flags so that WRONLY becomes RDWR,
- * as required by this package. Also set our internal
- * flag for RDONLY.
- */
- if (flags & O_WRONLY)
- flags = (flags & ~O_WRONLY) | O_RDWR;
- if (flags & O_RDONLY)
- db->flags = DBM_RDONLY;
-/*
- * open the files in sequence, and stat the dirfile.
- * If we fail anywhere, undo everything, return NULL.
- */
- flags |= O_BINARY;
- if ((db->pagf = open(pagname, flags, mode)) > -1) {
- if ((db->dirf = open(dirname, flags, mode)) > -1) {
-/*
- * need the dirfile size to establish max bit number.
- */
- if (fstat(db->dirf, &dstat) == 0) {
-/*
- * zero size: either a fresh database, or one with a single,
- * unsplit data page: dirpage is all zeros.
- */
- db->dirbno = (!dstat.st_size) ? 0 : -1;
- db->pagbno = -1;
- db->maxbno = dstat.st_size * (long) BYTESIZ;
-
- (void) memset(db->pagbuf, 0, PBLKSIZ);
- (void) memset(db->dirbuf, 0, DBLKSIZ);
- /*
- * success
- */
- return db;
- }
- (void) close(db->dirf);
- }
- (void) close(db->pagf);
- }
- free((char *) db);
- return (DBM *) NULL;
-}
-
-void
-sdbm_close(db)
-register DBM *db;
-{
- if (db == NULL)
- errno = EINVAL;
- else {
- (void) close(db->dirf);
- (void) close(db->pagf);
- free((char *) db);
- }
-}
-
-datum
-sdbm_fetch(db, key)
-register DBM *db;
-datum key;
-{
- if (db == NULL || bad(key))
- return errno = EINVAL, nullitem;
-
- if (getpage(db, exhash(key)))
- return getpair(db->pagbuf, key);
-
- return ioerr(db), nullitem;
-}
-
-int
-sdbm_delete(db, key)
-register DBM *db;
-datum key;
-{
- if (db == NULL || bad(key))
- return errno = EINVAL, -1;
- if (sdbm_rdonly(db))
- return errno = EPERM, -1;
-
- if (getpage(db, exhash(key))) {
- if (!delpair(db->pagbuf, key))
- return -1;
-/*
- * update the page file
- */
- if (lseek(db->pagf, OFF_PAG(db->pagbno), SEEK_SET) < 0
- || write(db->pagf, db->pagbuf, PBLKSIZ) < 0)
- return ioerr(db), -1;
-
- return 0;
- }
-
- return ioerr(db), -1;
-}
-
-int
-sdbm_store(db, key, val, flags)
-register DBM *db;
-datum key;
-datum val;
-int flags;
-{
- int need;
- register long hash;
-
- if (db == NULL || bad(key))
- return errno = EINVAL, -1;
- if (sdbm_rdonly(db))
- return errno = EPERM, -1;
-
- need = key.dsize + val.dsize;
-/*
- * is the pair too big (or too small) for this database ??
- */
- if (need < 0 || need > PAIRMAX)
- return errno = EINVAL, -1;
-
- if (getpage(db, (hash = exhash(key)))) {
-/*
- * if we need to replace, delete the key/data pair
- * first. If it is not there, ignore.
- */
- if (flags == DBM_REPLACE)
- (void) delpair(db->pagbuf, key);
-#ifdef SEEDUPS
- else if (duppair(db->pagbuf, key))
- return 1;
-#endif
-/*
- * if we do not have enough room, we have to split.
- */
- if (!fitpair(db->pagbuf, need))
- if (!makroom(db, hash, need))
- return ioerr(db), -1;
-/*
- * we have enough room or split is successful. insert the key,
- * and update the page file.
- */
- (void) putpair(db->pagbuf, key, val);
-
- if (lseek(db->pagf, OFF_PAG(db->pagbno), SEEK_SET) < 0
- || write(db->pagf, db->pagbuf, PBLKSIZ) < 0)
- return ioerr(db), -1;
- /*
- * success
- */
- return 0;
- }
-
- return ioerr(db), -1;
-}
-
-/*
- * makroom - make room by splitting the overfull page
- * this routine will attempt to make room for SPLTMAX times before
- * giving up.
- */
-static int
-makroom(db, hash, need)
-register DBM *db;
-long hash;
-int need;
-{
- long newp;
- char twin[PBLKSIZ];
-#if defined MSDOS || (defined _WIN32 && !defined __CYGWIN__)
- char zer[PBLKSIZ];
- long oldtail;
-#endif
- char *pag = db->pagbuf;
- char *new = twin;
- register int smax = SPLTMAX;
-
- do {
-/*
- * split the current page
- */
- (void) splpage(pag, new, db->hmask + 1);
-/*
- * address of the new page
- */
- newp = (hash & db->hmask) | (db->hmask + 1);
- debug(("newp: %ld\n", newp));
-/*
- * write delay, read avoidence/cache shuffle:
- * select the page for incoming pair: if key is to go to the new page,
- * write out the previous one, and copy the new one over, thus making
- * it the current page. If not, simply write the new page, and we are
- * still looking at the page of interest. current page is not updated
- * here, as sdbm_store will do so, after it inserts the incoming pair.
- */
-
-#if defined MSDOS || (defined _WIN32 && !defined __CYGWIN__)
- /*
- * Fill hole with 0 if made it.
- * (hole is NOT read as 0)
- */
- oldtail = lseek(db->pagf, 0L, SEEK_END);
- memset(zer, 0, PBLKSIZ);
- while (OFF_PAG(newp) > oldtail) {
- if (lseek(db->pagf, 0L, SEEK_END) < 0 ||
- write(db->pagf, zer, PBLKSIZ) < 0) {
-
- return 0;
- }
- oldtail += PBLKSIZ;
- }
-#endif
-
- if (hash & (db->hmask + 1)) {
- if (lseek(db->pagf, OFF_PAG(db->pagbno), SEEK_SET) < 0
- || write(db->pagf, db->pagbuf, PBLKSIZ) < 0)
- return 0;
- db->pagbno = newp;
- (void) memcpy(pag, new, PBLKSIZ);
- }
- else if (lseek(db->pagf, OFF_PAG(newp), SEEK_SET) < 0
- || write(db->pagf, new, PBLKSIZ) < 0)
- return 0;
-
- if (!setdbit(db, db->curbit))
- return 0;
-/*
- * see if we have enough room now
- */
- if (fitpair(pag, need))
- return 1;
-/*
- * try again... update curbit and hmask as getpage would have
- * done. because of our update of the current page, we do not
- * need to read in anything. BUT we have to write the current
- * [deferred] page out, as the window of failure is too great.
- */
- db->curbit = 2 * db->curbit +
- ((hash & (db->hmask + 1)) ? 2 : 1);
- db->hmask |= (db->hmask + 1);
-
- if (lseek(db->pagf, OFF_PAG(db->pagbno), SEEK_SET) < 0
- || write(db->pagf, db->pagbuf, PBLKSIZ) < 0)
- return 0;
-
- } while (--smax);
-/*
- * if we are here, this is real bad news. After SPLTMAX splits,
- * we still cannot fit the key. say goodnight.
- */
-#ifdef BADMESS
- (void) write(2, "sdbm: cannot insert after SPLTMAX attempts.\n", 44);
-#endif
- return 0;
-
-}
-
-/*
- * the following two routines will break if
- * deletions aren't taken into account. (ndbm bug)
- */
-datum
-sdbm_firstkey(db)
-register DBM *db;
-{
- if (db == NULL)
- return errno = EINVAL, nullitem;
-/*
- * start at page 0
- */
- (void) memset(db->pagbuf, 0, PBLKSIZ);
- if (lseek(db->pagf, OFF_PAG(0), SEEK_SET) < 0
- || read(db->pagf, db->pagbuf, PBLKSIZ) < 0)
- return ioerr(db), nullitem;
- db->pagbno = 0;
- db->blkptr = 0;
- db->keyptr = 0;
-
- return getnext(db);
-}
-
-datum
-sdbm_nextkey(db)
-register DBM *db;
-{
- if (db == NULL)
- return errno = EINVAL, nullitem;
- return getnext(db);
-}
-
-/*
- * all important binary trie traversal
- */
-static int
-getpage(db, hash)
-register DBM *db;
-register long hash;
-{
- register int hbit;
- register long dbit;
- register long pagb;
-
- dbit = 0;
- hbit = 0;
- while (dbit < db->maxbno && getdbit(db, dbit))
- dbit = 2 * dbit + ((hash & ((long) 1 << hbit++)) ? 2 : 1);
-
- debug(("dbit: %d...", dbit));
-
- db->curbit = dbit;
- db->hmask = masks[hbit];
-
- pagb = hash & db->hmask;
-/*
- * see if the block we need is already in memory.
- * note: this lookaside cache has about 10% hit rate.
- */
- if (pagb != db->pagbno) {
-/*
- * note: here, we assume a "hole" is read as 0s.
- * if not, must zero pagbuf first.
- */
- (void) memset(db->pagbuf, 0, PBLKSIZ);
-
- if (lseek(db->pagf, OFF_PAG(pagb), SEEK_SET) < 0
- || read(db->pagf, db->pagbuf, PBLKSIZ) < 0)
- return 0;
- if (!chkpage(db->pagbuf)) {
- return 0;
- }
- db->pagbno = pagb;
-
- debug(("pag read: %d\n", pagb));
- }
- return 1;
-}
-
-static int
-getdbit(db, dbit)
-register DBM *db;
-register long dbit;
-{
- register long c;
- register long dirb;
-
- c = dbit / BYTESIZ;
- dirb = c / DBLKSIZ;
-
- if (dirb != db->dirbno) {
- if (lseek(db->dirf, OFF_DIR(dirb), SEEK_SET) < 0
- || read(db->dirf, db->dirbuf, DBLKSIZ) < 0)
- return 0;
- db->dirbno = dirb;
-
- debug(("dir read: %d\n", dirb));
- }
-
- return db->dirbuf[c % DBLKSIZ] & (1 << (dbit % BYTESIZ));
-}
-
-static int
-setdbit(db, dbit)
-register DBM *db;
-register long dbit;
-{
- register long c;
- register long dirb;
-
- c = dbit / BYTESIZ;
- dirb = c / DBLKSIZ;
-
- if (dirb != db->dirbno) {
- if (lseek(db->dirf, OFF_DIR(dirb), SEEK_SET) < 0
- || read(db->dirf, db->dirbuf, DBLKSIZ) < 0)
- return 0;
- db->dirbno = dirb;
-
- debug(("dir read: %d\n", dirb));
- }
-
- db->dirbuf[c % DBLKSIZ] |= (1 << (dbit % BYTESIZ));
-
- if (dbit >= db->maxbno)
- db->maxbno += (long) DBLKSIZ * BYTESIZ;
-
- if (lseek(db->dirf, OFF_DIR(dirb), SEEK_SET) < 0
- || write(db->dirf, db->dirbuf, DBLKSIZ) < 0)
- return 0;
-
- return 1;
-}
-
-/*
- * getnext - get the next key in the page, and if done with
- * the page, try the next page in sequence
- */
-static datum
-getnext(db)
-register DBM *db;
-{
- datum key;
-
- for (;;) {
- db->keyptr++;
- key = getnkey(db->pagbuf, db->keyptr);
- if (key.dptr != NULL)
- return key;
-/*
- * we either run out, or there is nothing on this page..
- * try the next one... If we lost our position on the
- * file, we will have to seek.
- */
- db->keyptr = 0;
- if (db->pagbno != db->blkptr++)
- if (lseek(db->pagf, OFF_PAG(db->blkptr), SEEK_SET) < 0)
- break;
- db->pagbno = db->blkptr;
- if (read(db->pagf, db->pagbuf, PBLKSIZ) <= 0)
- break;
- if (!chkpage(db->pagbuf)) {
- break;
- }
- }
-
- return ioerr(db), nullitem;
-}
-
-/* pair.c */
-/*
- * sdbm - ndbm work-alike hashed database library
- * based on Per-Aake Larson's Dynamic Hashing algorithms. BIT 18 (1978).
- * author: oz@nexus.yorku.ca
- * status: public domain.
- *
- * page-level routines
- */
-
-#ifndef lint
-/*char pair_rcsid[] = "$Id$";*/
-#endif
-
-#ifndef BSD42
-/*#include <memory.h>*/
-#endif
-
-#define exhash(item) sdbm_hash((item).dptr, (item).dsize)
-
-/*
- * forward
- */
-static int seepair proto((char *, int, char *, int));
-
-/*
- * page format:
- * +------------------------------+
- * ino | n | keyoff | datoff | keyoff |
- * +------------+--------+--------+
- * | datoff | - - - ----> |
- * +--------+---------------------+
- * | F R E E A R E A |
- * +--------------+---------------+
- * | <---- - - - | data |
- * +--------+-----+----+----------+
- * | key | data | key |
- * +--------+----------+----------+
- *
- * calculating the offsets for free area: if the number
- * of entries (ino[0]) is zero, the offset to the END of
- * the free area is the block size. Otherwise, it is the
- * nth (ino[ino[0]]) entry's offset.
- */
-
-static int
-fitpair(pag, need)
-char *pag;
-int need;
-{
- register int n;
- register int off;
- register int free;
- register short *ino = (short *) pag;
-
- off = ((n = GET_SHORT(ino,0)) > 0) ? GET_SHORT(ino,n) : PBLKSIZ;
- free = off - (n + 1) * sizeof(short);
- need += 2 * sizeof(short);
-
- debug(("free %d need %d\n", free, need));
-
- return need <= free;
-}
-
-static void
-putpair(pag, key, val)
-char *pag;
-datum key;
-datum val;
-{
- register int n;
- register int off;
- register short *ino = (short *) pag;
-
- off = ((n = GET_SHORT(ino,0)) > 0) ? GET_SHORT(ino,n) : PBLKSIZ;
-/*
- * enter the key first
- */
- off -= key.dsize;
- if (key.dsize)
- (void) memcpy(pag + off, key.dptr, key.dsize);
- PUT_SHORT(ino,n + 1,off);
-/*
- * now the data
- */
- off -= val.dsize;
- if (val.dsize)
- (void) memcpy(pag + off, val.dptr, val.dsize);
- PUT_SHORT(ino,n + 2,off);
-/*
- * adjust item count
- */
- PUT_SHORT(ino,0,GET_SHORT(ino,0) + 2);
-}
-
-static datum
-getpair(pag, key)
-char *pag;
-datum key;
-{
- register int i;
- register int n;
- datum val;
- register short *ino = (short *) pag;
-
- if ((n = GET_SHORT(ino,0)) == 0)
- return nullitem;
-
- if ((i = seepair(pag, n, key.dptr, key.dsize)) == 0)
- return nullitem;
-
- val.dptr = pag + GET_SHORT(ino,i + 1);
- val.dsize = GET_SHORT(ino,i) - GET_SHORT(ino,i + 1);
- return val;
-}
-
-#ifdef SEEDUPS
-static int
-duppair(pag, key)
-char *pag;
-datum key;
-{
- register short *ino = (short *) pag;
- return GET_SHORT(ino,0) > 0 &&
- seepair(pag, GET_SHORT(ino,0), key.dptr, key.dsize) > 0;
-}
-#endif
-
-static datum
-getnkey(pag, num)
-char *pag;
-int num;
-{
- datum key;
- register int off;
- register short *ino = (short *) pag;
-
- num = num * 2 - 1;
- if (GET_SHORT(ino,0) == 0 || num > GET_SHORT(ino,0))
- return nullitem;
-
- off = (num > 1) ? GET_SHORT(ino,num - 1) : PBLKSIZ;
-
- key.dptr = pag + GET_SHORT(ino,num);
- key.dsize = off - GET_SHORT(ino,num);
-
- return key;
-}
-
-static int
-delpair(pag, key)
-char *pag;
-datum key;
-{
- register int n;
- register int i;
- register short *ino = (short *) pag;
-
- if ((n = GET_SHORT(ino,0)) == 0)
- return 0;
-
- if ((i = seepair(pag, n, key.dptr, key.dsize)) == 0)
- return 0;
-/*
- * found the key. if it is the last entry
- * [i.e. i == n - 1] we just adjust the entry count.
- * hard case: move all data down onto the deleted pair,
- * shift offsets onto deleted offsets, and adjust them.
- * [note: 0 < i < n]
- */
- if (i < n - 1) {
- register int m;
- register char *dst = pag + (i == 1 ? PBLKSIZ : GET_SHORT(ino,i - 1));
- register char *src = pag + GET_SHORT(ino,i + 1);
- register int zoo = dst - src;
-
- debug(("free-up %d ", zoo));
-/*
- * shift data/keys down
- */
- m = GET_SHORT(ino,i + 1) - GET_SHORT(ino,n);
-#ifdef DUFF
-#define MOVB *--dst = *--src
-
- if (m > 0) {
- register int loop = (m + 8 - 1) >> 3;
-
- switch (m & (8 - 1)) {
- case 0: do {
- MOVB; case 7: MOVB;
- case 6: MOVB; case 5: MOVB;
- case 4: MOVB; case 3: MOVB;
- case 2: MOVB; case 1: MOVB;
- } while (--loop);
- }
- }
-#else
-#ifdef MEMMOVE
- memmove(dst, src, m);
-#else
- while (m--)
- *--dst = *--src;
-#endif
-#endif
-/*
- * adjust offset index up
- */
- while (i < n - 1) {
- PUT_SHORT(ino,i, GET_SHORT(ino,i + 2) + zoo);
- i++;
- }
- }
- PUT_SHORT(ino, 0, GET_SHORT(ino, 0) - 2);
- return 1;
-}
-
-/*
- * search for the key in the page.
- * return offset index in the range 0 < i < n.
- * return 0 if not found.
- */
-static int
-seepair(pag, n, key, siz)
-char *pag;
-register int n;
-register char *key;
-register int siz;
-{
- register int i;
- register int off = PBLKSIZ;
- register short *ino = (short *) pag;
-
- for (i = 1; i < n; i += 2) {
- if (siz == off - GET_SHORT(ino,i) &&
- memcmp(key, pag + GET_SHORT(ino,i), siz) == 0)
- return i;
- off = GET_SHORT(ino,i + 1);
- }
- return 0;
-}
-
-static void
-splpage(pag, new, sbit)
-char *pag;
-char *new;
-long sbit;
-{
- datum key;
- datum val;
-
- register int n;
- register int off = PBLKSIZ;
- char cur[PBLKSIZ];
- register short *ino = (short *) cur;
-
- (void) memcpy(cur, pag, PBLKSIZ);
- (void) memset(pag, 0, PBLKSIZ);
- (void) memset(new, 0, PBLKSIZ);
-
- n = GET_SHORT(ino,0);
- for (ino++; n > 0; ino += 2) {
- key.dptr = cur + GET_SHORT(ino,0);
- key.dsize = off - GET_SHORT(ino,0);
- val.dptr = cur + GET_SHORT(ino,1);
- val.dsize = GET_SHORT(ino,0) - GET_SHORT(ino,1);
-/*
- * select the page pointer (by looking at sbit) and insert
- */
- (void) putpair((exhash(key) & sbit) ? new : pag, key, val);
-
- off = GET_SHORT(ino,1);
- n -= 2;
- }
-
- debug(("%d split %d/%d\n", ((short *) cur)[0] / 2,
- ((short *) new)[0] / 2,
- ((short *) pag)[0] / 2));
-}
-
-/*
- * check page sanity:
- * number of entries should be something
- * reasonable, and all offsets in the index should be in order.
- * this could be made more rigorous.
- */
-static int
-chkpage(pag)
-char *pag;
-{
- register int n;
- register int off;
- register short *ino = (short *) pag;
-
- if ((n = GET_SHORT(ino,0)) < 0 || n > PBLKSIZ / sizeof(short))
- return 0;
-
- if (n > 0) {
- off = PBLKSIZ;
- for (ino++; n > 0; ino += 2) {
- if (GET_SHORT(ino,0) > off || GET_SHORT(ino,1) > off ||
- GET_SHORT(ino,1) > GET_SHORT(ino,0))
- return 0;
- off = GET_SHORT(ino,1);
- n -= 2;
- }
- }
- return 1;
-}
-
-/* hash.c */
-/*
- * sdbm - ndbm work-alike hashed database library
- * based on Per-Aake Larson's Dynamic Hashing algorithms. BIT 18 (1978).
- * author: oz@nexus.yorku.ca
- * status: public domain. keep it that way.
- *
- * hashing routine
- */
-
-/*
- * polynomial conversion ignoring overflows
- * [this seems to work remarkably well, in fact better
- * then the ndbm hash function. Replace at your own risk]
- * use: 65599 nice.
- * 65587 even better.
- */
-long
-sdbm_hash(str, len)
-register char *str;
-register int len;
-{
- register unsigned long n = 0;
-
-#ifdef DUFF
-
-#define HASHC n = *str++ + 65599 * n
-
- if (len > 0) {
- register int loop = (len + 8 - 1) >> 3;
-
- switch(len & (8 - 1)) {
- case 0: do {
- HASHC; case 7: HASHC;
- case 6: HASHC; case 5: HASHC;
- case 4: HASHC; case 3: HASHC;
- case 2: HASHC; case 1: HASHC;
- } while (--loop);
- }
-
- }
-#else
- while (len--)
- n = ((*str++) & 255) + 65587L * n;
-#endif
- return n;
-}
diff --git a/ext/sdbm/depend b/ext/sdbm/depend
deleted file mode 100644
index 1d8b13d13f..0000000000
--- a/ext/sdbm/depend
+++ /dev/null
@@ -1,2 +0,0 @@
-_sdbm.o: _sdbm.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h
-init.o: init.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h
diff --git a/ext/sdbm/extconf.rb b/ext/sdbm/extconf.rb
deleted file mode 100644
index cc6c8cefd1..0000000000
--- a/ext/sdbm/extconf.rb
+++ /dev/null
@@ -1,3 +0,0 @@
-require 'mkmf'
-
-create_makefile("sdbm")
diff --git a/ext/sdbm/init.c b/ext/sdbm/init.c
deleted file mode 100644
index 5412dd8452..0000000000
--- a/ext/sdbm/init.c
+++ /dev/null
@@ -1,761 +0,0 @@
-/************************************************
-
- sdbminit.c -
-
- $Author$
- $Date$
- created at: Fri May 7 08:34:24 JST 1999
-
- Copyright (C) 1995-2001 Yukihiro Matsumoto
-
-************************************************/
-
-#include "ruby.h"
-
-#include "sdbm.h"
-#include <fcntl.h>
-#include <errno.h>
-
-static VALUE rb_cDBM, rb_eDBMError;
-
-struct dbmdata {
- int di_size;
- DBM *di_dbm;
-};
-
-static void
-closed_sdbm()
-{
- rb_raise(rb_eDBMError, "closed SDBM file");
-}
-
-#define GetDBM(obj, dbmp) {\
- Data_Get_Struct(obj, struct dbmdata, dbmp);\
- if (dbmp->di_dbm == 0) closed_sdbm();\
-}
-
-static void
-free_sdbm(dbmp)
- struct dbmdata *dbmp;
-{
-
- if (dbmp->di_dbm) sdbm_close(dbmp->di_dbm);
- free(dbmp);
-}
-
-static VALUE
-fsdbm_close(obj)
- VALUE obj;
-{
- struct dbmdata *dbmp;
-
- GetDBM(obj, dbmp);
- sdbm_close(dbmp->di_dbm);
- dbmp->di_dbm = 0;
-
- return Qnil;
-}
-
-static VALUE
-fsdbm_s_new(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- VALUE obj = Data_Wrap_Struct(klass, 0, free_sdbm, 0);
- rb_obj_call_init(obj, argc, argv);
- return obj;
-}
-
-static VALUE
-fsdbm_initialize(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- VALUE file, vmode;
- DBM *dbm;
- struct dbmdata *dbmp;
- int mode;
-
- if (rb_scan_args(argc, argv, "11", &file, &vmode) == 1) {
- mode = 0666; /* default value */
- }
- else if (NIL_P(vmode)) {
- mode = -1; /* return nil if DB not exist */
- }
- else {
- mode = NUM2INT(vmode);
- }
- SafeStringValue(file);
-
- dbm = 0;
- if (mode >= 0)
- dbm = sdbm_open(RSTRING(file)->ptr, O_RDWR|O_CREAT, mode);
- if (!dbm)
- dbm = sdbm_open(RSTRING(file)->ptr, O_RDWR, 0);
- if (!dbm)
- dbm = sdbm_open(RSTRING(file)->ptr, O_RDONLY, 0);
-
- if (!dbm) {
- if (mode == -1) return Qnil;
- rb_sys_fail(RSTRING(file)->ptr);
- }
-
- dbmp = ALLOC(struct dbmdata);
- DATA_PTR(obj) = dbmp;
- dbmp->di_dbm = dbm;
- dbmp->di_size = -1;
-
- return obj;
-}
-
-static VALUE
-fsdbm_s_open(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- VALUE obj = Data_Wrap_Struct(klass, 0, free_sdbm, 0);
-
- if (NIL_P(fsdbm_initialize(argc, argv, obj))) {
- return Qnil;
- }
-
- if (rb_block_given_p()) {
- return rb_ensure(rb_yield, obj, fsdbm_close, obj);
- }
-
- return obj;
-}
-
-static VALUE
-fsdbm_fetch(obj, keystr, ifnone)
- VALUE obj, keystr, ifnone;
-{
- datum key, value;
- struct dbmdata *dbmp;
- DBM *dbm;
-
- StringValue(keystr);
- key.dptr = RSTRING(keystr)->ptr;
- key.dsize = RSTRING(keystr)->len;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- value = sdbm_fetch(dbm, key);
- if (value.dptr == 0) {
- if (ifnone == Qnil && rb_block_given_p())
- return rb_yield(rb_tainted_str_new(key.dptr, key.dsize));
- return ifnone;
- }
- return rb_tainted_str_new(value.dptr, value.dsize);
-}
-
-static VALUE
-fsdbm_aref(obj, keystr)
- VALUE obj, keystr;
-{
- return fsdbm_fetch(obj, keystr, Qnil);
-}
-
-static VALUE
-fsdbm_fetch_m(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- VALUE keystr, valstr, ifnone;
-
- rb_scan_args(argc, argv, "11", &keystr, &ifnone);
- valstr = fsdbm_fetch(obj, keystr, ifnone);
- if (argc == 1 && !rb_block_given_p() && NIL_P(valstr))
- rb_raise(rb_eIndexError, "key not found");
-
- return valstr;
-}
-
-static VALUE
-fsdbm_index(obj, valstr)
- VALUE obj, valstr;
-{
- datum key, val;
- struct dbmdata *dbmp;
- DBM *dbm;
-
- StringValue(valstr);
- val.dptr = RSTRING(valstr)->ptr;
- val.dsize = RSTRING(valstr)->len;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) {
- val = sdbm_fetch(dbm, key);
- if (val.dsize == RSTRING(valstr)->len &&
- memcmp(val.dptr, RSTRING(valstr)->ptr, val.dsize) == 0)
- return rb_tainted_str_new(key.dptr, key.dsize);
- }
- return Qnil;
-}
-
-static VALUE
-fsdbm_indexes(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- VALUE new;
- int i;
-
- new = rb_ary_new2(argc);
- for (i=0; i<argc; i++) {
- rb_ary_push(new, fsdbm_fetch(obj, argv[i]));
- }
-
- return new;
-}
-
-static VALUE
-fsdbm_select(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- VALUE new = rb_ary_new2(argc);
- int i;
-
- if (rb_block_given_p()) {
- datum key, val;
- DBM *dbm;
- struct dbmdata *dbmp;
- VALUE keystr, valstr;
-
- if (argc > 0) {
- rb_raise(rb_eArgError, "wrong number arguments(%d for 0)", argc);
- }
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) {
- VALUE assoc;
- val = sdbm_fetch(dbm, key);
- assoc = rb_assoc_new(rb_tainted_str_new(key.dptr, key.dsize),
- rb_tainted_str_new(val.dptr, val.dsize));
- if (RTEST(rb_yield(assoc)))
- rb_ary_push(new, assoc);
- }
- }
- else {
- for (i=0; i<argc; i++) {
- rb_ary_push(new, fsdbm_fetch(obj, argv[i]));
- }
- }
-
- return new;
-}
-
-static VALUE
-fsdbm_delete(obj, keystr)
- VALUE obj, keystr;
-{
- datum key, value;
- struct dbmdata *dbmp;
- DBM *dbm;
- VALUE valstr;
-
- rb_secure(4);
- StringValue(keystr);
- key.dptr = RSTRING(keystr)->ptr;
- key.dsize = RSTRING(keystr)->len;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- dbmp->di_size = -1;
-
- value = sdbm_fetch(dbm, key);
- if (value.dptr == 0) {
- if (rb_block_given_p()) return rb_yield(keystr);
- return Qnil;
- }
-
- /* need to save value before sdbm_delete() */
- valstr = rb_tainted_str_new(value.dptr, value.dsize);
-
- if (sdbm_delete(dbm, key)) {
- dbmp->di_size = -1;
- rb_raise(rb_eDBMError, "dbm_delete failed");
- }
- else if (dbmp->di_size >= 0) {
- dbmp->di_size--;
- }
- return valstr;
-}
-
-static VALUE
-fsdbm_shift(obj)
- VALUE obj;
-{
- datum key, val;
- struct dbmdata *dbmp;
- DBM *dbm;
- VALUE keystr, valstr;
-
- rb_secure(4);
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- key = sdbm_firstkey(dbm);
- if (!key.dptr) return Qnil;
- val = sdbm_fetch(dbm, key);
- keystr = rb_tainted_str_new(key.dptr, key.dsize);
- valstr = rb_tainted_str_new(val.dptr, val.dsize);
- sdbm_delete(dbm, key);
- if (dbmp->di_size >= 0) {
- dbmp->di_size--;
- }
-
- return rb_assoc_new(keystr, valstr);
-}
-
-static VALUE
-fsdbm_delete_if(obj)
- VALUE obj;
-{
- datum key, val;
- struct dbmdata *dbmp;
- DBM *dbm;
- VALUE keystr, valstr;
- VALUE ret, ary = rb_ary_new();
- int i, status = 0, n;
-
- rb_secure(4);
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- n = dbmp->di_size;
- dbmp->di_size = -1;
- for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) {
- val = sdbm_fetch(dbm, key);
- keystr = rb_tainted_str_new(key.dptr, key.dsize);
- valstr = rb_tainted_str_new(val.dptr, val.dsize);
- ret = rb_protect(rb_yield, rb_assoc_new(rb_str_dup(keystr), valstr), &status);
- if (status != 0) break;
- if (RTEST(ret)) rb_ary_push(ary, keystr);
- }
-
- for (i = 0; i < RARRAY(ary)->len; i++) {
- keystr = RARRAY(ary)->ptr[i];
- key.dptr = RSTRING(keystr)->ptr;
- key.dsize = RSTRING(keystr)->len;
- if (sdbm_delete(dbm, key)) {
- rb_raise(rb_eDBMError, "sdbm_delete failed");
- }
- }
- if (status) rb_jump_tag(status);
- if (n > 0) dbmp->di_size = n - RARRAY(ary)->len;
-
- return obj;
-}
-
-static VALUE
-fsdbm_clear(obj)
- VALUE obj;
-{
- datum key;
- struct dbmdata *dbmp;
- DBM *dbm;
-
- rb_secure(4);
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- dbmp->di_size = -1;
- while (key = sdbm_firstkey(dbm), key.dptr) {
- if (sdbm_delete(dbm, key)) {
- rb_raise(rb_eDBMError, "sdbm_delete failed");
- }
- }
- dbmp->di_size = 0;
-
- return obj;
-}
-
-static VALUE
-fsdbm_invert(obj)
- VALUE obj;
-{
- datum key, val;
- struct dbmdata *dbmp;
- DBM *dbm;
- VALUE keystr, valstr;
- VALUE hash = rb_hash_new();
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) {
- val = sdbm_fetch(dbm, key);
- keystr = rb_tainted_str_new(key.dptr, key.dsize);
- valstr = rb_tainted_str_new(val.dptr, val.dsize);
- rb_hash_aset(hash, valstr, keystr);
- }
- return hash;
-}
-
-static VALUE
-each_pair(obj)
- VALUE obj;
-{
- return rb_funcall(obj, rb_intern("each_pair"), 0, 0);
-}
-
-static VALUE fsdbm_store _((VALUE,VALUE,VALUE));
-
-static VALUE
-update_i(pair, dbm)
- VALUE pair, dbm;
-{
- Check_Type(pair, T_ARRAY);
- if (RARRAY(pair)->len < 2) {
- rb_raise(rb_eArgError, "pair must be [key, value]");
- }
- fsdbm_store(dbm, RARRAY(pair)->ptr[0], RARRAY(pair)->ptr[1]);
- return Qnil;
-}
-
-static VALUE
-fsdbm_update(obj, other)
- VALUE obj, other;
-{
- rb_iterate(each_pair, other, update_i, obj);
- return obj;
-}
-
-static VALUE
-fsdbm_replace(obj, other)
- VALUE obj, other;
-{
- fsdbm_clear(obj);
- rb_iterate(each_pair, other, update_i, obj);
- return obj;
-}
-
-static VALUE
-fsdbm_store(obj, keystr, valstr)
- VALUE obj, keystr, valstr;
-{
- datum key, val;
- struct dbmdata *dbmp;
- DBM *dbm;
-
- if (valstr == Qnil) {
- fsdbm_delete(obj, keystr);
- return Qnil;
- }
-
- rb_secure(4);
- keystr = rb_obj_as_string(keystr);
-
- key.dptr = RSTRING(keystr)->ptr;
- key.dsize = RSTRING(keystr)->len;
-
- if (NIL_P(valstr)) return fsdbm_delete(obj, keystr);
-
- valstr = rb_obj_as_string(valstr);
- val.dptr = RSTRING(valstr)->ptr;
- val.dsize = RSTRING(valstr)->len;
-
- GetDBM(obj, dbmp);
- dbmp->di_size = -1;
- dbm = dbmp->di_dbm;
- if (sdbm_store(dbm, key, val, DBM_REPLACE)) {
-#ifdef HAVE_DBM_CLAERERR
- sdbm_clearerr(dbm);
-#endif
- if (errno == EPERM) rb_sys_fail(0);
- rb_raise(rb_eDBMError, "sdbm_store failed");
- }
-
- return valstr;
-}
-
-static VALUE
-fsdbm_length(obj)
- VALUE obj;
-{
- datum key;
- struct dbmdata *dbmp;
- DBM *dbm;
- int i = 0;
-
- GetDBM(obj, dbmp);
- if (dbmp->di_size > 0) return INT2FIX(dbmp->di_size);
- dbm = dbmp->di_dbm;
-
- for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) {
- i++;
- }
- dbmp->di_size = i;
-
- return INT2FIX(i);
-}
-
-static VALUE
-fsdbm_empty_p(obj)
- VALUE obj;
-{
- datum key;
- struct dbmdata *dbmp;
- DBM *dbm;
- int i = 0;
-
- GetDBM(obj, dbmp);
- if (dbmp->di_size < 0) {
- dbm = dbmp->di_dbm;
-
- for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) {
- i++;
- }
- }
- else {
- i = dbmp->di_size;
- }
- if (i == 0) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-fsdbm_each_value(obj)
- VALUE obj;
-{
- datum key, val;
- struct dbmdata *dbmp;
- DBM *dbm;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) {
- val = sdbm_fetch(dbm, key);
- rb_yield(rb_tainted_str_new(val.dptr, val.dsize));
- }
- return obj;
-}
-
-static VALUE
-fsdbm_each_key(obj)
- VALUE obj;
-{
- datum key;
- struct dbmdata *dbmp;
- DBM *dbm;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) {
- rb_yield(rb_tainted_str_new(key.dptr, key.dsize));
- }
- return obj;
-}
-
-static VALUE
-fsdbm_each_pair(obj)
- VALUE obj;
-{
- datum key, val;
- DBM *dbm;
- struct dbmdata *dbmp;
- VALUE keystr, valstr;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) {
- val = sdbm_fetch(dbm, key);
- keystr = rb_tainted_str_new(key.dptr, key.dsize);
- valstr = rb_tainted_str_new(val.dptr, val.dsize);
- rb_yield(rb_assoc_new(keystr, valstr));
- }
-
- return obj;
-}
-
-static VALUE
-fsdbm_keys(obj)
- VALUE obj;
-{
- datum key;
- struct dbmdata *dbmp;
- DBM *dbm;
- VALUE ary;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- ary = rb_ary_new();
- for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) {
- rb_ary_push(ary, rb_tainted_str_new(key.dptr, key.dsize));
- }
-
- return ary;
-}
-
-static VALUE
-fsdbm_values(obj)
- VALUE obj;
-{
- datum key, val;
- struct dbmdata *dbmp;
- DBM *dbm;
- VALUE ary;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- ary = rb_ary_new();
- for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) {
- val = sdbm_fetch(dbm, key);
- rb_ary_push(ary, rb_tainted_str_new(val.dptr, val.dsize));
- }
-
- return ary;
-}
-
-static VALUE
-fsdbm_has_key(obj, keystr)
- VALUE obj, keystr;
-{
- datum key, val;
- struct dbmdata *dbmp;
- DBM *dbm;
-
- StringValue(keystr);
- key.dptr = RSTRING(keystr)->ptr;
- key.dsize = RSTRING(keystr)->len;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- val = sdbm_fetch(dbm, key);
- if (val.dptr) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-fsdbm_has_value(obj, valstr)
- VALUE obj, valstr;
-{
- datum key, val;
- struct dbmdata *dbmp;
- DBM *dbm;
-
- StringValue(valstr);
- val.dptr = RSTRING(valstr)->ptr;
- val.dsize = RSTRING(valstr)->len;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) {
- val = sdbm_fetch(dbm, key);
- if (val.dsize == RSTRING(valstr)->len &&
- memcmp(val.dptr, RSTRING(valstr)->ptr, val.dsize) == 0)
- return Qtrue;
- }
- return Qfalse;
-}
-
-static VALUE
-fsdbm_to_a(obj)
- VALUE obj;
-{
- datum key, val;
- struct dbmdata *dbmp;
- DBM *dbm;
- VALUE ary;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- ary = rb_ary_new();
- for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) {
- val = sdbm_fetch(dbm, key);
- rb_ary_push(ary, rb_assoc_new(rb_tainted_str_new(key.dptr, key.dsize),
- rb_tainted_str_new(val.dptr, val.dsize)));
- }
-
- return ary;
-}
-
-static VALUE
-fsdbm_to_hash(obj)
- VALUE obj;
-{
- datum key, val;
- struct dbmdata *dbmp;
- DBM *dbm;
- VALUE hash;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- hash = rb_hash_new();
- for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) {
- val = sdbm_fetch(dbm, key);
- rb_hash_aset(hash, rb_tainted_str_new(key.dptr, key.dsize),
- rb_tainted_str_new(val.dptr, val.dsize));
- }
-
- return hash;
-}
-
-static VALUE
-fsdbm_reject(obj)
- VALUE obj;
-{
- return rb_hash_delete_if(fsdbm_to_hash(obj));
-}
-
-void
-Init_sdbm()
-{
- rb_cDBM = rb_define_class("SDBM", rb_cObject);
- rb_eDBMError = rb_define_class("SDBMError", rb_eStandardError);
- rb_include_module(rb_cDBM, rb_mEnumerable);
-
- rb_define_singleton_method(rb_cDBM, "new", fsdbm_s_new, -1);
- rb_define_singleton_method(rb_cDBM, "open", fsdbm_s_open, -1);
-
- rb_define_method(rb_cDBM, "initialize", fsdbm_initialize, -1);
- rb_define_method(rb_cDBM, "close", fsdbm_close, 0);
- rb_define_method(rb_cDBM, "[]", fsdbm_aref, 1);
- rb_define_method(rb_cDBM, "fetch", fsdbm_fetch_m, -1);
- rb_define_method(rb_cDBM, "[]=", fsdbm_store, 2);
- rb_define_method(rb_cDBM, "store", fsdbm_store, 2);
- rb_define_method(rb_cDBM, "index", fsdbm_index, 1);
- rb_define_method(rb_cDBM, "indexes", fsdbm_indexes, -1);
- rb_define_method(rb_cDBM, "indices", fsdbm_indexes, -1);
- rb_define_method(rb_cDBM, "select", fsdbm_select, -1);
- rb_define_method(rb_cDBM, "length", fsdbm_length, 0);
- rb_define_method(rb_cDBM, "size", fsdbm_length, 0);
- rb_define_method(rb_cDBM, "empty?", fsdbm_empty_p, 0);
- rb_define_method(rb_cDBM, "each", fsdbm_each_pair, 0);
- rb_define_method(rb_cDBM, "each_value", fsdbm_each_value, 0);
- rb_define_method(rb_cDBM, "each_key", fsdbm_each_key, 0);
- rb_define_method(rb_cDBM, "each_pair", fsdbm_each_pair, 0);
- rb_define_method(rb_cDBM, "keys", fsdbm_keys, 0);
- rb_define_method(rb_cDBM, "values", fsdbm_values, 0);
- rb_define_method(rb_cDBM, "shift", fsdbm_shift, 0);
- rb_define_method(rb_cDBM, "delete", fsdbm_delete, 1);
- rb_define_method(rb_cDBM, "delete_if", fsdbm_delete_if, 0);
- rb_define_method(rb_cDBM, "reject!", fsdbm_delete_if, 0);
- rb_define_method(rb_cDBM, "reject", fsdbm_reject, 0);
- rb_define_method(rb_cDBM, "clear", fsdbm_clear, 0);
- rb_define_method(rb_cDBM,"invert", fsdbm_invert, 0);
- rb_define_method(rb_cDBM,"update", fsdbm_update, 1);
- rb_define_method(rb_cDBM,"replace", fsdbm_replace, 1);
-
- rb_define_method(rb_cDBM, "include?", fsdbm_has_key, 1);
- rb_define_method(rb_cDBM, "has_key?", fsdbm_has_key, 1);
- rb_define_method(rb_cDBM, "member?", fsdbm_has_key, 1);
- rb_define_method(rb_cDBM, "has_value?", fsdbm_has_value, 1);
- rb_define_method(rb_cDBM, "key?", fsdbm_has_key, 1);
- rb_define_method(rb_cDBM, "value?", fsdbm_has_value, 1);
-
- rb_define_method(rb_cDBM, "to_a", fsdbm_to_a, 0);
- rb_define_method(rb_cDBM, "to_hash", fsdbm_to_hash, 0);
-}
diff --git a/ext/sdbm/sdbm.h b/ext/sdbm/sdbm.h
deleted file mode 100644
index ce8f54c4d4..0000000000
--- a/ext/sdbm/sdbm.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * sdbm - ndbm work-alike hashed database library
- * based on Per-Ake Larson's Dynamic Hashing algorithms. BIT 18 (1978).
- * author: oz@nexus.yorku.ca
- * status: public domain.
- */
-#ifndef _SDBM_H_
-#define _SDBM_H_
-
-#define DBLKSIZ 4096
-#define PBLKSIZ 1024
-#define PAIRMAX 1008 /* arbitrary on PBLKSIZ-N */
-#define SPLTMAX 10 /* maximum allowed splits */
- /* for a single insertion */
-#define DIRFEXT ".dir"
-#define PAGFEXT ".pag"
-
-typedef struct {
- int dirf; /* directory file descriptor */
- int pagf; /* page file descriptor */
- int flags; /* status/error flags, see below */
- long maxbno; /* size of dirfile in bits */
- long curbit; /* current bit number */
- long hmask; /* current hash mask */
- long blkptr; /* current block for nextkey */
- int keyptr; /* current key for nextkey */
- long blkno; /* current page to read/write */
- long pagbno; /* current page in pagbuf */
- char pagbuf[PBLKSIZ]; /* page file block buffer */
- long dirbno; /* current block in dirbuf */
- char dirbuf[DBLKSIZ]; /* directory file block buffer */
-} DBM;
-
-#define DBM_RDONLY 0x1 /* data base open read-only */
-#define DBM_IOERR 0x2 /* data base I/O error */
-
-/*
- * utility macros
- */
-#define sdbm_rdonly(db) ((db)->flags & DBM_RDONLY)
-#define sdbm_error(db) ((db)->flags & DBM_IOERR)
-
-#define sdbm_clearerr(db) ((db)->flags &= ~DBM_IOERR) /* ouch */
-
-#define sdbm_dirfno(db) ((db)->dirf)
-#define sdbm_pagfno(db) ((db)->pagf)
-
-typedef struct {
- char *dptr;
- int dsize;
-} datum;
-
-extern datum nullitem;
-
-#if defined(__STDC__) || defined(MSDOS)
-#define proto(p) p
-#else
-#define proto(p) ()
-#endif
-
-/*
- * flags to sdbm_store
- */
-#define DBM_INSERT 0
-#define DBM_REPLACE 1
-
-/*
- * ndbm interface
- */
-extern DBM *sdbm_open proto((char *, int, int));
-extern void sdbm_close proto((DBM *));
-extern datum sdbm_fetch proto((DBM *, datum));
-extern int sdbm_delete proto((DBM *, datum));
-extern int sdbm_store proto((DBM *, datum, datum, int));
-extern datum sdbm_firstkey proto((DBM *));
-extern datum sdbm_nextkey proto((DBM *));
-
-/*
- * other
- */
-extern DBM *sdbm_prep proto((char *, char *, int, int));
-extern long sdbm_hash proto((char *, int));
-
-#endif /* _SDBM_H_ */
diff --git a/ext/sdbm/testsdbm.rb b/ext/sdbm/testsdbm.rb
deleted file mode 100644
index 550b47a008..0000000000
--- a/ext/sdbm/testsdbm.rb
+++ /dev/null
@@ -1,556 +0,0 @@
-require 'runit/testcase'
-require 'runit/cui/testrunner'
-
-if $".grep(/\bsdbm.so\b/).empty?
- begin
- require './sdbm'
- rescue LoadError
- require 'sdbm'
- end
-end
-
-def uname_s
- require 'rbconfig'
- case Config::CONFIG['host_os']
- when 'cygwin'
- require 'Win32API'
- uname = Win32API.new 'cygwin1', 'uname', 'P', 'I'
- utsname = ' ' * 100
- raise 'cannot get system name' if uname.call(utsname) == -1
-
- utsname.unpack('A20' * 5)[0]
- else
- Config::CONFIG['host_os']
- end
-end
-
-SYSTEM = uname_s
-
-class TestSDBM < RUNIT::TestCase
- def setup
- @path = "tmptest_sdbm_"
- assert_instance_of(SDBM, @sdbm = SDBM.new(@path))
- end
- def teardown
- assert_nil(@sdbm.close)
- GC.start
- File.delete *Dir.glob("tmptest_sdbm*").to_a
- p Dir.glob("tmptest_sdbm*") if $DEBUG
- end
-
- def check_size(expect, sdbm=@sdbm)
- assert_equals(expect, sdbm.size)
- n = 0
- sdbm.each { n+=1 }
- assert_equals(expect, n)
- if expect == 0
- assert_equals(true, sdbm.empty?)
- else
- assert_equals(false, sdbm.empty?)
- end
- end
-
- def test_version
- STDERR.print SDBM::VERSION
- end
-
- def test_s_new_has_no_block
- # SDBM.new ignore the block
- foo = true
- assert_instance_of(SDBM, sdbm = SDBM.new("tmptest_sdbm") { foo = false })
- assert_equals(foo, true)
- assert_nil(sdbm.close)
- end
- def test_s_open_no_create
- assert_nil(sdbm = SDBM.open("tmptest_sdbm", nil))
- ensure
- sdbm.close if sdbm
- end
- def test_s_open_with_block
- assert_equals(SDBM.open("tmptest_sdbm") { :foo }, :foo)
- end
-=begin
- # Is it guaranteed on many OS?
- def test_s_open_lock_one_process
- # locking on one process
- assert_instance_of(SDBM, sdbm = SDBM.open("tmptest_sdbm", 0644))
- assert_exception(Errno::EWOULDBLOCK) {
- begin
- SDBM.open("tmptest_sdbm", 0644)
- rescue Errno::EAGAIN
- raise Errno::EWOULDBLOCK
- end
- }
- end
-=end
-
- def test_s_open_nolock
- # sdbm 1.8.0 specific
- if not defined? SDBM::NOLOCK
- return
- end
-
- fork() {
- assert_instance_of(SDBM, sdbm = SDBM.open("tmptest_sdbm", 0644,
- SDBM::NOLOCK))
- sleep 2
- }
- sleep 1
- begin
- sdbm2 = nil
- assert_no_exception(Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EACCES) {
- assert_instance_of(SDBM, sdbm2 = SDBM.open("tmptest_sdbm", 0644))
- }
- ensure
- Process.wait
- sdbm2.close if sdbm2
- end
-
- p Dir.glob("tmptest_sdbm*") if $DEBUG
-
- fork() {
- assert_instance_of(SDBM, sdbm = SDBM.open("tmptest_sdbm", 0644))
- sleep 2
- }
- begin
- sleep 1
- sdbm2 = nil
- assert_no_exception(Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EACCES) {
- # this test is failed on Cygwin98 (???)
- assert_instance_of(SDBM, sdbm2 = SDBM.open("tmptest_sdbm", 0644,
- SDBM::NOLOCK))
- }
- ensure
- Process.wait
- sdbm2.close if sdbm2
- end
- end
-
- def test_s_open_error
- assert_instance_of(SDBM, sdbm = SDBM.open("tmptest_sdbm", 0))
- assert_exception(Errno::EACCES) {
- SDBM.open("tmptest_sdbm", 0)
- }
- sdbm.close
- end
-
- def test_close
- assert_instance_of(SDBM, sdbm = SDBM.open("tmptest_sdbm"))
- assert_nil(sdbm.close)
-
- # closed SDBM file
- assert_exception(SDBMError) { sdbm.close }
- end
-
- def test_aref
- assert_equals('bar', @sdbm['foo'] = 'bar')
- assert_equals('bar', @sdbm['foo'])
-
- assert_nil(@sdbm['bar'])
- end
-
- def test_fetch
- assert_equals('bar', @sdbm['foo']='bar')
- assert_equals('bar', @sdbm.fetch('foo'))
-
- # key not found
- assert_exception(IndexError) {
- @sdbm.fetch('bar')
- }
-
- # test for `ifnone' arg
- assert_equals('baz', @sdbm.fetch('bar', 'baz'))
-
- # test for `ifnone' block
- assert_equals('foobar', @sdbm.fetch('bar') {|key| 'foo' + key })
- end
-
- def test_aset
- num = 0
- 2.times {|i|
- assert_equals('foo', @sdbm['foo'] = 'foo')
- assert_equals('foo', @sdbm['foo'])
- assert_equals('bar', @sdbm['foo'] = 'bar')
- assert_equals('bar', @sdbm['foo'])
-
- num += 1 if i == 0
- assert_equals(num, @sdbm.size)
-
- # assign nil
- assert_equals('', @sdbm['bar'] = '')
- assert_equals('', @sdbm['bar'])
-
- num += 1 if i == 0
- assert_equals(num, @sdbm.size)
-
- # empty string
- assert_equals('', @sdbm[''] = '')
- assert_equals('', @sdbm[''])
-
- num += 1 if i == 0
- assert_equals(num, @sdbm.size)
-
- # Fixnum
- assert_equals('200', @sdbm['100'] = '200')
- assert_equals('200', @sdbm['100'])
-
- num += 1 if i == 0
- assert_equals(num, @sdbm.size)
-
- # Big key and value
- assert_equals('y' * 100, @sdbm['x' * 100] = 'y' * 100)
- assert_equals('y' * 100, @sdbm['x' * 100])
-
- num += 1 if i == 0
- assert_equals(num, @sdbm.size)
- }
- end
-
- def test_index
- assert_equals('bar', @sdbm['foo'] = 'bar')
- assert_equals('foo', @sdbm.index('bar'))
- assert_nil(@sdbm['bar'])
- end
-
- def test_indexes
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
- @sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values
- assert_equals(values.reverse, @sdbm.indexes(*keys.reverse))
- end
-
- def test_select
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
- @sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values
- assert_equals(values.reverse, @sdbm.select(*keys.reverse))
- end
-
- def test_select_with_block
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
- @sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values
- ret = @sdbm.select {|k,v|
- assert_equals(k.upcase, v)
- k != "bar"
- }
- assert_equals([['baz', 'BAZ'], ['foo', 'FOO']],
- ret.sort)
- end
-
- def test_length
- num = 10
- assert_equals(0, @sdbm.size)
- num.times {|i|
- i = i.to_s
- @sdbm[i] = i
- }
- assert_equals(num, @sdbm.size)
-
- @sdbm.shift
-
- assert_equals(num - 1, @sdbm.size)
- end
-
- def test_empty?
- assert_equals(true, @sdbm.empty?)
- @sdbm['foo'] = 'FOO'
- assert_equals(false, @sdbm.empty?)
- end
-
- def test_each_pair
- n = 0
- @sdbm.each_pair { n += 1 }
- assert_equals(0, n)
-
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
-
- @sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values
-
- n = 0
- ret = @sdbm.each_pair {|key, val|
- assert_not_nil(i = keys.index(key))
- assert_equals(val, values[i])
-
- n += 1
- }
- assert_equals(keys.size, n)
- assert_equals(@sdbm, ret)
- end
-
- def test_each_value
- n = 0
- @sdbm.each_value { n += 1 }
- assert_equals(0, n)
-
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
-
- @sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values
-
- n = 0
- ret = @sdbm.each_value {|val|
- assert_not_nil(key = @sdbm.index(val))
- assert_not_nil(i = keys.index(key))
- assert_equals(val, values[i])
-
- n += 1
- }
- assert_equals(keys.size, n)
- assert_equals(@sdbm, ret)
- end
-
- def test_each_key
- n = 0
- @sdbm.each_key { n += 1 }
- assert_equals(0, n)
-
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
-
- @sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values
-
- n = 0
- ret = @sdbm.each_key {|key|
- assert_not_nil(i = keys.index(key))
- assert_equals(@sdbm[key], values[i])
-
- n += 1
- }
- assert_equals(keys.size, n)
- assert_equals(@sdbm, ret)
- end
-
- def test_keys
- assert_equals([], @sdbm.keys)
-
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
-
- @sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values
-
- assert_equals(keys.sort, @sdbm.keys.sort)
- assert_equals(values.sort, @sdbm.values.sort)
- end
-
- def test_values
- test_keys
- end
-
- def test_shift
- assert_nil(@sdbm.shift)
- assert_equals(0, @sdbm.size)
-
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
-
- @sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values
-
- ret_keys = []
- ret_values = []
- while ret = @sdbm.shift
- ret_keys.push ret[0]
- ret_values.push ret[1]
-
- assert_equals(keys.size - ret_keys.size, @sdbm.size)
- end
-
- assert_equals(keys.sort, ret_keys.sort)
- assert_equals(values.sort, ret_values.sort)
- end
-
- def test_delete
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
- key = keys[1]
-
- assert_nil(@sdbm.delete(key))
- assert_equals(0, @sdbm.size)
-
- @sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values
-
- assert_equals('BAR', @sdbm.delete(key))
- assert_nil(@sdbm[key])
- assert_equals(2, @sdbm.size)
-
- assert_nil(@sdbm.delete(key))
- end
- def test_delete_with_block
- key = 'no called block'
- @sdbm[key] = 'foo'
- assert_equals('foo', @sdbm.delete(key) {|k| k.replace 'called block'})
- assert_equals('no called block', key)
- assert_equals(0, @sdbm.size)
-
- key = 'no called block'
- assert_equals(:blockval,
- @sdbm.delete(key) {|k| k.replace 'called block'; :blockval})
- assert_equals('called block', key)
- assert_equals(0, @sdbm.size)
- end
-
- def test_delete_if
- v = "0"
- 100.times {@sdbm[v] = v; v = v.next}
-
- ret = @sdbm.delete_if {|key, val| key.to_i < 50}
- assert_equals(@sdbm, ret)
- check_size(50, @sdbm)
-
- ret = @sdbm.delete_if {|key, val| key.to_i >= 50}
- assert_equals(@sdbm, ret)
- check_size(0, @sdbm)
-
- # break
- v = "0"
- 100.times {@sdbm[v] = v; v = v.next}
- check_size(100, @sdbm)
- n = 0;
- @sdbm.delete_if {|key, val|
- break if n > 50
- n+=1
- true
- }
- assert_equals(51, n)
- check_size(49, @sdbm)
-
- @sdbm.clear
-
- # raise
- v = "0"
- 100.times {@sdbm[v] = v; v = v.next}
- check_size(100, @sdbm)
- n = 0;
- begin
- @sdbm.delete_if {|key, val|
- raise "runtime error" if n > 50
- n+=1
- true
- }
- rescue
- end
- assert_equals(51, n)
- check_size(49, @sdbm)
- end
-
- def test_reject
- v = "0"
- 100.times {@sdbm[v] = v; v = v.next}
-
- hash = @sdbm.reject {|key, val| key.to_i < 50}
- assert_instance_of(Hash, hash)
- assert_equals(100, @sdbm.size)
-
- assert_equals(50, hash.size)
- hash.each_pair {|key,val|
- assert_equals(false, key.to_i < 50)
- assert_equals(key, val)
- }
-
- hash = @sdbm.reject {|key, val| key.to_i < 100}
- assert_instance_of(Hash, hash)
- assert_equals(true, hash.empty?)
- end
-
- def test_clear
- v = "1"
- 100.times {v = v.next; @sdbm[v] = v}
-
- assert_equals(@sdbm, @sdbm.clear)
-
- # validate SDBM#size
- i = 0
- @sdbm.each { i += 1 }
- assert_equals(@sdbm.size, i)
- assert_equals(0, i)
- end
-
- def test_invert
- v = "0"
- 100.times {@sdbm[v] = v; v = v.next}
-
- hash = @sdbm.invert
- assert_instance_of(Hash, hash)
- assert_equals(100, hash.size)
- hash.each_pair {|key, val|
- assert_equals(key.to_i, val.to_i)
- }
- end
-
- def test_update
- hash = {}
- v = "0"
- 100.times {v = v.next; hash[v] = v}
-
- @sdbm["101"] = "101"
- @sdbm.update hash
- assert_equals(101, @sdbm.size)
- @sdbm.each_pair {|key, val|
- assert_equals(key.to_i, val.to_i)
- }
- end
-
- def test_replace
- hash = {}
- v = "0"
- 100.times {v = v.next; hash[v] = v}
-
- @sdbm["101"] = "101"
- @sdbm.replace hash
- assert_equals(100, @sdbm.size)
- @sdbm.each_pair {|key, val|
- assert_equals(key.to_i, val.to_i)
- }
- end
-
- def test_haskey?
- assert_equals('bar', @sdbm['foo']='bar')
- assert_equals(true, @sdbm.has_key?('foo'))
- assert_equals(false, @sdbm.has_key?('bar'))
- end
-
- def test_has_value?
- assert_equals('bar', @sdbm['foo']='bar')
- assert_equals(true, @sdbm.has_value?('bar'))
- assert_equals(false, @sdbm.has_value?('foo'))
- end
-
- def test_to_a
- v = "0"
- 100.times {v = v.next; @sdbm[v] = v}
-
- ary = @sdbm.to_a
- assert_instance_of(Array, ary)
- assert_equals(100, ary.size)
- ary.each {|key,val|
- assert_equals(key.to_i, val.to_i)
- }
- end
-
- def test_to_hash
- v = "0"
- 100.times {v = v.next; @sdbm[v] = v}
-
- hash = @sdbm.to_hash
- assert_instance_of(Hash, hash)
- assert_equals(100, hash.size)
- hash.each {|key,val|
- assert_equals(key.to_i, val.to_i)
- }
- end
-end
-
-if $0 == __FILE__
- if ARGV.size == 0
- suite = RUNIT::TestSuite.new
- suite.add_test(TestSDBM.suite)
- else
- suite = RUNIT::TestSuite.new
- ARGV.each do |testmethod|
- suite.add_test(TestSDBM.new(testmethod))
- end
- end
-
- RUNIT::CUI::TestRunner.run(suite)
-end
diff --git a/ext/socket/.cvsignore b/ext/socket/.cvsignore
deleted file mode 100644
index fc802ff1c2..0000000000
--- a/ext/socket/.cvsignore
+++ /dev/null
@@ -1,2 +0,0 @@
-Makefile
-mkmf.log
diff --git a/ext/socket/MANIFEST b/ext/socket/MANIFEST
deleted file mode 100644
index 616d459d92..0000000000
--- a/ext/socket/MANIFEST
+++ /dev/null
@@ -1,8 +0,0 @@
-MANIFEST
-addrinfo.h
-depend
-extconf.rb
-getaddrinfo.c
-getnameinfo.c
-sockport.h
-socket.c
diff --git a/ext/socket/addrinfo.h b/ext/socket/addrinfo.h
deleted file mode 100644
index bd3de72e10..0000000000
--- a/ext/socket/addrinfo.h
+++ /dev/null
@@ -1,170 +0,0 @@
-/*
- * Copyright (C) 1995, 1996, 1997, 1998, and 1999 WIDE Project.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the project nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#ifndef ADDR_INFO_H
-#define ADDR_INFO_H
-#ifndef HAVE_GETADDRINFO
-
-/* special compatibility hack */
-#undef EAI_ADDRFAMILY
-#undef EAI_AGAIN
-#undef EAI_BADFLAGS
-#undef EAI_FAIL
-#undef EAI_FAMILY
-#undef EAI_MEMORY
-#undef EAI_NODATA
-#undef EAI_NONAME
-#undef EAI_SERVICE
-#undef EAI_SOCKTYPE
-#undef EAI_SYSTEM
-#undef EAI_BADHINTS
-#undef EAI_PROTOCOL
-#undef EAI_MAX
-
-#undef AI_PASSIVE
-#undef AI_CANONNAME
-#undef AI_NUMERICHOST
-#undef AI_ALL
-#undef AI_ADDRCONFIG
-#undef AI_V4MAPPED
-#undef AI_DEFAULT
-
-#undef NI_NOFQDN
-#undef NI_NUMERICHOST
-#undef NI_NAMEREQD
-#undef NI_NUMERICSERV
-#undef NI_DGRAM
-
-#define addrinfo addrinfo__compat
-#define getaddrinfo getaddrinfo__compat
-#define getnameinfo getnameinfo__compat
-#define freehostent freehostent__compat
-#define freeaddrinfo freeaddrinfo__compat
-
-#ifndef __P
-# ifdef HAVE_PROTOTYPES
-# define __P(args) args
-# else
-# define __P(args) ()
-# endif
-#endif
-
-/* special compatibility hack -- end*/
-
-
-/*
- * Error return codes from getaddrinfo()
- */
-#define EAI_ADDRFAMILY 1 /* address family for hostname not supported */
-#define EAI_AGAIN 2 /* temporary failure in name resolution */
-#define EAI_BADFLAGS 3 /* invalid value for ai_flags */
-#define EAI_FAIL 4 /* non-recoverable failure in name resolution */
-#define EAI_FAMILY 5 /* ai_family not supported */
-#define EAI_MEMORY 6 /* memory allocation failure */
-#define EAI_NODATA 7 /* no address associated with hostname */
-#define EAI_NONAME 8 /* hostname nor servname provided, or not known */
-#define EAI_SERVICE 9 /* servname not supported for ai_socktype */
-#define EAI_SOCKTYPE 10 /* ai_socktype not supported */
-#define EAI_SYSTEM 11 /* system error returned in errno */
-#define EAI_BADHINTS 12
-#define EAI_PROTOCOL 13
-#define EAI_MAX 14
-
-/*
- * Flag values for getaddrinfo()
- */
-#define AI_PASSIVE 0x00000001 /* get address to use bind() */
-#define AI_CANONNAME 0x00000002 /* fill ai_canonname */
-#define AI_NUMERICHOST 0x00000004 /* prevent name resolution */
-/* valid flags for addrinfo */
-#define AI_MASK (AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST)
-
-#define AI_ALL 0x00000100 /* IPv6 and IPv4-mapped (with AI_V4MAPPED) */
-#define AI_V4MAPPED_CFG 0x00000200 /* accept IPv4-mapped if kernel supports */
-#define AI_ADDRCONFIG 0x00000400 /* only if any address is assigned */
-#define AI_V4MAPPED 0x00000800 /* accept IPv4-mapped IPv6 address */
-/* special recommended flags for getipnodebyname */
-#define AI_DEFAULT (AI_V4MAPPED_CFG | AI_ADDRCONFIG)
-
-/*
- * Constants for getnameinfo()
- */
-#define NI_MAXHOST 1025
-#define NI_MAXSERV 32
-
-/*
- * Flag values for getnameinfo()
- */
-#define NI_NOFQDN 0x00000001
-#define NI_NUMERICHOST 0x00000002
-#define NI_NAMEREQD 0x00000004
-#define NI_NUMERICSERV 0x00000008
-#define NI_DGRAM 0x00000010
-
-struct addrinfo {
- int ai_flags; /* AI_PASSIVE, AI_CANONNAME */
- int ai_family; /* PF_xxx */
- int ai_socktype; /* SOCK_xxx */
- int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */
- size_t ai_addrlen; /* length of ai_addr */
- char *ai_canonname; /* canonical name for hostname */
- struct sockaddr *ai_addr; /* binary address */
- struct addrinfo *ai_next; /* next structure in linked list */
-};
-
-extern int getaddrinfo __P((
- const char *hostname, const char *servname,
- const struct addrinfo *hints,
- struct addrinfo **res));
-
-extern int getnameinfo __P((
- const struct sockaddr *sa,
- size_t salen,
- char *host,
- size_t hostlen,
- char *serv,
- size_t servlen,
- int flags));
-
-extern void freehostent __P((struct hostent *));
-extern void freeaddrent __P((struct addrinfo *));
-#if defined __UCLIBC__
-const
-#endif
-extern char *gai_strerror __P((int));
-
-/* In case there is no definition of offsetof() provided - though any proper
-Standard C system should have one. */
-
-#ifndef offsetof
-#define offsetof(p_type,field) ((size_t)&(((p_type *)0)->field))
-#endif
-
-#endif
-#endif
diff --git a/ext/socket/depend b/ext/socket/depend
deleted file mode 100644
index cca6d4e62a..0000000000
--- a/ext/socket/depend
+++ /dev/null
@@ -1,3 +0,0 @@
-socket.o : socket.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h $(hdrdir)/rubyio.h $(hdrdir)/rubysig.h sockport.h
-getnameinfo.o: getnameinfo.c $(topdir)/config.h addrinfo.h sockport.h
-getaddrinfo.o: getaddrinfo.c $(topdir)/config.h addrinfo.h sockport.h
diff --git a/ext/socket/extconf.rb b/ext/socket/extconf.rb
deleted file mode 100644
index 46557682a7..0000000000
--- a/ext/socket/extconf.rb
+++ /dev/null
@@ -1,386 +0,0 @@
-require 'mkmf'
-
-$CPPFLAGS += " -Dss_family=__ss_family -Dss_len=__ss_len"
-
-def have_struct_member(type, member, header=nil)
- #printf "checking for %s.%s... ", type, member
- #STDOUT.flush
-
- libs = $libs
- src =
- if /mswin32|mingw/ =~ RUBY_PLATFORM
- r = <<"SRC"
-#include <windows.h>
-#include <winsock.h>
-SRC
- else
- ""
- end
- unless header.nil?
- header = [header] unless header.kind_of? Array
- header.each {|h|
- src << <<"SRC"
-#include <#{h}>
-SRC
- }
- end
- src << <<"SRC"
-int main() { return 0; }
-int s = (char *)&((#{type}*)0)->#{member} - (char *)0;
-SRC
- r = try_link(src, libs) # xxx try_compile is not available.
- unless r
- #print "no\n"
- return false
- end
- $defs.push(format("-DHAVE_ST_%s", member.upcase))
- #print "yes\n"
- return true
-end
-
-case RUBY_PLATFORM
-when /mswin32|mingw/
- test_func = "WSACleanup"
- have_library("wsock32", "WSACleanup")
- have_func("closesocket")
-when /cygwin/
-# $LDFLAGS << " -L/usr/lib" if File.directory?("/usr/lib")
-# $CFLAGS << " -I/usr/include"
- test_func = "socket"
-# have_library("bind", "gethostbyaddr")
-when /beos/
- test_func = "socket"
- have_library("net", "socket")
- have_func("closesocket")
-when /i386-os2_emx/
- test_func = "socket"
- have_library("socket", "socket")
-else
- test_func = "socket"
- have_library("nsl", "t_open")
- have_library("socket", "socket")
-end
-
-$ipv6 = false
-if enable_config("ipv6", false)
- if try_link(<<EOF)
-#include <sys/types.h>
-#include <sys/socket.h>
-main()
-{
- socket(AF_INET6, SOCK_STREAM, 0);
-}
-EOF
- $CFLAGS+=" -DENABLE_IPV6"
- $ipv6 = true
- end
-end
-
-$ipv6type = nil
-$ipv6lib = nil
-$ipv6libdir = nil
-$ipv6trylibc = nil
-if $ipv6
- if egrep_cpp("yes", <<EOF)
-#include <netinet/in.h>
-#ifdef IPV6_INRIA_VERSION
-yes
-#endif
-EOF
- $ipv6type = "inria"
- $CFLAGS="-DINET6 "+$CFLAGS
- elsif egrep_cpp("yes", <<EOF)
-#include <netinet/in.h>
-#ifdef __KAME__
-yes
-#endif
-EOF
- $ipv6type = "kame"
- $ipv6lib="inet6"
- $ipv6libdir="/usr/local/v6/lib"
- $ipv6trylibc=true
- $CFLAGS="-DINET6 "+$CFLAGS
- elsif File.directory? "/usr/inet6"
- $ipv6type = "linux"
- $ipv6lib="inet6"
- $ipv6libdir="/usr/inet6/lib"
- $CFLAGS="-DINET6 -I/usr/inet6/include "+$CFLAGS
- elsif egrep_cpp("yes", <<EOF)
-#include <sys/param.h>
-#ifdef _TOSHIBA_INET6
-yes
-#endif
-EOF
- $ipv6type = "toshiba"
- $ipv6lib="inet6"
- $ipv6libdir="/usr/local/v6/lib"
- $CFLAGS="-DINET6 "+$CFLAGS
- elsif egrep_cpp("yes", <<EOF)
-#include </usr/local/v6/include/sys/v6config.h>
-#ifdef __V6D__
-yes
-#endif
-EOF
- $ipv6type = "v6d"
- $ipv6lib="v6"
- $ipv6libdir="/usr/local/v6/lib"
- $CFLAGS="-DINET6 -I/usr/local/v6/include "+$CFLAGS
- elsif egrep_cpp("yes", <<EOF)
-#include <sys/param.h>
-#ifdef _ZETA_MINAMI_INET6
-yes
-#endif
-EOF
- $ipv6type = "zeta"
- $ipv6lib="inet6"
- $ipv6libdir="/usr/local/v6/lib"
- $CFLAGS="-DINET6 "+$CFLAGS
- else
- $ipv6lib=with_config("ipv6-lib", nil)
- $ipv6libdir=with_config("ipv6-libdir", nil)
- $CFLAGS="-DINET6 "+$CFLAGS
- end
-
- if $ipv6lib
- if File.directory? $ipv6libdir and File.exist? "#{$ipv6libdir}/lib#{$ipv6lib}.a"
- $LOCAL_LIBS = " -L#$ipv6libdir -l#$ipv6lib"
- elsif !$ipv6trylibc
- print <<EOS
-
-Fatal: no #$ipv6lib library found. cannot continue.
-You need to fetch lib#{$ipv6lib}.a from appropriate
-ipv6 kit and compile beforehand.
-EOS
- exit
- end
- end
-end
-
- if try_link(<<EOF)
-#include <sys/types.h>
-#include <netdb.h>
-#include <string.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-int
-main()
-{
- struct sockaddr_in sin;
-
- sin.sin_len;
- return 0;
-}
-EOF
- $CFLAGS="-DHAVE_SIN_LEN "+$CFLAGS
-end
-
- if try_link(<<EOF)
-#include <sys/types.h>
-#include <netdb.h>
-#include <string.h>
-#include <sys/socket.h>
-int
-main()
-{
- struct sockaddr_storage ss;
-
- ss.ss_family;
- return 0;
-}
-EOF
- $CFLAGS="-DHAVE_SOCKADDR_STORAGE "+$CFLAGS
-end
-
- if try_link(<<EOF)
-#include <sys/types.h>
-#include <netdb.h>
-#include <string.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-int
-main()
-{
- struct sockaddr sa;
-
- sa.sa_len;
- return 0;
-}
-EOF
- $CFLAGS="-DHAVE_SA_LEN "+$CFLAGS
-end
-
-have_header("netinet/tcp.h") if not /cygwin/ === RUBY_PLATFORM # for cygwin 1.1.5
-have_header("netinet/udp.h")
-
-have_struct_member('struct msghdr', 'msg_control', header=['sys/types.h', 'sys/socket.h'])
-have_struct_member('struct msghdr', 'msg_accrights', header=['sys/types.h', 'sys/socket.h'])
-
-$getaddr_info_ok = false
-if not enable_config("wide-getaddrinfo", false) and try_run(<<EOF)
-#include <sys/types.h>
-#include <netdb.h>
-#include <string.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-
-#ifndef AF_LOCAL
-#define AF_LOCAL AF_UNIX
-#endif
-
-main()
-{
- int passive, gaierr, inet4 = 0, inet6 = 0;
- struct addrinfo hints, *ai, *aitop;
- char straddr[INET6_ADDRSTRLEN], strport[16];
-
- for (passive = 0; passive <= 1; passive++) {
- memset(&hints, 0, sizeof(hints));
- hints.ai_family = AF_UNSPEC;
- hints.ai_flags = passive ? AI_PASSIVE : 0;
- hints.ai_socktype = SOCK_STREAM;
- if ((gaierr = getaddrinfo(NULL, "54321", &hints, &aitop)) != 0) {
- (void)gai_strerror(gaierr);
- goto bad;
- }
- for (ai = aitop; ai; ai = ai->ai_next) {
- if (ai->ai_family == AF_LOCAL) continue;
- if (ai->ai_addr == NULL ||
- ai->ai_addrlen == 0 ||
- getnameinfo(ai->ai_addr, ai->ai_addrlen,
- straddr, sizeof(straddr), strport, sizeof(strport),
- NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
- goto bad;
- }
- if (strcmp(strport, "54321") != 0) {
- goto bad;
- }
- switch (ai->ai_family) {
- case AF_INET:
- if (passive) {
- if (strcmp(straddr, "0.0.0.0") != 0) {
- goto bad;
- }
- } else {
- if (strcmp(straddr, "127.0.0.1") != 0) {
- goto bad;
- }
- }
- inet4++;
- break;
- case AF_INET6:
- if (passive) {
- if (strcmp(straddr, "::") != 0) {
- goto bad;
- }
- } else {
- if (strcmp(straddr, "::1") != 0) {
- goto bad;
- }
- }
- inet6++;
- break;
- case AF_UNSPEC:
- goto bad;
- break;
- default:
- /* another family support? */
- break;
- }
- }
- }
-
- if (!(inet4 == 0 || inet4 == 2))
- goto bad;
- if (!(inet6 == 0 || inet6 == 2))
- goto bad;
-
- if (aitop)
- freeaddrinfo(aitop);
- exit(0);
-
- bad:
- if (aitop)
- freeaddrinfo(aitop);
- exit(1);
-}
-EOF
- $getaddr_info_ok = true
-end
-if $ipv6 and not $getaddr_info_ok
- print <<EOS
-
-Fatal: --enable-ipv6 is specified, and your OS seems to support IPv6 feature.
-But your getaddrinfo() and getnameinfo() are appeared to be broken. Sorry,
-you cannot compile IPv6 socket classes with broken these functions.
-EOS
- exit
-end
-
-case with_config("lookup-order-hack", "UNSPEC")
-when "INET"
- $CFLAGS="-DLOOKUP_ORDER_HACK_INET "+$CFLAGS
-when "INET6"
- $CFLAGS="-DLOOKUP_ORDER_HACK_INET6 "+$CFLAGS
-when "UNSPEC"
- # nothing special
-else
- print <<EOS
-
-Fatal: invalid value for --with-lookup-order-hack (expected INET, INET6 or UNSPEC)
-EOS
- exit
-end
-
-$objs = ["socket.#{$OBJEXT}"]
-
-if $getaddr_info_ok and have_func("getaddrinfo") and have_func("getnameinfo")
- have_getaddrinfo = true
-end
-
-if have_getaddrinfo
- $CFLAGS="-DHAVE_GETADDRINFO "+$CFLAGS
-else
- $CFLAGS="-I. "+$CFLAGS
- $objs += ["getaddrinfo.#{$OBJEXT}"]
- $objs += ["getnameinfo.#{$OBJEXT}"]
- have_func("inet_ntop") or have_func("inet_ntoa")
- have_func("inet_pton") or have_func("inet_aton")
- have_func("getservbyport")
- have_header("arpa/inet.h")
- have_header("arpa/nameser.h")
- have_header("resolv.h")
-end
-
-if !try_link(<<EOF)
-#include <sys/types.h>
-#include <netdb.h>
-#include <string.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-int
-main()
-{
- socklen_t len;
- return 0;
-}
-EOF
- $CFLAGS="-Dsocklen_t=int "+$CFLAGS
-end
-
-have_header("sys/un.h")
-have_header("sys/uio.h")
-
-if have_func(test_func)
- have_func("hsterror")
- unless have_func("gethostname")
- have_func("uname")
- end
- if ENV["SOCKS_SERVER"] or enable_config("socks", false)
- if have_library("socks5", "SOCKSinit")
- $CFLAGS+=" -DSOCKS5 -DSOCKS"
- elsif have_library("socks", "Rconnect")
- $CFLAGS+=" -DSOCKS"
- end
- end
- create_makefile("socket")
-end
diff --git a/ext/socket/getaddrinfo.c b/ext/socket/getaddrinfo.c
deleted file mode 100644
index fa060ad171..0000000000
--- a/ext/socket/getaddrinfo.c
+++ /dev/null
@@ -1,686 +0,0 @@
-/*
- * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the project nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-/*
- * "#ifdef FAITH" part is local hack for supporting IPv4-v6 translator.
- *
- * Issues to be discussed:
- * - Thread safe-ness must be checked.
- * - Return values. There are nonstandard return values defined and used
- * in the source code. This is because RFC2133 is silent about which error
- * code must be returned for which situation.
- * - PF_UNSPEC case would be handled in getipnodebyname() with the AI_ALL flag.
- */
-
-#include "config.h"
-#include <sys/types.h>
-#ifndef NT
-#include <sys/param.h>
-#if defined(__BEOS__)
-# include <net/socket.h>
-#else
-# include <sys/socket.h>
-#endif
-#include <netinet/in.h>
-#if defined(HAVE_ARPA_INET_H)
-#include <arpa/inet.h>
-#endif
-#if defined(HAVE_ARPA_NAMESER_H)
-#include <arpa/nameser.h>
-#endif
-#include <netdb.h>
-#if defined(HAVE_RESOLV_H)
-#include <resolv.h>
-#endif
-#include <unistd.h>
-#else
-#include <winsock2.h>
-#include <io.h>
-#endif
-#include <string.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <stddef.h>
-#include <ctype.h>
-
-#ifdef SOCKS5
-#include <socks.h>
-#endif
-
-#include "addrinfo.h"
-#include "sockport.h"
-
-#if defined(__KAME__) && defined(INET6)
-# define FAITH
-#endif
-
-#define SUCCESS 0
-#define ANY 0
-#define YES 1
-#define NO 0
-
-#ifdef FAITH
-static int translate = NO;
-static struct in6_addr faith_prefix = IN6ADDR_ANY_INIT;
-#endif
-
-static const char in_addrany[] = { 0, 0, 0, 0 };
-static const char in6_addrany[] = {
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
-};
-static const char in_loopback[] = { 127, 0, 0, 1 };
-static const char in6_loopback[] = {
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
-};
-
-struct sockinet {
- u_char si_len;
- u_char si_family;
- u_short si_port;
-};
-
-static struct afd {
- int a_af;
- int a_addrlen;
- int a_socklen;
- int a_off;
- const char *a_addrany;
- const char *a_loopback;
-} afdl [] = {
-#ifdef INET6
-#define N_INET6 0
- {PF_INET6, sizeof(struct in6_addr),
- sizeof(struct sockaddr_in6),
- offsetof(struct sockaddr_in6, sin6_addr),
- in6_addrany, in6_loopback},
-#define N_INET 1
-#else
-#define N_INET 0
-#endif
- {PF_INET, sizeof(struct in_addr),
- sizeof(struct sockaddr_in),
- offsetof(struct sockaddr_in, sin_addr),
- in_addrany, in_loopback},
- {0, 0, 0, 0, NULL, NULL},
-};
-
-#ifdef INET6
-#define PTON_MAX 16
-#else
-#define PTON_MAX 4
-#endif
-
-static int get_name __P((const char *, struct afd *,
- struct addrinfo **, char *, struct addrinfo *,
- int));
-static int get_addr __P((const char *, int, struct addrinfo **,
- struct addrinfo *, int));
-static int str_isnumber __P((const char *));
-
-static char *ai_errlist[] = {
- "success.",
- "address family for hostname not supported.", /* EAI_ADDRFAMILY */
- "temporary failure in name resolution.", /* EAI_AGAIN */
- "invalid value for ai_flags.", /* EAI_BADFLAGS */
- "non-recoverable failure in name resolution.", /* EAI_FAIL */
- "ai_family not supported.", /* EAI_FAMILY */
- "memory allocation failure.", /* EAI_MEMORY */
- "no address associated with hostname.", /* EAI_NODATA */
- "hostname nor servname provided, or not known.",/* EAI_NONAME */
- "servname not supported for ai_socktype.", /* EAI_SERVICE */
- "ai_socktype not supported.", /* EAI_SOCKTYPE */
- "system error returned in errno.", /* EAI_SYSTEM */
- "invalid value for hints.", /* EAI_BADHINTS */
- "resolved protocol is unknown.", /* EAI_PROTOCOL */
- "unknown error.", /* EAI_MAX */
-};
-
-#define GET_CANONNAME(ai, str) \
-if (pai->ai_flags & AI_CANONNAME) {\
- if (((ai)->ai_canonname = (char *)malloc(strlen(str) + 1)) != NULL) {\
- strcpy((ai)->ai_canonname, (str));\
- } else {\
- error = EAI_MEMORY;\
- goto free;\
- }\
-}
-
-#define GET_AI(ai, afd, addr, port) {\
- char *p;\
- if (((ai) = (struct addrinfo *)malloc(sizeof(struct addrinfo) +\
- ((afd)->a_socklen)))\
- == NULL) {\
- error = EAI_MEMORY;\
- goto free;\
- }\
- memcpy(ai, pai, sizeof(struct addrinfo));\
- (ai)->ai_addr = (struct sockaddr *)((ai) + 1);\
- memset((ai)->ai_addr, 0, (afd)->a_socklen);\
- SET_SA_LEN((ai)->ai_addr, (ai)->ai_addrlen = (afd)->a_socklen);\
- (ai)->ai_addr->sa_family = (ai)->ai_family = (afd)->a_af;\
- ((struct sockinet *)(ai)->ai_addr)->si_port = port;\
- p = (char *)((ai)->ai_addr);\
- memcpy(p + (afd)->a_off, (addr), (afd)->a_addrlen);\
-}
-
-#define ERR(err) { error = (err); goto bad; }
-
-#if defined __UCLIBC__
-const
-#endif
-char *
-gai_strerror(ecode)
- int ecode;
-{
- if (ecode < 0 || ecode > EAI_MAX)
- ecode = EAI_MAX;
- return ai_errlist[ecode];
-}
-
-void
-freeaddrinfo(ai)
- struct addrinfo *ai;
-{
- struct addrinfo *next;
-
- do {
- next = ai->ai_next;
- if (ai->ai_canonname)
- free(ai->ai_canonname);
- /* no need to free(ai->ai_addr) */
- free(ai);
- } while ((ai = next) != NULL);
-}
-
-static int
-str_isnumber(p)
- const char *p;
-{
- char *q = (char *)p;
- while (*q) {
- if (! isdigit(*q))
- return NO;
- q++;
- }
- return YES;
-}
-
-#ifndef HAVE_INET_PTON
-
-static int
-inet_pton(af, hostname, pton)
- int af;
- const char *hostname;
- void *pton;
-{
- struct in_addr in;
-
-#ifdef HAVE_INET_ATON
- if (!inet_aton(hostname, &in))
- return 0;
-#else
- int d1, d2, d3, d4;
- char ch;
-
- if (sscanf(hostname, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
- 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
- 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
- in.s_addr = htonl(
- ((long) d1 << 24) | ((long) d2 << 16) |
- ((long) d3 << 8) | ((long) d4 << 0));
- }
- else {
- return 0;
- }
-#endif
- memcpy(pton, &in, sizeof(in));
- return 1;
-}
-#endif
-
-int
-getaddrinfo(hostname, servname, hints, res)
- const char *hostname, *servname;
- const struct addrinfo *hints;
- struct addrinfo **res;
-{
- struct addrinfo sentinel;
- struct addrinfo *top = NULL;
- struct addrinfo *cur;
- int i, error = 0;
- char pton[PTON_MAX];
- struct addrinfo ai;
- struct addrinfo *pai;
- u_short port;
-
-#ifdef FAITH
- static int firsttime = 1;
-
- if (firsttime) {
- /* translator hack */
- {
- char *q = getenv("GAI");
- if (q && inet_pton(AF_INET6, q, &faith_prefix) == 1)
- translate = YES;
- }
- firsttime = 0;
- }
-#endif
-
- /* initialize file static vars */
- sentinel.ai_next = NULL;
- cur = &sentinel;
- pai = &ai;
- pai->ai_flags = 0;
- pai->ai_family = PF_UNSPEC;
- pai->ai_socktype = ANY;
- pai->ai_protocol = ANY;
- pai->ai_addrlen = 0;
- pai->ai_canonname = NULL;
- pai->ai_addr = NULL;
- pai->ai_next = NULL;
- port = ANY;
-
- if (hostname == NULL && servname == NULL)
- return EAI_NONAME;
- if (hints) {
- /* error check for hints */
- if (hints->ai_addrlen || hints->ai_canonname ||
- hints->ai_addr || hints->ai_next)
- ERR(EAI_BADHINTS); /* xxx */
- if (hints->ai_flags & ~AI_MASK)
- ERR(EAI_BADFLAGS);
- switch (hints->ai_family) {
- case PF_UNSPEC:
- case PF_INET:
-#ifdef INET6
- case PF_INET6:
-#endif
- break;
- default:
- ERR(EAI_FAMILY);
- }
- memcpy(pai, hints, sizeof(*pai));
- switch (pai->ai_socktype) {
- case ANY:
- switch (pai->ai_protocol) {
- case ANY:
- break;
- case IPPROTO_UDP:
- pai->ai_socktype = SOCK_DGRAM;
- break;
- case IPPROTO_TCP:
- pai->ai_socktype = SOCK_STREAM;
- break;
- default:
-#if defined(SOCK_RAW)
- pai->ai_socktype = SOCK_RAW;
-#endif
- break;
- }
- break;
-#if defined(SOCK_RAW)
- case SOCK_RAW:
- break;
-#endif
- case SOCK_DGRAM:
- if (pai->ai_protocol != IPPROTO_UDP &&
- pai->ai_protocol != ANY)
- ERR(EAI_BADHINTS); /*xxx*/
- pai->ai_protocol = IPPROTO_UDP;
- break;
- case SOCK_STREAM:
- if (pai->ai_protocol != IPPROTO_TCP &&
- pai->ai_protocol != ANY)
- ERR(EAI_BADHINTS); /*xxx*/
- pai->ai_protocol = IPPROTO_TCP;
- break;
- default:
- ERR(EAI_SOCKTYPE);
- break;
- }
- }
-
- /*
- * service port
- */
- if (servname) {
- if (str_isnumber(servname)) {
- if (pai->ai_socktype == ANY) {
- /* caller accept *ANY* socktype */
- pai->ai_socktype = SOCK_DGRAM;
- pai->ai_protocol = IPPROTO_UDP;
- }
- port = htons((unsigned short)atoi(servname));
- } else {
- struct servent *sp;
- char *proto;
-
- proto = NULL;
- switch (pai->ai_socktype) {
- case ANY:
- proto = NULL;
- break;
- case SOCK_DGRAM:
- proto = "udp";
- break;
- case SOCK_STREAM:
- proto = "tcp";
- break;
- default:
- fprintf(stderr, "panic!\n");
- break;
- }
- if ((sp = getservbyname(servname, proto)) == NULL)
- ERR(EAI_SERVICE);
- port = sp->s_port;
- if (pai->ai_socktype == ANY)
- if (strcmp(sp->s_proto, "udp") == 0) {
- pai->ai_socktype = SOCK_DGRAM;
- pai->ai_protocol = IPPROTO_UDP;
- } else if (strcmp(sp->s_proto, "tcp") == 0) {
- pai->ai_socktype = SOCK_STREAM;
- pai->ai_protocol = IPPROTO_TCP;
- } else
- ERR(EAI_PROTOCOL); /*xxx*/
- }
- }
-
- /*
- * hostname == NULL.
- * passive socket -> anyaddr (0.0.0.0 or ::)
- * non-passive socket -> localhost (127.0.0.1 or ::1)
- */
- if (hostname == NULL) {
- struct afd *afd;
- int s;
-
- for (afd = &afdl[0]; afd->a_af; afd++) {
- if (!(pai->ai_family == PF_UNSPEC
- || pai->ai_family == afd->a_af)) {
- continue;
- }
-
- /*
- * filter out AFs that are not supported by the kernel
- * XXX errno?
- */
- s = socket(afd->a_af, SOCK_DGRAM, 0);
- if (s < 0)
- continue;
-#if defined(HAVE_CLOSESOCKET)
- closesocket(s);
-#else
- close(s);
-#endif
-
- if (pai->ai_flags & AI_PASSIVE) {
- GET_AI(cur->ai_next, afd, afd->a_addrany, port);
- /* xxx meaningless?
- * GET_CANONNAME(cur->ai_next, "anyaddr");
- */
- } else {
- GET_AI(cur->ai_next, afd, afd->a_loopback,
- port);
- /* xxx meaningless?
- * GET_CANONNAME(cur->ai_next, "localhost");
- */
- }
- cur = cur->ai_next;
- }
- top = sentinel.ai_next;
- if (top)
- goto good;
- else
- ERR(EAI_FAMILY);
- }
-
- /* hostname as numeric name */
- for (i = 0; afdl[i].a_af; i++) {
- if (inet_pton(afdl[i].a_af, hostname, pton)) {
- u_long v4a;
-#ifdef INET6
- u_char pfx;
-#endif
-
- switch (afdl[i].a_af) {
- case AF_INET:
- v4a = ((struct in_addr *)pton)->s_addr;
- if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a))
- pai->ai_flags &= ~AI_CANONNAME;
- v4a >>= IN_CLASSA_NSHIFT;
- if (v4a == 0 || v4a == IN_LOOPBACKNET)
- pai->ai_flags &= ~AI_CANONNAME;
- break;
-#ifdef INET6
- case AF_INET6:
- pfx = ((struct in6_addr *)pton)->s6_addr8[0];
- if (pfx == 0 || pfx == 0xfe || pfx == 0xff)
- pai->ai_flags &= ~AI_CANONNAME;
- break;
-#endif
- }
-
- if (pai->ai_family == afdl[i].a_af ||
- pai->ai_family == PF_UNSPEC) {
- if (! (pai->ai_flags & AI_CANONNAME)) {
- GET_AI(top, &afdl[i], pton, port);
- goto good;
- }
- /*
- * if AI_CANONNAME and if reverse lookup
- * fail, return ai anyway to pacify
- * calling application.
- *
- * XXX getaddrinfo() is a name->address
- * translation function, and it looks strange
- * that we do addr->name translation here.
- */
- get_name(pton, &afdl[i], &top, pton, pai, port);
- goto good;
- } else
- ERR(EAI_FAMILY); /*xxx*/
- }
- }
-
- if (pai->ai_flags & AI_NUMERICHOST)
- ERR(EAI_NONAME);
-
- /* hostname as alphabetical name */
- error = get_addr(hostname, pai->ai_family, &top, pai, port);
- if (error == 0) {
- if (top) {
- good:
- *res = top;
- return SUCCESS;
- } else
- error = EAI_FAIL;
- }
- free:
- if (top)
- freeaddrinfo(top);
- bad:
- *res = NULL;
- return error;
-}
-
-static int
-get_name(addr, afd, res, numaddr, pai, port0)
- const char *addr;
- struct afd *afd;
- struct addrinfo **res;
- char *numaddr;
- struct addrinfo *pai;
- int port0;
-{
- u_short port = port0 & 0xffff;
- struct hostent *hp;
- struct addrinfo *cur;
- int error = 0;
-#ifdef INET6
- int h_error;
-#endif
-
-#ifdef INET6
- hp = getipnodebyaddr(addr, afd->a_addrlen, afd->a_af, &h_error);
-#else
- hp = gethostbyaddr(addr, afd->a_addrlen, AF_INET);
-#endif
- if (hp && hp->h_name && hp->h_name[0] && hp->h_addr_list[0]) {
- GET_AI(cur, afd, hp->h_addr_list[0], port);
- GET_CANONNAME(cur, hp->h_name);
- } else
- GET_AI(cur, afd, numaddr, port);
-
-#ifdef INET6
- if (hp)
- freehostent(hp);
-#endif
- *res = cur;
- return SUCCESS;
- free:
- if (cur)
- freeaddrinfo(cur);
-#ifdef INET6
- if (hp)
- freehostent(hp);
-#endif
- /* bad: */
- *res = NULL;
- return error;
-}
-
-static int
-get_addr(hostname, af, res, pai, port0)
- const char *hostname;
- int af;
- struct addrinfo **res;
- struct addrinfo *pai;
- int port0;
-{
- u_short port = port0 & 0xffff;
- struct addrinfo sentinel;
- struct hostent *hp;
- struct addrinfo *top, *cur;
- struct afd *afd;
- int i, error = 0, h_error;
- char *ap;
-
- top = NULL;
- sentinel.ai_next = NULL;
- cur = &sentinel;
-#ifdef INET6
- if (af == AF_UNSPEC) {
- hp = getipnodebyname(hostname, AF_INET6,
- AI_ADDRCONFIG|AI_ALL|AI_V4MAPPED, &h_error);
- } else
- hp = getipnodebyname(hostname, af, AI_ADDRCONFIG, &h_error);
-#else
- hp = gethostbyname(hostname);
- h_error = h_errno;
-#endif
- if (hp == NULL) {
- switch (h_error) {
- case HOST_NOT_FOUND:
- case NO_DATA:
- error = EAI_NODATA;
- break;
- case TRY_AGAIN:
- error = EAI_AGAIN;
- break;
- case NO_RECOVERY:
- default:
- error = EAI_FAIL;
- break;
- }
- goto bad;
- }
-
- if ((hp->h_name == NULL) || (hp->h_name[0] == 0) ||
- (hp->h_addr_list[0] == NULL))
- ERR(EAI_FAIL);
-
- for (i = 0; (ap = hp->h_addr_list[i]) != NULL; i++) {
- switch (af) {
-#ifdef INET6
- case AF_INET6:
- afd = &afdl[N_INET6];
- break;
-#endif
-#ifndef INET6
- default: /* AF_UNSPEC */
-#endif
- case AF_INET:
- afd = &afdl[N_INET];
- break;
-#ifdef INET6
- default: /* AF_UNSPEC */
- if (IN6_IS_ADDR_V4MAPPED((struct in6_addr *)ap)) {
- ap += sizeof(struct in6_addr) -
- sizeof(struct in_addr);
- afd = &afdl[N_INET];
- } else
- afd = &afdl[N_INET6];
- break;
-#endif
- }
-#ifdef FAITH
- if (translate && afd->a_af == AF_INET) {
- struct in6_addr *in6;
-
- GET_AI(cur->ai_next, &afdl[N_INET6], ap, port);
- in6 = &((struct sockaddr_in6 *)cur->ai_next->ai_addr)->sin6_addr;
- memcpy(&in6->s6_addr32[0], &faith_prefix,
- sizeof(struct in6_addr) - sizeof(struct in_addr));
- memcpy(&in6->s6_addr32[3], ap, sizeof(struct in_addr));
- } else
-#endif /* FAITH */
- GET_AI(cur->ai_next, afd, ap, port);
- if (cur == &sentinel) {
- top = cur->ai_next;
- GET_CANONNAME(top, hp->h_name);
- }
- cur = cur->ai_next;
- }
-#ifdef INET6
- freehostent(hp);
-#endif
- *res = top;
- return SUCCESS;
- free:
- if (top)
- freeaddrinfo(top);
-#ifdef INET6
- if (hp)
- freehostent(hp);
-#endif
- bad:
- *res = NULL;
- return error;
-}
diff --git a/ext/socket/getnameinfo.c b/ext/socket/getnameinfo.c
deleted file mode 100644
index b8a1e310a3..0000000000
--- a/ext/socket/getnameinfo.c
+++ /dev/null
@@ -1,261 +0,0 @@
-/*
- * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the project nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-/*
- * Issues to be discussed:
- * - Thread safe-ness must be checked
- * - Return values. There seems to be no standard for return value (RFC2133)
- * but INRIA implementation returns EAI_xxx defined for getaddrinfo().
- */
-
-#include "config.h"
-#include <sys/types.h>
-#ifndef NT
-#if defined(__BEOS__)
-# include <net/socket.h>
-#else
-# include <sys/socket.h>
-#endif
-#include <netinet/in.h>
-#if defined(HAVE_ARPA_INET_H)
-#include <arpa/inet.h>
-#endif
-#if defined(HAVE_ARPA_NAMESER_H)
-#include <arpa/nameser.h>
-#endif
-#include <netdb.h>
-#if defined(HAVE_RESOLV_H)
-#include <resolv.h>
-#endif
-#endif
-#ifdef NT
-#include <winsock2.h>
-#include <stdio.h>
-#define snprintf _snprintf
-#endif
-
-#include <string.h>
-#include <stddef.h>
-
-#ifdef SOCKS5
-#include <socks.h>
-#endif
-
-#include "addrinfo.h"
-#include "sockport.h"
-
-#define SUCCESS 0
-#define ANY 0
-#define YES 1
-#define NO 0
-
-struct sockinet {
- u_char si_len;
- u_char si_family;
- u_short si_port;
-};
-
-static struct afd {
- int a_af;
- int a_addrlen;
- int a_socklen;
- int a_off;
-} afdl [] = {
-#ifdef INET6
-#define N_INET6 0
- {PF_INET6, sizeof(struct in6_addr),
- sizeof(struct sockaddr_in6),
- offsetof(struct sockaddr_in6, sin6_addr)},
-#define N_INET 1
-#else
-#define N_INET 0
-#endif
- {PF_INET, sizeof(struct in_addr),
- sizeof(struct sockaddr_in),
- offsetof(struct sockaddr_in, sin_addr)},
- {0, 0, 0, 0},
-};
-
-#define ENI_NOSOCKET 0
-#define ENI_NOSERVNAME 1
-#define ENI_NOHOSTNAME 2
-#define ENI_MEMORY 3
-#define ENI_SYSTEM 4
-#define ENI_FAMILY 5
-#define ENI_SALEN 6
-
-#ifndef HAVE_INET_NTOP
-static const char *
-inet_ntop(af, addr, numaddr, numaddr_len)
- int af;
- const void *addr;
- char *numaddr;
- size_t numaddr_len;
-{
-#ifdef HAVE_INET_NTOA
- struct in_addr in;
- memcpy(&in.s_addr, addr, sizeof(in.s_addr));
- snprintf(numaddr, numaddr_len, "%s", inet_ntoa(in));
-#else
- unsigned long x = ntohl(*(unsigned long*)addr);
- snprintf(numaddr, numaddr_len, "%d.%d.%d.%d",
- (int) (x>>24) & 0xff, (int) (x>>16) & 0xff,
- (int) (x>> 8) & 0xff, (int) (x>> 0) & 0xff);
-#endif
- return numaddr;
-}
-#endif
-
-int
-getnameinfo(sa, salen, host, hostlen, serv, servlen, flags)
- const struct sockaddr *sa;
- size_t salen;
- char *host;
- size_t hostlen;
- char *serv;
- size_t servlen;
- int flags;
-{
- struct afd *afd;
- struct servent *sp;
- struct hostent *hp;
- u_short port;
- int family, len, i;
- char *addr, *p;
- u_long v4a;
-#ifdef INET6
- u_char pfx;
-#endif
- int h_error;
- char numserv[512];
- char numaddr[512];
-
- if (sa == NULL)
- return ENI_NOSOCKET;
-
- len = SA_LEN(sa);
- if (len != salen) return ENI_SALEN;
-
- family = sa->sa_family;
- for (i = 0; afdl[i].a_af; i++)
- if (afdl[i].a_af == family) {
- afd = &afdl[i];
- goto found;
- }
- return ENI_FAMILY;
-
- found:
- if (len != afd->a_socklen) return ENI_SALEN;
-
- port = ((struct sockinet *)sa)->si_port; /* network byte order */
- addr = (char *)sa + afd->a_off;
-
- if (serv == NULL || servlen == 0) {
- /* what we should do? */
- } else if (flags & NI_NUMERICSERV) {
- snprintf(numserv, sizeof(numserv), "%d", ntohs(port));
- if (strlen(numserv) + 1 > servlen)
- return ENI_MEMORY;
- strcpy(serv, numserv);
- } else {
-#if defined(HAVE_GETSERVBYPORT)
- sp = getservbyport(port, (flags & NI_DGRAM) ? "udp" : "tcp");
- if (sp) {
- if (strlen(sp->s_name) + 1 > servlen)
- return ENI_MEMORY;
- strcpy(serv, sp->s_name);
- } else
- return ENI_NOSERVNAME;
-#else
- return ENI_NOSERVNAME;
-#endif
- }
-
- switch (sa->sa_family) {
- case AF_INET:
- v4a = ntohl(((struct sockaddr_in *)sa)->sin_addr.s_addr);
- if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a))
- flags |= NI_NUMERICHOST;
- v4a >>= IN_CLASSA_NSHIFT;
- if (v4a == 0)
- flags |= NI_NUMERICHOST;
- break;
-#ifdef INET6
- case AF_INET6:
- pfx = ((struct sockaddr_in6 *)sa)->sin6_addr.s6_addr8[0];
- if (pfx == 0 || pfx == 0xfe || pfx == 0xff)
- flags |= NI_NUMERICHOST;
- break;
-#endif
- }
- if (host == NULL || hostlen == 0) {
- /* what should we do? */
- } else if (flags & NI_NUMERICHOST) {
- if (inet_ntop(afd->a_af, addr, numaddr, sizeof(numaddr))
- == NULL)
- return ENI_SYSTEM;
- if (strlen(numaddr) > hostlen)
- return ENI_MEMORY;
- strcpy(host, numaddr);
- } else {
-#ifdef INET6
- hp = getipnodebyaddr(addr, afd->a_addrlen, afd->a_af, &h_error);
-#else
- hp = gethostbyaddr(addr, afd->a_addrlen, afd->a_af);
- h_error = h_errno;
-#endif
-
- if (hp) {
- if (flags & NI_NOFQDN) {
- p = strchr(hp->h_name, '.');
- if (p) *p = '\0';
- }
- if (strlen(hp->h_name) + 1 > hostlen) {
-#ifdef INET6
- freehostent(hp);
-#endif
- return ENI_MEMORY;
- }
- strcpy(host, hp->h_name);
-#ifdef INET6
- freehostent(hp);
-#endif
- } else {
- if (flags & NI_NAMEREQD)
- return ENI_NOHOSTNAME;
- if (inet_ntop(afd->a_af, addr, numaddr, sizeof(numaddr))
- == NULL)
- return ENI_NOHOSTNAME;
- if (strlen(numaddr) > hostlen)
- return ENI_MEMORY;
- strcpy(host, numaddr);
- }
- }
- return SUCCESS;
-}
diff --git a/ext/socket/socket.c b/ext/socket/socket.c
deleted file mode 100644
index 281a1fe1ea..0000000000
--- a/ext/socket/socket.c
+++ /dev/null
@@ -1,2837 +0,0 @@
-/************************************************
-
- socket.c -
-
- $Author$
- $Date$
- created at: Thu Mar 31 12:21:29 JST 1994
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
-
-************************************************/
-
-#include "ruby.h"
-#include "rubyio.h"
-#include "rubysig.h"
-#include <stdio.h>
-#include <sys/types.h>
-
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-
-#ifdef HAVE_SYS_UIO_H
-#include <sys/uio.h>
-#endif
-
-#ifndef NT
-#if defined(__BEOS__)
-# include <net/socket.h>
-#else
-# include <sys/socket.h>
-#endif
-#include <netinet/in.h>
-#ifdef HAVE_NETINET_TCP_H
-# include <netinet/tcp.h>
-#endif
-#ifdef HAVE_NETINET_UDP_H
-# include <netinet/udp.h>
-#endif
-#include <netdb.h>
-#endif
-#include <errno.h>
-#ifdef HAVE_SYS_UN_H
-#include <sys/un.h>
-#endif
-
-#if defined(HAVE_FCNTL)
-#ifdef HAVE_SYS_SELECT_H
-#include <sys/select.h>
-#endif
-#include <sys/types.h>
-#include <sys/time.h>
-#include <fcntl.h>
-#endif
-#ifndef EWOULDBLOCK
-#define EWOULDBLOCK EAGAIN
-#endif
-#ifndef HAVE_GETADDRINFO
-# include "addrinfo.h"
-#endif
-#include "sockport.h"
-
-static int do_not_reverse_lookup = 0;
-
-VALUE rb_cBasicSocket;
-VALUE rb_cIPSocket;
-VALUE rb_cTCPSocket;
-VALUE rb_cTCPServer;
-VALUE rb_cUDPSocket;
-#ifdef AF_UNIX
-VALUE rb_cUNIXSocket;
-VALUE rb_cUNIXServer;
-#endif
-VALUE rb_cSocket;
-
-static VALUE rb_eSocket;
-
-#ifdef SOCKS
-VALUE rb_cSOCKSSocket;
-#ifdef SOCKS5
-#include <socks.h>
-#else
-void SOCKSinit();
-int Rconnect();
-#endif
-#endif
-
-#define INET_CLIENT 0
-#define INET_SERVER 1
-#define INET_SOCKS 2
-
-#ifndef HAVE_SOCKADDR_STORAGE
-/*
- * RFC 2553: protocol-independent placeholder for socket addresses
- */
-#define _SS_MAXSIZE 128
-#define _SS_ALIGNSIZE (sizeof(double))
-#define _SS_PAD1SIZE (_SS_ALIGNSIZE - sizeof(unsigned char) * 2)
-#define _SS_PAD2SIZE (_SS_MAXSIZE - sizeof(unsigned char) * 2 - \
- _SS_PAD1SIZE - _SS_ALIGNSIZE)
-
-struct sockaddr_storage {
-#ifdef HAVE_SA_LEN
- unsigned char ss_len; /* address length */
- unsigned char ss_family; /* address family */
-#else
- unsigned short ss_family;
-#endif
- char __ss_pad1[_SS_PAD1SIZE];
- double __ss_align; /* force desired structure storage alignment */
- char __ss_pad2[_SS_PAD2SIZE];
-};
-#endif
-
-#if defined(INET6) && (defined(LOOKUP_ORDER_HACK_INET) || defined(LOOKUP_ORDER_HACK_INET6))
-#define LOOKUP_ORDERS 3
-static int lookup_order_table[LOOKUP_ORDERS] = {
-#if defined(LOOKUP_ORDER_HACK_INET)
- PF_INET, PF_INET6, PF_UNSPEC,
-#elif defined(LOOKUP_ORDER_HACK_INET6)
- PF_INET6, PF_INET, PF_UNSPEC,
-#else
- /* should not happen */
-#endif
-};
-
-static int
-rb_getaddrinfo(nodename, servname, hints, res)
- char *nodename;
- char *servname;
- struct addrinfo *hints;
- struct addrinfo **res;
-{
- struct addrinfo tmp_hints;
- int i, af, error;
-
- if (hints->ai_family != PF_UNSPEC) {
- return getaddrinfo(nodename, servname, hints, res);
- }
-
- for (i = 0; i < LOOKUP_ORDERS; i++) {
- af = lookup_order_table[i];
- MEMCPY(&tmp_hints, hints, struct addrinfo, 1);
- tmp_hints.ai_family = af;
- error = getaddrinfo(nodename, servname, &tmp_hints, res);
- if (error) {
- if (tmp_hints.ai_family == PF_UNSPEC) {
- break;
- }
- }
- else {
- break;
- }
- }
-
- return error;
-}
-#define getaddrinfo(node,serv,hints,res) rb_getaddrinfo((node),(serv),(hints),(res))
-#endif
-
-#ifdef NT
-static void sock_finalize _((OpenFile *fptr));
-
-static void
-sock_finalize(fptr)
- OpenFile *fptr;
-{
- SOCKET s;
-
- if (!fptr->f) return;
- s = get_osfhandle(fileno(fptr->f));
- myfdclose(fptr->f);
- if (fptr->f2) myfdclose(fptr->f2);
- closesocket(s);
-}
-#endif
-
-static VALUE
-init_sock(sock, fd)
- VALUE sock;
- int fd;
-{
- OpenFile *fp;
-
- MakeOpenFile(sock, fp);
- fp->f = rb_fdopen(fd, "r");
-#ifdef NT
- fp->finalize = sock_finalize;
-#else
-#endif
- fp->f2 = rb_fdopen(fd, "w");
- fp->mode = FMODE_READWRITE;
- rb_io_synchronized(fp);
-
- return sock;
-}
-
-static VALUE
-bsock_s_for_fd(klass, fd)
- VALUE klass, fd;
-{
- return init_sock(rb_obj_alloc(klass), NUM2INT(fd));
-}
-
-static VALUE
-bsock_shutdown(argc, argv, sock)
- int argc;
- VALUE *argv;
- VALUE sock;
-{
- VALUE howto;
- int how;
- OpenFile *fptr;
-
- if (rb_safe_level() >= 4 && !OBJ_TAINTED(sock)) {
- rb_raise(rb_eSecurityError, "Insecure: can't shutdown socket");
- }
- rb_scan_args(argc, argv, "01", &howto);
- if (howto == Qnil)
- how = 2;
- else {
- how = NUM2INT(howto);
- if (how < 0 || 2 < how) {
- rb_raise(rb_eArgError, "`how' should be either 0, 1, 2");
- }
- }
- GetOpenFile(sock, fptr);
- if (shutdown(fileno(fptr->f), how) == -1)
- rb_sys_fail(0);
-
- return INT2FIX(0);
-}
-
-static VALUE
-bsock_close_read(sock)
- VALUE sock;
-{
- OpenFile *fptr;
-
- if (rb_safe_level() >= 4 && !OBJ_TAINTED(sock)) {
- rb_raise(rb_eSecurityError, "Insecure: can't close socket");
- }
- GetOpenFile(sock, fptr);
- shutdown(fileno(fptr->f), 0);
- if (!(fptr->mode & FMODE_WRITABLE)) {
- return rb_io_close(sock);
- }
- fptr->mode &= ~FMODE_READABLE;
-
- return Qnil;
-}
-
-static VALUE
-bsock_close_write(sock)
- VALUE sock;
-{
- OpenFile *fptr;
-
- if (rb_safe_level() >= 4 && !OBJ_TAINTED(sock)) {
- rb_raise(rb_eSecurityError, "Insecure: can't close socket");
- }
- GetOpenFile(sock, fptr);
- if (!(fptr->mode & FMODE_READABLE)) {
- return rb_io_close(sock);
- }
- shutdown(fileno(fptr->f2), 1);
- fptr->mode &= ~FMODE_WRITABLE;
-
- return Qnil;
-}
-
-static VALUE
-bsock_setsockopt(sock, lev, optname, val)
- VALUE sock, lev, optname, val;
-{
- int level, option;
- OpenFile *fptr;
- int i;
- char *v;
- int vlen;
-
- rb_secure(2);
- level = NUM2INT(lev);
- option = NUM2INT(optname);
- switch (TYPE(val)) {
- case T_FIXNUM:
- i = FIX2INT(val);
- goto numval;
- case T_FALSE:
- i = 0;
- goto numval;
- case T_TRUE:
- i = 1;
- numval:
- v = (char*)&i; vlen = sizeof(i);
- break;
- default:
- StringValue(val);
- v = RSTRING(val)->ptr;
- vlen = RSTRING(val)->len;
- break;
- }
-
- GetOpenFile(sock, fptr);
- if (setsockopt(fileno(fptr->f), level, option, v, vlen) < 0)
- rb_sys_fail(fptr->path);
-
- return INT2FIX(0);
-}
-
-static VALUE
-bsock_getsockopt(sock, lev, optname)
- VALUE sock, lev, optname;
-{
-#if !defined(__BEOS__)
- int level, option;
- socklen_t len;
- char *buf;
- OpenFile *fptr;
-
- level = NUM2INT(lev);
- option = NUM2INT(optname);
- len = 256;
- buf = ALLOCA_N(char,len);
-
- GetOpenFile(sock, fptr);
- if (getsockopt(fileno(fptr->f), level, option, buf, &len) < 0)
- rb_sys_fail(fptr->path);
-
- return rb_tainted_str_new(buf, len);
-#else
- rb_notimplement();
-#endif
-}
-
-static VALUE
-bsock_getsockname(sock)
- VALUE sock;
-{
- char buf[1024];
- socklen_t len = sizeof buf;
- OpenFile *fptr;
-
- GetOpenFile(sock, fptr);
- if (getsockname(fileno(fptr->f), (struct sockaddr*)buf, &len) < 0)
- rb_sys_fail("getsockname(2)");
- return rb_tainted_str_new(buf, len);
-}
-
-static VALUE
-bsock_getpeername(sock)
- VALUE sock;
-{
- char buf[1024];
- socklen_t len = sizeof buf;
- OpenFile *fptr;
-
- GetOpenFile(sock, fptr);
- if (getpeername(fileno(fptr->f), (struct sockaddr*)buf, &len) < 0)
- rb_sys_fail("getpeername(2)");
- return rb_tainted_str_new(buf, len);
-}
-
-static VALUE
-bsock_send(argc, argv, sock)
- int argc;
- VALUE *argv;
- VALUE sock;
-{
- VALUE mesg, to;
- VALUE flags;
- OpenFile *fptr;
- FILE *f;
- int fd, n;
-
- rb_secure(4);
- rb_scan_args(argc, argv, "21", &mesg, &flags, &to);
-
- GetOpenFile(sock, fptr);
- f = GetWriteFile(fptr);
- fd = fileno(f);
- retry:
- rb_thread_fd_writable(fd);
- StringValue(mesg);
- if (!NIL_P(to)) {
- StringValue(to);
- n = sendto(fd, RSTRING(mesg)->ptr, RSTRING(mesg)->len, NUM2INT(flags),
- (struct sockaddr*)RSTRING(to)->ptr, RSTRING(to)->len);
- }
- else {
- n = send(fd, RSTRING(mesg)->ptr, RSTRING(mesg)->len, NUM2INT(flags));
- }
- if (n < 0) {
- switch (errno) {
- case EINTR:
- rb_thread_schedule();
- goto retry;
- }
- rb_sys_fail("send(2)");
- }
- return INT2FIX(n);
-}
-
-static VALUE ipaddr _((struct sockaddr *));
-#ifdef HAVE_SYS_UN_H
-static VALUE unixaddr _((struct sockaddr_un *));
-#endif
-
-enum sock_recv_type {
- RECV_RECV, /* BasicSocket#recv(no from) */
- RECV_IP, /* IPSocket#recvfrom */
- RECV_UNIX, /* UNIXSocket#recvfrom */
- RECV_SOCKET /* Socket#recvfrom */
-};
-
-static VALUE
-s_recvfrom(sock, argc, argv, from)
- VALUE sock;
- int argc;
- VALUE *argv;
- enum sock_recv_type from;
-{
- OpenFile *fptr;
- VALUE str;
- char buf[1024];
- socklen_t alen = sizeof buf;
- VALUE len, flg;
- int fd, flags;
-
- rb_scan_args(argc, argv, "11", &len, &flg);
-
- if (flg == Qnil) flags = 0;
- else flags = NUM2INT(flg);
-
- GetOpenFile(sock, fptr);
- if (rb_read_pending(fptr->f)) {
- rb_raise(rb_eIOError, "recv for buffered IO");
- }
- fd = fileno(fptr->f);
-
- str = rb_tainted_str_new(0, NUM2INT(len));
-
- retry:
- rb_thread_wait_fd(fd);
- TRAP_BEG;
- RSTRING(str)->len = recvfrom(fd, RSTRING(str)->ptr, RSTRING(str)->len, flags,
- (struct sockaddr*)buf, &alen);
- TRAP_END;
-
- if (RSTRING(str)->len < 0) {
- switch (errno) {
- case EINTR:
- rb_thread_schedule();
- goto retry;
- }
- rb_sys_fail("recvfrom(2)");
- }
- rb_obj_taint(str);
- switch (from) {
- case RECV_RECV:
- return (VALUE)str;
- case RECV_IP:
-#if 0
- if (alen != sizeof(struct sockaddr_in)) {
- rb_raise(rb_eTypeError, "sockaddr size differs - should not happen");
- }
-#endif
- return rb_assoc_new(str, ipaddr((struct sockaddr *)buf));
-#ifdef HAVE_SYS_UN_H
- case RECV_UNIX:
- return rb_assoc_new(str, unixaddr((struct sockaddr_un *)buf));
-#endif
- case RECV_SOCKET:
- return rb_assoc_new(str, rb_tainted_str_new(buf, alen));
- default:
- rb_bug("s_recvfrom called with bad value");
- }
-}
-
-static VALUE
-bsock_recv(argc, argv, sock)
- int argc;
- VALUE *argv;
- VALUE sock;
-{
- return s_recvfrom(sock, argc, argv, RECV_RECV);
-}
-
-static VALUE
-bsock_do_not_rev_lookup()
-{
- return do_not_reverse_lookup?Qtrue:Qfalse;
-}
-
-static VALUE
-bsock_do_not_rev_lookup_set(self, val)
-{
- do_not_reverse_lookup = RTEST(val);
- return val;
-}
-
-static void
-mkipaddr0(addr, buf, len)
- struct sockaddr *addr;
- char *buf;
- size_t len;
-{
- int error;
-
- error = getnameinfo(addr, SA_LEN(addr), buf, len, NULL, 0, NI_NUMERICHOST);
- if (error) {
- rb_raise(rb_eSocket, "getnameinfo: %s", gai_strerror(error));
- }
-}
-
-static VALUE
-mkipaddr(addr)
- struct sockaddr *addr;
-{
- char buf[1024];
-
- mkipaddr0(addr, buf, sizeof(buf));
- return rb_tainted_str_new2(buf);
-}
-
-static void
-mkinetaddr(host, buf, len)
- long host;
- char *buf;
- size_t len;
-{
- struct sockaddr_in sin;
-
- MEMZERO(&sin, struct sockaddr_in, 1);
- sin.sin_family = AF_INET;
- SET_SIN_LEN(&sin, sizeof(sin));
- sin.sin_addr.s_addr = host;
- mkipaddr0((struct sockaddr *)&sin, buf, len);
-}
-
-static struct addrinfo*
-ip_addrsetup(host, port)
- VALUE host, port;
-{
- struct addrinfo hints, *res;
- char *hostp, *portp;
- int error;
- char hbuf[1024], pbuf[16];
-
- if (NIL_P(host)) {
- hostp = NULL;
- }
- else if (rb_obj_is_kind_of(host, rb_cInteger)) {
- long i = NUM2LONG(host);
-
- mkinetaddr(htonl(i), hbuf, sizeof(hbuf));
- hostp = hbuf;
- }
- else {
- char *name;
-
- SafeStringValue(host);
- name = RSTRING(host)->ptr;
- if (*name == 0) {
- mkinetaddr(INADDR_ANY, hbuf, sizeof(hbuf));
- }
- else if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
- mkinetaddr(INADDR_BROADCAST, hbuf, sizeof(hbuf));
- }
- else if (strlen(name) >= sizeof(hbuf)) {
- rb_raise(rb_eArgError, "hostname too long (%d)", strlen(name));
- }
- else {
- strcpy(hbuf, name);
- }
- hostp = hbuf;
- }
- if (NIL_P(port)) {
- portp = 0;
- }
- else if (FIXNUM_P(port)) {
- snprintf(pbuf, sizeof(pbuf), "%ld", FIX2INT(port));
- portp = pbuf;
- }
- else {
- SafeStringValue(port);
- portp = RSTRING(port)->ptr;
- }
-
- MEMZERO(&hints, struct addrinfo, 1);
- hints.ai_family = PF_UNSPEC;
- hints.ai_socktype = SOCK_DGRAM;
- error = getaddrinfo(hostp, portp, &hints, &res);
- if (error) {
- if (hostp && hostp[strlen(hostp)-1] == '\n') {
- rb_raise(rb_eSocket, "newline at the end of hostname");
- }
- rb_raise(rb_eSocket, "getaddrinfo: %s", gai_strerror(error));
- }
-
- return res;
-}
-
-static void
-setipaddr(name, addr)
- VALUE name;
- struct sockaddr *addr;
-{
- struct addrinfo *res = ip_addrsetup(name, Qnil);
-
- /* just take the first one */
- memcpy(addr, res->ai_addr, res->ai_addrlen);
- freeaddrinfo(res);
-}
-
-static VALUE
-ipaddr(sockaddr)
- struct sockaddr *sockaddr;
-{
- VALUE family, port, addr1, addr2;
- VALUE ary;
- int error;
- char hbuf[1024], pbuf[1024];
-
- switch (sockaddr->sa_family) {
- case AF_UNSPEC:
- family = rb_str_new2("AF_UNSPEC");
- break;
- case AF_INET:
- family = rb_str_new2("AF_INET");
- break;
-#ifdef INET6
- case AF_INET6:
- family = rb_str_new2("AF_INET6");
- break;
-#endif
-#ifdef AF_LOCAL
- case AF_LOCAL:
- family = rb_str_new2("AF_LOCAL");
- break;
-#elif AF_UNIX
- case AF_UNIX:
- family = rb_str_new2("AF_UNIX");
- break;
-#endif
- default:
- sprintf(pbuf, "unknown:%d", sockaddr->sa_family);
- family = rb_str_new2(pbuf);
- break;
- }
- if (!do_not_reverse_lookup) {
- error = getnameinfo(sockaddr, SA_LEN(sockaddr), hbuf, sizeof(hbuf),
- NULL, 0, 0);
- if (error) {
- rb_raise(rb_eSocket, "getnameinfo: %s", gai_strerror(error));
- }
- addr1 = rb_tainted_str_new2(hbuf);
- }
- error = getnameinfo(sockaddr, SA_LEN(sockaddr), hbuf, sizeof(hbuf),
- pbuf, sizeof(pbuf), NI_NUMERICHOST | NI_NUMERICSERV);
- if (error) {
- rb_raise(rb_eSocket, "getnameinfo %s", gai_strerror(error));
- }
- addr2 = rb_tainted_str_new2(hbuf);
- if (do_not_reverse_lookup) {
- addr1 = addr2;
- }
- port = INT2FIX(atoi(pbuf));
- ary = rb_ary_new3(4, family, port, addr1, addr2);
-
- return ary;
-}
-
-static int
-ruby_socket(domain, type, proto)
- int domain, type, proto;
-{
- int fd;
-
- fd = socket(domain, type, proto);
- if (fd < 0) {
- if (errno == EMFILE || errno == ENFILE) {
- rb_gc();
- fd = socket(domain, type, proto);
- }
- }
- return fd;
-}
-
-static void
-thread_read_select(fd)
- int fd;
-{
- fd_set fds;
-
- FD_ZERO(&fds);
- FD_SET(fd, &fds);
- rb_thread_select(fd+1, &fds, 0, 0, 0);
-}
-
-static void
-thread_write_select(fd)
- int fd;
-{
- fd_set fds;
-
- FD_ZERO(&fds);
- FD_SET(fd, &fds);
- rb_thread_select(fd+1, 0, &fds, 0, 0);
-}
-
-static int
-ruby_connect(fd, sockaddr, len, socks)
- int fd;
- struct sockaddr *sockaddr;
- int len;
- int socks;
-{
- int status;
- int mode;
-#if defined __CYGWIN__
- int wait_in_progress = -1;
-#endif
-
-#if defined(HAVE_FCNTL)
- mode = fcntl(fd, F_GETFL, 0);
-
-#ifdef O_NDELAY
-# define NONBLOCKING O_NDELAY
-#else
-#ifdef O_NBIO
-# define NONBLOCKING O_NBIO
-#else
-# define NONBLOCKING O_NONBLOCK
-#endif
-#endif
-#ifdef SOCKS5
- if (!socks)
-#endif
- fcntl(fd, F_SETFL, mode|NONBLOCKING);
-#endif /* HAVE_FCNTL */
-
- for (;;) {
-#if defined(SOCKS) && !defined(SOCKS5)
- if (socks) {
- status = Rconnect(fd, sockaddr, len);
- }
- else
-#endif
- {
- status = connect(fd, sockaddr, len);
- }
- if (status < 0) {
- switch (errno) {
- case EAGAIN:
-#ifdef EINPROGRESS
- case EINPROGRESS:
-#if defined __CYGWIN__
- case EALREADY:
- wait_in_progress = 10;
-#endif
-#endif
- thread_write_select(fd);
- continue;
-
-#if defined __CYGWIN__
- case EINVAL:
- if (wait_in_progress-- > 0) {
- struct timeval tv = {0, 100000};
- rb_thread_wait_for(tv);
- continue;
- }
- break;
-#endif
-
-#ifdef EISCONN
- case EISCONN:
- status = 0;
- errno = 0;
- break;
-#endif
- default:
- break;
- }
- }
-#ifdef HAVE_FCNTL
- fcntl(fd, F_SETFL, mode);
-#endif
- return status;
- }
-}
-
-static void
-load_addr_info(h, serv, type, res)
- VALUE h, serv;
- int type;
- struct addrinfo **res;
-{
- char *host;
- char pbuf[1024], *portp;
- struct addrinfo hints;
- int error;
-
- if (!NIL_P(h)) {
- SafeStringValue(h);
- host = RSTRING(h)->ptr;
- }
- else {
- host = NULL;
- }
- if (FIXNUM_P(serv)) {
- snprintf(pbuf, sizeof(pbuf), "%ld", FIX2UINT(serv));
- portp = pbuf;
- }
- else {
- SafeStringValue(serv);
- if (RSTRING(serv)->len >= sizeof(pbuf))
- rb_raise(rb_eArgError, "servicename too long (%d)", RSTRING(serv)->len);
- strcpy(pbuf, RSTRING(serv)->ptr);
- portp = pbuf;
- }
- MEMZERO(&hints, struct addrinfo, 1);
- hints.ai_family = PF_UNSPEC;
- hints.ai_socktype = SOCK_STREAM;
- if (type == INET_SERVER) {
- hints.ai_flags = AI_PASSIVE;
- }
- error = getaddrinfo(host, portp, &hints, res);
- if (error) {
- rb_raise(rb_eSocket, "getaddrinfo: %s", gai_strerror(error));
- }
-}
-
-static VALUE
-init_inetsock(sock, remote_host, remote_serv, local_host, local_serv, type)
- VALUE sock, remote_host, remote_serv, local_host, local_serv;
- int type;
-{
- struct addrinfo hints, *res, *res_remote, *res_local = NULL;
- int fd, status;
- char *syscall;
-
- load_addr_info(remote_host, remote_serv, type, &res_remote);
-
- /*
- * Maybe also accept a local address
- */
-
- if (type != INET_SERVER && (!NIL_P(local_host) || !NIL_P(local_serv)))
- load_addr_info(local_host, local_serv, type, &res_local);
-
- fd = -1;
- for (res = res_remote; res; res = res->ai_next) {
- status = ruby_socket(res->ai_family,res->ai_socktype,res->ai_protocol);
- syscall = "socket(2)";
- fd = status;
- if (fd < 0) {
- continue;
- }
- if (type == INET_SERVER) {
-#ifndef NT
- status = 1;
- setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
- (char*)&status, sizeof(status));
-#endif
- status = bind(fd, res->ai_addr, res->ai_addrlen);
- syscall = "bind(2)";
- }
- else {
- if (res_local) {
- status = bind(fd, res_local->ai_addr, res_local->ai_addrlen);
- syscall = "bind(2)";
- }
-
- if (status >= 0) {
- status = ruby_connect(fd, res->ai_addr, res->ai_addrlen,
- (type == INET_SOCKS));
- syscall = "connect(2)";
- }
- }
-
- if (status < 0) {
-#if defined(HAVE_CLOSESOCKET)
- closesocket(fd);
-#else
- close(fd);
-#endif
- fd = -1;
- continue;
- } else
- break;
- }
- if (status < 0) {
- if (fd >= 0)
-#if defined(HAVE_CLOSESOCKET)
- closesocket(fd);
-#else
- close(fd);
-#endif
- freeaddrinfo(res_remote);
- if (res_local) {
- freeaddrinfo(res_local);
- }
- rb_sys_fail(syscall);
- }
-
- if (type == INET_SERVER)
- listen(fd, 5);
-
- /* create new instance */
- if (res_local)
- freeaddrinfo(res_local);
- freeaddrinfo(res_remote);
- return init_sock(sock, fd);
-}
-
-static VALUE
-tcp_init(argc, argv, sock)
- int argc;
- VALUE *argv;
- VALUE sock;
-{
- VALUE remote_host, remote_serv;
- VALUE local_host, local_serv;
-
- int pcount = rb_scan_args(argc, argv, "22",
- &remote_host, &remote_serv,
- &local_host, &local_serv);
-
- return init_inetsock(sock, remote_host, remote_serv,
- local_host, local_serv, INET_CLIENT);
-}
-
-#ifdef SOCKS
-static VALUE
-socks_init(sock, host, serv)
- VALUE sock, host, serv;
-{
- static init = 0;
-
- if (init == 0) {
- SOCKSinit("ruby");
- init = 1;
- }
-
- return init_inetsock(class, host, serv, Qnil, Qnil, INET_SOCKS);
-}
-
-#ifdef SOCKS5
-static VALUE
-socks_s_close(sock)
- VALUE sock;
-{
- OpenFile *fptr;
-
- if (rb_safe_level() >= 4 && !OBJ_TAINTED(sock)) {
- rb_raise(rb_eSecurityError, "Insecure: can't close socket");
- }
- GetOpenFile(sock, fptr);
- shutdown(fileno(fptr->f), 2);
- shutdown(fileno(fptr->f2), 2);
- return rb_io_close(sock);
-}
-#endif
-#endif
-
-/*
- * NOTE: using gethostbyname() against AF_INET6 is a bad idea, as it
- * does not initialize sin_flowinfo nor sin_scope_id properly.
- */
-static VALUE
-tcp_s_gethostbyname(obj, host)
- VALUE obj, host;
-{
- struct sockaddr_storage addr;
- struct hostent *h;
- char **pch;
- VALUE ary, names;
-
- rb_secure(3);
- if (rb_obj_is_kind_of(host, rb_cInteger)) {
- long i = NUM2LONG(host);
- struct sockaddr_in *sin;
-
- sin = (struct sockaddr_in *)&addr;
- MEMZERO(sin, struct sockaddr_in, 1);
- sin->sin_family = AF_INET;
- SET_SIN_LEN(sin, sizeof(*sin));
- sin->sin_addr.s_addr = htonl(i);
- }
- else {
- setipaddr(host, &addr);
- }
- switch (addr.ss_family) {
- case AF_INET:
- {
- struct sockaddr_in *sin;
- sin = (struct sockaddr_in *)&addr;
- h = gethostbyaddr((char *)&sin->sin_addr,
- sizeof(sin->sin_addr),
- sin->sin_family);
- break;
- }
-#ifdef INET6
- case AF_INET6:
- {
- struct sockaddr_in6 *sin6;
- sin6 = (struct sockaddr_in6 *)&addr;
- h = gethostbyaddr((char *)&sin6->sin6_addr,
- sizeof(sin6->sin6_addr),
- sin6->sin6_family);
- break;
- }
-#endif
- default:
- h = NULL;
- }
-
- if (h == NULL) {
-#ifdef HAVE_HSTERROR
- extern int h_errno;
- rb_raise(rb_eSocket, "%s", (char *)hsterror(h_errno));
-#else
- rb_raise(rb_eSocket, "host not found");
-#endif
- }
- ary = rb_ary_new();
- rb_ary_push(ary, rb_tainted_str_new2(h->h_name));
- names = rb_ary_new();
- rb_ary_push(ary, names);
- for (pch = h->h_aliases; *pch; pch++) {
- rb_ary_push(names, rb_tainted_str_new2(*pch));
- }
- rb_ary_push(ary, INT2NUM(h->h_addrtype));
-#ifdef h_addr
- for (pch = h->h_addr_list; *pch; pch++) {
- switch (addr.ss_family) {
- case AF_INET:
- {
- struct sockaddr_in sin;
- MEMZERO(&sin, struct sockaddr_in, 1);
- sin.sin_family = AF_INET;
- SET_SIN_LEN(&sin, sizeof(sin));
- memcpy((char *) &sin.sin_addr, *pch, h->h_length);
- h = gethostbyaddr((char *)&sin.sin_addr,
- sizeof(sin.sin_addr),
- sin.sin_family);
- rb_ary_push(ary, mkipaddr((struct sockaddr *)&sin));
- break;
- }
-#ifdef INET6
- case AF_INET6:
- {
- struct sockaddr_in6 sin6;
- MEMZERO(&sin6, struct sockaddr_in6, 1);
- sin6.sin6_family = AF_INET;
-#ifdef SIN6_LEN
- sin6.sin6_len = sizeof(sin6);
-#endif
- memcpy((char *) &sin6.sin6_addr, *pch, h->h_length);
- h = gethostbyaddr((char *)&sin6.sin6_addr,
- sizeof(sin6.sin6_addr),
- sin6.sin6_family);
- rb_ary_push(ary, mkipaddr((struct sockaddr *)&sin6));
- break;
- }
-#endif
- default:
- h = NULL;
- }
- }
-#else
- memcpy((char *)&addr.sin_addr, h->h_addr, h->h_length);
- rb_ary_push(ary, mkipaddr((struct sockaddr *)&addr));
-#endif
-
- return ary;
-}
-
-static VALUE
-tcp_svr_init(argc, argv, sock)
- int argc;
- VALUE *argv;
- VALUE sock;
-{
- VALUE arg1, arg2;
-
- if (rb_scan_args(argc, argv, "11", &arg1, &arg2) == 2)
- return init_inetsock(sock, arg1, arg2, NULL, Qnil, INET_SERVER);
- else
- return init_inetsock(sock, Qnil, arg1, NULL, Qnil, INET_SERVER);
-}
-
-static VALUE
-s_accept(klass, fd, sockaddr, len)
- VALUE klass;
- int fd;
- struct sockaddr *sockaddr;
- socklen_t *len;
-{
- int fd2;
- int retry = 0;
-
- rb_secure(3);
- retry:
- rb_thread_wait_fd(fd);
-#if defined(_nec_ews)
- fd2 = accept(fd, sockaddr, len);
-#else
- TRAP_BEG;
- fd2 = accept(fd, sockaddr, len);
- TRAP_END;
-#endif
- if (fd2 < 0) {
- switch (errno) {
- case EMFILE:
- case ENFILE:
- if (retry) break;
- rb_gc();
- retry = 1;
- goto retry;
- case EINTR:
- rb_thread_schedule();
- goto retry;
- }
- rb_sys_fail(0);
- }
- return init_sock(rb_obj_alloc(klass), fd2);
-}
-
-static VALUE
-tcp_accept(sock)
- VALUE sock;
-{
- OpenFile *fptr;
- struct sockaddr_storage from;
- socklen_t fromlen;
-
- GetOpenFile(sock, fptr);
- fromlen = sizeof(from);
- return s_accept(rb_cTCPSocket, fileno(fptr->f),
- (struct sockaddr*)&from, &fromlen);
-}
-
-#ifdef HAVE_SYS_UN_H
-static VALUE
-init_unixsock(sock, path, server)
- VALUE sock;
- VALUE path;
- int server;
-{
- struct sockaddr_un sockaddr;
- int fd, status;
- OpenFile *fptr;
-
- SafeStringValue(path);
- fd = ruby_socket(AF_UNIX, SOCK_STREAM, 0);
- if (fd < 0) {
- rb_sys_fail("socket(2)");
- }
-
- MEMZERO(&sockaddr, struct sockaddr_un, 1);
- sockaddr.sun_family = AF_UNIX;
- strncpy(sockaddr.sun_path, RSTRING(path)->ptr, sizeof(sockaddr.sun_path)-1);
- sockaddr.sun_path[sizeof(sockaddr.sun_path)-1] = '\0';
-
- if (server) {
- status = bind(fd, (struct sockaddr*)&sockaddr, sizeof(sockaddr));
- }
- else {
- status = ruby_connect(fd, (struct sockaddr*)&sockaddr, sizeof(sockaddr), 0);
- }
-
- if (status < 0) {
-#if defined(HAVE_CLOSESOCKET)
- closesocket(fd);
-#else
- close(fd);
-#endif
- rb_sys_fail(sockaddr.sun_path);
- }
-
- if (server) listen(fd, 5);
-
- init_sock(sock, fd);
- GetOpenFile(sock, fptr);
- fptr->path = strdup(RSTRING(path)->ptr);
-
- return sock;
-}
-#endif
-
-static VALUE
-ip_addr(sock)
- VALUE sock;
-{
- OpenFile *fptr;
- struct sockaddr_storage addr;
- socklen_t len = sizeof addr;
-
- GetOpenFile(sock, fptr);
-
- if (getsockname(fileno(fptr->f), (struct sockaddr*)&addr, &len) < 0)
- rb_sys_fail("getsockname(2)");
- return ipaddr((struct sockaddr *)&addr);
-}
-
-static VALUE
-ip_peeraddr(sock)
- VALUE sock;
-{
- OpenFile *fptr;
- struct sockaddr_storage addr;
- socklen_t len = sizeof addr;
-
- GetOpenFile(sock, fptr);
-
- if (getpeername(fileno(fptr->f), (struct sockaddr*)&addr, &len) < 0)
- rb_sys_fail("getpeername(2)");
- return ipaddr((struct sockaddr *)&addr);
-}
-
-static VALUE
-ip_recvfrom(argc, argv, sock)
- int argc;
- VALUE *argv;
- VALUE sock;
-{
- return s_recvfrom(sock, argc, argv, RECV_IP);
-}
-
-static VALUE
-ip_s_getaddress(obj, host)
- VALUE obj, host;
-{
- struct sockaddr_storage addr;
-
- setipaddr(host, &addr);
- return mkipaddr((struct sockaddr *)&addr);
-}
-
-static VALUE
-udp_init(argc, argv, sock)
- int argc;
- VALUE *argv;
- VALUE sock;
-{
- VALUE arg;
- int socktype = AF_INET;
- int fd;
-
- rb_secure(3);
- if (rb_scan_args(argc, argv, "01", &arg) == 1) {
- socktype = NUM2INT(arg);
- }
- fd = ruby_socket(socktype, SOCK_DGRAM, 0);
- if (fd < 0) {
- rb_sys_fail("socket(2) - udp");
- }
-
- return init_sock(sock, fd);
-}
-
-static VALUE
-udp_connect(sock, host, port)
- VALUE sock, host, port;
-{
- OpenFile *fptr;
- int fd;
- struct addrinfo *res0, *res;
-
- rb_secure(3);
- GetOpenFile(sock, fptr);
- fd = fileno(fptr->f);
- res0 = ip_addrsetup(host, port);
- for (res = res0; res; res = res->ai_next) {
- if (ruby_connect(fd, res->ai_addr, res->ai_addrlen, 0) >= 0) {
- freeaddrinfo(res0);
- return INT2FIX(0);
- }
- }
-
- freeaddrinfo(res0);
- rb_sys_fail("connect(2)");
- return INT2FIX(0);
-}
-
-static VALUE
-udp_bind(sock, host, port)
- VALUE sock, host, port;
-{
- OpenFile *fptr;
- struct addrinfo *res0, *res;
-
- rb_secure(3);
- GetOpenFile(sock, fptr);
- res0 = ip_addrsetup(host, port);
- for (res = res0; res; res = res->ai_next) {
- if (bind(fileno(fptr->f), res->ai_addr, res->ai_addrlen) < 0) {
- continue;
- }
- freeaddrinfo(res0);
- return INT2FIX(0);
- }
- freeaddrinfo(res0);
- rb_sys_fail("bind(2)");
- return INT2FIX(0);
-}
-
-static VALUE
-udp_send(argc, argv, sock)
- int argc;
- VALUE *argv;
- VALUE sock;
-{
- VALUE mesg, flags, host, port;
- OpenFile *fptr;
- FILE *f;
- int n;
- struct addrinfo *res0, *res;
-
- if (argc == 2 || argc == 3) {
- return bsock_send(argc, argv, sock);
- }
- rb_secure(4);
- rb_scan_args(argc, argv, "4", &mesg, &flags, &host, &port);
-
- GetOpenFile(sock, fptr);
- res0 = ip_addrsetup(host, port);
- f = GetWriteFile(fptr);
- StringValue(mesg);
- for (res = res0; res; res = res->ai_next) {
- retry:
- n = sendto(fileno(f), RSTRING(mesg)->ptr, RSTRING(mesg)->len, NUM2INT(flags),
- res->ai_addr, res->ai_addrlen);
- if (n >= 0) {
- freeaddrinfo(res0);
- return INT2FIX(n);
- }
- switch (errno) {
- case EINTR:
- rb_thread_schedule();
- goto retry;
- }
- }
- freeaddrinfo(res0);
- rb_sys_fail("sendto(2)");
- return INT2FIX(n);
-}
-
-#ifdef HAVE_SYS_UN_H
-static VALUE
-unix_init(sock, path)
- VALUE sock, path;
-{
- return init_unixsock(sock, path, 0);
-}
-
-static VALUE
-unix_path(sock)
- VALUE sock;
-{
- OpenFile *fptr;
-
- GetOpenFile(sock, fptr);
- if (fptr->path == 0) {
- struct sockaddr_un addr;
- socklen_t len = sizeof(addr);
- if (getsockname(fileno(fptr->f), (struct sockaddr*)&addr, &len) < 0)
- rb_sys_fail(0);
- fptr->path = strdup(addr.sun_path);
- }
- return rb_tainted_str_new2(fptr->path);
-}
-
-static VALUE
-unix_svr_s_open(klass, path)
- VALUE klass, path;
-{
- return init_unixsock(rb_obj_alloc(klass), path, 1);
-}
-
-static VALUE
-unix_svr_init(sock, path)
- VALUE sock, path;
-{
- return init_unixsock(sock, path, 1);
-}
-
-static VALUE
-unix_recvfrom(argc, argv, sock)
- int argc;
- VALUE *argv;
- VALUE sock;
-{
- return s_recvfrom(sock, argc, argv, RECV_UNIX);
-}
-
-static VALUE
-unix_send_io(sock, val)
- VALUE sock, val;
-{
-#if defined(HAVE_ST_MSG_CONTROL) || defined(HAVE_ST_MSG_ACCRIGHTS)
- int fd;
- OpenFile *fptr;
- struct msghdr msg;
- struct iovec vec[1];
- char buf[1];
-
-#if defined(HAVE_ST_MSG_CONTROL)
- struct {
- struct cmsghdr hdr;
- int fd;
- } cmsg;
-#endif
-
- if (rb_obj_is_kind_of(val, rb_cIO)) {
- OpenFile *valfptr;
- GetOpenFile(val, valfptr);
- fd = fileno(valfptr->f);
- }
- else if (FIXNUM_P(val)) {
- fd = FIX2INT(val);
- }
- else {
- rb_raise(rb_eTypeError, "IO nor file descriptor");
- }
-
- GetOpenFile(sock, fptr);
-
- msg.msg_name = NULL;
- msg.msg_namelen = 0;
-
- /* Linux and Solaris doesn't work if msg_iov is NULL. */
- buf[0] = '\0';
- vec[0].iov_base = buf;
- vec[0].iov_len = 1;
- msg.msg_iov = vec;
- msg.msg_iovlen = 1;
-
-#if defined(HAVE_ST_MSG_CONTROL)
- msg.msg_control = (caddr_t)&cmsg;
- msg.msg_controllen = sizeof(struct cmsghdr) + sizeof(int);
- msg.msg_flags = 0;
- cmsg.hdr.cmsg_len = sizeof(struct cmsghdr) + sizeof(int);
- cmsg.hdr.cmsg_level = SOL_SOCKET;
- cmsg.hdr.cmsg_type = SCM_RIGHTS;
- cmsg.fd = fd;
-#else
- msg.msg_accrights = (caddr_t)&fd;
- msg.msg_accrightslen = sizeof(fd);
-#endif
-
- if (sendmsg(fileno(fptr->f), &msg, 0) == -1)
- rb_sys_fail("sendmsg(2)");
-
- return Qnil;
-#else
- rb_notimplement();
-#endif
-}
-
-static VALUE
-unix_recv_io(argc, argv, sock)
- int argc;
- VALUE *argv;
- VALUE sock;
-{
-#if defined(HAVE_ST_MSG_CONTROL) || defined(HAVE_ST_MSG_ACCRIGHTS)
- VALUE klass, mode;
- OpenFile *fptr;
- struct msghdr msg;
- struct iovec vec[2];
- char buf[1];
-
- int fd;
-#if defined(HAVE_ST_MSG_CONTROL)
- struct {
- struct cmsghdr hdr;
- int fd;
- } cmsg;
-#endif
-
- rb_scan_args(argc, argv, "02", &klass, &mode);
- if (argc == 0)
- klass = rb_cIO;
- if (argc <= 1)
- mode = Qnil;
-
- GetOpenFile(sock, fptr);
-
- thread_read_select(fileno(fptr->f));
-
- msg.msg_name = NULL;
- msg.msg_namelen = 0;
-
- vec[0].iov_base = buf;
- vec[0].iov_len = sizeof(buf);
- msg.msg_iov = vec;
- msg.msg_iovlen = 1;
-
-#if defined(HAVE_ST_MSG_CONTROL)
- msg.msg_control = (caddr_t)&cmsg;
- msg.msg_controllen = sizeof(struct cmsghdr) + sizeof(int);
- msg.msg_flags = 0;
- cmsg.hdr.cmsg_len = sizeof(struct cmsghdr) + sizeof(int);
- cmsg.hdr.cmsg_level = SOL_SOCKET;
- cmsg.hdr.cmsg_type = SCM_RIGHTS;
- cmsg.fd = -1;
-#else
- msg.msg_accrights = (caddr_t)&fd;
- msg.msg_accrightslen = sizeof(fd);
- fd = -1;
-#endif
-
- if (recvmsg(fileno(fptr->f), &msg, 0) == -1)
- rb_sys_fail("recvmsg(2)");
-
- if (
-#if defined(HAVE_ST_MSG_CONTROL)
- msg.msg_controllen != sizeof(struct cmsghdr) + sizeof(int) ||
- cmsg.hdr.cmsg_len != sizeof(struct cmsghdr) + sizeof(int) ||
- cmsg.hdr.cmsg_level != SOL_SOCKET ||
- cmsg.hdr.cmsg_type != SCM_RIGHTS
-#else
- msg.msg_accrightslen != sizeof(fd)
-#endif
- ) {
- rb_raise(rb_eSocket, "File descriptor was not passed");
- }
-
-#if defined(HAVE_ST_MSG_CONTROL)
- fd = cmsg.fd;
-#endif
-
- if (klass == Qnil)
- return INT2FIX(fd);
- else {
- static ID for_fd = 0;
- int ff_argc;
- VALUE ff_argv[2];
- if (!for_fd)
- for_fd = rb_intern("for_fd");
- ff_argc = mode == Qnil ? 1 : 2;
- ff_argv[0] = INT2FIX(fd);
- ff_argv[1] = mode;
- return rb_funcall2(klass, for_fd, ff_argc, ff_argv);
- }
-#else
- rb_notimplement();
-#endif
-}
-
-static VALUE
-unix_accept(sock)
- VALUE sock;
-{
- OpenFile *fptr;
- struct sockaddr_un from;
- socklen_t fromlen;
-
- GetOpenFile(sock, fptr);
- fromlen = sizeof(struct sockaddr_un);
- return s_accept(rb_cUNIXSocket, fileno(fptr->f),
- (struct sockaddr*)&from, &fromlen);
-}
-
-static VALUE
-unixaddr(sockaddr)
- struct sockaddr_un *sockaddr;
-{
- return rb_assoc_new(rb_str_new2("AF_UNIX"),
- rb_tainted_str_new2(sockaddr->sun_path));
-}
-
-static VALUE
-unix_addr(sock)
- VALUE sock;
-{
- OpenFile *fptr;
- struct sockaddr_un addr;
- socklen_t len = sizeof addr;
-
- GetOpenFile(sock, fptr);
-
- if (getsockname(fileno(fptr->f), (struct sockaddr*)&addr, &len) < 0)
- rb_sys_fail("getsockname(2)");
- if (len == 0)
- addr.sun_path[0] = '\0';
- return unixaddr(&addr);
-}
-
-static VALUE
-unix_peeraddr(sock)
- VALUE sock;
-{
- OpenFile *fptr;
- struct sockaddr_un addr;
- socklen_t len = sizeof addr;
-
- GetOpenFile(sock, fptr);
-
- if (getpeername(fileno(fptr->f), (struct sockaddr*)&addr, &len) < 0)
- rb_sys_fail("getsockname(2)");
- if (len == 0)
- addr.sun_path[0] = '\0';
- return unixaddr(&addr);
-}
-#endif
-
-static void
-setup_domain_and_type(domain, dv, type, tv)
- VALUE domain, type;
- int *dv, *tv;
-{
- char *ptr;
-
- if (TYPE(domain) == T_STRING) {
- SafeStringValue(domain);
- ptr = RSTRING(domain)->ptr;
- if (strcmp(ptr, "AF_INET") == 0)
- *dv = AF_INET;
-#ifdef AF_UNIX
- else if (strcmp(ptr, "AF_UNIX") == 0)
- *dv = AF_UNIX;
-#endif
-#ifdef AF_ISO
- else if (strcmp(ptr, "AF_ISO") == 0)
- *dv = AF_ISO;
-#endif
-#ifdef AF_NS
- else if (strcmp(ptr, "AF_NS") == 0)
- *dv = AF_NS;
-#endif
-#ifdef AF_IMPLINK
- else if (strcmp(ptr, "AF_IMPLINK") == 0)
- *dv = AF_IMPLINK;
-#endif
-#ifdef PF_INET
- else if (strcmp(ptr, "PF_INET") == 0)
- *dv = PF_INET;
-#endif
-#ifdef PF_UNIX
- else if (strcmp(ptr, "PF_UNIX") == 0)
- *dv = PF_UNIX;
-#endif
-#ifdef PF_IMPLINK
- else if (strcmp(ptr, "PF_IMPLINK") == 0)
- *dv = PF_IMPLINK;
- else if (strcmp(ptr, "AF_IMPLINK") == 0)
- *dv = AF_IMPLINK;
-#endif
-#ifdef PF_AX25
- else if (strcmp(ptr, "PF_AX25") == 0)
- *dv = PF_AX25;
-#endif
-#ifdef PF_IPX
- else if (strcmp(ptr, "PF_IPX") == 0)
- *dv = PF_IPX;
-#endif
- else
- rb_raise(rb_eSocket, "Unknown socket domain %s", ptr);
- }
- else {
- *dv = NUM2INT(domain);
- }
- if (TYPE(type) == T_STRING) {
- SafeStringValue(type);
- ptr = RSTRING(type)->ptr;
- if (strcmp(ptr, "SOCK_STREAM") == 0)
- *tv = SOCK_STREAM;
- else if (strcmp(ptr, "SOCK_DGRAM") == 0)
- *tv = SOCK_DGRAM;
-#ifdef SOCK_RAW
- else if (strcmp(ptr, "SOCK_RAW") == 0)
- *tv = SOCK_RAW;
-#endif
-#ifdef SOCK_SEQPACKET
- else if (strcmp(ptr, "SOCK_SEQPACKET") == 0)
- *tv = SOCK_SEQPACKET;
-#endif
-#ifdef SOCK_RDM
- else if (strcmp(ptr, "SOCK_RDM") == 0)
- *tv = SOCK_RDM;
-#endif
-#ifdef SOCK_PACKET
- else if (strcmp(ptr, "SOCK_PACKET") == 0)
- *tv = SOCK_PACKET;
-#endif
- else
- rb_raise(rb_eSocket, "Unknown socket type %s", ptr);
- }
- else {
- *tv = NUM2INT(type);
- }
-}
-
-static VALUE
-sock_init(sock, domain, type, protocol)
- VALUE sock, domain, type, protocol;
-{
- int fd;
- int d, t;
-
- rb_secure(3);
- setup_domain_and_type(domain, &d, type, &t);
- fd = ruby_socket(d, t, NUM2INT(protocol));
- if (fd < 0) rb_sys_fail("socket(2)");
-
- return init_sock(sock, fd);
-}
-
-static VALUE
-sock_s_socketpair(klass, domain, type, protocol)
- VALUE klass, domain, type, protocol;
-{
-#if !defined(NT) && !defined(__BEOS__) && !defined(__EMX__) && !defined(__QNXNTO__)
- int d, t, sp[2];
-
- setup_domain_and_type(domain, &d, type, &t);
- again:
- if (socketpair(d, t, NUM2INT(protocol), sp) < 0) {
- if (errno == EMFILE || errno == ENFILE) {
- rb_gc();
- goto again;
- }
- rb_sys_fail("socketpair(2)");
- }
-
- return rb_assoc_new(init_sock(rb_obj_alloc(klass), sp[0]),
- init_sock(rb_obj_alloc(klass), sp[1]));
-#else
- rb_notimplement();
-#endif
-}
-
-#ifdef HAVE_SYS_UN_H
-static VALUE
-unix_s_socketpair(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- VALUE domain, type, protocol;
- domain = INT2FIX(PF_UNIX);
-
- rb_scan_args(argc, argv, "02", &type, &protocol);
- if (argc == 0)
- type = INT2FIX(SOCK_STREAM);
- if (argc <= 1)
- protocol = INT2FIX(0);
-
- return sock_s_socketpair(klass, domain, type, protocol);
-}
-#endif
-
-static VALUE
-sock_connect(sock, addr)
- VALUE sock, addr;
-{
- OpenFile *fptr;
- int fd;
-
- StringValue(addr);
- rb_str_modify(addr);
-
- GetOpenFile(sock, fptr);
- fd = fileno(fptr->f);
- if (ruby_connect(fd, (struct sockaddr*)RSTRING(addr)->ptr, RSTRING(addr)->len, 0) < 0) {
- rb_sys_fail("connect(2)");
- }
-
- return INT2FIX(0);
-}
-
-static VALUE
-sock_bind(sock, addr)
- VALUE sock, addr;
-{
- OpenFile *fptr;
-
- StringValue(addr);
- rb_str_modify(addr);
-
- GetOpenFile(sock, fptr);
- if (bind(fileno(fptr->f), (struct sockaddr*)RSTRING(addr)->ptr, RSTRING(addr)->len) < 0)
- rb_sys_fail("bind(2)");
-
- return INT2FIX(0);
-}
-
-static VALUE
-sock_listen(sock, log)
- VALUE sock, log;
-{
- OpenFile *fptr;
-
- rb_secure(4);
- GetOpenFile(sock, fptr);
- if (listen(fileno(fptr->f), NUM2INT(log)) < 0)
- rb_sys_fail("listen(2)");
-
- return INT2FIX(0);
-}
-
-static VALUE
-sock_recvfrom(argc, argv, sock)
- int argc;
- VALUE *argv;
- VALUE sock;
-{
- return s_recvfrom(sock, argc, argv, RECV_SOCKET);
-}
-
-static VALUE
-sock_accept(sock)
- VALUE sock;
-{
- OpenFile *fptr;
- VALUE sock2;
- char buf[1024];
- socklen_t len = sizeof buf;
-
- GetOpenFile(sock, fptr);
- sock2 = s_accept(rb_cSocket,fileno(fptr->f),(struct sockaddr*)buf,&len);
-
- return rb_assoc_new(sock2, rb_tainted_str_new(buf, len));
-}
-
-#ifdef HAVE_GETHOSTNAME
-static VALUE
-sock_gethostname(obj)
- VALUE obj;
-{
- char buf[1024];
-
- rb_secure(3);
- if (gethostname(buf, (int)sizeof buf - 1) < 0)
- rb_sys_fail("gethostname");
-
- buf[sizeof buf - 1] = '\0';
- return rb_tainted_str_new2(buf);
-}
-#else
-#ifdef HAVE_UNAME
-
-#include <sys/utsname.h>
-
-static VALUE
-sock_gethostname(obj)
- VALUE obj;
-{
- struct utsname un;
-
- rb_secure(3);
- uname(&un);
- return rb_tainted_str_new2(un.nodename);
-}
-#else
-static VALUE
-sock_gethostname(obj)
- VALUE obj;
-{
- rb_notimplement();
-}
-#endif
-#endif
-
-static VALUE
-mkhostent(h)
- struct hostent *h;
-{
- char **pch;
- VALUE ary, names;
-
- if (h == NULL) {
-#ifdef HAVE_HSTRERROR
- extern int h_errno;
- rb_raise(rb_eSocket, "%s", (char *)hstrerror(h_errno));
-#else
- rb_raise(rb_eSocket, "host not found");
-#endif
- }
- ary = rb_ary_new();
- rb_ary_push(ary, rb_tainted_str_new2(h->h_name));
- names = rb_ary_new();
- rb_ary_push(ary, names);
- for (pch = h->h_aliases; *pch; pch++) {
- rb_ary_push(names, rb_tainted_str_new2(*pch));
- }
- rb_ary_push(ary, INT2NUM(h->h_addrtype));
-#ifdef h_addr
- for (pch = h->h_addr_list; *pch; pch++) {
- rb_ary_push(ary, rb_tainted_str_new(*pch, h->h_length));
- }
-#else
- rb_ary_push(ary, rb_tainted_str_new(h->h_addr, h->h_length));
-#endif
-
- return ary;
-}
-
-static VALUE
-mkaddrinfo(res0)
- struct addrinfo *res0;
-{
- VALUE base, ary;
- struct addrinfo *res;
-
- if (res0 == NULL) {
- rb_raise(rb_eSocket, "host not found");
- }
- base = rb_ary_new();
- for (res = res0; res; res = res->ai_next) {
- ary = ipaddr(res->ai_addr);
- rb_ary_push(ary, INT2FIX(res->ai_family));
- rb_ary_push(ary, INT2FIX(res->ai_socktype));
- rb_ary_push(ary, INT2FIX(res->ai_protocol));
- rb_ary_push(base, ary);
- }
- return base;
-}
-
-/*
- * NOTE: using gethostbyname() against AF_INET6 is a bad idea, as it
- * does not initialize sin_flowinfo nor sin_scope_id properly.
- */
-static VALUE
-sock_s_gethostbyname(obj, host)
- VALUE obj, host;
-{
- struct sockaddr_storage addr;
- struct hostent *h;
-
- if (rb_obj_is_kind_of(host, rb_cInteger)) {
- long i = NUM2LONG(host);
- struct sockaddr_in *sin;
- sin = (struct sockaddr_in *)&addr;
- MEMZERO(sin, struct sockaddr_in, 1);
- sin->sin_family = AF_INET;
- SET_SIN_LEN(sin, sizeof(*sin));
- sin->sin_addr.s_addr = htonl(i);
- }
- else {
- setipaddr(host, (struct sockaddr *)&addr);
- }
- switch (addr.ss_family) {
- case AF_INET:
- {
- struct sockaddr_in *sin;
- sin = (struct sockaddr_in *)&addr;
- h = gethostbyaddr((char *)&sin->sin_addr,
- sizeof(sin->sin_addr),
- sin->sin_family);
- break;
- }
-#ifdef INET6
- case AF_INET6:
- {
- struct sockaddr_in6 *sin6;
- sin6 = (struct sockaddr_in6 *)&addr;
- h = gethostbyaddr((char *)&sin6->sin6_addr,
- sizeof(sin6->sin6_addr),
- sin6->sin6_family);
- break;
- }
-#endif
- default:
- h = NULL;
- }
-
- return mkhostent(h);
-}
-
-static VALUE
-sock_s_gethostbyaddr(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE addr, type;
- struct hostent *h;
- struct sockaddr *sa;
- int t = AF_INET;
-
- rb_scan_args(argc, argv, "11", &addr, &type);
- sa = (struct sockaddr*)StringValuePtr(addr);
- if (!NIL_P(type)) {
- t = NUM2INT(type);
- }
-#ifdef INET6
- else if (RSTRING(addr)->len == 16) {
- t = AF_INET6;
- }
-#endif
- h = gethostbyaddr(RSTRING(addr)->ptr, RSTRING(addr)->len, t);
-
- return mkhostent(h);
-}
-
-static VALUE
-sock_s_getservbyaname(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE service, protocol;
- char *proto;
- struct servent *sp;
- int port;
-
- rb_scan_args(argc, argv, "11", &service, &protocol);
- if (NIL_P(protocol)) proto = "tcp";
- else proto = StringValuePtr(protocol);
-
- StringValue(service);
- sp = getservbyname(RSTRING(service)->ptr, proto);
- if (sp) {
- port = ntohs(sp->s_port);
- }
- else {
- char *s = RSTRING(service)->ptr;
- char *end;
-
- port = strtoul(s, &end, 0);
- if (*end != '\0') {
- rb_raise(rb_eSocket, "no such service %s/%s", s, proto);
- }
- }
- return INT2FIX(port);
-}
-
-static VALUE
-sock_s_getaddrinfo(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE host, port, family, socktype, protocol, flags, ret;
- char hbuf[1024], pbuf[1024];
- char *hptr, *pptr;
- struct addrinfo hints, *res;
- int error;
-
- host = port = family = socktype = protocol = flags = Qnil;
- rb_scan_args(argc, argv, "24", &host, &port, &family, &socktype, &protocol, &flags);
- if (NIL_P(host)) {
- hptr = NULL;
- }
- else {
- strncpy(hbuf, StringValuePtr(host), sizeof(hbuf));
- hbuf[sizeof(hbuf) - 1] = '\0';
- hptr = hbuf;
- }
- if (NIL_P(port)) {
- pptr = NULL;
- }
- else if (FIXNUM_P(port)) {
- snprintf(pbuf, sizeof(pbuf), "%ld", FIX2INT(port));
- pptr = pbuf;
- }
- else {
- strncpy(pbuf, StringValuePtr(port), sizeof(pbuf));
- pbuf[sizeof(pbuf) - 1] = '\0';
- pptr = pbuf;
- }
-
- MEMZERO(&hints, struct addrinfo, 1);
- if (NIL_P(family)) {
- hints.ai_family = PF_UNSPEC;
- }
- else if (FIXNUM_P(family)) {
- hints.ai_family = FIX2INT(family);
- }
- else {
- StringValue(family);
- if (strcmp(RSTRING(family)->ptr, "AF_INET") == 0) {
- hints.ai_family = PF_INET;
- }
-#ifdef INET6
- else if (strcmp(RSTRING(family)->ptr, "AF_INET6") == 0) {
- hints.ai_family = PF_INET6;
- }
-#endif
- }
-
- if (!NIL_P(socktype)) {
- hints.ai_socktype = NUM2INT(socktype);
- }
- if (!NIL_P(protocol)) {
- hints.ai_protocol = NUM2INT(protocol);
- }
- if (!NIL_P(flags)) {
- hints.ai_flags = NUM2INT(flags);
- }
- error = getaddrinfo(hptr, pptr, &hints, &res);
- if (error) {
- rb_raise(rb_eSocket, "getaddrinfo: %s", gai_strerror(error));
- }
-
- ret = mkaddrinfo(res);
- freeaddrinfo(res);
- return ret;
-}
-
-static VALUE
-sock_s_getnameinfo(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE sa, af = Qnil, host = Qnil, port = Qnil, flags;
- char *hptr, *pptr;
- char hbuf[1024], pbuf[1024];
- int fl;
- struct addrinfo hints, *res = NULL, *r;
- int error;
- struct sockaddr_storage ss;
- struct sockaddr *sap;
- char *ep;
-
- sa = flags = Qnil;
- rb_scan_args(argc, argv, "11", &sa, &flags);
-
- fl = 0;
- if (!NIL_P(flags)) {
- fl = NUM2INT(flags);
- }
- if (TYPE(sa) == T_STRING) {
- if (sizeof(ss) < RSTRING(sa)->len) {
- rb_raise(rb_eTypeError, "sockaddr length too big");
- }
- memcpy(&ss, RSTRING(sa)->ptr, RSTRING(sa)->len);
- if (RSTRING(sa)->len != SA_LEN((struct sockaddr *)&ss)) {
- rb_raise(rb_eTypeError, "sockaddr size differs - should not happen");
- }
- sap = (struct sockaddr *)&ss;
- }
- else if (TYPE(sa) == T_ARRAY) {
- MEMZERO(&hints, struct addrinfo, 1);
- if (RARRAY(sa)->len == 3) {
- af = RARRAY(sa)->ptr[0];
- port = RARRAY(sa)->ptr[1];
- host = RARRAY(sa)->ptr[2];
- }
- else if (RARRAY(sa)->len >= 4) {
- af = RARRAY(sa)->ptr[0];
- port = RARRAY(sa)->ptr[1];
- host = RARRAY(sa)->ptr[3];
- if (NIL_P(host)) {
- host = RARRAY(sa)->ptr[2];
- }
- else {
- /*
- * 4th element holds numeric form, don't resolve.
- * see ipaddr().
- */
- hints.ai_flags |= AI_NUMERICHOST;
- }
- }
- else {
- rb_raise(rb_eArgError, "array size should be 3 or 4, %d given",
- RARRAY(sa)->len);
- }
- /* host */
- if (NIL_P(host)) {
- hptr = NULL;
- }
- else {
- strncpy(hbuf, StringValuePtr(host), sizeof(hbuf));
- hbuf[sizeof(hbuf) - 1] = '\0';
- hptr = hbuf;
- }
- /* port */
- if (NIL_P(port)) {
- strcpy(pbuf, "0");
- pptr = NULL;
- }
- else if (FIXNUM_P(port)) {
- snprintf(pbuf, sizeof(pbuf), "%ld", NUM2INT(port));
- pptr = pbuf;
- }
- else {
- strncpy(pbuf, StringValuePtr(port), sizeof(pbuf));
- pbuf[sizeof(pbuf) - 1] = '\0';
- pptr = pbuf;
- }
- hints.ai_socktype = (fl & NI_DGRAM) ? SOCK_DGRAM : SOCK_STREAM;
- /* af */
- if (NIL_P(af)) {
- hints.ai_family = PF_UNSPEC;
- }
- else if (FIXNUM_P(af)) {
- hints.ai_family = FIX2INT(af);
- }
- else {
- StringValue(af);
- if (strcmp(RSTRING(af)->ptr, "AF_INET") == 0) {
- hints.ai_family = PF_INET;
- }
-#ifdef INET6
- else if (strcmp(RSTRING(af)->ptr, "AF_INET6") == 0) {
- hints.ai_family = PF_INET6;
- }
-#endif
- }
- error = getaddrinfo(hptr, pptr, &hints, &res);
- if (error) goto error_exit_addr;
- sap = res->ai_addr;
- }
- else {
- rb_raise(rb_eTypeError, "expecting String or Array");
- }
-
- error = getnameinfo(sap, SA_LEN(sap), hbuf, sizeof(hbuf),
- pbuf, sizeof(pbuf), fl);
- if (error) goto error_exit_name;
- if (res) {
- for (r = res->ai_next; r; r = r->ai_next) {
- char hbuf2[1024], pbuf2[1024];
-
- sap = r->ai_addr;
- error = getnameinfo(sap, SA_LEN(sap), hbuf2, sizeof(hbuf2),
- pbuf2, sizeof(pbuf2), fl);
- if (error) goto error_exit_name;
- if (strcmp(hbuf, hbuf2) != 0|| strcmp(pbuf, pbuf2) != 0) {
- freeaddrinfo(res);
- rb_raise(rb_eSocket, "sockaddr resolved to multiple nodename");
- }
- }
- freeaddrinfo(res);
- }
- return rb_assoc_new(rb_tainted_str_new2(hbuf), rb_tainted_str_new2(pbuf));
-
- error_exit_addr:
- if (res) freeaddrinfo(res);
- rb_raise(rb_eSocket, "getaddrinfo: %s", gai_strerror(error));
-
- error_exit_name:
- if (res) freeaddrinfo(res);
- rb_raise(rb_eSocket, "getnameinfo: %s", gai_strerror(error));
-}
-
-static VALUE
-sock_s_pack_sockaddr_in(self, port, host)
- VALUE self, port, host;
-{
- struct addrinfo *res = ip_addrsetup(host, port);
- VALUE addr = rb_str_new((char*)res->ai_addr, res->ai_addrlen);
-
- freeaddrinfo(res);
- OBJ_INFECT(addr, port);
- OBJ_INFECT(addr, host);
-
- return addr;
-}
-
-static VALUE
-sock_s_unpack_sockaddr_in(self, addr)
- VALUE self, addr;
-{
- struct sockaddr_in * sockaddr;
-
- sockaddr = (struct sockaddr_in*)StringValuePtr(addr);
- return rb_assoc_new(INT2NUM(ntohs(sockaddr->sin_port)), mkipaddr(sockaddr));
-}
-
-#ifdef HAVE_SYS_UN_H
-static VALUE
-sock_s_pack_sockaddr_un(self, path)
- VALUE self, path;
-{
- struct sockaddr_un sockaddr;
- VALUE addr;
-
- MEMZERO(&sockaddr, struct sockaddr_un, 1);
- sockaddr.sun_family = AF_UNIX;
- strncpy(sockaddr.sun_path, StringValuePtr(path), sizeof(sockaddr.sun_path)-1);
- addr = rb_str_new((char*)&sockaddr, sizeof(sockaddr));
- OBJ_INFECT(addr, path);
-
- return addr;
-}
-
-static VALUE
-sock_s_unpack_sockaddr_un(self, addr)
- VALUE self, addr;
-{
- struct sockaddr_un * sockaddr;
-
- sockaddr = (struct sockaddr_un*)StringValuePtr(addr);
- /* xxx: should I check against sun_path size? */
- return rb_tainted_str_new2(sockaddr->sun_path);
-}
-#endif
-
-static VALUE mConst;
-
-static void
-sock_define_const(name, value)
- char *name;
- int value;
-{
- rb_define_const(rb_cSocket, name, INT2FIX(value));
- rb_define_const(mConst, name, INT2FIX(value));
-}
-
-void
-Init_socket()
-{
- rb_eSocket = rb_define_class("SocketError", rb_eStandardError);
-
- rb_cBasicSocket = rb_define_class("BasicSocket", rb_cIO);
- rb_undef_method(rb_cBasicSocket, "initialize");
-
- rb_define_singleton_method(rb_cBasicSocket, "do_not_reverse_lookup",
- bsock_do_not_rev_lookup, 0);
- rb_define_singleton_method(rb_cBasicSocket, "do_not_reverse_lookup=",
- bsock_do_not_rev_lookup_set, 1);
- rb_define_singleton_method(rb_cBasicSocket, "for_fd", bsock_s_for_fd, 1);
-
- rb_define_method(rb_cBasicSocket, "close_read", bsock_close_read, 0);
- rb_define_method(rb_cBasicSocket, "close_write", bsock_close_write, 0);
- rb_define_method(rb_cBasicSocket, "shutdown", bsock_shutdown, -1);
- rb_define_method(rb_cBasicSocket, "setsockopt", bsock_setsockopt, 3);
- rb_define_method(rb_cBasicSocket, "getsockopt", bsock_getsockopt, 2);
- rb_define_method(rb_cBasicSocket, "getsockname", bsock_getsockname, 0);
- rb_define_method(rb_cBasicSocket, "getpeername", bsock_getpeername, 0);
- rb_define_method(rb_cBasicSocket, "send", bsock_send, -1);
- rb_define_method(rb_cBasicSocket, "recv", bsock_recv, -1);
-
- rb_cIPSocket = rb_define_class("IPSocket", rb_cBasicSocket);
- rb_define_global_const("IPsocket", rb_cIPSocket);
- rb_define_method(rb_cIPSocket, "addr", ip_addr, 0);
- rb_define_method(rb_cIPSocket, "peeraddr", ip_peeraddr, 0);
- rb_define_method(rb_cIPSocket, "recvfrom", ip_recvfrom, -1);
- rb_define_singleton_method(rb_cIPSocket, "getaddress", ip_s_getaddress, 1);
-
- rb_cTCPSocket = rb_define_class("TCPSocket", rb_cIPSocket);
- rb_define_global_const("TCPsocket", rb_cTCPSocket);
- rb_define_singleton_method(rb_cTCPSocket, "gethostbyname", tcp_s_gethostbyname, 1);
- rb_define_method(rb_cTCPSocket, "initialize", tcp_init, -1);
-
-#ifdef SOCKS
- rb_cSOCKSSocket = rb_define_class("SOCKSSocket", rb_cTCPSocket);
- rb_define_global_const("SOCKSsocket", rb_cSOCKSSocket);
- rb_define_method(rb_cSOCKSSocket, "initialize", socks_init, 2);
-#ifdef SOCKS5
- rb_define_method(rb_cSOCKSSocket, "close", socks_s_close, 0);
-#endif
-#endif
-
- rb_cTCPServer = rb_define_class("TCPServer", rb_cTCPSocket);
- rb_define_global_const("TCPserver", rb_cTCPServer);
- rb_define_method(rb_cTCPServer, "accept", tcp_accept, 0);
- rb_define_method(rb_cTCPServer, "initialize", tcp_svr_init, -1);
- rb_define_method(rb_cTCPServer, "listen", sock_listen, 1);
-
- rb_cUDPSocket = rb_define_class("UDPSocket", rb_cIPSocket);
- rb_define_global_const("UDPsocket", rb_cUDPSocket);
- rb_define_method(rb_cUDPSocket, "initialize", udp_init, -1);
- rb_define_method(rb_cUDPSocket, "connect", udp_connect, 2);
- rb_define_method(rb_cUDPSocket, "bind", udp_bind, 2);
- rb_define_method(rb_cUDPSocket, "send", udp_send, -1);
-
-#ifdef HAVE_SYS_UN_H
- rb_cUNIXSocket = rb_define_class("UNIXSocket", rb_cBasicSocket);
- rb_define_global_const("UNIXsocket", rb_cUNIXSocket);
- rb_define_method(rb_cUNIXSocket, "initialize", unix_init, 1);
- rb_define_method(rb_cUNIXSocket, "path", unix_path, 0);
- rb_define_method(rb_cUNIXSocket, "addr", unix_addr, 0);
- rb_define_method(rb_cUNIXSocket, "peeraddr", unix_peeraddr, 0);
- rb_define_method(rb_cUNIXSocket, "recvfrom", unix_recvfrom, -1);
- rb_define_method(rb_cUNIXSocket, "send_io", unix_send_io, 1);
- rb_define_method(rb_cUNIXSocket, "recv_io", unix_recv_io, -1);
- rb_define_singleton_method(rb_cUNIXSocket, "socketpair", unix_s_socketpair, -1);
- rb_define_singleton_method(rb_cUNIXSocket, "pair", unix_s_socketpair, -1);
-
- rb_cUNIXServer = rb_define_class("UNIXServer", rb_cUNIXSocket);
- rb_define_global_const("UNIXserver", rb_cUNIXServer);
- rb_define_method(rb_cUNIXServer, "initialize", unix_svr_init, 1);
- rb_define_method(rb_cUNIXServer, "accept", unix_accept, 0);
- rb_define_method(rb_cUNIXServer, "listen", sock_listen, 1);
-#endif
-
- rb_cSocket = rb_define_class("Socket", rb_cBasicSocket);
-
- rb_define_method(rb_cSocket, "initialize", sock_init, 3);
- rb_define_method(rb_cSocket, "connect", sock_connect, 1);
- rb_define_method(rb_cSocket, "bind", sock_bind, 1);
- rb_define_method(rb_cSocket, "listen", sock_listen, 1);
- rb_define_method(rb_cSocket, "accept", sock_accept, 0);
-
- rb_define_method(rb_cSocket, "recvfrom", sock_recvfrom, -1);
-
- rb_define_singleton_method(rb_cSocket, "socketpair", sock_s_socketpair, 3);
- rb_define_singleton_method(rb_cSocket, "pair", sock_s_socketpair, 3);
- rb_define_singleton_method(rb_cSocket, "gethostname", sock_gethostname, 0);
- rb_define_singleton_method(rb_cSocket, "gethostbyname", sock_s_gethostbyname, 1);
- rb_define_singleton_method(rb_cSocket, "gethostbyaddr", sock_s_gethostbyaddr, -1);
- rb_define_singleton_method(rb_cSocket, "getservbyname", sock_s_getservbyaname, -1);
- rb_define_singleton_method(rb_cSocket, "getaddrinfo", sock_s_getaddrinfo, -1);
- rb_define_singleton_method(rb_cSocket, "getnameinfo", sock_s_getnameinfo, -1);
- rb_define_singleton_method(rb_cSocket, "sockaddr_in", sock_s_pack_sockaddr_in, 2);
- rb_define_singleton_method(rb_cSocket, "pack_sockaddr_in", sock_s_pack_sockaddr_in, 2);
- rb_define_singleton_method(rb_cSocket, "unpack_sockaddr_in", sock_s_unpack_sockaddr_in, 1);
-#ifdef HAVE_SYS_UN_H
- rb_define_singleton_method(rb_cSocket, "sockaddr_un", sock_s_pack_sockaddr_un, 1);
- rb_define_singleton_method(rb_cSocket, "pack_sockaddr_un", sock_s_pack_sockaddr_un, 1);
- rb_define_singleton_method(rb_cSocket, "unpack_sockaddr_un", sock_s_unpack_sockaddr_un, 1);
-#endif
-
- /* constants */
- mConst = rb_define_module_under(rb_cSocket, "Constants");
- sock_define_const("SOCK_STREAM", SOCK_STREAM);
- sock_define_const("SOCK_DGRAM", SOCK_DGRAM);
-#ifdef SOCK_RAW
- sock_define_const("SOCK_RAW", SOCK_RAW);
-#endif
-#ifdef SOCK_RDM
- sock_define_const("SOCK_RDM", SOCK_RDM);
-#endif
-#ifdef SOCK_SEQPACKET
- sock_define_const("SOCK_SEQPACKET", SOCK_SEQPACKET);
-#endif
-#ifdef SOCK_PACKET
- sock_define_const("SOCK_PACKET", SOCK_PACKET);
-#endif
-
- sock_define_const("AF_INET", AF_INET);
-#ifdef PF_INET
- sock_define_const("PF_INET", PF_INET);
-#endif
-#ifdef AF_UNIX
- sock_define_const("AF_UNIX", AF_UNIX);
- sock_define_const("PF_UNIX", PF_UNIX);
-#endif
-#ifdef AF_AX25
- sock_define_const("AF_AX25", AF_AX25);
- sock_define_const("PF_AX25", PF_AX25);
-#endif
-#ifdef AF_IPX
- sock_define_const("AF_IPX", AF_IPX);
- sock_define_const("PF_IPX", PF_IPX);
-#endif
-#ifdef AF_APPLETALK
- sock_define_const("AF_APPLETALK", AF_APPLETALK);
- sock_define_const("PF_APPLETALK", PF_APPLETALK);
-#endif
-#ifdef AF_UNSPEC
- sock_define_const("AF_UNSPEC", AF_UNSPEC);
- sock_define_const("PF_UNSPEC", PF_UNSPEC);
-#endif
-#ifdef AF_INET6
- sock_define_const("AF_INET6", AF_INET6);
-#endif
-#ifdef PF_INET6
- sock_define_const("PF_INET6", PF_INET6);
-#endif
-
- sock_define_const("MSG_OOB", MSG_OOB);
-#ifdef MSG_PEEK
- sock_define_const("MSG_PEEK", MSG_PEEK);
-#endif
-#ifdef MSG_DONTROUTE
- sock_define_const("MSG_DONTROUTE", MSG_DONTROUTE);
-#endif
-
- sock_define_const("SOL_SOCKET", SOL_SOCKET);
-#ifdef SOL_IP
- sock_define_const("SOL_IP", SOL_IP);
-#endif
-#ifdef SOL_IPX
- sock_define_const("SOL_IPX", SOL_IPX);
-#endif
-#ifdef SOL_AX25
- sock_define_const("SOL_AX25", SOL_AX25);
-#endif
-#ifdef SOL_ATALK
- sock_define_const("SOL_ATALK", SOL_ATALK);
-#endif
-#ifdef SOL_TCP
- sock_define_const("SOL_TCP", SOL_TCP);
-#endif
-#ifdef SOL_UDP
- sock_define_const("SOL_UDP", SOL_UDP);
-#endif
-
-#ifdef IPPROTO_IP
- sock_define_const("IPPROTO_IP", IPPROTO_IP);
-#else
- sock_define_const("IPPROTO_IP", 0);
-#endif
-#ifdef IPPROTO_ICMP
- sock_define_const("IPPROTO_ICMP", IPPROTO_ICMP);
-#else
- sock_define_const("IPPROTO_ICMP", 1);
-#endif
-#ifdef IPPROTO_IGMP
- sock_define_const("IPPROTO_IGMP", IPPROTO_IGMP);
-#endif
-#ifdef IPPROTO_GGP
- sock_define_const("IPPROTO_GGP", IPPROTO_GGP);
-#endif
-#ifdef IPPROTO_TCP
- sock_define_const("IPPROTO_TCP", IPPROTO_TCP);
-#else
- sock_define_const("IPPROTO_TCP", 6);
-#endif
-#ifdef IPPROTO_EGP
- sock_define_const("IPPROTO_EGP", IPPROTO_EGP);
-#endif
-#ifdef IPPROTO_PUP
- sock_define_const("IPPROTO_PUP", IPPROTO_PUP);
-#endif
-#ifdef IPPROTO_UDP
- sock_define_const("IPPROTO_UDP", IPPROTO_UDP);
-#else
- sock_define_const("IPPROTO_UDP", 17);
-#endif
-#ifdef IPPROTO_IDP
- sock_define_const("IPPROTO_IDP", IPPROTO_IDP);
-#endif
-#ifdef IPPROTO_HELLO
- sock_define_const("IPPROTO_HELLO", IPPROTO_HELLO);
-#endif
-#ifdef IPPROTO_ND
- sock_define_const("IPPROTO_ND", IPPROTO_ND);
-#endif
-#ifdef IPPROTO_TP
- sock_define_const("IPPROTO_TP", IPPROTO_TP);
-#endif
-#ifdef IPPROTO_XTP
- sock_define_const("IPPROTO_XTP", IPPROTO_XTP);
-#endif
-#ifdef IPPROTO_EON
- sock_define_const("IPPROTO_EON", IPPROTO_EON);
-#endif
-#ifdef IPPROTO_BIP
- sock_define_const("IPPROTO_BIP", IPPROTO_BIP);
-#endif
-/**/
-#ifdef IPPROTO_RAW
- sock_define_const("IPPROTO_RAW", IPPROTO_RAW);
-#else
- sock_define_const("IPPROTO_RAW", 255);
-#endif
-#ifdef IPPROTO_MAX
- sock_define_const("IPPROTO_MAX", IPPROTO_MAX);
-#endif
-
- /* Some port configuration */
-#ifdef IPPORT_RESERVED
- sock_define_const("IPPORT_RESERVED", IPPORT_RESERVED);
-#else
- sock_define_const("IPPORT_RESERVED", 1024);
-#endif
-#ifdef IPPORT_USERRESERVED
- sock_define_const("IPPORT_USERRESERVED", IPPORT_USERRESERVED);
-#else
- sock_define_const("IPPORT_USERRESERVED", 5000);
-#endif
- /* Some reserved IP v.4 addresses */
-#ifdef INADDR_ANY
- sock_define_const("INADDR_ANY", INADDR_ANY);
-#else
- sock_define_const("INADDR_ANY", 0x00000000);
-#endif
-#ifdef INADDR_BROADCAST
- sock_define_const("INADDR_BROADCAST", INADDR_BROADCAST);
-#else
- sock_define_const("INADDR_BROADCAST", 0xffffffff);
-#endif
-#ifdef INADDR_LOOPBACK
- sock_define_const("INADDR_LOOPBACK", INADDR_LOOPBACK);
-#else
- sock_define_const("INADDR_LOOPBACK", 0x7F000001);
-#endif
-#ifdef INADDR_UNSPEC_GROUP
- sock_define_const("INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
-#else
- sock_define_const("INADDR_UNSPEC_GROUP", 0xe0000000);
-#endif
-#ifdef INADDR_ALLHOSTS_GROUP
- sock_define_const("INADDR_ALLHOSTS_GROUP", INADDR_ALLHOSTS_GROUP);
-#else
- sock_define_const("INADDR_ALLHOSTS_GROUP", 0xe0000001);
-#endif
-#ifdef INADDR_MAX_LOCAL_GROUP
- sock_define_const("INADDR_MAX_LOCAL_GROUP", INADDR_MAX_LOCAL_GROUP);
-#else
- sock_define_const("INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
-#endif
-#ifdef INADDR_NONE
- sock_define_const("INADDR_NONE", INADDR_NONE);
-#else
- sock_define_const("INADDR_NONE", 0xffffffff);
-#endif
- /* IP [gs]etsockopt options */
-#ifdef IP_OPTIONS
- sock_define_const("IP_OPTIONS", IP_OPTIONS);
-#endif
-#ifdef IP_HDRINCL
- sock_define_const("IP_HDRINCL", IP_HDRINCL);
-#endif
-#ifdef IP_TOS
- sock_define_const("IP_TOS", IP_TOS);
-#endif
-#ifdef IP_TTL
- sock_define_const("IP_TTL", IP_TTL);
-#endif
-#ifdef IP_RECVOPTS
- sock_define_const("IP_RECVOPTS", IP_RECVOPTS);
-#endif
-#ifdef IP_RECVRETOPTS
- sock_define_const("IP_RECVRETOPTS", IP_RECVRETOPTS);
-#endif
-#ifdef IP_RECVDSTADDR
- sock_define_const("IP_RECVDSTADDR", IP_RECVDSTADDR);
-#endif
-#ifdef IP_RETOPTS
- sock_define_const("IP_RETOPTS", IP_RETOPTS);
-#endif
-#ifdef IP_MULTICAST_IF
- sock_define_const("IP_MULTICAST_IF", IP_MULTICAST_IF);
-#endif
-#ifdef IP_MULTICAST_TTL
- sock_define_const("IP_MULTICAST_TTL", IP_MULTICAST_TTL);
-#endif
-#ifdef IP_MULTICAST_LOOP
- sock_define_const("IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
-#endif
-#ifdef IP_ADD_MEMBERSHIP
- sock_define_const("IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
-#endif
-#ifdef IP_DROP_MEMBERSHIP
- sock_define_const("IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
-#endif
-#ifdef IP_DEFAULT_MULTICAST_TTL
- sock_define_const("IP_DEFAULT_MULTICAST_TTL", IP_DEFAULT_MULTICAST_TTL);
-#endif
-#ifdef IP_DEFAULT_MULTICAST_LOOP
- sock_define_const("IP_DEFAULT_MULTICAST_LOOP", IP_DEFAULT_MULTICAST_LOOP);
-#endif
-#ifdef IP_MAX_MEMBERSHIPS
- sock_define_const("IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS);
-#endif
-#ifdef SO_DEBUG
- sock_define_const("SO_DEBUG", SO_DEBUG);
-#endif
- sock_define_const("SO_REUSEADDR", SO_REUSEADDR);
-#ifdef SO_TYPE
- sock_define_const("SO_TYPE", SO_TYPE);
-#endif
-#ifdef SO_ERROR
- sock_define_const("SO_ERROR", SO_ERROR);
-#endif
-#ifdef SO_DONTROUTE
- sock_define_const("SO_DONTROUTE", SO_DONTROUTE);
-#endif
-#ifdef SO_BROADCAST
- sock_define_const("SO_BROADCAST", SO_BROADCAST);
-#endif
-#ifdef SO_SNDBUF
- sock_define_const("SO_SNDBUF", SO_SNDBUF);
-#endif
-#ifdef SO_RCVBUF
- sock_define_const("SO_RCVBUF", SO_RCVBUF);
-#endif
-#ifdef SO_KEEPALIVE
- sock_define_const("SO_KEEPALIVE", SO_KEEPALIVE);
-#endif
-#ifdef SO_OOBINLINE
- sock_define_const("SO_OOBINLINE", SO_OOBINLINE);
-#endif
-#ifdef SO_NO_CHECK
- sock_define_const("SO_NO_CHECK", SO_NO_CHECK);
-#endif
-#ifdef SO_PRIORITY
- sock_define_const("SO_PRIORITY", SO_PRIORITY);
-#endif
-#ifdef SO_LINGER
- sock_define_const("SO_LINGER", SO_LINGER);
-#endif
-#ifdef SO_PASSCRED
- sock_define_const("SO_PASSCRED", SO_PASSCRED);
-#endif
-#ifdef SO_PEERCRED
- sock_define_const("SO_PEERCRED", SO_PEERCRED);
-#endif
-#ifdef SO_RCVLOWAT
- sock_define_const("SO_RCVLOWAT", SO_RCVLOWAT);
-#endif
-#ifdef SO_SNDLOWAT
- sock_define_const("SO_SNDLOWAT", SO_SNDLOWAT);
-#endif
-#ifdef SO_RCVTIMEO
- sock_define_const("SO_RCVTIMEO", SO_RCVTIMEO);
-#endif
-#ifdef SO_SNDTIMEO
- sock_define_const("SO_SNDTIMEO", SO_SNDTIMEO);
-#endif
-
-#ifdef SO_SECURITY_AUTHENTICATION
- sock_define_const("SO_SECURITY_AUTHENTICATION", SO_SECURITY_AUTHENTICATION);
-#endif
-#ifdef SO_SECURITY_ENCRYPTION_TRANSPORT
- sock_define_const("SO_SECURITY_ENCRYPTION_TRANSPORT", SO_SECURITY_ENCRYPTION_TRANSPORT);
-#endif
-#ifdef SO_SECURITY_ENCRYPTION_NETWORK
- sock_define_const("SO_SECURITY_ENCRYPTION_NETWORK", SO_SECURITY_ENCRYPTION_NETWORK);
-#endif
-
-#ifdef SO_BINDTODEVICE
- sock_define_const("SO_BINDTODEVICE", SO_BINDTODEVICE);
-#endif
-#ifdef SO_ATTACH_FILTER
- sock_define_const("SO_ATTACH_FILTER", SO_ATTACH_FILTER);
-#endif
-#ifdef SO_DETACH_FILTER
- sock_define_const("SO_DETACH_FILTER", SO_DETACH_FILTER);
-#endif
-#ifdef SO_PEERNAME
- sock_define_const("SO_PEERNAME", SO_PEERNAME);
-#endif
-#ifdef SO_TIMESTAMP
- sock_define_const("SO_TIMESTAMP", SO_TIMESTAMP);
-#endif
-
-#ifdef SOPRI_INTERACTIVE
- sock_define_const("SOPRI_INTERACTIVE", SOPRI_INTERACTIVE);
-#endif
-#ifdef SOPRI_NORMAL
- sock_define_const("SOPRI_NORMAL", SOPRI_NORMAL);
-#endif
-#ifdef SOPRI_BACKGROUND
- sock_define_const("SOPRI_BACKGROUND", SOPRI_BACKGROUND);
-#endif
-
-#ifdef IPX_TYPE
- sock_define_const("IPX_TYPE", IPX_TYPE);
-#endif
-
-#ifdef TCP_NODELAY
- sock_define_const("TCP_NODELAY", TCP_NODELAY);
-#endif
-#ifdef TCP_MAXSEG
- sock_define_const("TCP_MAXSEG", TCP_MAXSEG);
-#endif
-
-#ifdef EAI_ADDRFAMILY
- sock_define_const("EAI_ADDRFAMILY", EAI_ADDRFAMILY);
-#endif
-#ifdef EAI_AGAIN
- sock_define_const("EAI_AGAIN", EAI_AGAIN);
-#endif
-#ifdef EAI_BADFLAGS
- sock_define_const("EAI_BADFLAGS", EAI_BADFLAGS);
-#endif
-#ifdef EAI_FAIL
- sock_define_const("EAI_FAIL", EAI_FAIL);
-#endif
-#ifdef EAI_FAMILY
- sock_define_const("EAI_FAMILY", EAI_FAMILY);
-#endif
-#ifdef EAI_MEMORY
- sock_define_const("EAI_MEMORY", EAI_MEMORY);
-#endif
-#ifdef EAI_NODATA
- sock_define_const("EAI_NODATA", EAI_NODATA);
-#endif
-#ifdef EAI_NONAME
- sock_define_const("EAI_NONAME", EAI_NONAME);
-#endif
-#ifdef EAI_SERVICE
- sock_define_const("EAI_SERVICE", EAI_SERVICE);
-#endif
-#ifdef EAI_SOCKTYPE
- sock_define_const("EAI_SOCKTYPE", EAI_SOCKTYPE);
-#endif
-#ifdef EAI_SYSTEM
- sock_define_const("EAI_SYSTEM", EAI_SYSTEM);
-#endif
-#ifdef EAI_BADHINTS
- sock_define_const("EAI_BADHINTS", EAI_BADHINTS);
-#endif
-#ifdef EAI_PROTOCOL
- sock_define_const("EAI_PROTOCOL", EAI_PROTOCOL);
-#endif
-#ifdef EAI_MAX
- sock_define_const("EAI_MAX", EAI_MAX);
-#endif
-#ifdef AI_PASSIVE
- sock_define_const("AI_PASSIVE", AI_PASSIVE);
-#endif
-#ifdef AI_CANONNAME
- sock_define_const("AI_CANONNAME", AI_CANONNAME);
-#endif
-#ifdef AI_NUMERICHOST
- sock_define_const("AI_NUMERICHOST", AI_NUMERICHOST);
-#endif
-#ifdef AI_MASK
- sock_define_const("AI_MASK", AI_MASK);
-#endif
-#ifdef AI_ALL
- sock_define_const("AI_ALL", AI_ALL);
-#endif
-#ifdef AI_V4MAPPED_CFG
- sock_define_const("AI_V4MAPPED_CFG", AI_V4MAPPED_CFG);
-#endif
-#ifdef AI_ADDRCONFIG
- sock_define_const("AI_ADDRCONFIG", AI_ADDRCONFIG);
-#endif
-#ifdef AI_V4MAPPED
- sock_define_const("AI_V4MAPPED", AI_V4MAPPED);
-#endif
-#ifdef AI_DEFAULT
- sock_define_const("AI_DEFAULT", AI_DEFAULT);
-#endif
-#ifdef NI_MAXHOST
- sock_define_const("NI_MAXHOST", NI_MAXHOST);
-#endif
-#ifdef NI_MAXSERV
- sock_define_const("NI_MAXSERV", NI_MAXSERV);
-#endif
-#ifdef NI_NOFQDN
- sock_define_const("NI_NOFQDN", NI_NOFQDN);
-#endif
-#ifdef NI_NUMERICHOST
- sock_define_const("NI_NUMERICHOST", NI_NUMERICHOST);
-#endif
-#ifdef NI_NAMEREQD
- sock_define_const("NI_NAMEREQD", NI_NAMEREQD);
-#endif
-#ifdef NI_NUMERICSERV
- sock_define_const("NI_NUMERICSERV", NI_NUMERICSERV);
-#endif
-#ifdef NI_DGRAM
- sock_define_const("NI_DGRAM", NI_DGRAM);
-#endif
-}
diff --git a/ext/socket/sockport.h b/ext/socket/sockport.h
deleted file mode 100644
index e1cddf53f4..0000000000
--- a/ext/socket/sockport.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/************************************************
-
- sockport.h -
-
- $Author$
- $Date$
- created at: Fri Apr 30 23:19:34 JST 1999
-
-************************************************/
-
-#ifndef SOCKPORT_H
-#define SOCKPORT_H
-
-#ifndef SA_LEN
-# ifdef HAVE_SA_LEN
-# define SA_LEN(sa) (sa)->sa_len
-# else
-# ifdef INET6
-# define SA_LEN(sa) \
- (((sa)->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) \
- : sizeof(struct sockaddr))
-# else
- /* by tradition, sizeof(struct sockaddr) covers most of the sockaddrs */
-# define SA_LEN(sa) (sizeof(struct sockaddr))
-# endif
-# endif
-#endif
-
-#ifdef HAVE_SA_LEN
-# define SET_SA_LEN(sa, len) (sa)->sa_len = (len)
-#else
-# define SET_SA_LEN(sa, len) (len)
-#endif
-
-#ifdef HAVE_SIN_LEN
-# define SIN_LEN(si) (si)->sin_len
-# define SET_SIN_LEN(si,len) (si)->sin_len = (len)
-#else
-# define SIN_LEN(si) sizeof(struct sockaddr_in)
-# define SET_SIN_LEN(si,len)
-#endif
-
-#ifndef IN_MULTICAST
-# define IN_CLASSD(i) (((long)(i) & 0xf0000000) == 0xe0000000)
-# define IN_MULTICAST(i) IN_CLASSD(i)
-#endif
-
-#ifndef IN_EXPERIMENTAL
-# define IN_EXPERIMENTAL(i) ((((long)(i)) & 0xe0000000) == 0xe0000000)
-#endif
-
-#ifndef IN_CLASSA_NSHIFT
-# define IN_CLASSA_NSHIFT 24
-#endif
-
-#ifndef IN_LOOPBACKNET
-# define IN_LOOPBACKNET 127
-#endif
-
-#ifndef AF_UNSPEC
-# define AF_UNSPEC 0
-#endif
-
-#ifndef PF_UNSPEC
-# define PF_UNSPEC AF_UNSPEC
-#endif
-
-#ifndef PF_INET
-# define PF_INET AF_INET
-#endif
-
-#if defined(HOST_NOT_FOUND) && !defined(h_errno) && !defined(__CYGWIN__)
-extern int h_errno;
-#endif
-
-#endif
diff --git a/ext/stringio/MANIFEST b/ext/stringio/MANIFEST
deleted file mode 100644
index 4f3a7dc6d0..0000000000
--- a/ext/stringio/MANIFEST
+++ /dev/null
@@ -1,4 +0,0 @@
-MANIFEST
-README
-stringio.c
-depend
diff --git a/ext/stringio/README b/ext/stringio/README
deleted file mode 100644
index c4031f7e97..0000000000
--- a/ext/stringio/README
+++ /dev/null
@@ -1,19 +0,0 @@
--*- rd -*-
-$Author$
-$Date$
-
-=begin
-
-= StringIO
-Pseudo (({IO})) class from/to (({String})).
-
-This library is based on MoonWolf version written in Ruby. Thanks a lot.
-
-= Differences to (({IO}))
-
-* not implemented: (({fcntl})), (({reopen})).
-* (({fileno})) returns nil.
-* (({pos=})) returns new position, not 0.
-* (({ungetc})) does nothing at start of the string.
-
-=end
diff --git a/ext/stringio/depend b/ext/stringio/depend
deleted file mode 100644
index cc9eae3f55..0000000000
--- a/ext/stringio/depend
+++ /dev/null
@@ -1,2 +0,0 @@
-stringio.o: stringio.c $(hdrdir)/ruby.h $(topdir)/config.h \
- $(hdrdir)/defines.h $(hdrdir)/intern.h $(hdrdir)/rubyio.h
diff --git a/ext/stringio/stringio.c b/ext/stringio/stringio.c
deleted file mode 100644
index 27b8aba8ba..0000000000
--- a/ext/stringio/stringio.c
+++ /dev/null
@@ -1,920 +0,0 @@
-/**********************************************************************
-
- stringio.c -
-
- $Author$
- $Date$
- $RoughId: stringio.c,v 1.13 2002/03/14 03:24:18 nobu Exp $
- created at: Tue Feb 19 04:10:38 JST 2002
-
- All the files in this distribution are covered under the Ruby's
- license (see the file COPYING).
-
-**********************************************************************/
-
-#include "ruby.h"
-#include "rubyio.h"
-
-#define STRIO_APPEND 4
-
-struct StringIO {
- VALUE string;
- long pos;
- long lineno;
- int flags;
- int count;
-};
-
-static struct StringIO* strio_alloc _((void));
-static void strio_mark _((struct StringIO *));
-static void strio_free _((struct StringIO *));
-static struct StringIO* check_strio _((VALUE));
-static struct StringIO* get_strio _((VALUE));
-static struct StringIO* readable _((struct StringIO *));
-static struct StringIO* writable _((struct StringIO *));
-static void check_modifiable _((struct StringIO *));
-
-#define IS_STRIO(obj) (RDATA(obj)->dmark == (RUBY_DATA_FUNC)strio_mark)
-#define error_inval(msg) (errno = EINVAL, rb_sys_fail(msg))
-
-static struct StringIO *
-strio_alloc()
-{
- struct StringIO *ptr = ALLOC(struct StringIO);
- ptr->string = Qnil;
- ptr->pos = 0;
- ptr->lineno = 0;
- ptr->flags = 0;
- ptr->count = 1;
- return ptr;
-}
-
-static void
-strio_mark(ptr)
- struct StringIO *ptr;
-{
- rb_gc_mark(ptr->string);
-}
-
-static void
-strio_free(ptr)
- struct StringIO *ptr;
-{
- if (--ptr->count <= 0) {
- xfree(ptr);
- }
-}
-
-static struct StringIO*
-check_strio(self)
- VALUE self;
-{
- Check_Type(self, T_DATA);
- if (!IS_STRIO(self)) {
- rb_raise(rb_eTypeError, "wrong argument type %s (expected String::IO)",
- rb_class2name(CLASS_OF(self)));
- }
- return DATA_PTR(self);
-}
-
-static struct StringIO*
-get_strio(self)
- VALUE self;
-{
- struct StringIO *ptr = check_strio(self);
-
- if (!ptr) {
- rb_raise(rb_eIOError, "uninitialized stream");
- }
- return ptr;
-}
-
-#define StringIO(obj) get_strio(obj)
-
-#define CLOSED(ptr) NIL_P((ptr)->string)
-#define READABLE(ptr) (!CLOSED(ptr) && ((ptr)->flags & FMODE_READABLE))
-#define WRITABLE(ptr) (!CLOSED(ptr) && ((ptr)->flags & FMODE_WRITABLE))
-
-static struct StringIO*
-readable(ptr)
- struct StringIO *ptr;
-{
- if (!READABLE(ptr)) {
- rb_raise(rb_eIOError, "not opened for reading");
- }
- return ptr;
-}
-
-static struct StringIO*
-writable(ptr)
- struct StringIO *ptr;
-{
- if (!WRITABLE(ptr)) {
- rb_raise(rb_eIOError, "not opened for writing");
- }
- if (!OBJ_TAINTED(ptr->string)) {
- rb_secure(4);
- }
- return ptr;
-}
-
-static void
-check_modifiable(ptr)
- struct StringIO *ptr;
-{
- if (OBJ_FROZEN(ptr->string)) {
- rb_raise(rb_eIOError, "not modifiable string");
- }
- rb_str_modify(ptr->string);
-}
-
-static VALUE strio_s_allocate _((VALUE));
-static VALUE strio_s_open _((int, VALUE *, VALUE));
-static VALUE strio_initialize _((int, VALUE *, VALUE));
-static VALUE strio_finalize _((VALUE));
-static VALUE strio_self _((VALUE));
-static VALUE strio_false _((VALUE));
-static VALUE strio_nil _((VALUE));
-static VALUE strio_0 _((VALUE));
-static VALUE strio_first _((VALUE, VALUE));
-static VALUE strio_unimpl _((int, VALUE *, VALUE));
-static VALUE strio_get_string _((VALUE));
-static VALUE strio_set_string _((VALUE, VALUE));
-static VALUE strio_close _((VALUE));
-static VALUE strio_close_read _((VALUE));
-static VALUE strio_close_write _((VALUE));
-static VALUE strio_closed _((VALUE));
-static VALUE strio_closed_read _((VALUE));
-static VALUE strio_closed_write _((VALUE));
-static VALUE strio_eof _((VALUE));
-static VALUE strio_clone _((VALUE));
-static VALUE strio_get_lineno _((VALUE));
-static VALUE strio_set_lineno _((VALUE, VALUE));
-static VALUE strio_get_pos _((VALUE));
-static VALUE strio_set_pos _((VALUE, VALUE));
-static VALUE strio_rewind _((VALUE));
-static VALUE strio_seek _((int, VALUE *, VALUE));
-static VALUE strio_get_sync _((VALUE));
-static VALUE strio_set_sync _((VALUE, VALUE));
-static VALUE strio_each_byte _((VALUE));
-static VALUE strio_getc _((VALUE));
-static VALUE strio_ungetc _((VALUE, VALUE));
-static VALUE strio_readchar _((VALUE));
-static VALUE strio_gets_internal _((int, VALUE *, struct StringIO *));
-static VALUE strio_gets _((int, VALUE *, VALUE));
-static VALUE strio_readline _((int, VALUE *, VALUE));
-static VALUE strio_each _((int, VALUE *, VALUE));
-static VALUE strio_readlines _((int, VALUE *, VALUE));
-static VALUE strio_write _((VALUE, VALUE));
-static VALUE strio_print _((int, VALUE *, VALUE));
-static VALUE strio_printf _((int, VALUE *, VALUE));
-static VALUE strio_putc _((VALUE, VALUE));
-static VALUE strio_read _((int, VALUE *, VALUE));
-static VALUE strio_size _((VALUE));
-static VALUE strio_truncate _((VALUE, VALUE));
-void Init_stringio _((void));
-
-/* Boyer-Moore search: copied from regex.c */
-static void bm_init_skip _((long *, const char *, long));
-static long bm_search _((const char *, long, const char *, long, const long *));
-
-static VALUE
-strio_s_allocate(klass)
- VALUE klass;
-{
- struct StringIO *ptr;
- return Data_Wrap_Struct(klass, strio_mark, strio_free, 0);
-}
-
-static VALUE
-strio_s_open(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- VALUE obj = rb_class_new_instance(argc, argv, klass);
- if (!rb_block_given_p()) return obj;
- return rb_ensure(rb_yield, obj, strio_finalize, obj);
-}
-
-static VALUE
-strio_initialize(argc, argv, self)
- int argc;
- VALUE *argv;
- VALUE self;
-{
- struct StringIO *ptr = check_strio(self);
- VALUE string, mode;
-
- if (!ptr) {
- DATA_PTR(self) = ptr = strio_alloc();
- }
- rb_call_super(0, 0);
- switch (rb_scan_args(argc, argv, "02", &string, &mode)) {
- case 2:
- StringValue(mode);
- StringValue(string);
- ptr->flags = rb_io_mode_flags(RSTRING(mode)->ptr);
- if (ptr->flags & FMODE_WRITABLE && OBJ_FROZEN(string)) {
- errno = EACCES;
- rb_sys_fail(0);
- }
- switch (*RSTRING(mode)->ptr) {
- case 'a':
- ptr->flags |= STRIO_APPEND;
- break;
- case 'w':
- rb_str_resize(string, 0);
- break;
- }
- break;
- case 1:
- StringValue(string);
- ptr->flags = OBJ_FROZEN(string) ? FMODE_READABLE : FMODE_READWRITE;
- break;
- case 0:
- string = rb_str_new("", 0);
- ptr->flags = FMODE_READWRITE;
- break;
- }
- ptr->string = string;
- return self;
-}
-
-static VALUE
-strio_finalize(self)
- VALUE self;
-{
- struct StringIO *ptr = StringIO(self);
- ptr->string = Qnil;
- ptr->flags &= ~FMODE_READWRITE;
- return self;
-}
-
-static VALUE
-strio_false(self)
- VALUE self;
-{
- StringIO(self);
- return Qfalse;
-}
-
-static VALUE
-strio_nil(self)
- VALUE self;
-{
- StringIO(self);
- return Qnil;
-}
-
-static VALUE
-strio_self(self)
- VALUE self;
-{
- StringIO(self);
- return self;
-}
-
-static VALUE
-strio_0(self)
- VALUE self;
-{
- StringIO(self);
- return INT2FIX(0);
-}
-
-static VALUE
-strio_first(self, arg)
- VALUE self, arg;
-{
- StringIO(self);
- return arg;
-}
-
-static VALUE
-strio_unimpl(argc, argv, self)
- int argc;
- VALUE *argv;
- VALUE self;
-{
- StringIO(self);
- rb_notimplement();
- return Qnil; /* not reached */
-}
-
-static VALUE
-strio_get_string(self)
- VALUE self;
-{
- return StringIO(self)->string;
-}
-
-static VALUE
-strio_set_string(self, string)
- VALUE self, string;
-{
- struct StringIO *ptr = StringIO(self);
-
- if (NIL_P(string)) {
- ptr->flags &= ~FMODE_READWRITE;
- }
- else {
- StringValue(string);
- ptr->flags |= FMODE_READWRITE;
- }
- return ptr->string = string;
-}
-
-static VALUE
-strio_close(self)
- VALUE self;
-{
- struct StringIO *ptr = StringIO(self);
- if (CLOSED(ptr)) {
- rb_raise(rb_eIOError, "closed stream");
- }
- ptr->string = Qnil;
- ptr->flags &= ~FMODE_READWRITE;
- return self;
-}
-
-static VALUE
-strio_close_read(self)
- VALUE self;
-{
- struct StringIO *ptr = StringIO(self);
- if (!READABLE(ptr)) {
- rb_raise(rb_eIOError, "closing non-duplex IO for reading");
- }
- if (!((ptr->flags &= ~FMODE_READABLE) & FMODE_READWRITE)) {
- ptr->string = Qnil;
- }
- return self;
-}
-
-static VALUE
-strio_close_write(self)
- VALUE self;
-{
- struct StringIO *ptr = StringIO(self);
- if (!WRITABLE(ptr)) {
- rb_raise(rb_eIOError, "closing non-duplex IO for writing");
- }
- if (!((ptr->flags &= ~FMODE_WRITABLE) & FMODE_READWRITE)) {
- ptr->string = Qnil;
- }
- return self;
-}
-
-static VALUE
-strio_closed(self)
- VALUE self;
-{
- struct StringIO *ptr = StringIO(self);
- if (!CLOSED(ptr)) return Qfalse;
- return Qtrue;
-}
-
-static VALUE
-strio_closed_read(self)
- VALUE self;
-{
- struct StringIO *ptr = StringIO(self);
- if (READABLE(ptr)) return Qfalse;
- return Qtrue;
-}
-
-static VALUE
-strio_closed_write(self)
- VALUE self;
-{
- struct StringIO *ptr = StringIO(self);
- if (WRITABLE(ptr)) return Qfalse;
- return Qtrue;
-}
-
-static VALUE
-strio_eof(self)
- VALUE self;
-{
- struct StringIO *ptr = readable(StringIO(self));
- if (ptr->pos < RSTRING(ptr->string)->len) return Qfalse;
- return Qtrue;
-}
-
-static VALUE
-strio_clone(self)
- VALUE self;
-{
- struct StringIO *ptr = StringIO(self);
- VALUE clone = rb_call_super(0, 0);
- DATA_PTR(clone) = ptr;
- ++ptr->count;
- return self;
-}
-
-static VALUE
-strio_get_lineno(self)
- VALUE self;
-{
- return LONG2NUM(StringIO(self)->lineno);
-}
-
-static VALUE
-strio_set_lineno(self, lineno)
- VALUE self, lineno;
-{
- StringIO(self)->lineno = NUM2LONG(lineno);
- return lineno;
-}
-
-#define strio_binmode strio_self
-
-#define strio_reopen strio_unimpl
-
-#define strio_fcntl strio_unimpl
-
-#define strio_flush strio_self
-
-#define strio_fsync strio_0
-
-static VALUE
-strio_get_pos(self)
- VALUE self;
-{
- return LONG2NUM(StringIO(self)->pos);
-}
-
-static VALUE
-strio_set_pos(self, pos)
- VALUE self;
- VALUE pos;
-{
- struct StringIO *ptr = StringIO(self);
- long p = NUM2LONG(pos);
- if (p < 0) {
- error_inval(0);
- }
- ptr->pos = p;
- return pos;
-}
-
-static VALUE
-strio_rewind(self)
- VALUE self;
-{
- struct StringIO *ptr = StringIO(self);
- ptr->pos = 0;
- ptr->lineno = 0;
- return INT2FIX(0);
-}
-
-static VALUE
-strio_seek(argc, argv, self)
- int argc;
- VALUE *argv;
- VALUE self;
-{
- VALUE whence;
- struct StringIO *ptr = StringIO(self);
- long offset;
-
- rb_scan_args(argc, argv, "11", NULL, &whence);
- offset = NUM2LONG(argv[0]);
- switch (NIL_P(whence) ? 0 : NUM2LONG(whence)) {
- case 0:
- break;
- case 1:
- offset += ptr->pos;
- break;
- case 2:
- offset += RSTRING(ptr->string)->len;
- break;
- default:
- rb_raise(rb_eArgError, "invalid whence %ld", NUM2LONG(whence));
- }
- if (offset < 0) {
- error_inval(0);
- }
- ptr->pos = offset;
- return INT2FIX(0);
-}
-
-static VALUE
-strio_get_sync(self)
- VALUE self;
-{
- StringIO(self);
- return Qtrue;
-}
-
-#define strio_set_sync strio_first
-
-#define strio_tell strio_get_pos
-
-static VALUE
-strio_each_byte(self)
- VALUE self;
-{
- struct StringIO *ptr = readable(StringIO(self));
- while (ptr->pos < RSTRING(ptr->string)->len) {
- char c = RSTRING(ptr->string)->ptr[ptr->pos++];
- rb_yield(CHR2FIX(c));
- }
- return Qnil;
-}
-
-static VALUE
-strio_getc(self)
- VALUE self;
-{
- struct StringIO *ptr = readable(StringIO(self));
- int c;
- if (ptr->pos >= RSTRING(ptr->string)->len) {
- return Qnil;
- }
- c = RSTRING(ptr->string)->ptr[ptr->pos++];
- return CHR2FIX(c);
-}
-
-static VALUE
-strio_ungetc(self, ch)
- VALUE self, ch;
-{
- struct StringIO *ptr = readable(StringIO(self));
- int cc = NUM2INT(ch);
-
- if (cc != EOF && ptr->pos > 0) {
- if ((unsigned char)RSTRING(ptr->string)->ptr[--ptr->pos] !=
- (unsigned char)cc) {
- check_modifiable(ptr);
- RSTRING(ptr->string)->ptr[ptr->pos] = cc;
- }
- }
- return Qnil;
-}
-
-static VALUE
-strio_readchar(self)
- VALUE self;
-{
- VALUE c = strio_getc(self);
- if (NIL_P(c)) rb_eof_error();
- return c;
-}
-
-static void
-bm_init_skip(skip, pat, m)
- long *skip;
- const char *pat;
- long m;
-{
- int c;
-
- for (c = 0; c < (1 << CHAR_BIT); c++) {
- skip[c] = m;
- }
- while (--m) {
- skip[(unsigned char)*pat++] = m;
- }
-}
-
-static long
-bm_search(little, llen, big, blen, skip)
- const char *little;
- long llen;
- const char *big;
- long blen;
- const long *skip;
-{
- long i, j, k;
-
- i = llen - 1;
- while (i < blen) {
- k = i;
- j = llen - 1;
- while (j >= 0 && big[k] == little[j]) {
- k--;
- j--;
- }
- if (j < 0) return k + 1;
- i += skip[(unsigned char)big[i]];
- }
- return -1;
-}
-
-static VALUE
-strio_gets_internal(argc, argv, ptr)
- int argc;
- VALUE *argv;
- struct StringIO *ptr;
-{
- const char *s, *e, *p;
- long n;
- VALUE str;
-
- if (argc == 0) {
- str = rb_rs;
- }
- else {
- rb_scan_args(argc, argv, "1", &str);
- if (!NIL_P(str)) StringValue(str);
- }
-
- if (ptr->pos >= (n = RSTRING(ptr->string)->len)) return Qnil;
- s = RSTRING(ptr->string)->ptr;
- e = s + RSTRING(ptr->string)->len;
- s += ptr->pos;
- if (NIL_P(str)) {
- str = rb_str_substr(ptr->string, ptr->pos, e - s);
- }
- else if ((n = RSTRING(str)->len) == 0) {
- p = s;
- while (*p == '\n') {
- if (++p == e) return Qnil;
- }
- s = p;
- while (p = memchr(p, '\n', e - p)) {
- if (p == e) break;
- if (*++p == '\n') {
- e = p;
- break;
- }
- }
- str = rb_str_substr(ptr->string, s - RSTRING(ptr->string)->ptr, e - s);
- }
- else if (n == 1) {
- if (p = memchr(s, RSTRING(str)->ptr[0], e - s)) {
- e = p + 1;
- }
- str = rb_str_substr(ptr->string, ptr->pos, e - s);
- }
- else {
- if (n < s - e) {
- if (s - e < 1024) {
- for (p = s; p + n <= e; ++p) {
- if (MEMCMP(p, RSTRING(str)->ptr, char, n) == 0) {
- e = p + n;
- break;
- }
- }
- }
- else {
- long skip[1 << CHAR_BIT], pos;
- p = RSTRING(str)->ptr;
- bm_init_skip(skip, p, n);
- if ((pos = bm_search(p, n, s, e - s, skip)) >= 0) {
- e = s + pos + n;
- }
- }
- }
- str = rb_str_substr(ptr->string, ptr->pos, e - s);
- }
- ptr->pos = e - RSTRING(ptr->string)->ptr;
- ptr->lineno++;
- rb_lastline_set(str);
- return str;
-}
-
-static VALUE
-strio_gets(argc, argv, self)
- int argc;
- VALUE *argv;
- VALUE self;
-{
- return strio_gets_internal(argc, argv, readable(StringIO(self)));
-}
-
-static VALUE
-strio_readline(argc, argv, self)
- int argc;
- VALUE *argv;
- VALUE self;
-{
- VALUE line = strio_gets_internal(argc, argv, readable(StringIO(self)));
- if (NIL_P(line)) rb_eof_error();
- return line;
-}
-
-static VALUE
-strio_each(argc, argv, self)
- int argc;
- VALUE *argv;
- VALUE self;
-{
- struct StringIO *ptr = StringIO(self);
- VALUE line;
-
- while (!NIL_P(line = strio_gets_internal(argc, argv, readable(ptr)))) {
- rb_yield(line);
- }
- return self;
-}
-
-static VALUE
-strio_readlines(argc, argv, self)
- int argc;
- VALUE *argv;
- VALUE self;
-{
- struct StringIO *ptr = StringIO(self);
- VALUE ary = rb_ary_new(), line;
- while (!NIL_P(line = strio_gets_internal(argc, argv, readable(ptr)))) {
- rb_ary_push(ary, line);
- }
- return ary;
-}
-
-static VALUE
-strio_write(self, str)
- VALUE self, str;
-{
- struct StringIO *ptr = writable(StringIO(self));
- long len;
-
- if (TYPE(str) != T_STRING)
- str = rb_obj_as_string(str);
- len = RSTRING(str)->len;
- if (!len) return INT2FIX(0);
- check_modifiable(ptr);
- if (ptr->flags & STRIO_APPEND) {
- ptr->pos = RSTRING(ptr->string)->len;
- }
- if (ptr->pos + len > RSTRING(ptr->string)->len) {
- rb_str_resize(ptr->string, ptr->pos + len);
- }
- rb_str_update(ptr->string, ptr->pos, len, str);
- ptr->pos += len;
- return LONG2NUM(len);
-}
-
-#define strio_addstr rb_io_addstr
-
-#define strio_print rb_io_print
-
-#define strio_printf rb_io_printf
-
-static VALUE
-strio_putc(self, ch)
- VALUE self, ch;
-{
- struct StringIO *ptr = writable(StringIO(self));
- int c = NUM2CHR(ch);
-
- check_modifiable(ptr);
- if (ptr->flags & STRIO_APPEND) {
- ptr->pos = RSTRING(ptr->string)->len;
- }
- if (ptr->pos >= RSTRING(ptr->string)->len) {
- rb_str_resize(ptr->string, ptr->pos + 1);
- }
- RSTRING(ptr->string)->ptr[ptr->pos++] = c;
- return ch;
-}
-
-#define strio_puts rb_io_puts
-
-static VALUE
-strio_read(argc, argv, self)
- int argc;
- VALUE *argv;
- VALUE self;
-{
- struct StringIO *ptr = readable(StringIO(self));
- VALUE str;
- long len;
-
- if (ptr->pos >= RSTRING(ptr->string)->len) {
- return Qnil;
- }
- switch (argc) {
- case 1:
- if (!NIL_P(argv[0])) {
- len = NUM2LONG(argv[0]);
- break;
- }
- /* fall through */
- case 0:
- len = RSTRING(ptr->string)->len - ptr->pos;
- break;
- default:
- rb_raise(rb_eArgError, "wrong number arguments (%d for 0)", argc);
- }
- str = rb_str_substr(ptr->string, ptr->pos, len);
- ptr->pos += len;
- return str;
-}
-
-static VALUE
-strio_sysread(argc, argv, self)
- int argc;
- VALUE *argv;
- VALUE self;
-{
- VALUE val = strio_read(argc, argv, self);
- if (NIL_P(val)) {
- rb_eof_error();
- }
- return val;
-}
-
-#define strio_syswrite strio_write
-
-#define strio_path rb_inspect
-
-#define strio_isatty strio_false
-
-#define strio_pid strio_nil
-
-#define strio_fileno strio_nil
-
-static VALUE
-strio_size(self)
- VALUE self;
-{
- VALUE string = StringIO(self)->string;
- if (NIL_P(string)) {
- rb_raise(rb_eIOError, "not opened");
- }
- return ULONG2NUM(RSTRING(string)->len);
-}
-
-static VALUE
-strio_truncate(self, len)
- VALUE self, len;
-{
- VALUE string = writable(StringIO(self))->string;
- long l = NUM2LONG(len);
- if (l < 0) {
- error_inval("negative legnth");
- }
- rb_str_resize(string, l);
- return len;
-}
-
-void
-Init_stringio()
-{
- VALUE StringIO = rb_define_class("StringIO", rb_cData);
- rb_define_singleton_method(StringIO, "allocate", strio_s_allocate, 0);
- rb_define_singleton_method(StringIO, "open", strio_s_open, -1);
- rb_define_method(StringIO, "initialize", strio_initialize, -1);
- rb_enable_super(StringIO, "initialize");
- rb_define_method(StringIO, "clone", strio_clone, 0);
- rb_enable_super(StringIO, "clone");
- rb_define_method(StringIO, "reopen", strio_reopen, -1);
-
- rb_define_method(StringIO, "string", strio_get_string, 0);
- rb_define_method(StringIO, "string=", strio_set_string, 1);
- rb_define_method(StringIO, "lineno", strio_get_lineno, 0);
- rb_define_method(StringIO, "lineno=", strio_set_lineno, 1);
-
- rb_define_method(StringIO, "binmode", strio_binmode, 0);
- rb_define_method(StringIO, "close", strio_close, 0);
- rb_define_method(StringIO, "close_read", strio_close_read, 0);
- rb_define_method(StringIO, "close_write", strio_close_write, 0);
- rb_define_method(StringIO, "closed?", strio_closed, 0);
- rb_define_method(StringIO, "closed_read?", strio_closed_read, 0);
- rb_define_method(StringIO, "closed_write?", strio_closed_write, 0);
- rb_define_method(StringIO, "eof", strio_eof, 0);
- rb_define_method(StringIO, "eof?", strio_eof, 0);
- rb_define_method(StringIO, "fcntl", strio_fcntl, -1);
- rb_define_method(StringIO, "flush", strio_flush, 0);
- rb_define_method(StringIO, "fsync", strio_fsync, 0);
- rb_define_method(StringIO, "pos", strio_get_pos, 0);
- rb_define_method(StringIO, "pos=", strio_set_pos, 1);
- rb_define_method(StringIO, "rewind", strio_rewind, 0);
- rb_define_method(StringIO, "seek", strio_seek, -1);
- rb_define_method(StringIO, "sync", strio_get_sync, 0);
- rb_define_method(StringIO, "sync=", strio_set_sync, 1);
- rb_define_method(StringIO, "tell", strio_tell, 0);
- rb_define_method(StringIO, "path", strio_path, 0);
-
- rb_define_method(StringIO, "each", strio_each, -1);
- rb_define_method(StringIO, "each_byte", strio_each_byte, 0);
- rb_define_method(StringIO, "each_line", strio_each, -1);
- rb_define_method(StringIO, "getc", strio_getc, 0);
- rb_define_method(StringIO, "ungetc", strio_ungetc, 1);
- rb_define_method(StringIO, "readchar", strio_readchar, 0);
- rb_define_method(StringIO, "gets", strio_gets, -1);
- rb_define_method(StringIO, "readline", strio_readline, -1);
- rb_define_method(StringIO, "readlines", strio_readlines, -1);
- rb_define_method(StringIO, "read", strio_read, -1);
- rb_define_method(StringIO, "sysread", strio_sysread, -1);
-
- rb_define_method(StringIO, "write", strio_write, 1);
- rb_define_method(StringIO, "<<", strio_addstr, 1);
- rb_define_method(StringIO, "print", strio_print, -1);
- rb_define_method(StringIO, "printf", strio_printf, -1);
- rb_define_method(StringIO, "putc", strio_putc, 1);
- rb_define_method(StringIO, "puts", strio_puts, -1);
- rb_define_method(StringIO, "syswrite", strio_syswrite, 1);
-
- rb_define_method(StringIO, "isatty", strio_isatty, 0);
- rb_define_method(StringIO, "tty?", strio_isatty, 0);
- rb_define_method(StringIO, "pid", strio_pid, 0);
- rb_define_method(StringIO, "fileno", strio_fileno, 0);
- rb_define_method(StringIO, "size", strio_size, 0);
- rb_define_method(StringIO, "length", strio_size, 0);
- rb_define_method(StringIO, "truncate", strio_truncate, 1);
-}
diff --git a/ext/syslog/.cvsignore b/ext/syslog/.cvsignore
deleted file mode 100644
index fc802ff1c2..0000000000
--- a/ext/syslog/.cvsignore
+++ /dev/null
@@ -1,2 +0,0 @@
-Makefile
-mkmf.log
diff --git a/ext/syslog/MANIFEST b/ext/syslog/MANIFEST
deleted file mode 100644
index b5306034b7..0000000000
--- a/ext/syslog/MANIFEST
+++ /dev/null
@@ -1,6 +0,0 @@
-MANIFEST
-extconf.rb
-syslog.c
-syslog.txt
-test.rb
-depend
diff --git a/ext/syslog/depend b/ext/syslog/depend
deleted file mode 100644
index 45cbea293a..0000000000
--- a/ext/syslog/depend
+++ /dev/null
@@ -1,2 +0,0 @@
-syslog.o: syslog.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h \
- $(hdrdir)/intern.h
diff --git a/ext/syslog/extconf.rb b/ext/syslog/extconf.rb
deleted file mode 100644
index 0fa0bc339b..0000000000
--- a/ext/syslog/extconf.rb
+++ /dev/null
@@ -1,10 +0,0 @@
-# $RoughId: extconf.rb,v 1.3 2001/11/24 17:49:26 knu Exp $
-# $Id$
-
-require 'mkmf'
-
-have_header("syslog.h") &&
- have_func("openlog") &&
- have_func("setlogmask") &&
- create_makefile("syslog")
-
diff --git a/ext/syslog/syslog.c b/ext/syslog/syslog.c
deleted file mode 100644
index 22e1e02a87..0000000000
--- a/ext/syslog/syslog.c
+++ /dev/null
@@ -1,381 +0,0 @@
-/*
- * UNIX Syslog extension for Ruby
- * Amos Gouaux, University of Texas at Dallas
- * <amos+ruby@utdallas.edu>
- *
- * $RoughId: syslog.c,v 1.21 2002/02/25 12:21:17 knu Exp $
- * $Id$
- */
-
-#include "ruby.h"
-#include <syslog.h>
-
-/* Syslog class */
-static VALUE mSyslog, mSyslogConstants;
-static VALUE syslog_ident = Qnil, syslog_options = INT2FIX(-1),
- syslog_facility = INT2FIX(-1), syslog_mask = INT2FIX(-1);
-static int syslog_opened = 0;
-
-/* Package helper routines */
-static void syslog_write(int pri, int argc, VALUE *argv)
-{
- VALUE str;
-
- if (argc < 1) {
- rb_raise(rb_eArgError, "no log message supplied");
- }
-
- if (!syslog_opened) {
- rb_raise(rb_eRuntimeError, "must open syslog before write");
- }
-
- str = rb_f_sprintf(argc, argv);
-
- syslog(pri, "%s", RSTRING(str)->ptr);
-}
-
-/* Syslog module methods */
-static VALUE mSyslog_close(VALUE self)
-{
- closelog();
- syslog_opened = 0;
-
- return Qnil;
-}
-
-static VALUE mSyslog_open(int argc, VALUE *argv, VALUE self)
-{
- VALUE ident, opt, fac;
- int mask;
-
- if (syslog_opened) {
- rb_raise(rb_eRuntimeError, "syslog already open");
- }
- rb_scan_args(argc, argv, "03", &ident, &opt, &fac);
- if (NIL_P(ident)) {
- ident = rb_gv_get("$0");
- }
- if (NIL_P(opt)) {
- opt = INT2NUM(LOG_PID | LOG_CONS);
- }
- if (NIL_P(fac)) {
- fac = INT2NUM(LOG_USER);
- }
-
-#ifdef SafeStringValue
- SafeStringValue(ident);
-#else
- Check_SafeStr(ident);
-#endif
- syslog_ident = ident;
- syslog_options = opt;
- syslog_facility = fac;
- openlog(RSTRING(ident)->ptr, NUM2INT(opt), NUM2INT(fac));
- syslog_opened = 1;
-
- setlogmask(mask = setlogmask(0));
- syslog_mask = INT2NUM(mask);
-
- /* be like File.new.open {...} */
- if (rb_block_given_p()) {
- rb_ensure(rb_yield, self, mSyslog_close, self);
- }
-
- return self;
-}
-
-static VALUE mSyslog_reopen(int argc, VALUE *argv, VALUE self)
-{
- mSyslog_close(self);
-
- return mSyslog_open(argc, argv, self);
-}
-
-static VALUE mSyslog_isopen(VALUE self)
-{
- return syslog_opened ? Qtrue : Qfalse;
-}
-
-static VALUE mSyslog_ident(VALUE self)
-{
- return syslog_ident;
-}
-
-static VALUE mSyslog_options(VALUE self)
-{
- return syslog_options;
-}
-
-static VALUE mSyslog_facility(VALUE self)
-{
- return syslog_facility;
-}
-
-static VALUE mSyslog_get_mask(VALUE self)
-{
- return syslog_mask;
-}
-
-static VALUE mSyslog_set_mask(VALUE self, VALUE mask)
-{
- if (!syslog_opened) {
- rb_raise(rb_eRuntimeError, "must open syslog before setting log mask");
- }
-
- setlogmask(NUM2INT(mask));
- syslog_mask = mask;
-
- return mask;
-}
-
-static VALUE mSyslog_log(int argc, VALUE *argv, VALUE self)
-{
- VALUE pri;
-
- if (argc < 2) {
- rb_raise(rb_eArgError, "wrong # of arguments(%d for 2+)", argc);
- }
-
- argc--;
- pri = *argv++;
-
- if (!FIXNUM_P(pri)) {
- rb_raise(rb_eTypeError, "type mismatch: %s given", rb_class2name(CLASS_OF(pri)));
- }
-
- syslog_write(FIX2INT(pri), argc, argv);
-
- return self;
-}
-
-static VALUE mSyslog_inspect(VALUE self)
-{
-#define N 7
- int argc = N;
- VALUE argv[N];
- const char fmt[] =
- "<#%s: opened=%s, ident=\"%s\", options=%d, facility=%d, mask=%d>";
-
- argv[0] = rb_str_new(fmt, sizeof(fmt) - 1);
- argv[1] = mSyslog;
- argv[2] = syslog_opened ? Qtrue : Qfalse;
- argv[3] = syslog_ident;
- argv[4] = syslog_options;
- argv[5] = syslog_facility;
- argv[6] = syslog_mask;
-
- return rb_f_sprintf(argc, argv);
-#undef N
-}
-
-static VALUE mSyslog_instance(VALUE self)
-{
- return self;
-}
-
-#define define_syslog_shortcut_method(pri, name) \
-static VALUE mSyslog_##name(int argc, VALUE *argv, VALUE self) \
-{ \
- syslog_write(pri, argc, argv); \
-\
- return self; \
-}
-
-#ifdef LOG_EMERG
-define_syslog_shortcut_method(LOG_EMERG, emerg)
-#endif
-#ifdef LOG_ALERT
-define_syslog_shortcut_method(LOG_ALERT, alert)
-#endif
-#ifdef LOG_CRIT
-define_syslog_shortcut_method(LOG_CRIT, crit)
-#endif
-#ifdef LOG_ERR
-define_syslog_shortcut_method(LOG_ERR, err)
-#endif
-#ifdef LOG_WARNING
-define_syslog_shortcut_method(LOG_WARNING, warning)
-#endif
-#ifdef LOG_NOTICE
-define_syslog_shortcut_method(LOG_NOTICE, notice)
-#endif
-#ifdef LOG_INFO
-define_syslog_shortcut_method(LOG_INFO, info)
-#endif
-#ifdef LOG_DEBUG
-define_syslog_shortcut_method(LOG_DEBUG, debug)
-#endif
-
-static VALUE mSyslogConstants_LOG_MASK(VALUE klass, VALUE pri)
-{
- return INT2FIX(LOG_MASK(FIX2INT(pri)));
-}
-
-static VALUE mSyslogConstants_LOG_UPTO(VALUE klass, VALUE pri)
-{
- return INT2FIX(LOG_UPTO(FIX2INT(pri)));
-}
-
-/* Init for package syslog */
-void Init_syslog()
-{
- mSyslog = rb_define_module("Syslog");
-
- mSyslogConstants = rb_define_module_under(mSyslog, "Constants");
-
- rb_include_module(mSyslog, mSyslogConstants);
-
- rb_define_module_function(mSyslog, "open", mSyslog_open, -1);
- rb_define_module_function(mSyslog, "reopen", mSyslog_reopen, -1);
- rb_define_module_function(mSyslog, "open!", mSyslog_reopen, -1);
- rb_define_module_function(mSyslog, "opened?", mSyslog_isopen, 0);
-
- rb_define_module_function(mSyslog, "ident", mSyslog_ident, 0);
- rb_define_module_function(mSyslog, "options", mSyslog_options, 0);
- rb_define_module_function(mSyslog, "facility", mSyslog_facility, 0);
-
- rb_define_module_function(mSyslog, "log", mSyslog_log, -1);
- rb_define_module_function(mSyslog, "close", mSyslog_close, 0);
- rb_define_module_function(mSyslog, "mask", mSyslog_get_mask, 0);
- rb_define_module_function(mSyslog, "mask=", mSyslog_set_mask, 1);
-
- rb_define_module_function(mSyslog, "LOG_MASK", mSyslogConstants_LOG_MASK, 1);
- rb_define_module_function(mSyslog, "LOG_UPTO", mSyslogConstants_LOG_UPTO, 1);
-
- rb_define_module_function(mSyslog, "inspect", mSyslog_inspect, 0);
- rb_define_module_function(mSyslog, "instance", mSyslog_instance, 0);
-
- rb_define_module_function(mSyslogConstants, "LOG_MASK", mSyslogConstants_LOG_MASK, 1);
- rb_define_module_function(mSyslogConstants, "LOG_UPTO", mSyslogConstants_LOG_UPTO, 1);
-
-#define rb_define_syslog_const(id) \
- rb_define_const(mSyslogConstants, #id, INT2NUM(id))
-
- /* Various options when opening log */
-#ifdef LOG_PID
- rb_define_syslog_const(LOG_PID);
-#endif
-#ifdef LOG_CONS
- rb_define_syslog_const(LOG_CONS);
-#endif
-#ifdef LOG_ODELAY
- rb_define_syslog_const(LOG_ODELAY); /* deprecated */
-#endif
-#ifdef LOG_NDELAY
- rb_define_syslog_const(LOG_NDELAY);
-#endif
-#ifdef LOG_NOWAIT
- rb_define_syslog_const(LOG_NOWAIT); /* deprecated */
-#endif
-#ifdef LOG_PERROR
- rb_define_syslog_const(LOG_PERROR);
-#endif
-
- /* Various syslog facilities */
-#ifdef LOG_AUTH
- rb_define_syslog_const(LOG_AUTH);
-#endif
-#ifdef LOG_AUTHPRIV
- rb_define_syslog_const(LOG_AUTHPRIV);
-#endif
-#ifdef LOG_CONSOLE
- rb_define_syslog_const(LOG_CONSOLE);
-#endif
-#ifdef LOG_CRON
- rb_define_syslog_const(LOG_CRON);
-#endif
-#ifdef LOG_DAEMON
- rb_define_syslog_const(LOG_DAEMON);
-#endif
-#ifdef LOG_FTP
- rb_define_syslog_const(LOG_FTP);
-#endif
-#ifdef LOG_KERN
- rb_define_syslog_const(LOG_KERN);
-#endif
-#ifdef LOG_LPR
- rb_define_syslog_const(LOG_LPR);
-#endif
-#ifdef LOG_MAIL
- rb_define_syslog_const(LOG_MAIL);
-#endif
-#ifdef LOG_NEWS
- rb_define_syslog_const(LOG_NEWS);
-#endif
-#ifdef LOG_NTP
- rb_define_syslog_const(LOG_NTP);
-#endif
-#ifdef LOG_SECURITY
- rb_define_syslog_const(LOG_SECURITY);
-#endif
-#ifdef LOG_SYSLOG
- rb_define_syslog_const(LOG_SYSLOG);
-#endif
-#ifdef LOG_USER
- rb_define_syslog_const(LOG_USER);
-#endif
-#ifdef LOG_UUCP
- rb_define_syslog_const(LOG_UUCP);
-#endif
-#ifdef LOG_LOCAL0
- rb_define_syslog_const(LOG_LOCAL0);
-#endif
-#ifdef LOG_LOCAL1
- rb_define_syslog_const(LOG_LOCAL1);
-#endif
-#ifdef LOG_LOCAL2
- rb_define_syslog_const(LOG_LOCAL2);
-#endif
-#ifdef LOG_LOCAL3
- rb_define_syslog_const(LOG_LOCAL3);
-#endif
-#ifdef LOG_LOCAL4
- rb_define_syslog_const(LOG_LOCAL4);
-#endif
-#ifdef LOG_LOCAL5
- rb_define_syslog_const(LOG_LOCAL5);
-#endif
-#ifdef LOG_LOCAL6
- rb_define_syslog_const(LOG_LOCAL6);
-#endif
-#ifdef LOG_LOCAL7
- rb_define_syslog_const(LOG_LOCAL7);
-#endif
-
-#define rb_define_syslog_shortcut(name) \
- rb_define_module_function(mSyslog, #name, mSyslog_##name, -1)
-
- /* Various syslog priorities and the shortcut methods */
-#ifdef LOG_EMERG
- rb_define_syslog_const(LOG_EMERG);
- rb_define_syslog_shortcut(emerg);
-#endif
-#ifdef LOG_ALERT
- rb_define_syslog_const(LOG_ALERT);
- rb_define_syslog_shortcut(alert);
-#endif
-#ifdef LOG_CRIT
- rb_define_syslog_const(LOG_CRIT);
- rb_define_syslog_shortcut(crit);
-#endif
-#ifdef LOG_ERR
- rb_define_syslog_const(LOG_ERR);
- rb_define_syslog_shortcut(err);
-#endif
-#ifdef LOG_WARNING
- rb_define_syslog_const(LOG_WARNING);
- rb_define_syslog_shortcut(warning);
-#endif
-#ifdef LOG_NOTICE
- rb_define_syslog_const(LOG_NOTICE);
- rb_define_syslog_shortcut(notice);
-#endif
-#ifdef LOG_INFO
- rb_define_syslog_const(LOG_INFO);
- rb_define_syslog_shortcut(info);
-#endif
-#ifdef LOG_DEBUG
- rb_define_syslog_const(LOG_DEBUG);
- rb_define_syslog_shortcut(debug);
-#endif
-}
diff --git a/ext/syslog/syslog.txt b/ext/syslog/syslog.txt
deleted file mode 100644
index 9aed35133d..0000000000
--- a/ext/syslog/syslog.txt
+++ /dev/null
@@ -1,121 +0,0 @@
-.\" syslog.txt - -*- Indented-Text -*-
-$RoughId: syslog.txt,v 1.18 2002/02/25 08:20:14 knu Exp $
-$Id$
-
-UNIX Syslog extension for Ruby
-Amos Gouaux, University of Texas at Dallas
-<amos+ruby@utdallas.edu>
-&
-Akinori MUSHA
-<knu@ruby-lang.org>
-
-** Syslog(Module)
-
-Included Modules: Syslog::Constants
-
-require 'syslog'
-
-A Simple wrapper for the UNIX syslog system calls that might be handy
-if you're writing a server in Ruby. For the details of the syslog(8)
-architecture and constants, see the syslog(3) manual page of your
-platform.
-
-Module Methods:
-
- open(ident = $0, logopt = Syslog::LOG_PID | Syslog::LOG_CONS,
- facility = Syslog::LOG_USER) [{ |syslog| ... }]
-
- Opens syslog with the given options and returns the module
- itself. If a block is given, calls it with an argument of
- itself. If syslog is already opened, raises RuntimeError.
-
- Example:
- Syslog.open('ftpd', Syslog::LOG_PID | Syslog::LOG_NDELAY,
- Syslog::LOG_FTP)
-
- open!(ident = $0, logopt = Syslog::LOG_PID | Syslog::LOG_CONS,
- facility = Syslog::LOG_USER)
- reopen(ident = $0, logopt = Syslog::LOG_PID | Syslog::LOG_CONS,
- facility = Syslog::LOG_USER)
-
- Same as open, but does a close first.
-
- opened?
-
- Returns true if syslog opened, otherwise false.
-
- ident
- options
- facility
-
- Returns the parameters given in the last open, respectively.
- Every call of Syslog::open resets these values.
-
- log(pri, message, ...)
-
- Writes message to syslog.
-
- Example:
- Syslog.log(Syslog::LOG_CRIT, "the sky is falling in %d seconds!", 10)
-
- crit(message, ...)
- emerg(message, ...)
- alert(message, ...)
- err(message, ...)
- warning(message, ...)
- notice(message, ...)
- info(message, ...)
- debug(message, ...)
-
- These are shortcut methods of Syslog::log(). The lineup may
- vary depending on what priorities are defined on your system.
-
- Example:
- Syslog.crit("the sky is falling in %d seconds!", 5)
-
- mask
- mask=(mask)
-
- Returns or sets the log priority mask. The value of the mask
- is persistent and will not be reset by Syslog::open or
- Syslog::close.
-
- Example:
- Syslog.mask = Syslog::LOG_UPTO(Syslog::LOG_ERR)
-
- close
-
- Closes syslog.
-
- inspect
-
- Returns the "inspect" string of the Syslog module.
-
- instance
-
- Returns the module itself. (Just for backward compatibility)
-
- LOG_MASK(pri)
-
- Creates a mask for one priority.
-
- LOG_UPTO(pri)
-
- Creates a mask for all priorities up to pri.
-
-** Syslog::Constants(Module)
-
-require 'syslog'
-include Syslog::Constants
-
-This module includes the LOG_* constants available on the system.
-
-Module Methods:
-
- LOG_MASK(pri)
-
- Creates a mask for one priority.
-
- LOG_UPTO(pri)
-
- Creates a mask for all priorities up to pri.
diff --git a/ext/syslog/test.rb b/ext/syslog/test.rb
deleted file mode 100644
index 6cd861b2b2..0000000000
--- a/ext/syslog/test.rb
+++ /dev/null
@@ -1,161 +0,0 @@
-#!/usr/bin/env ruby
-# $RoughId: test.rb,v 1.9 2002/02/25 08:20:14 knu Exp $
-# $Id$
-
-# Please only run this test on machines reasonable for testing.
-# If in doubt, ask your admin.
-
-require 'runit/testcase'
-require 'runit/cui/testrunner'
-
-# Prepend current directory to load path for testing.
-$:.unshift('.')
-
-require 'syslog'
-
-class TestSyslog < RUNIT::TestCase
- def test_new
- assert_exception(NameError) {
- Syslog.new
- }
- end
-
- def test_instance
- sl1 = Syslog.instance
- sl2 = Syslog.open
- sl3 = Syslog.instance
-
- assert_equal(Syslog, sl1)
- assert_equal(Syslog, sl2)
- assert_equal(Syslog, sl3)
- ensure
- Syslog.close
- end
-
- def test_open
- # default parameters
- Syslog.open
-
- assert_equal($0, Syslog.ident)
- assert_equal(Syslog::LOG_PID | Syslog::LOG_CONS, Syslog.options)
- assert_equal(Syslog::LOG_USER, Syslog.facility)
-
- # open without close
- assert_exception(RuntimeError) {
- Syslog.open
- }
-
- Syslog.close
-
- # given parameters
- Syslog.open("foo", Syslog::LOG_NDELAY | Syslog::LOG_PERROR, Syslog::LOG_DAEMON)
-
- assert_equal('foo', Syslog.ident)
- assert_equal(Syslog::LOG_NDELAY | Syslog::LOG_PERROR, Syslog.options)
- assert_equal(Syslog::LOG_DAEMON, Syslog.facility)
-
- Syslog.close
-
- # default parameters again (after close)
- Syslog.open
- Syslog.close
-
- assert_equal($0, Syslog.ident)
- assert_equal(Syslog::LOG_PID | Syslog::LOG_CONS, Syslog.options)
- assert_equal(Syslog::LOG_USER, Syslog.facility)
-
- # block
- param = nil
- Syslog.open { |param| }
- assert_equal(Syslog, param)
- ensure
- Syslog.close
- end
-
- def test_opened?
- assert_equal(false, Syslog.opened?)
-
- Syslog.open
- assert_equal(true, Syslog.opened?)
-
- Syslog.close
- assert_equal(false, Syslog.opened?)
-
- Syslog.open {
- assert_equal(true, Syslog.opened?)
- }
-
- assert_equal(false, Syslog.opened?)
- end
-
- def test_mask
- Syslog.open
-
- orig = Syslog.mask
-
- Syslog.mask = Syslog.LOG_UPTO(Syslog::LOG_ERR)
- assert_equal(Syslog.LOG_UPTO(Syslog::LOG_ERR), Syslog.mask)
-
- Syslog.mask = Syslog.LOG_MASK(Syslog::LOG_CRIT)
- assert_equal(Syslog.LOG_MASK(Syslog::LOG_CRIT), Syslog.mask)
-
- Syslog.mask = orig
- ensure
- Syslog.close
- end
-
- def test_log
- stderr = IO::pipe
-
- pid = fork {
- stderr[0].close
- STDERR.reopen(stderr[1])
- stderr[1].close
-
- options = Syslog::LOG_PERROR | Syslog::LOG_NDELAY
-
- Syslog.open("syslog_test", options) { |sl|
- sl.log(Syslog::LOG_NOTICE, "test1 - hello, %s!", "world")
- sl.notice("test1 - hello, %s!", "world")
- }
-
- Syslog.open("syslog_test", options | Syslog::LOG_PID) { |sl|
- sl.log(Syslog::LOG_CRIT, "test2 - pid")
- sl.crit("test2 - pid")
- }
- exit!
- }
-
- stderr[1].close
- Process.waitpid(pid)
-
- # LOG_PERROR is not yet implemented on Cygwin.
- return if RUBY_PLATFORM =~ /cygwin/
-
- 2.times {
- assert_equal("syslog_test: test1 - hello, world!\n", stderr[0].gets)
- }
-
- 2.times {
- assert_equal(format("syslog_test[%d]: test2 - pid\n", pid), stderr[0].gets)
- }
- end
-
- def test_inspect
- Syslog.open { |sl|
- assert_equal(format('<#%s: opened=%s, ident="%s", ' +
- 'options=%d, facility=%d, mask=%d>',
- Syslog, sl.opened?, sl.ident,
- sl.options, sl.facility, sl.mask),
- sl.inspect)
- }
- end
-end
-
-if $0 == __FILE__
- suite = RUNIT::TestSuite.new
-
- suite.add_test(TestSyslog.suite)
-
- RUNIT::CUI::TestRunner.run(suite)
-end
diff --git a/ext/tcltklib/.cvsignore b/ext/tcltklib/.cvsignore
deleted file mode 100644
index f3c7a7c5da..0000000000
--- a/ext/tcltklib/.cvsignore
+++ /dev/null
@@ -1 +0,0 @@
-Makefile
diff --git a/ext/tcltklib/MANIFEST b/ext/tcltklib/MANIFEST
deleted file mode 100644
index 4e37fb900f..0000000000
--- a/ext/tcltklib/MANIFEST
+++ /dev/null
@@ -1,16 +0,0 @@
-MANIFEST
-README.euc
-MANUAL.euc
-tcltklib.c
-stubs.c
-depend
-extconf.rb
-lib/tcltk.rb
-demo/lines1.rb
-demo/lines0.tcl
-demo/lines2.rb
-sample/sample1.rb
-sample/sample2.rb
-sample/maru.gif
-sample/batsu.gif
-sample/sample0.rb
diff --git a/ext/tcltklib/MANUAL.euc b/ext/tcltklib/MANUAL.euc
deleted file mode 100644
index 789e85a9de..0000000000
--- a/ext/tcltklib/MANUAL.euc
+++ /dev/null
@@ -1,124 +0,0 @@
-(tof)
- MANUAL.euc
- Sep. 19, 1997 Y. Shigehiro
-
-以下, 「tcl/tk」という表記は, tclsh や wish を実現している, 一般でいう
-ところの tcl/tk を指します. 「tcltk ライブラリ」, 「tcltklib ライブラ
-リ」という表記は, 本パッケージに含まれる ruby 用のライブラリを指します.
-
-<< tcltk ライブラリ >>
-
-tcl/tk の C ライブラリを利用するための高(中?)水準インターフェースを提
-供します.
-
-このライブラリは ruby から tcl/tk ライブラリを利用するためのもので, 内
-部で tcltklib ライブラリを利用しています.
-
-[説明]
-
-tcl/tk インタプリタでは, ウィジェットに何か指示を送るには, ウィジェッ
-ト名に続いてパラメータを書きます. したがって, ウィジェットがオブジェク
-トであり, それに対してメソッドを送っている, とみなすことができます. さ
-て, tcl/tk インタプリタでは, 組み込みコマンドも, 前述のウィジェットと
-同じような書式の命令で実行されます. すなわち, コマンドもオブジェクトで
-あると考えることができます.
-
-このような考えに基づき, tcltk ライブラリでは, tcl/tk のコマンドやウィ
-ジェットに対応するオブジェクトを生成します. オブジェクトに対するメソッ
-ド呼び出しは, e() メソッドにより実行されます. 例えば, tcl/tk の info
-コマンドに対応する ruby のオブジェクトが info という名前であるとすると,
-tcl/tk の
- info commands
-という命令は tcltk ライブラリでは
- info.e("commands")
-と記述されます. また, 「.」というウィジェット (wish 実行時に自動的に生
-成されるルートウィジェット) に対応する ruby のオブジェクトが root とい
-う名前であるとすると,
- . configure -height 300 -width 300
-という tcl/tk の命令は
- root.e("configure -height 300 -width 300")
-と記述されます. このような記述は, 見ためには美しくありませんが, そして,
-スクリプトを読む人には見づらいかも知れませんが, 実際にスクリプトを書い
-てみると予想外に手軽です.
-
-[使用法]
-
-1. ライブラリを読み込む.
- require "tcltk"
-
-2. tcl/tk インタプリタを生成する.
- ip = TclTkInterpreter.new()
-
-3. tcl/tk のコマンドに対応するオブジェクトを変数に代入しておく.
- # コマンドに対応するオブジェクトが入った Hash を取り出す.
- c = ip.commands()
- # 使いたいコマンドに対応するオブジェクトを個別の変数に代入する.
- bind, button, info, wm = c.indexes("bind", "button", "info", "wm")
-
-4. 必要な処理を行う.
- 詳しくは, サンプルを参照のこと.
-
-5. 準備ができたら, イベントループに入る.
- TclTk.mainloop()
-
-(( 以下, モジュール, クラス等の説明を書く予定.))
-
-
-
-<< tcltklib ライブラリ >>
-
-tcl/tk の C ライブラリを利用するための低水準インターフェースを提供しま
-す.
-
-コンパイル/実行には, tcl/tk の C ライブラリが必要です.
-
-[説明]
-
-このライブラリを用いると, ruby から tcl/tk の C ライブラリを利用できま
-す. 具体的には, ruby インタプリタから tcl/tk インタプリタを呼び出すこ
-とができます. さらに, その(ruby インタプリタから呼び出した) tcl/tk イ
-ンタプリタから, 逆に ruby インタプリタを呼び出すこともできます.
-
-[使用法]
-
-require "tcltklib" すると, 以下のモジュール, クラスが利用可能です.
-
-モジュール TclTkLib
- tcl/tk ライブラリを呼び出すメソッドを集めたモジュールです. ただし,
- tcl/tk インタプリタ関係のメソッドはクラス TclTkIp にあります.
-
- モジュールメソッド mainloop()
- Tk_MainLoop を実行します. 全ての tk のウインドウが無くなると終了
- します(例えば, tcl/tk で書くところの "destroy ." をした場合等).
- 引数: 無し
- 戻り値: nil
-
-クラス TclTkIp
- インスタンスが tcl/tk のインタプリタに対応します. tcl/tk のライブ
- ラリの仕様通り, インスタンスを複数個生成しても正しく動作します(そ
- んなことをする必要はあまり無いはずですが). インタプリタは wish の
- tcl/tk コマンドを実行できます. さらに, 以下のコマンドを実行できま
- す.
- コマンド ruby
- 引数を ruby で実行します(ruby_eval_string を実行します). 引数
- は 1 つでなければなりません. 戻り値は ruby の実行結果です.
- ruby の実行結果は nil か String でなければなりません.
-
- クラスメソッド new()
- TclTkIp クラスのインスタンスを生成します
- 引数: 無し
- 戻り値 (TclTkIp): 生成されたインスタンス
-
- メソッド _eval(script)
- インタプリタで script を評価します(Tcl_Eval を実行します). 前述
- のように, ruby コマンドにより script 内から ruby スクリプトを実
- 行できます.
- 引数: script (String) - インタプリタで評価するスクリプト文字列
- 戻り値 (String): 評価結果 ((Tcl_Interp *)->result)
-
- メソッド _return_value()
- 直前の Tcl_Eval の戻り値を返します. 0(TCL_OK) で正常終了です.
- 引数: 無し
- 戻り値 (Fixnum): 直前の Tcl_Eval() が返した値.
-
-(eof)
diff --git a/ext/tcltklib/README.euc b/ext/tcltklib/README.euc
deleted file mode 100644
index 290ffb0b60..0000000000
--- a/ext/tcltklib/README.euc
+++ /dev/null
@@ -1,133 +0,0 @@
-(tof)
- tcltk ライブラリ
- tcltklib ライブラリ
- Sep. 19, 1997 Y. Shigehiro
-
-以下, 「tcl/tk」という表記は, tclsh や wish を実現している, 一般でいう
-ところの tcl/tk を指します. 「tcltk ライブラリ」, 「tcltklib ライブラ
-リ」という表記は, 本パッケージに含まれる ruby 用のライブラリを指します.
-
-[ファイルについて]
-
-README.euc : このファイル(注意, 特徴, インストールの方法).
-MANUAL.euc : マニュアル.
-
-lib/, ext/ : ライブラリの実体.
-
-sample/ : マニュアル代わりのサンプルプログラム.
-sample/sample0.rb : tcltklib ライブラリのテスト.
-sample/sample1.rb : tcltk ライブラリのテスト.
- tcl/tk (wish) でできそうなことを一通り書いてみました.
-sample/sample2.rb : tcltk ライブラリのサンプル.
- maeda shugo (shugo@po.aianet.ne.jp) 氏による
- (`rb.tk' で書かれていた) ruby のサンプルプログラム
- http://www.aianet.or.jp/~shugo/ruby/othello.rb.gz
- を tcltk ライブラリを使うように, 機械的に変更してみました.
-
-demo/ : 100 本の線を 100 回描くデモプログラム.
- 最初に空ループの時間を測定し, 続いて実際に線を引く時間を測定します.
- tcl/tk は(再)描画のときに backing store を使わずに律義に 10000 本(?)
- 線を引くので, (再)描画を始めると, マシンがかなり重くなります.
-demo/lines0.tcl : wish 用のスクリプト.
-demo/lines1.rb : `tk.rb' 用のスクリプト.
-demo/lines2.rb : tcltk ライブラリ用のスクリプト.
-
-[注意]
-
-コンパイル/実行には, tcl/tk の C ライブラリが必要です.
-
-このライブラリは,
-
- ruby-1.0-970701, ruby-1.0-970911, ruby-1.0-970919
- FreeBSD 2.2.2-RELEASE
- およびそのパッケージ jp-tcl-7.6.tgz, jp-tk-4.2.tgz
-
-で作成/動作確認しました. 他の環境では動作するかどうかわかりません.
-
-TclTkLib.mainloop を実行中に Control-C が効かないのは不便なので, ruby
-のソースを参考に, #include "sig.h" して trap_immediate を操作していま
-すが, ruby の README.EXT にも書いてないのに, こんなことをして良いのか
-どうかわかりません.
-
--d オプションでデバッグ情報を表示させるために, ruby のソースを参考に,
-debug という大域変数を参照していますが, ruby の README.EXT にも書いて
-ないのに, こんなことをして良いのかどうかわかりません.
-
-extconf.rb は書きましたが, (いろいろな意味で)これで良いのか良く分かり
-ません.
-
-[特徴]
-
-ruby から tcl/tk ライブラリを利用できます.
-
-tcl/tk インタプリタのスクリプトは, 機械的に tcltk ライブラリ用の ruby
-スクリプトに変換できます.
-
-(`tk.rb' との違い)
-
-1. tcl/tk インタプリタのスクリプトが, どのように, tcltk ライブラリ用の
- ruby スクリプトに変換されるかが理解できれば, マニュアル類が無いに等
- しい `tk.rb' とは異なり
-
- tcl/tk のマニュアルやオンラインドキュメントを用いて
-
- 効率良くプログラミングを行うことができます.
- 記述方法がわからない, コマンドに与えるパラメータがわからない...
- - Canvas.new { ... } と, なぜイテレータブロックを書けるの??
- - Canvas の bbox は数値のリストを返すのに, xview は文字列を返すの??
- と, いちいち, ライブラリのソースを追いかける必要はありません.
-
-2. 個々の機能(オプション)を個別処理によりサポートしており, そのためサ
- ポートしていない機能は使うことができない(本当は使えないこともないの
- ですが) `tk.rb' とは異なり, tcl/tk インタプリタで可能なことは
-
- ほとんど
-
- ruby からも実行できます. 現在, ruby から実行できないことが確認され
- ているのは,
-
- bind コマンドでスクリプトを追加する構文
- 「bind tag sequence +script」
- ^
-
- のみです.
- - `. configure -width' をしようとして, `Tk.root.height()' と書い
- たのに, `undefined method `height'' と怒られてしまった. tk.rb を
- 読んでみて, ガーン. できないのか...
- ということはありません.
-
-3. wish プロセスを起動しプロセス間通信で wish を利用する `tk.rb' とは
- 異なり, tcl/tk の C ライブラリをリンクし
-
- より高速に (といっても, 思った程は速くないですが)
-
- 処理を行います.
-
-4. `tk.rb' ほど, 高水準なインターフェースを備えていないため, tcl/tk イ
- ンタプリタの生成等
-
- 何から何まで自分で記述
-
- しなければなりません(その代わり, tcl/tk ライブラリの仕様通り,
- tcl/tk インタプリタを複数生成することもできますが).
- インターフェースは(おそらく) ruby の思想に沿ったものではありません.
- また, スクリプトの記述は
-
- ダサダサ
-
- です. スクリプトは, 一見, 読みづらいものとなります. が, 書く人にとっ
- ては, それほど煩わしいものではないと思います.
-
-[インストールの方法]
-
-0. ruby のソースファイル(ruby-1.0-なんたら.tgz)を展開しておきます.
-
-1. ruby-1.0-なんたら/ext に ext/tcltklib をコピーします.
- cp -r ext/tcltklib ???/ruby-1.0-なんたら/ext/
-
-2. ruby のインストール法に従い make 等をします.
-
-3. ruby のライブラリ置場に lib/* をコピーします.
- cp lib/* /usr/local/lib/ruby/
-
-(eof)
diff --git a/ext/tcltklib/demo/lines0.tcl b/ext/tcltklib/demo/lines0.tcl
deleted file mode 100644
index 8ed3c5e1c1..0000000000
--- a/ext/tcltklib/demo/lines0.tcl
+++ /dev/null
@@ -1,42 +0,0 @@
-#! /usr/local/bin/wish
-
-proc drawlines {} {
- puts [clock format [clock seconds]]
-
- for {set j 0} {$j < 100} {incr j} {
- puts -nonewline "*"
- flush stdout
- if {$j & 1} {
- set c "blue"
- } {
- set c "red"
- }
- for {set i 0} {$i < 100} {incr i} {
-# .a create line $i 0 0 [expr 500 - $i] -fill $c
- }
- }
-
- puts [clock format [clock seconds]]
-
- for {set j 0} {$j < 100} {incr j} {
- puts -nonewline "*"
- flush stdout
- if {$j & 1} {
- set c "blue"
- } {
- set c "red"
- }
- for {set i 0} {$i < 100} {incr i} {
- .a create line $i 0 0 [expr 500 - $i] -fill $c
- }
- }
-
- puts [clock format [clock seconds]]
-# destroy .
-}
-
-canvas .a -height 500 -width 500
-button .b -text draw -command drawlines
-pack .a .b -side left
-
-# eof
diff --git a/ext/tcltklib/demo/lines1.rb b/ext/tcltklib/demo/lines1.rb
deleted file mode 100644
index e459589f50..0000000000
--- a/ext/tcltklib/demo/lines1.rb
+++ /dev/null
@@ -1,54 +0,0 @@
-#! /usr/local/bin/ruby
-
-require "tk"
-
-def drawlines()
- print Time.now, "\n"
-
- for j in 0 .. 99
- print "*"
- $stdout.flush
- if (j & 1) != 0
- col = "blue"
- else
- col = "red"
- end
- for i in 0 .. 99
-# TkcLine.new($a, i, 0, 0, 500 - i, "-fill", col)
- end
- end
-
- print Time.now, "\n"
-
- for j in 0 .. 99
- print "*"
- $stdout.flush
- if (j & 1) != 0
- col = "blue"
- else
- col = "red"
- end
- for i in 0 .. 99
- TkcLine.new($a, i, 0, 0, 500 - i, "-fill", col)
- end
- end
-
- print Time.now, "\n"
-# Tk.root.destroy
-end
-
-$a = TkCanvas.new{
- height(500)
- width(500)
-}
-
-$b = TkButton.new{
- text("draw")
- command(proc{drawlines()})
-}
-
-TkPack.configure($a, $b, {"side"=>"left"})
-
-Tk.mainloop
-
-# eof
diff --git a/ext/tcltklib/demo/lines2.rb b/ext/tcltklib/demo/lines2.rb
deleted file mode 100644
index 9f21ae6377..0000000000
--- a/ext/tcltklib/demo/lines2.rb
+++ /dev/null
@@ -1,50 +0,0 @@
-#! /usr/local/bin/ruby
-
-require "tcltk"
-
-def drawlines()
- print Time.now, "\n"
-
- for j in 0 .. 99
- print "*"
- $stdout.flush
- if (j & 1) != 0
- col = "blue"
- else
- col = "red"
- end
- for i in 0 .. 99
-# $a.e("create line", i, 0, 0, 500 - i, "-fill", col)
- end
- end
-
- print Time.now, "\n"
-
- for j in 0 .. 99
- print "*"
- $stdout.flush
- if (j & 1) != 0
- col = "blue"
- else
- col = "red"
- end
- for i in 0 .. 99
- $a.e("create line", i, 0, 0, 500 - i, "-fill", col)
- end
- end
-
- print Time.now, "\n"
-# $ip.commands()["destroy"].e($root)
-end
-
-$ip = TclTkInterpreter.new()
-$root = $ip.rootwidget()
-$a = TclTkWidget.new($ip, $root, "canvas", "-height 500 -width 500")
-$c = TclTkCallback.new($ip, proc{drawlines()})
-$b = TclTkWidget.new($ip, $root, "button", "-text draw -command", $c)
-
-$ip.commands()["pack"].e($a, $b, "-side left")
-
-TclTk.mainloop
-
-# eof
diff --git a/ext/tcltklib/depend b/ext/tcltklib/depend
deleted file mode 100644
index 2cd9c400f7..0000000000
--- a/ext/tcltklib/depend
+++ /dev/null
@@ -1,2 +0,0 @@
-tcltklib.o: tcltklib.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h
-stubs.o: stubs.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h
diff --git a/ext/tcltklib/extconf.rb b/ext/tcltklib/extconf.rb
deleted file mode 100644
index fd98b1e7da..0000000000
--- a/ext/tcltklib/extconf.rb
+++ /dev/null
@@ -1,72 +0,0 @@
-# extconf.rb for tcltklib
-
-require 'mkmf'
-
-if RUBY_PLATFORM !~ /mswin32|mingw|cygwin/
- have_library("nsl", "t_open")
- have_library("socket", "socket")
- have_library("dl", "dlopen")
- have_library("m", "log")
-end
-
-dir_config("tk")
-dir_config("tcl")
-dir_config("X11")
-
-tklib = with_config("tklib")
-tcllib = with_config("tcllib")
-stubs = enable_config("tcltk_stubs") || with_config("tcltk_stubs")
-
-def find_tcl(tcllib, stubs)
- paths = ["/usr/local/lib", "/usr/pkg/lib", "/usr/lib"]
- func = stubs ? "Tcl_InitStubs" : "Tcl_FindExecutable"
- if tcllib
- find_library(tcllib, func, *paths)
- elsif RUBY_PLATFORM =~ /mswin32|mingw|cygwin/
- find_library("tcl", func, *paths) or
- find_library("tcl84", func, *paths) or
- find_library("tcl83", func, *paths) or
- find_library("tcl82", func, *paths) or
- find_library("tcl80", func, *paths) or
- find_library("tcl76", func, *paths)
- else
- find_library("tcl", func, *paths) or
- find_library("tcl8.4", func, *paths) or
- find_library("tcl8.3", func, *paths) or
- find_library("tcl8.2", func, *paths) or
- find_library("tcl8.0", func, *paths) or
- find_library("tcl7.6", func, *paths)
- end
-end
-
-def find_tk(tklib, stubs)
- paths = ["/usr/local/lib", "/usr/pkg/lib", "/usr/lib"]
- func = stubs ? "Tk_InitStubs" : "Tk_Init"
- if tklib
- find_library(tklib, func, *paths)
- elsif RUBY_PLATFORM =~ /mswin32|mingw|cygwin/
- find_library("tk", func, *paths) or
- find_library("tk84", func, *paths) or
- find_library("tk83", func, *paths) or
- find_library("tk82", func, *paths) or
- find_library("tk80", func, *paths) or
- find_library("tk42", func, *paths)
- else
- find_library("tk", func, *paths) or
- find_library("tk8.4", func, *paths) or
- find_library("tk8.3", func, *paths) or
- find_library("tk8.2", func, *paths) or
- find_library("tk8.0", func, *paths) or
- find_library("tk4.2", func, *paths)
- end
-end
-
-if have_header("tcl.h") && have_header("tk.h") &&
- (/mswin32|mingw|cygwin/ =~ RUBY_PLATFORM || find_library("X11", "XOpenDisplay",
- "/usr/X11/lib", "/usr/X11R6/lib", "/usr/openwin/lib")) &&
- find_tcl(tcllib, stubs) &&
- find_tk(tklib, stubs)
- $CPPFLAGS += ' -DUSE_TCL_STUBS -DUSE_TK_STUBS' if stubs
- $CPPFLAGS += ' -D_WIN32' if /cygwin/ =~ RUBY_PLATFORM
- create_makefile("tcltklib")
-end
diff --git a/ext/tcltklib/lib/tcltk.rb b/ext/tcltklib/lib/tcltk.rb
deleted file mode 100644
index 54a00e8f3c..0000000000
--- a/ext/tcltklib/lib/tcltk.rb
+++ /dev/null
@@ -1,367 +0,0 @@
-# tof
-
-#### tcltk library, more direct manipulation of tcl/tk
-#### Sep. 5, 1997 Y. Shigehiro
-
-require "tcltklib"
-
-################
-
-# module TclTk: collection of tcl/tk utilities (supplies namespace.)
-module TclTk
-
- # initialize Hash to hold unique symbols and such
- @namecnt = {}
-
- # initialize Hash to hold callbacks
- @callback = {}
-end
-
-# TclTk.mainloop(): call TclTkLib.mainloop()
-def TclTk.mainloop()
- print("mainloop: start\n") if $DEBUG
- TclTkLib.mainloop()
- print("mainloop: end\n") if $DEBUG
-end
-
-# TclTk.deletecallbackkey(ca): remove callback from TclTk module
-# this does not remove callbacks from tcl/tk interpreter
-# without calling this method, TclTkInterpreter will not be GCed
-# ca: callback(TclTkCallback)
-def TclTk.deletecallbackkey(ca)
- print("deletecallbackkey: ", ca.to_s(), "\n") if $DEBUG
- @callback.delete(ca.to_s)
-end
-
-# TclTk.dcb(ca, wid, W): call TclTk.deletecallbackkey() for each callbacks
-# in an array.
-# this is for callback for top-level <Destroy>
-# ca: array of callbacks(TclTkCallback)
-# wid: top-level widget(TclTkWidget)
-# w: information about window given by %W(String)
-def TclTk.dcb(ca, wid, w)
- if wid.to_s() == w
- ca.each{|i|
- TclTk.deletecallbackkey(i)
- }
- end
-end
-
-# TclTk._addcallback(ca): register callback
-# ca: callback(TclTkCallback)
-def TclTk._addcallback(ca)
- print("_addcallback: ", ca.to_s(), "\n") if $DEBUG
- @callback[ca.to_s()] = ca
-end
-
-# TclTk._callcallback(key, arg): invoke registered callback
-# key: key to select callback (to_s value of the TclTkCallback)
-# arg: parameter from tcl/tk interpreter
-def TclTk._callcallback(key, arg)
- print("_callcallback: ", @callback[key].inspect, "\n") if $DEBUG
- @callback[key]._call(arg)
- # throw out callback value
- # should return String to satisfy rb_eval_string()
- return ""
-end
-
-# TclTk._newname(prefix): generate unique name(String)
-# prefix: prefix of the unique name
-def TclTk._newname(prefix)
- # generated name counter is stored in @namecnt
- if !@namecnt.key?(prefix)
- # first appearing prefix, initialize
- @namecnt[prefix] = 1
- else
- # already appeared prefix, generate next name
- @namecnt[prefix] += 1
- end
- return "#{prefix}#{@namecnt[prefix]}"
-end
-
-################
-
-# class TclTkInterpreter: tcl/tk interpreter
-class TclTkInterpreter
-
- # initialize():
- def initialize()
- # generate interpreter object
- @ip = TclTkIp.new()
-
- # add ruby_fmt command to tcl interpreter
- # ruby_fmt command format arguments by `format' and call `ruby' command
- # (notice ruby command receives only one argument)
- if $DEBUG
- @ip._eval("proc ruby_fmt {fmt args} { puts \"ruby_fmt: $fmt $args\" ; ruby [format $fmt $args] }")
- else
- @ip._eval("proc ruby_fmt {fmt args} { ruby [format $fmt $args] }")
- end
-
- # @ip._get_eval_string(*args): generate string to evaluate in tcl interpreter
- # *args: script which is going to be evaluated under tcl/tk
- def @ip._get_eval_string(*args)
- argstr = ""
- args.each{|arg|
- argstr += " " if argstr != ""
- # call to_eval if it is defined
- if (arg.respond_to?(:to_eval))
- argstr += arg.to_eval()
- else
- # call to_s unless defined
- argstr += arg.to_s()
- end
- }
- return argstr
- end
-
- # @ip._eval_args(*args): evaluate string under tcl/tk interpreter
- # returns result string.
- # *args: script which is going to be evaluated under tcl/tk
- def @ip._eval_args(*args)
- # calculate the string to eval in the interpreter
- argstr = _get_eval_string(*args)
-
- # evaluate under the interpreter
- print("_eval: \"", argstr, "\"") if $DEBUG
- res = _eval(argstr)
- if $DEBUG
- print(" -> \"", res, "\"\n")
- elsif _return_value() != 0
- print(res, "\n")
- end
- fail(%Q/can't eval "#{argstr}"/) if _return_value() != 0 #'
- return res
- end
-
- # generate tcl/tk command object and register in the hash
- @commands = {}
- # for all commands registered in tcl/tk interpreter:
- @ip._eval("info command").split(/ /).each{|comname|
- if comname =~ /^[.]/
- # if command is a widget (path), generate TclTkWidget,
- # and register it in the hash
- @commands[comname] = TclTkWidget.new(@ip, comname)
- else
- # otherwise, generate TclTkCommand
- @commands[comname] = TclTkCommand.new(@ip, comname)
- end
- }
- end
-
- # commands(): returns hash of the tcl/tk commands
- def commands()
- return @commands
- end
-
- # rootwidget(): returns root widget(TclTkWidget)
- def rootwidget()
- return @commands["."]
- end
-
- # _tcltkip(): returns @ip(TclTkIp)
- def _tcltkip()
- return @ip
- end
-
- # method_missing(id, *args): execute undefined method as tcl/tk command
- # id: method symbol
- # *args: method arguments
- def method_missing(id, *args)
- # if command named by id registered, then execute it
- if @commands.key?(id.id2name)
- return @commands[id.id2name].e(*args)
- else
- # otherwise, exception
- super
- end
- end
-end
-
-# class TclTkObject: base class of the tcl/tk objects
-class TclTkObject
-
- # initialize(ip, exp):
- # ip: interpreter(TclTkIp)
- # exp: tcl/tk representation
- def initialize(ip, exp)
- fail("type is not TclTkIp") if !ip.kind_of?(TclTkIp)
- @ip = ip
- @exp = exp
- end
-
- # to_s(): returns tcl/tk representation
- def to_s()
- return @exp
- end
-end
-
-# class TclTkCommand: tcl/tk commands
-# you should not call TclTkCommand.new()
-# commands are created by TclTkInterpreter:initialize()
-class TclTkCommand < TclTkObject
-
- # e(*args): execute command. returns String (e is for exec or eval)
- # *args: command arguments
- def e(*args)
- return @ip._eval_args(to_s(), *args)
- end
-end
-
-# class TclTkLibCommand: tcl/tk commands in the library
-class TclTkLibCommand < TclTkCommand
-
- # initialize(ip, name):
- # ip: interpreter(TclTkInterpreter)
- # name: command name (String)
- def initialize(ip, name)
- super(ip._tcltkip, name)
- end
-end
-
-# class TclTkVariable: tcl/tk variable
-class TclTkVariable < TclTkObject
-
- # initialize(interp, dat):
- # interp: interpreter(TclTkInterpreter)
- # dat: the value to set(String)
- # if nil, not initialize variable
- def initialize(interp, dat)
- # auto-generate tcl/tk representation (variable name)
- exp = TclTk._newname("v_")
- # initialize TclTkObject
- super(interp._tcltkip(), exp)
- # safe this for `set' command
- @set = interp.commands()["set"]
- # set value
- set(dat) if dat
- end
-
- # although you can set/refer variable by using set in tcl/tk,
- # we provide the method for accessing variables
-
- # set(data): set tcl/tk variable using `set'
- # data: new value
- def set(data)
- @set.e(to_s(), data.to_s())
- end
-
- # get(): read tcl/tk variable(String) using `set'
- def get()
- return @set.e(to_s())
- end
-end
-
-# class TclTkWidget: tcl/tk widget
-class TclTkWidget < TclTkCommand
-
- # initialize(*args):
- # *args: parameters
- def initialize(*args)
- if args[0].kind_of?(TclTkIp)
- # in case the 1st argument is TclTkIp:
-
- # Wrap tcl/tk widget by TclTkWidget
- # (used in TclTkInterpreter#initialize())
-
- # need two arguments
- fail("illegal # of parameter") if args.size != 2
-
- # ip: interpreter(TclTkIp)
- # exp: tcl/tk representation
- ip, exp = args
-
- # initialize TclTkObject
- super(ip, exp)
- elsif args[0].kind_of?(TclTkInterpreter)
- # in case 1st parameter is TclTkInterpreter:
-
- # generate new widget from parent widget
-
- # interp: interpreter(TclTkInterpreter)
- # parent: parent widget
- # command: widget generating tk command(label 等)
- # *args: argument to the command
- interp, parent, command, *args = args
-
- # generate widget name
- exp = parent.to_s()
- exp += "." if exp !~ /[.]$/
- exp += TclTk._newname("w_")
- # initialize TclTkObject
- super(interp._tcltkip(), exp)
- # generate widget
- res = @ip._eval_args(command, exp, *args)
-# fail("can't create Widget") if res != exp
- # for tk_optionMenu, it is legal res != exp
- else
- fail("first parameter is not TclTkInterpreter")
- end
- end
-end
-
-# class TclTkCallback: tcl/tk callbacks
-class TclTkCallback < TclTkObject
-
- # initialize(interp, pr, arg):
- # interp: interpreter(TclTkInterpreter)
- # pr: callback procedure(Proc)
- # arg: string to pass as block parameters of pr
- # bind command of tcl/tk uses % replacement for parameters
- # pr can receive replaced data using block parameter
- # its format is specified by arg string
- # You should not specify arg for the command like
- # scrollbar with -command option, which receives parameters
- # without specifying any replacement
- def initialize(interp, pr, arg = nil)
- # auto-generate tcl/tk representation (variable name)
- exp = TclTk._newname("c_")
- # initialize TclTkObject
- super(interp._tcltkip(), exp)
- # save parameters
- @pr = pr
- @arg = arg
- # register in the module
- TclTk._addcallback(self)
- end
-
- # to_eval(): retuens string representation for @ip._eval_args
- def to_eval()
- if @arg
- # bind replaces %s before calling ruby_fmt, so %%s is used
- s = %Q/{ruby_fmt {TclTk._callcallback("#{to_s()}", "%%s")} #{@arg}}/
- else
- s = %Q/{ruby_fmt {TclTk._callcallback("#{to_s()}", "%s")}}/
- end
-
- return s
- end
-
- # _call(arg): invoke callback
- # arg: callback parameter
- def _call(arg)
- @pr.call(arg)
- end
-end
-
-# class TclTkImage: tcl/tk images
-class TclTkImage < TclTkCommand
-
- # initialize(interp, t, *args):
- # generating image is done by TclTkImage.new()
- # destrying is done by image delete (inconsistent, sigh)
- # interp: interpreter(TclTkInterpreter)
- # t: image type (photo, bitmap, etc.)
- # *args: command argument
- def initialize(interp, t, *args)
- # auto-generate tcl/tk representation
- exp = TclTk._newname("i_")
- # initialize TclTkObject
- super(interp._tcltkip(), exp)
- # generate image
- res = @ip._eval_args("image create", t, exp, *args)
- fail("can't create Image") if res != exp
- end
-end
-
-# eof
diff --git a/ext/tcltklib/sample/batsu.gif b/ext/tcltklib/sample/batsu.gif
deleted file mode 100644
index 880cc73e09..0000000000
--- a/ext/tcltklib/sample/batsu.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tcltklib/sample/maru.gif b/ext/tcltklib/sample/maru.gif
deleted file mode 100644
index 2c0202892e..0000000000
--- a/ext/tcltklib/sample/maru.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tcltklib/sample/sample0.rb b/ext/tcltklib/sample/sample0.rb
deleted file mode 100644
index cd4c8069b4..0000000000
--- a/ext/tcltklib/sample/sample0.rb
+++ /dev/null
@@ -1,39 +0,0 @@
-#! /usr/local/bin/ruby -vd
-
-# tcltklib ライブラリのテスト
-
-require "tcltklib"
-
-def test
- # インタプリタを生成する
- ip1 = TclTkIp.new()
-
- # 評価してみる
- print ip1._return_value().inspect, "\n"
- print ip1._eval("puts {abc}").inspect, "\n"
-
- # ボタンを作ってみる
- print ip1._return_value().inspect, "\n"
- print ip1._eval("button .lab -text exit -command \"destroy .\"").inspect,
- "\n"
- print ip1._return_value().inspect, "\n"
- print ip1._eval("pack .lab").inspect, "\n"
- print ip1._return_value().inspect, "\n"
-
- # インタプリタから ruby コマンドを評価してみる
-# print ip1._eval(%q/ruby {print "print by ruby\n"}/).inspect, "\n"
- print ip1._eval(%q+puts [ruby {print "print by ruby\n"; "puts by tcl/tk"}]+).inspect, "\n"
- print ip1._return_value().inspect, "\n"
-
- # もう一つインタプリタを生成してみる
- ip2 = TclTkIp.new()
- ip2._eval("button .lab -text test -command \"puts test ; destroy .\"")
- ip2._eval("pack .lab")
-
- TclTkLib.mainloop
-end
-
-test
-GC.start
-
-print "exit\n"
diff --git a/ext/tcltklib/sample/sample1.rb b/ext/tcltklib/sample/sample1.rb
deleted file mode 100644
index 28ba7b547a..0000000000
--- a/ext/tcltklib/sample/sample1.rb
+++ /dev/null
@@ -1,634 +0,0 @@
-#! /usr/local/bin/ruby -d
-#! /usr/local/bin/ruby
-# -d オプションを付けると, デバッグ情報を表示する.
-
-# tcltk ライブラリのサンプル
-
-# まず, ライブラリを require する.
-require "tcltk"
-
-# 以下は, Test1 のインスタンスの initialize() で,
-# tcl/tk に関する処理を行う例である.
-# 必ずしもそのようにする必要は無く,
-# (もし, そうしたければ) class の外で tcl/tk に関する処理を行っても良い.
-
-class Test1
- # 初期化(インタプリタを生成してウィジェットを生成する).
- def initialize()
-
- #### 使う前のおまじない
-
- # インタプリタの生成.
- ip = TclTkInterpreter.new()
- # コマンドに対応するオブジェクトを c に設定しておく.
- c = ip.commands()
- # 使用するコマンドに対応するオブジェクトは変数に入れておく.
- append, bind, button, destroy, incr, info, label, place, set, wm =
- c.indexes(
- "append", "bind", "button", "destroy", "incr", "info", "label", "place",
- "set", "wm")
-
- #### tcl/tk のコマンドに対応するオブジェクト(TclTkCommand)の操作
-
- # 実行する時は, e() メソッドを使う.
- # (以下は, tcl/tk における info command r* を実行.)
- print info.e("command", "r*"), "\n"
- # 引数は, まとめた文字列にしても同じ.
- print info.e("command r*"), "\n"
- # 変数を用いなくとも実行できるが, 見ためが悪い.
- print c["info"].e("command", "r*"), "\n"
- # インタプリタのメソッドとしても実行できるが, 効率が悪い.
- print ip.info("command", "r*"), "\n"
-
- ####
-
- # 以下, 生成したオブジェクトは変数に代入しておかないと
- # GC の対象になってしまう.
-
- #### tcl/tk の変数に対応するオブジェクト(TclTkVariable)の操作
-
- # 生成と同時に値を設定する.
- v1 = TclTkVariable.new(ip, "20")
- # 読み出しは get メソッドを使う.
- print v1.get(), "\n"
- # 設定は set メソッドを使う.
- v1.set(40)
- print v1.get(), "\n"
- # set コマンドを使って読み出し, 設定は可能だが見ためが悪い.
- # e() メソッド等の引数に直接 TclTkObject や数値を書いても良い.
- set.e(v1, 30)
- print set.e(v1), "\n"
- # tcl/tk のコマンドで変数を操作できる.
- incr.e(v1)
- print v1.get(), "\n"
- append.e(v1, 10)
- print v1.get(), "\n"
-
- #### tcl/tk のウィジェットに対応するオブジェクト(TclTkWidget)の操作
-
- # ルートウィジェットを取り出す.
- root = ip.rootwidget()
- # ウィジェットの操作.
- root.e("configure -height 300 -width 300")
- # タイトルを付けるときは wm を使う.
- wm.e("title", root, $0)
- # 親ウィジェットとコマンドを指定して, ウィジェットを作る.
- l1 = TclTkWidget.new(ip, root, label, "-text {type `x' to print}")
- # place すると表示される.
- place.e(l1, "-x 0 -rely 0.0 -relwidth 1 -relheight 0.1")
- # コマンド名は文字列で指定しても良いが, 見ためが悪い.
- # (コマンド名は独立した引数でなければならない.)
- l2 = TclTkWidget.new(ip, root, "label")
- # ウィジェットの操作.
- l2.e("configure -text {type `q' to exit}")
- place.e(l2, "-x 0 -rely 0.1 -relwidth 1 -relheight 0.1")
-
- #### tcl/tk のコールバックに対応するオブジェクト(TclTkCallback)の操作
-
- # コールバックを生成する.
- c1 = TclTkCallback.new(ip, proc{sample(ip, root)})
- # コールバックを持つウィジェットを生成する.
- b1 = TclTkWidget.new(ip, root, button, "-text sample -command", c1)
- place.e(b1, "-x 0 -rely 0.2 -relwidth 1 -relheight 0.1")
- # イベントループを抜けるには destroy.e(root) する.
- c2 = TclTkCallback.new(ip, proc{destroy.e(root)})
- b2 = TclTkWidget.new(ip, root, button, "-text exit -command", c2)
- place.e(b2, "-x 0 -rely 0.3 -relwidth 1 -relheight 0.1")
-
- #### イベントのバインド
- # script の追加 (bind tag sequence +script) は今のところできない.
- # (イテレータ変数の設定がうまくいかない.)
-
- # 基本的にはウィジェットに対するコールバックと同じ.
- c3 = TclTkCallback.new(ip, proc{print("q pressed\n"); destroy.e(root)})
- bind.e(root, "q", c3)
- # bind コマンドで % 置換によりパラメータを受け取りたいときは,
- # proc{} の後ろに文字列で指定すると,
- # 置換結果をイテレータ変数を通して受け取ることができる.
- # ただし proc{} の後ろの文字列は,
- # bind コマンドに与えるコールバック以外で指定してはいけない.
- c4 = TclTkCallback.new(ip, proc{|i| print("#{i} pressed\n")}, "%A")
- bind.e(root, "x", c4)
- # TclTkCallback を GC の対象にしたければ,
- # dcb() (または deletecallbackkeys()) する必要がある.
- cb = [c1, c2, c3, c4]
- c5 = TclTkCallback.new(ip, proc{|w| TclTk.dcb(cb, root, w)}, "%W")
- bind.e(root, "<Destroy>", c5)
- cb.push(c5)
-
- #### tcl/tk のイメージに対応するオブジェクト(TclTkImage)の操作
-
- # データを指定して生成する.
- i1 = TclTkImage.new(ip, "photo", "-file maru.gif")
- # ラベルに張り付けてみる.
- l3 = TclTkWidget.new(ip, root, label, "-relief raised -image", i1)
- place.e(l3, "-x 0 -rely 0.4 -relwidth 0.2 -relheight 0.2")
- # 空のイメージを生成して後で操作する.
- i2 = TclTkImage.new(ip, "photo")
- # イメージを操作する.
- i2.e("copy", i1)
- i2.e("configure -gamma 0.5")
- l4 = TclTkWidget.new(ip, root, label, "-relief raised -image", i2)
- place.e(l4, "-relx 0.2 -rely 0.4 -relwidth 0.2 -relheight 0.2")
-
- ####
- end
-
- # サンプルのためのウィジェットを生成する.
- def sample(ip, parent)
- bind, button, destroy, grid, toplevel, wm = ip.commands().indexes(
- "bind", "button", "destroy", "grid", "toplevel", "wm")
-
- ## toplevel
-
- # 新しいウインドウを開くには, toplevel を使う.
- t1 = TclTkWidget.new(ip, parent, toplevel)
- # タイトルを付けておく
- wm.e("title", t1, "sample")
-
- # ウィジェットが破壊されたとき, コールバックが GC の対象になるようにする.
- cb = []
- cb.push(c = TclTkCallback.new(ip, proc{|w| TclTk.dcb(cb, t1, w)}, "%W"))
- bind.e(t1, "<Destroy>", c)
-
- # ボタンの生成.
- wid = []
- # toplevel ウィジェットを破壊するには destroy する.
- cb.push(c = TclTkCallback.new(ip, proc{destroy.e(t1)}))
- wid.push(TclTkWidget.new(ip, t1, button, "-text close -command", c))
- cb.push(c = TclTkCallback.new(ip, proc{test_label(ip, t1)}))
- wid.push(TclTkWidget.new(ip, t1, button, "-text label -command", c))
- cb.push(c = TclTkCallback.new(ip, proc{test_button(ip, t1)}))
- wid.push(TclTkWidget.new(ip, t1, button, "-text button -command", c))
- cb.push(c = TclTkCallback.new(ip, proc{test_checkbutton(ip, t1)}))
- wid.push(TclTkWidget.new(ip, t1, button, "-text checkbutton -command", c))
- cb.push(c = TclTkCallback.new(ip, proc{test_radiobutton(ip, t1)}))
- wid.push(TclTkWidget.new(ip, t1, button, "-text radiobutton -command", c))
- cb.push(c = TclTkCallback.new(ip, proc{test_scale(ip, t1)}))
- wid.push(TclTkWidget.new(ip, t1, button, "-text scale -command", c))
- cb.push(c = TclTkCallback.new(ip, proc{test_entry(ip, t1)}))
- wid.push(TclTkWidget.new(ip, t1, button, "-text entry -command", c))
- cb.push(c = TclTkCallback.new(ip, proc{test_text(ip, t1)}))
- wid.push(TclTkWidget.new(ip, t1, button, "-text text -command", c))
- cb.push(c = TclTkCallback.new(ip, proc{test_raise(ip, t1)}))
- wid.push(TclTkWidget.new(ip, t1, button, "-text raise/lower -command", c))
- cb.push(c = TclTkCallback.new(ip, proc{test_modal(ip, t1)}))
- wid.push(TclTkWidget.new(ip, t1, button, "-text message/modal -command",
- c))
- cb.push(c = TclTkCallback.new(ip, proc{test_menu(ip, t1)}))
- wid.push(TclTkWidget.new(ip, t1, button, "-text menu -command", c))
- cb.push(c = TclTkCallback.new(ip, proc{test_listbox(ip, t1)}))
- wid.push(TclTkWidget.new(ip, t1, button, "-text listbox/scrollbar",
- "-command", c))
- cb.push(c = TclTkCallback.new(ip, proc{test_canvas(ip, t1)}))
- wid.push(TclTkWidget.new(ip, t1, button, "-text canvas -command", c))
-
- # grid で表示する.
- ro = co = 0
- wid.each{|w|
- grid.e(w, "-row", ro, "-column", co, "-sticky news")
- ro += 1
- if ro == 7
- ro = 0
- co += 1
- end
- }
- end
-
- # inittoplevel(ip, parent, title)
- # 以下の処理をまとめて行う.
- # 1. toplevel ウィジェットを作成する.
- # 2. コールバックを登録する配列を用意し, toplevel ウィジェットの
- # <Destroy> イベントにコールバックを削除する手続きを登録する.
- # 3. クローズボタンを作る.
- # 作成した toplevel ウィジェット, クローズボタン, コールバック登録用変数
- # を返す.
- # ip: インタプリタ
- # parent: 親ウィジェット
- # title: toplevel ウィジェットのウインドウのタイトル
- def inittoplevel(ip, parent, title)
- bind, button, destroy, toplevel, wm = ip.commands().indexes(
- "bind", "button", "destroy", "toplevel", "wm")
-
- # 新しいウインドウを開くには, toplevel を使う.
- t1 = TclTkWidget.new(ip, parent, toplevel)
- # タイトルを付けておく
- wm.e("title", t1, title)
-
- # ウィジェットが破壊されたとき, コールバックが GC の対象になるようにする.
- cb = []
- cb.push(c = TclTkCallback.new(ip, proc{|w| TclTk.dcb(cb, t1, w)}, "%W"))
- bind.e(t1, "<Destroy>", c)
- # close ボタンを作っておく.
- # toplevel ウィジェットを破壊するには destroy する.
- cb.push(c = TclTkCallback.new(ip, proc{destroy.e(t1)}))
- b1 = TclTkWidget.new(ip, t1, button, "-text close -command", c)
-
- return t1, b1, cb
- end
-
- # label のサンプル.
- def test_label(ip, parent)
- button, global, label, pack = ip.commands().indexes(
- "button", "global", "label", "pack")
- t1, b1, cb = inittoplevel(ip, parent, "label")
-
- ## label
-
- # いろいろな形のラベル.
- l1 = TclTkWidget.new(ip, t1, label, "-text {default(flat)}")
- l2 = TclTkWidget.new(ip, t1, label, "-text raised -relief raised")
- l3 = TclTkWidget.new(ip, t1, label, "-text sunken -relief sunken")
- l4 = TclTkWidget.new(ip, t1, label, "-text groove -relief groove")
- l5 = TclTkWidget.new(ip, t1, label, "-text ridge -relief ridge")
- l6 = TclTkWidget.new(ip, t1, label, "-bitmap error")
- l7 = TclTkWidget.new(ip, t1, label, "-bitmap questhead")
-
- # pack しても表示される.
- pack.e(b1, l1, l2, l3, l4, l5, l6, l7, "-pady 3")
-
- ## -textvariable
-
- # tcltk ライブラリの実装では, コールバックは tcl/tk の``手続き''を通して
- # 呼ばれる. したがって, コールバックの中で(大域)変数にアクセスするときは,
- # global する必要がある.
- # global する前に変数に値を設定してしまうとエラーになるので,
- # tcl/tk における表現形だけ生成して, 実際に値を設定しないように,
- # 2 番目の引数には nil を与える.
- v1 = TclTkVariable.new(ip, nil)
- global.e(v1)
- v1.set(100)
- # -textvariable で変数を設定する.
- l6 = TclTkWidget.new(ip, t1, label, "-textvariable", v1)
- # コールバックの中から変数を操作する.
- cb.push(c = TclTkCallback.new(ip, proc{
- global.e(v1); v1.set(v1.get().to_i + 10)}))
- b2 = TclTkWidget.new(ip, t1, button, "-text +10 -command", c)
- cb.push(c = TclTkCallback.new(ip, proc{
- global.e(v1); v1.set(v1.get().to_i - 10)}))
- b3 = TclTkWidget.new(ip, t1, button, "-text -10 -command", c)
- pack.e(l6, b2, b3)
- end
-
- # button のサンプル.
- def test_button(ip, parent)
- button, pack = ip.commands().indexes("button", "pack")
- t1, b1, cb = inittoplevel(ip, parent, "button")
-
- ## button
-
- # コールバック内で参照する変数は先に宣言しておかなければならない.
- b3 = b4 = nil
- cb.push(c = TclTkCallback.new(ip, proc{b3.e("flash"); b4.e("flash")}))
- b2 = TclTkWidget.new(ip, t1, button, "-text flash -command", c)
- cb.push(c = TclTkCallback.new(ip, proc{b2.e("configure -state normal")}))
- b3 = TclTkWidget.new(ip, t1, button, "-text normal -command", c)
- cb.push(c = TclTkCallback.new(ip, proc{b2.e("configure -state disabled")}))
- b4 = TclTkWidget.new(ip, t1, button, "-text disable -command", c)
- pack.e(b1, b2, b3, b4)
- end
-
- # checkbutton のサンプル.
- def test_checkbutton(ip, parent)
- checkbutton, global, pack = ip.commands().indexes(
- "checkbutton", "global", "pack")
- t1, b1, cb = inittoplevel(ip, parent, "checkbutton")
-
- ## checkbutton
-
- v1 = TclTkVariable.new(ip, nil)
- global.e(v1)
- # -variable で変数を設定する.
- ch1 = TclTkWidget.new(ip, t1, checkbutton, "-onvalue on -offvalue off",
- "-textvariable", v1, "-variable", v1)
- pack.e(b1, ch1)
- end
-
- # radiobutton のサンプル.
- def test_radiobutton(ip, parent)
- global, label, pack, radiobutton = ip.commands().indexes(
- "global", "label", "pack", "radiobutton")
- t1, b1, cb = inittoplevel(ip, parent, "radiobutton")
-
- ## radiobutton
-
- v1 = TclTkVariable.new(ip, nil)
- global.e(v1)
- # ヌルストリングは "{}" で指定する.
- v1.set("{}")
- l1 = TclTkWidget.new(ip, t1, label, "-textvariable", v1)
- # -variable で同じ変数を指定すると同じグループになる.
- ra1 = TclTkWidget.new(ip, t1, radiobutton,
- "-text radio1 -value r1 -variable", v1)
- ra2 = TclTkWidget.new(ip, t1, radiobutton,
- "-text radio2 -value r2 -variable", v1)
- cb.push(c = TclTkCallback.new(ip, proc{global.e(v1); v1.set("{}")}))
- ra3 = TclTkWidget.new(ip, t1, radiobutton,
- "-text clear -value r3 -variable", v1, "-command", c)
- pack.e(b1, l1, ra1, ra2, ra3)
- end
-
- # scale のサンプル.
- def test_scale(ip, parent)
- global, pack, scale = ip.commands().indexes(
- "global", "pack", "scale")
- t1, b1, cb = inittoplevel(ip, parent, "scale")
-
- ## scale
-
- v1 = TclTkVariable.new(ip, nil)
- global.e(v1)
- v1.set(219)
- # コールバック内で参照する変数は先に宣言しておかなければならない.
- sca1 = nil
- cb.push(c = TclTkCallback.new(ip, proc{global.e(v1); v = v1.get();
- sca1.e("configure -background", format("#%02x%02x%02x", v, v, v))}))
- sca1 = TclTkWidget.new(ip, t1, scale,
- "-label scale -orient h -from 0 -to 255 -variable", v1, "-command", c)
- pack.e(b1, sca1)
- end
-
- # entry のサンプル.
- def test_entry(ip, parent)
- button, entry, global, pack = ip.commands().indexes(
- "button", "entry", "global", "pack")
- t1, b1, cb = inittoplevel(ip, parent, "entry")
-
- ## entry
-
- v1 = TclTkVariable.new(ip, nil)
- global.e(v1)
- # ヌルストリングは "{}" で指定する.
- v1.set("{}")
- en1 = TclTkWidget.new(ip, t1, entry, "-textvariable", v1)
- cb.push(c = TclTkCallback.new(ip, proc{
- global.e(v1); print(v1.get(), "\n"); v1.set("{}")}))
- b2 = TclTkWidget.new(ip, t1, button, "-text print -command", c)
- pack.e(b1, en1, b2)
- end
-
- # text のサンプル.
- def test_text(ip, parent)
- button, pack, text = ip.commands().indexes(
- "button", "pack", "text")
- t1, b1, cb = inittoplevel(ip, parent, "text")
-
- ## text
-
- te1 = TclTkWidget.new(ip, t1, text)
- cb.push(c = TclTkCallback.new(ip, proc{
- # 1 行目の 0 文字目から最後までを表示し, 削除する.
- print(te1.e("get 1.0 end")); te1.e("delete 1.0 end")}))
- b2 = TclTkWidget.new(ip, t1, button, "-text print -command", c)
- pack.e(b1, te1, b2)
- end
-
- # raise/lower のサンプル.
- def test_raise(ip, parent)
- button, frame, lower, pack, raise = ip.commands().indexes(
- "button", "frame", "lower", "pack", "raise")
- t1, b1, cb = inittoplevel(ip, parent, "raise/lower")
-
- ## raise/lower
-
- # button を隠すテストのために, frame を使う.
- f1 = TclTkWidget.new(ip, t1, frame)
- # コールバック内で参照する変数は先に宣言しておかなければならない.
- b2 = nil
- cb.push(c = TclTkCallback.new(ip, proc{raise.e(f1, b2)}))
- b2 = TclTkWidget.new(ip, t1, button, "-text raise -command", c)
- cb.push(c = TclTkCallback.new(ip, proc{lower.e(f1, b2)}))
- b3 = TclTkWidget.new(ip, t1, button, "-text lower -command", c)
- lower.e(f1, b3)
-
- pack.e(b2, b3, "-in", f1)
- pack.e(b1, f1)
- end
-
- # modal なウィジェットのサンプル.
- def test_modal(ip, parent)
- button, frame, message, pack, tk_chooseColor, tk_getOpenFile,
- tk_messageBox = ip.commands().indexes(
- "button", "frame", "message", "pack", "tk_chooseColor",
- "tk_getOpenFile", "tk_messageBox")
- # 最初に load されていないライブラリは ip.commands() に存在しないので,
- # TclTkLibCommand を生成する必要がある.
- tk_dialog = TclTkLibCommand.new(ip, "tk_dialog")
- t1, b1, cb = inittoplevel(ip, parent, "message/modal")
-
- ## message
-
- mes = "これは message ウィジェットのテストです."
- mes += "以下は modal なウィジェットのテストです."
- me1 = TclTkWidget.new(ip, t1, message, "-text {#{mes}}")
-
- ## modal
-
- # tk_messageBox
- cb.push(c = TclTkCallback.new(ip, proc{
- print tk_messageBox.e("-type yesnocancel -message messageBox",
- "-icon error -default cancel -title messageBox"), "\n"}))
- b2 = TclTkWidget.new(ip, t1, button, "-text messageBox -command", c)
- # tk_dialog
- cb.push(c = TclTkCallback.new(ip, proc{
- # ウィジェット名を生成するためにダミーの frame を生成.
- print tk_dialog.e(TclTkWidget.new(ip, t1, frame),
- "dialog dialog error 2 yes no cancel"), "\n"}))
- b3 = TclTkWidget.new(ip, t1, button, "-text dialog -command", c)
- # tk_chooseColor
- cb.push(c = TclTkCallback.new(ip, proc{
- print tk_chooseColor.e("-title chooseColor"), "\n"}))
- b4 = TclTkWidget.new(ip, t1, button, "-text chooseColor -command", c)
- # tk_getOpenFile
- cb.push(c = TclTkCallback.new(ip, proc{
- print tk_getOpenFile.e("-defaultextension .rb",
- "-filetypes {{{Ruby Script} {.rb}} {{All Files} {*}}}",
- "-title getOpenFile"), "\n"}))
- b5 = TclTkWidget.new(ip, t1, button, "-text getOpenFile -command", c)
-
- pack.e(b1, me1, b2, b3, b4, b5)
- end
-
- # menu のサンプル.
- def test_menu(ip, parent)
- global, menu, menubutton, pack = ip.commands().indexes(
- "global", "menu", "menubutton", "pack")
- tk_optionMenu = TclTkLibCommand.new(ip, "tk_optionMenu")
- t1, b1, cb = inittoplevel(ip, parent, "menu")
-
- ## menu
-
- # menubutton を生成する.
- mb1 = TclTkWidget.new(ip, t1, menubutton, "-text menu")
- # menu を生成する.
- me1 = TclTkWidget.new(ip, mb1, menu)
- # mb1 から me1 が起動されるようにする.
- mb1.e("configure -menu", me1)
-
- # cascade で起動される menu を生成する.
- me11 = TclTkWidget.new(ip, me1, menu)
- # radiobutton のサンプル.
- v1 = TclTkVariable.new(ip, nil); global.e(v1); v1.set("r1")
- me11.e("add radiobutton -label radio1 -value r1 -variable", v1)
- me11.e("add radiobutton -label radio2 -value r2 -variable", v1)
- me11.e("add radiobutton -label radio3 -value r3 -variable", v1)
- # cascade により mb11 が起動されるようにする.
- me1.e("add cascade -label cascade -menu", me11)
-
- # checkbutton のサンプル.
- v2 = TclTkVariable.new(ip, nil); global.e(v2); v2.set("none")
- me1.e("add checkbutton -label check -variable", v2)
- # separator のサンプル.
- me1.e("add separator")
- # command のサンプル.
- v3 = nil
- cb.push(c = TclTkCallback.new(ip, proc{
- global.e(v1, v2, v3); print "v1: ", v1.get(), ", v2: ", v2.get(),
- ", v3: ", v3.get(), "\n"}))
- me1.e("add command -label print -command", c)
-
- ## tk_optionMenu
-
- v3 = TclTkVariable.new(ip, nil); global.e(v3); v3.set("opt2")
- om1 = TclTkWidget.new(ip, t1, tk_optionMenu, v3, "opt1 opt2 opt3 opt4")
-
- pack.e(b1, mb1, om1, "-side left")
- end
-
- # listbox のサンプル.
- def test_listbox(ip, parent)
- clipboard, frame, grid, listbox, lower, menu, menubutton, pack, scrollbar,
- selection = ip.commands().indexes(
- "clipboard", "frame", "grid", "listbox", "lower", "menu", "menubutton",
- "pack", "scrollbar", "selection")
- t1, b1, cb = inittoplevel(ip, parent, "listbox")
-
- ## listbox/scrollbar
-
- f1 = TclTkWidget.new(ip, t1, frame)
- # コールバック内で参照する変数は先に宣言しておかなければならない.
- li1 = sc1 = sc2 = nil
- # 実行時に, 後ろにパラメータがつくコールバックは,
- # イテレータ変数でそのパラメータを受け取ることができる.
- # (複数のパラメータはひとつの文字列にまとめられる.)
- cb.push(c1 = TclTkCallback.new(ip, proc{|i| li1.e("xview", i)}))
- cb.push(c2 = TclTkCallback.new(ip, proc{|i| li1.e("yview", i)}))
- cb.push(c3 = TclTkCallback.new(ip, proc{|i| sc1.e("set", i)}))
- cb.push(c4 = TclTkCallback.new(ip, proc{|i| sc2.e("set", i)}))
- # listbox
- li1 = TclTkWidget.new(ip, f1, listbox,
- "-xscrollcommand", c3, "-yscrollcommand", c4,
- "-selectmode extended -exportselection true")
- for i in 1..20
- li1.e("insert end {line #{i} line #{i} line #{i} line #{i} line #{i}}")
- end
- # scrollbar
- sc1 = TclTkWidget.new(ip, f1, scrollbar, "-orient horizontal -command", c1)
- sc2 = TclTkWidget.new(ip, f1, scrollbar, "-orient vertical -command", c2)
-
- ## selection/clipboard
-
- mb1 = TclTkWidget.new(ip, t1, menubutton, "-text edit")
- me1 = TclTkWidget.new(ip, mb1, menu)
- mb1.e("configure -menu", me1)
- cb.push(c = TclTkCallback.new(ip, proc{
- # clipboard をクリア.
- clipboard.e("clear")
- # selection から文字列を読み込み clipboard に追加する.
- clipboard.e("append {#{selection.e(\"get\")}}")}))
- me1.e("add command -label {selection -> clipboard} -command",c)
- cb.push(c = TclTkCallback.new(ip, proc{
- # li1 をクリア.
- li1.e("delete 0 end")
- # clipboard から文字列を取り出し, 1 行ずつ
- selection.e("get -selection CLIPBOARD").split(/\n/).each{|line|
- # li1 に挿入する.
- li1.e("insert end {#{line}}")}}))
- me1.e("add command -label {clipboard -> listbox} -command",c)
-
- grid.e(li1, "-row 0 -column 0 -sticky news")
- grid.e(sc1, "-row 1 -column 0 -sticky ew")
- grid.e(sc2, "-row 0 -column 1 -sticky ns")
- grid.e("rowconfigure", f1, "0 -weight 100")
- grid.e("columnconfigure", f1, "0 -weight 100")
- f2 = TclTkWidget.new(ip, t1, frame)
- lower.e(f2, b1)
- pack.e(b1, mb1, "-in", f2, "-side left")
- pack.e(f2, f1)
- end
-
- # canvas のサンプル.
- def test_canvas(ip, parent)
- canvas, lower, pack = ip.commands().indexes("canvas", "lower", "pack")
- t1, b1, cb = inittoplevel(ip, parent, "canvas")
-
- ## canvas
-
- ca1 = TclTkWidget.new(ip, t1, canvas, "-width 400 -height 300")
- lower.e(ca1, b1)
- # rectangle を作る.
- idr = ca1.e("create rectangle 10 10 20 20")
- # oval を作る.
- ca1.e("create oval 60 10 100 50")
- # polygon を作る.
- ca1.e("create polygon 110 10 110 30 140 10")
- # line を作る.
- ca1.e("create line 150 10 150 30 190 10")
- # arc を作る.
- ca1.e("create arc 200 10 250 50 -start 0 -extent 90 -style pieslice")
- # i1 は本当は, どこかで破壊しなければならないが, 面倒なので放ってある.
- i1 = TclTkImage.new(ip, "photo", "-file maru.gif")
- # image を作る.
- ca1.e("create image 100 100 -image", i1)
- # bitmap を作る.
- ca1.e("create bitmap 260 50 -bitmap questhead")
- # text を作る.
- ca1.e("create text 320 50 -text {drag rectangle}")
- # window を作る(クローズボタン).
- ca1.e("create window 200 200 -window", b1)
-
- # bind により rectangle を drag できるようにする.
- cb.push(c = TclTkCallback.new(ip, proc{|i|
- # i に x と y を受け取るので, 取り出す.
- x, y = i.split(/ /); x = x.to_f; y = y.to_f
- # 座標を変更する.
- ca1.e("coords current #{x - 5} #{y - 5} #{x + 5} #{y + 5}")},
- # x, y 座標を空白で区切ったものをイテレータ変数へ渡すように指定.
- "%x %y"))
- # rectangle に bind する.
- ca1.e("bind", idr, "<B1-Motion>", c)
-
- pack.e(ca1)
- end
-end
-
-# test driver
-
-if ARGV.size == 0
- print "#{$0} n で, n 個のインタプリタを起動します.\n"
- n = 1
-else
- n = ARGV[0].to_i
-end
-
-print "start\n"
-ip = []
-
-# インタプリタ, ウィジェット等の生成.
-for i in 1 .. n
- ip.push(Test1.new())
-end
-
-# 用意ができたらイベントループに入る.
-TclTk.mainloop()
-print "exit from mainloop\n"
-
-# インタプリタが GC されるかのテスト.
-ip = []
-print "GC.start\n" if $DEBUG
-GC.start() if $DEBUG
-print "end\n"
-
-exit
-
-# end
diff --git a/ext/tcltklib/sample/sample2.rb b/ext/tcltklib/sample/sample2.rb
deleted file mode 100644
index 969d8de09a..0000000000
--- a/ext/tcltklib/sample/sample2.rb
+++ /dev/null
@@ -1,449 +0,0 @@
-#!/usr/local/bin/ruby
-#----------------------> pretty simple othello game <-----------------------
-# othello.rb
-#
-# version 0.3
-# maeda shugo (shuto@po.aianet.ne.jp)
-#---------------------------------------------------------------------------
-
-# Sep. 17, 1997 modified by Y. Shigehiro for tcltk library
-# maeda shugo (shugo@po.aianet.ne.jp) 氏による
-# (ruby/tk で書かれていた) ruby のサンプルプログラム
-# http://www.aianet.or.jp/~shugo/ruby/othello.rb.gz
-# を tcltk ライブラリを使うように, 機械的に変更してみました.
-#
-# なるべくオリジナルと同じになるようにしてあります.
-
-require "observer"
-require "tcltk"
-$ip = TclTkInterpreter.new()
-$root = $ip.rootwidget()
-$button, $canvas, $checkbutton, $frame, $label, $pack, $update, $wm =
- $ip.commands().indexes(
- "button", "canvas", "checkbutton", "frame", "label", "pack", "update", "wm")
-
-class Othello
-
- EMPTY = 0
- BLACK = 1
- WHITE = - BLACK
-
- attr :in_com_turn
- attr :game_over
-
- class Board
-
- include Observable
-
- DIRECTIONS = [
- [-1, -1], [-1, 0], [-1, 1],
- [ 0, -1], [ 0, 1],
- [ 1, -1], [ 1, 0], [ 1, 1]
- ]
-
- attr :com_disk, TRUE
-
- def initialize(othello)
- @othello = othello
- reset
- end
-
- def notify_observers(*arg)
- if @observer_peers != nil
- super(*arg)
- end
- end
-
- def reset
- @data = [
- [EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY],
- [EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY],
- [EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY],
- [EMPTY, EMPTY, EMPTY, WHITE, BLACK, EMPTY, EMPTY, EMPTY],
- [EMPTY, EMPTY, EMPTY, BLACK, WHITE, EMPTY, EMPTY, EMPTY],
- [EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY],
- [EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY],
- [EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY]
- ]
- changed
- notify_observers
- end
-
- def man_disk
- return - @com_disk
- end
-
- def other_disk(disk)
- return - disk
- end
-
- def get_disk(row, col)
- return @data[row][col]
- end
-
- def reverse_to(row, col, my_disk, dir_y, dir_x)
- y = row
- x = col
- begin
- y += dir_y
- x += dir_x
- if y < 0 || x < 0 || y > 7 || x > 7 ||
- @data[y][x] == EMPTY
- return
- end
- end until @data[y][x] == my_disk
- begin
- @data[y][x] = my_disk
- changed
- notify_observers(y, x)
- y -= dir_y
- x -= dir_x
- end until y == row && x == col
- end
-
- def put_disk(row, col, disk)
- @data[row][col] = disk
- changed
- notify_observers(row, col)
- DIRECTIONS.each do |dir|
- reverse_to(row, col, disk, *dir)
- end
- end
-
- def count_disk(disk)
- num = 0
- @data.each do |rows|
- rows.each do |d|
- if d == disk
- num += 1
- end
- end
- end
- return num
- end
-
- def count_point_to(row, col, my_disk, dir_y, dir_x)
- return 0 if @data[row][col] != EMPTY
- count = 0
- loop do
- row += dir_y
- col += dir_x
- break if row < 0 || col < 0 || row > 7 || col > 7
- case @data[row][col]
- when my_disk
- return count
- when other_disk(my_disk)
- count += 1
- when EMPTY
- break
- end
- end
- return 0
- end
-
- def count_point(row, col, my_disk)
- count = 0
- DIRECTIONS.each do |dir|
- count += count_point_to(row, col, my_disk, *dir)
- end
- return count
- end
-
- def corner?(row, col)
- return (row == 0 && col == 0) ||
- (row == 0 && col == 7) ||
- (row == 7 && col == 0) ||
- (row == 7 && col == 7)
- end
-
- def search(my_disk)
- max = 0
- max_row = nil
- max_col = nil
- for row in 0 .. 7
- for col in 0 .. 7
- buf = count_point(row, col, my_disk)
- if (corner?(row, col) && buf > 0) || max < buf
- max = buf
- max_row = row
- max_col = col
- end
- end
- end
- return max_row, max_col
- end
- end #--------------------------> class Board ends here
-
- class BoardView < TclTkWidget
-
- BACK_GROUND_COLOR = "DarkGreen"
- HILIT_BG_COLOR = "green"
- BORDER_COLOR = "black"
- BLACK_COLOR = "black"
- WHITE_COLOR = "white"
- STOP_COLOR = "red"
-
- attr :left
- attr :top
- attr :right
- attr :bottom
-
- class Square
-
- attr :oval, TRUE
- attr :row
- attr :col
-
- def initialize(view, row, col)
- @view = view
- @id = @view.e("create rectangle", *view.tk_rect(view.left + col,
- view.top + row,
- view.left + col + 1,
- view.top + row + 1))
- @row = row
- @col = col
- @view.e("itemconfigure", @id,
- "-width 0.5m -outline #{BORDER_COLOR}")
- @view.e("bind", @id, "<Any-Enter>", TclTkCallback.new($ip, proc{
- if @oval == nil
- view.e("itemconfigure", @id, "-fill #{HILIT_BG_COLOR}")
- end
- }))
- @view.e("bind", @id, "<Any-Leave>", TclTkCallback.new($ip, proc{
- view.e("itemconfigure", @id, "-fill #{BACK_GROUND_COLOR}")
- }))
- @view.e("bind", @id, "<ButtonRelease-1>", TclTkCallback.new($ip,
- proc{
- view.click_square(self)
- }))
- end
-
- def blink(color)
- @view.e("itemconfigure", @id, "-fill #{color}")
- $update.e()
- sleep(0.1)
- @view.e("itemconfigure", @id, "-fill #{BACK_GROUND_COLOR}")
- end
- end #-----------------------> class Square ends here
-
- def initialize(othello, board)
- super($ip, $root, $canvas)
- @othello = othello
- @board = board
- @board.add_observer(self)
-
- @squares = Array.new(8)
- for i in 0 .. 7
- @squares[i] = Array.new(8)
- end
- @left = 1
- @top = 0.5
- @right = @left + 8
- @bottom = @top + 8
-
- i = self.e("create rectangle", *tk_rect(@left, @top, @right, @bottom))
- self.e("itemconfigure", i,
- "-width 1m -outline #{BORDER_COLOR} -fill #{BACK_GROUND_COLOR}")
-
- for row in 0 .. 7
- for col in 0 .. 7
- @squares[row][col] = Square.new(self, row, col)
- end
- end
-
- update
- end
-
- def tk_rect(left, top, right, bottom)
- return left.to_s + "c", top.to_s + "c",
- right.to_s + "c", bottom.to_s + "c"
- end
-
- def clear
- each_square do |square|
- if square.oval != nil
- self.e("delete", square.oval)
- square.oval = nil
- end
- end
- end
-
- def draw_disk(row, col, disk)
- if disk == EMPTY
- if @squares[row][col].oval != nil
- self.e("delete", @squares[row][col].oval)
- @squares[row][col].oval = nil
- end
- return
- end
-
- $update.e()
- sleep(0.05)
- oval = @squares[row][col].oval
- if oval == nil
- oval = self.e("create oval", *tk_rect(@left + col + 0.2,
- @top + row + 0.2,
- @left + col + 0.8,
- @top + row + 0.8))
- @squares[row][col].oval = oval
- end
- case disk
- when BLACK
- color = BLACK_COLOR
- when WHITE
- color = WHITE_COLOR
- else
- fail format("Unknown disk type: %d", disk)
- end
- self.e("itemconfigure", oval, "-outline #{color} -fill #{color}")
- end
-
- def update(row = nil, col = nil)
- if row && col
- draw_disk(row, col, @board.get_disk(row, col))
- else
- each_square do |square|
- draw_disk(square.row, square.col,
- @board.get_disk(square.row, square.col))
- end
- end
- @othello.show_point
- end
-
- def each_square
- @squares.each do |rows|
- rows.each do |square|
- yield(square)
- end
- end
- end
-
- def click_square(square)
- if @othello.in_com_turn || @othello.game_over ||
- @board.count_point(square.row,
- square.col,
- @board.man_disk) == 0
- square.blink(STOP_COLOR)
- return
- end
- @board.put_disk(square.row, square.col, @board.man_disk)
- @othello.com_turn
- end
-
- private :draw_disk
- public :update
- end #----------------------> class BoardView ends here
-
- def initialize
- @msg_label = TclTkWidget.new($ip, $root, $label)
- $pack.e(@msg_label)
-
- @board = Board.new(self)
- @board_view = BoardView.new(self, @board)
- #### added by Y. Shigehiro
- ## board_view の大きさを設定する.
- x1, y1, x2, y2 = @board_view.e("bbox all").split(/ /).collect{|i| i.to_f}
- @board_view.e("configure -width", x2 - x1)
- @board_view.e("configure -height", y2 - y1)
- ## scrollregion を設定する.
- @board_view.e("configure -scrollregion {", @board_view.e("bbox all"),
- "}")
- #### ここまで
- $pack.e(@board_view, "-fill both -expand true")
-
- panel = TclTkWidget.new($ip, $root, $frame)
-
- @play_black = TclTkWidget.new($ip, panel, $checkbutton,
- "-text {com is black} -command", TclTkCallback.new($ip, proc{
- switch_side
- }))
- $pack.e(@play_black, "-side left")
-
- quit = TclTkWidget.new($ip, panel, $button, "-text Quit -command",
- TclTkCallback.new($ip, proc{
- exit
- }))
- $pack.e(quit, "-side right -fill x")
-
- reset = TclTkWidget.new($ip, panel, $button, "-text Reset -command",
- TclTkCallback.new($ip, proc{
- reset_game
- }))
- $pack.e(reset, "-side right -fill x")
-
- $pack.e(panel, "-side bottom -fill x")
-
-# root = Tk.root
- $wm.e("title", $root, "Othello")
- $wm.e("iconname", $root, "Othello")
-
- @board.com_disk = WHITE
- @game_over = FALSE
-
- TclTk.mainloop
- end
-
- def switch_side
- if @in_com_turn
- @play_black.e("toggle")
- else
- @board.com_disk = @board.man_disk
- com_turn unless @game_over
- end
- end
-
- def reset_game
- if @board.com_disk == BLACK
- @board.com_disk = WHITE
- @play_black.e("toggle")
- end
- @board_view.clear
- @board.reset
- $wm.e("title", $root, "Othello")
- @game_over = FALSE
- end
-
- def com_turn
- @in_com_turn = TRUE
- $update.e()
- sleep(0.5)
- begin
- com_disk = @board.count_disk(@board.com_disk)
- man_disk = @board.count_disk(@board.man_disk)
- if @board.count_disk(EMPTY) == 0
- if man_disk == com_disk
- $wm.e("title", $root, "{Othello - Draw!}")
- elsif man_disk > com_disk
- $wm.e("title", $root, "{Othello - You Win!}")
- else
- $wm.e("title", $root, "{Othello - You Loose!}")
- end
- @game_over = TRUE
- break
- elsif com_disk == 0
- $wm.e("title", $root, "{Othello - You Win!}")
- @game_over = TRUE
- break
- elsif man_disk == 0
- $wm.e("title", $root, "{Othello - You Loose!}")
- @game_over = TRUE
- break
- end
- row, col = @board.search(@board.com_disk)
- break if row == nil || col == nil
- @board.put_disk(row, col, @board.com_disk)
- end while @board.search(@board.man_disk) == [nil, nil]
- @in_com_turn = FALSE
- end
-
- def show_point
- black = @board.count_disk(BLACK)
- white = @board.count_disk(WHITE)
- @msg_label.e("configure -text",
- %Q/{#{format("BLACK: %.2d WHITE: %.2d", black, white)}}/)
- end
-end #----------------------> class Othello ends here
-
-Othello.new
-
-#----------------------------------------------> othello.rb ends here
diff --git a/ext/tcltklib/stubs.c b/ext/tcltklib/stubs.c
deleted file mode 100644
index 69a5d6d3c0..0000000000
--- a/ext/tcltklib/stubs.c
+++ /dev/null
@@ -1,86 +0,0 @@
-#if defined USE_TCL_STUBS && defined USE_TK_STUBS
-#include <tcl.h>
-#include <tk.h>
-#include "ruby.h"
-
-#if defined _WIN32 || defined __CYGWIN__
-# include <windows.h>
- typedef HINSTANCE DL_HANDLE;
-# define DL_OPEN LoadLibrary
-# define DL_SYM GetProcAddress
-# define TCL_INDEX 4
-# define TK_INDEX 3
-# define TCL_NAME "tcl89%s"
-# define TK_NAME "tk89%s"
-# undef DLEXT
-# define DLEXT ".dll"
-#elif defined HAVE_DLOPEN
-# include <dlfcn.h>
- typedef void *DL_HANDLE;
-# define DL_OPEN(file) dlopen(file, RTLD_LAZY|RTLD_GLOBAL)
-# define DL_SYM dlsym
-# define TCL_INDEX 8
-# define TK_INDEX 7
-# define TCL_NAME "libtcl8.9%s"
-# define TK_NAME "libtk8.9%s"
-#endif
-
-int
-ruby_tcltk_stubs()
-{
- DL_HANDLE tcl_dll;
- DL_HANDLE tk_dll;
- Tcl_Interp *(*p_Tcl_CreateInterp)();
- int (*p_Tk_Init) _((Tcl_Interp *));
- Tcl_Interp *tcl_ip;
- int n;
- char *ruby_tcl_dll;
- char *ruby_tk_dll;
- char tcl_name[20];
- char tk_name[20];
-
- ruby_tcl_dll = getenv("RUBY_TCL_DLL");
- ruby_tk_dll = getenv("RUBY_TK_DLL");
- if (ruby_tcl_dll && ruby_tk_dll) {
- tcl_dll = (DL_HANDLE)DL_OPEN(ruby_tcl_dll);
- tk_dll = (DL_HANDLE)DL_OPEN(ruby_tk_dll);
- } else {
- snprintf(tcl_name, sizeof tcl_name, TCL_NAME, DLEXT);
- snprintf(tk_name, sizeof tk_name, TK_NAME, DLEXT);
- /* examine from 8.9 to 8.1 */
- for (n = '9'; n > '0'; n--) {
- tcl_name[TCL_INDEX] = n;
- tk_name[TK_INDEX] = n;
- tcl_dll = (DL_HANDLE)DL_OPEN(tcl_name);
- tk_dll = (DL_HANDLE)DL_OPEN(tk_name);
- if (tcl_dll && tk_dll)
- break;
- }
- }
-
- if (!tcl_dll || !tk_dll)
- return -1;
-
- p_Tcl_CreateInterp = (Tcl_Interp *(*)())DL_SYM(tcl_dll, "Tcl_CreateInterp");
- if (!p_Tcl_CreateInterp)
- return -2;
-
- tcl_ip = (*p_Tcl_CreateInterp)();
- if (!tcl_ip)
- return -3;
-
- p_Tk_Init = (int (*) _((Tcl_Interp *)))DL_SYM(tk_dll, "Tk_Init");
- if (!p_Tk_Init)
- return -4;
- (*p_Tk_Init)(tcl_ip);
-
- if (!Tcl_InitStubs(tcl_ip, "8.1", 0))
- return -5;
- if (!Tk_InitStubs(tcl_ip, "8.1", 0))
- return -6;
-
- Tcl_DeleteInterp(tcl_ip);
-
- return 0;
-}
-#endif
diff --git a/ext/tcltklib/tcltklib.c b/ext/tcltklib/tcltklib.c
deleted file mode 100644
index 7acbacdd94..0000000000
--- a/ext/tcltklib/tcltklib.c
+++ /dev/null
@@ -1,561 +0,0 @@
-/*
- * tcltklib.c
- * Aug. 27, 1997 Y. Shigehiro
- * Oct. 24, 1997 Y. Matsumoto
- */
-
-#include "ruby.h"
-#include "rubysig.h"
-#undef EXTERN /* avoid conflict with tcl.h of tcl8.2 or before */
-#include <stdio.h>
-#include <string.h>
-#include <tcl.h>
-#include <tk.h>
-
-#ifdef __MACOS__
-# include <tkMac.h>
-# include <Quickdraw.h>
-#endif
-
-/* for ruby_debug */
-
-#define DUMP1(ARG1) if (ruby_debug) { fprintf(stderr, "tcltklib: %s\n", ARG1);}
-#define DUMP2(ARG1, ARG2) if (ruby_debug) { fprintf(stderr, "tcltklib: ");\
-fprintf(stderr, ARG1, ARG2); fprintf(stderr, "\n"); }
-/*
-#define DUMP1(ARG1)
-#define DUMP2(ARG1, ARG2)
-*/
-
-/* for callback break & continue */
-static VALUE eTkCallbackBreak;
-static VALUE eTkCallbackContinue;
-
-static VALUE ip_invoke_real _((int, VALUE*, VALUE));
-
-/* from tkAppInit.c */
-
-#if !defined __MINGW32__
-/*
- * The following variable is a special hack that is needed in order for
- * Sun shared libraries to be used for Tcl.
- */
-
-extern int matherr();
-int *tclDummyMathPtr = (int *) matherr;
-#endif
-
-/*---- module TclTkLib ----*/
-
-struct invoke_queue {
- int argc;
- VALUE *argv;
- VALUE obj;
- int done;
- VALUE result;
- VALUE thread;
- struct invoke_queue *next;
-};
-
-static struct invoke_queue *iqueue;
-static VALUE main_thread;
-
-/* Tk_ThreadTimer */
-static Tcl_TimerToken timer_token;
-
-/* timer callback */
-static void
-_timer_for_tcl(clientData)
- ClientData clientData;
-{
- struct invoke_queue *q, *tmp;
- VALUE thread;
-
- Tk_DeleteTimerHandler(timer_token);
- timer_token = Tk_CreateTimerHandler(100, _timer_for_tcl, (ClientData)0);
-
- CHECK_INTS;
- q = iqueue;
- while (q) {
- tmp = q;
- q = q->next;
- if (!tmp->done) {
- tmp->done = 1;
- tmp->result = ip_invoke_real(tmp->argc, tmp->argv, tmp->obj);
- thread = tmp->thread;
- tmp = tmp->next;
- rb_thread_run(thread);
- }
- }
- rb_thread_schedule();
-}
-
-/* execute Tk_MainLoop */
-static VALUE
-lib_mainloop(self)
- VALUE self;
-{
- timer_token = Tk_CreateTimerHandler(100, _timer_for_tcl, (ClientData)0);
- DUMP1("start Tk_Mainloop");
- Tk_MainLoop();
- DUMP1("stop Tk_Mainloop");
- Tk_DeleteTimerHandler(timer_token);
-
- return Qnil;
-}
-
-/*---- class TclTkIp ----*/
-struct tcltkip {
- Tcl_Interp *ip; /* the interpreter */
- int return_value; /* return value */
-};
-
-/* Tcl command `ruby' */
-static VALUE
-ip_eval_rescue(failed, einfo)
- VALUE *failed;
- VALUE einfo;
-{
- *failed = einfo;
- return Qnil;
-}
-
-/* restart Tk */
-static VALUE
-lib_restart(self)
- VALUE self;
-{
- struct tcltkip *ptr; /* tcltkip data struct */
-
- /* get the data struct */
- Data_Get_Struct(self, struct tcltkip, ptr);
-
- /* destroy the root wdiget */
- ptr->return_value = Tcl_Eval(ptr->ip, "destroy .");
- /* ignore ERROR */
- DUMP2("(TCL_Eval result) %d", ptr->return_value);
-
- /* execute Tk_Init */
- DUMP1("Tk_Init");
- if (Tk_Init(ptr->ip) == TCL_ERROR) {
- rb_raise(rb_eRuntimeError, "%s", ptr->ip->result);
- }
-
- return Qnil;
-}
-
-static int
-#if TCL_MAJOR_VERSION >= 8
-ip_ruby(clientData, interp, argc, argv)
- ClientData clientData;
- Tcl_Interp *interp;
- int argc;
- Tcl_Obj *CONST argv[];
-#else
-ip_ruby(clientData, interp, argc, argv)
- ClientData clientData;
- Tcl_Interp *interp;
- int argc;
- char *argv[];
-#endif
-{
- VALUE res;
- int old_trapflg;
- VALUE failed = 0;
- char *arg;
- int dummy;
-
- /* ruby command has 1 arg. */
- if (argc != 2) {
- rb_raise(rb_eArgError, "wrong # of arguments (%d for 1)", argc);
- }
-
- /* get C string from Tcl object */
-#if TCL_MAJOR_VERSION >= 8
- arg = Tcl_GetStringFromObj(argv[1], &dummy);
-#else
- arg = argv[1];
-#endif
-
- /* evaluate the argument string by ruby */
- DUMP2("rb_eval_string(%s)", arg);
- old_trapflg = rb_trap_immediate;
- rb_trap_immediate = 0;
- res = rb_rescue2(rb_eval_string, (VALUE)arg,
- ip_eval_rescue, (VALUE)&failed,
- rb_eStandardError, rb_eScriptError, 0);
- rb_trap_immediate = old_trapflg;
-
- Tcl_ResetResult(interp);
- if (failed) {
- VALUE eclass = CLASS_OF(failed);
- Tcl_AppendResult(interp, StringValuePtr(failed), (char*)NULL);
- if (eclass == eTkCallbackBreak) {
- return TCL_BREAK;
- } else if (eclass == eTkCallbackContinue) {
- return TCL_CONTINUE;
- } else {
- return TCL_ERROR;
- }
- }
-
- /* result must be string or nil */
- if (NIL_P(res)) {
- DUMP1("(rb_eval_string result) nil");
- return TCL_OK;
- }
-
- /* copy result to the tcl interpreter */
- DUMP2("(rb_eval_string result) %s", StringValuePtr(res));
- DUMP1("Tcl_AppendResult");
- Tcl_AppendResult(interp, StringValuePtr(res), (char *)NULL);
-
- return TCL_OK;
-}
-
-/* destroy interpreter */
-static void
-ip_free(ptr)
- struct tcltkip *ptr;
-{
- DUMP1("Tcl_DeleteInterp");
- Tcl_DeleteInterp(ptr->ip);
- free(ptr);
-}
-
-/* create and initialize interpreter */
-static VALUE
-ip_new(self)
- VALUE self;
-{
- struct tcltkip *ptr; /* tcltkip data struct */
- VALUE obj; /* newly created object */
-
- /* create object */
- obj = Data_Make_Struct(self, struct tcltkip, 0, ip_free, ptr);
- ptr->return_value = 0;
-
- /* from Tk_Main() */
- DUMP1("Tcl_CreateInterp");
- ptr->ip = Tcl_CreateInterp();
-
- /* from Tcl_AppInit() */
- DUMP1("Tcl_Init");
- if (Tcl_Init(ptr->ip) == TCL_ERROR) {
- rb_raise(rb_eRuntimeError, "%s", ptr->ip->result);
- }
- DUMP1("Tk_Init");
- if (Tk_Init(ptr->ip) == TCL_ERROR) {
- rb_raise(rb_eRuntimeError, "%s", ptr->ip->result);
- }
- DUMP1("Tcl_StaticPackage(\"Tk\")");
- Tcl_StaticPackage(ptr->ip, "Tk", Tk_Init,
- (Tcl_PackageInitProc *) NULL);
-
- /* add ruby command to the interpreter */
-#if TCL_MAJOR_VERSION >= 8
- DUMP1("Tcl_CreateObjCommand(\"ruby\")");
- Tcl_CreateObjCommand(ptr->ip, "ruby", ip_ruby, (ClientData)NULL,
- (Tcl_CmdDeleteProc *)NULL);
-#else
- DUMP1("Tcl_CreateCommand(\"ruby\")");
- Tcl_CreateCommand(ptr->ip, "ruby", ip_ruby, (ClientData)NULL,
- (Tcl_CmdDeleteProc *)NULL);
-#endif
-
- return obj;
-}
-
-/* eval string in tcl by Tcl_Eval() */
-static VALUE
-ip_eval(self, str)
- VALUE self;
- VALUE str;
-{
- char *s;
- char *buf; /* Tcl_Eval requires re-writable string region */
- struct tcltkip *ptr; /* tcltkip data struct */
-
- /* get the data struct */
- Data_Get_Struct(self, struct tcltkip, ptr);
-
- /* call Tcl_Eval() */
- s = StringValuePtr(str);
- buf = ALLOCA_N(char, strlen(s)+1);
- strcpy(buf, s);
- DUMP2("Tcl_Eval(%s)", buf);
- ptr->return_value = Tcl_Eval(ptr->ip, buf);
- if (ptr->return_value == TCL_ERROR) {
- rb_raise(rb_eRuntimeError, "%s", ptr->ip->result);
- }
- DUMP2("(TCL_Eval result) %d", ptr->return_value);
-
- /* pass back the result (as string) */
- return(rb_str_new2(ptr->ip->result));
-}
-
-
-static VALUE
-ip_toUTF8(self, str, encodename)
- VALUE self;
- VALUE str;
- VALUE encodename;
-{
-#ifdef TCL_UTF_MAX
- Tcl_Interp *interp;
- Tcl_Encoding encoding;
- Tcl_DString dstr;
- struct tcltkip *ptr;
- char *buf;
-
- Data_Get_Struct(self,struct tcltkip, ptr);
- interp = ptr->ip;
-
- StringValue(encodename);
- StringValue(str);
- encoding = Tcl_GetEncoding(interp, RSTRING(encodename)->ptr);
- buf = ALLOCA_N(char,strlen(RSTRING(str)->ptr)+1);
- strcpy(buf, RSTRING(str)->ptr);
-
- Tcl_DStringInit(&dstr);
- Tcl_DStringFree(&dstr);
- Tcl_ExternalToUtfDString(encoding,buf,strlen(buf),&dstr);
- str = rb_str_new2(Tcl_DStringValue(&dstr));
-
- Tcl_FreeEncoding(encoding);
- Tcl_DStringFree(&dstr);
-#endif
- return str;
-}
-
-static VALUE
-ip_fromUTF8(self, str, encodename)
- VALUE self;
- VALUE str;
- VALUE encodename;
-{
-#ifdef TCL_UTF_MAX
- Tcl_Interp *interp;
- Tcl_Encoding encoding;
- Tcl_DString dstr;
- struct tcltkip *ptr;
- char *buf;
-
- Data_Get_Struct(self,struct tcltkip, ptr);
- interp = ptr->ip;
-
- StringValue(encodename);
- StringValue(str);
- encoding = Tcl_GetEncoding(interp,RSTRING(encodename)->ptr);
- buf = ALLOCA_N(char,strlen(RSTRING(str)->ptr)+1);
- strcpy(buf,RSTRING(str)->ptr);
-
- Tcl_DStringInit(&dstr);
- Tcl_DStringFree(&dstr);
- Tcl_UtfToExternalDString(encoding,buf,strlen(buf),&dstr);
- str = rb_str_new2(Tcl_DStringValue(&dstr));
-
- Tcl_FreeEncoding(encoding);
- Tcl_DStringFree(&dstr);
-
-#endif
- return str;
-}
-
-
-static VALUE
-ip_invoke_real(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- VALUE v;
- struct tcltkip *ptr; /* tcltkip data struct */
- int i;
- Tcl_CmdInfo info;
- char *cmd, *s;
- char **av = (char **)NULL;
-#if TCL_MAJOR_VERSION >= 8
- Tcl_Obj **ov = (Tcl_Obj **)NULL;
- Tcl_Obj *resultPtr;
-#endif
-
- /* get the data struct */
- Data_Get_Struct(obj, struct tcltkip, ptr);
-
- /* get the command name string */
- v = argv[0];
- cmd = StringValuePtr(v);
-
- /* map from the command name to a C procedure */
- if (!Tcl_GetCommandInfo(ptr->ip, cmd, &info)) {
- rb_raise(rb_eNameError, "invalid command name `%s'", cmd);
- }
-
- /* memory allocation for arguments of this command */
-#if TCL_MAJOR_VERSION >= 8
- if (info.isNativeObjectProc) {
- /* object interface */
- ov = (Tcl_Obj **)ALLOCA_N(Tcl_Obj *, argc+1);
- for (i = 0; i < argc; ++i) {
- v = argv[i];
- s = StringValuePtr(v);
- ov[i] = Tcl_NewStringObj(s, RSTRING(v)->len);
- Tcl_IncrRefCount(ov[i]);
- }
- ov[argc] = (Tcl_Obj *)NULL;
- }
- else
-#endif
- {
- /* string interface */
- av = (char **)ALLOCA_N(char *, argc+1);
- for (i = 0; i < argc; ++i) {
- v = argv[i];
- s = StringValuePtr(v);
- av[i] = ALLOCA_N(char, strlen(s)+1);
- strcpy(av[i], s);
- }
- av[argc] = (char *)NULL;
- }
-
- Tcl_ResetResult(ptr->ip);
-
- /* Invoke the C procedure */
-#if TCL_MAJOR_VERSION >= 8
- if (info.isNativeObjectProc) {
- int dummy;
- ptr->return_value = (*info.objProc)(info.objClientData,
- ptr->ip, argc, ov);
-
- /* get the string value from the result object */
- resultPtr = Tcl_GetObjResult(ptr->ip);
- Tcl_SetResult(ptr->ip, Tcl_GetStringFromObj(resultPtr, &dummy),
- TCL_VOLATILE);
-
- for (i=0; i<argc; i++) {
- Tcl_DecrRefCount(ov[i]);
- }
- }
- else
-#endif
- {
- ptr->return_value = (*info.proc)(info.clientData,
- ptr->ip, argc, av);
- }
-
- if (ptr->return_value == TCL_ERROR) {
- rb_raise(rb_eRuntimeError, "%s", ptr->ip->result);
- }
-
- /* pass back the result (as string) */
- return rb_str_new2(ptr->ip->result);
-}
-
-static VALUE
-ip_invoke(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- struct invoke_queue *tmp, *p;
- VALUE result = rb_thread_current();
-
- if (result == main_thread) {
- return ip_invoke_real(argc, argv, obj);
- }
- tmp = ALLOC(struct invoke_queue);
- tmp->obj = obj;
- tmp->argc = argc;
- tmp->argv = ALLOC_N(VALUE, argc);
- MEMCPY(tmp->argv, argv, VALUE, argc);
- tmp->thread = result;
- tmp->done = 0;
-
- tmp->next = iqueue;
- iqueue = tmp;
-
- rb_thread_stop();
- result = tmp->result;
- if (iqueue == tmp) {
- iqueue = tmp->next;
- free(tmp->argv);
- free(tmp);
- return result;
- }
-
- p = iqueue;
- while (p->next) {
- if (p->next == tmp) {
- p->next = tmp->next;
- free(tmp->argv);
- free(tmp);
- break;
- }
- p = p->next;
- }
- return result;
-}
-
-/* get return code from Tcl_Eval() */
-static VALUE
-ip_retval(self)
- VALUE self;
-{
- struct tcltkip *ptr; /* tcltkip data struct */
-
- /* get the data strcut */
- Data_Get_Struct(self, struct tcltkip, ptr);
-
- return (INT2FIX(ptr->return_value));
-}
-
-#ifdef __MACOS__
-static void
-_macinit()
-{
- tcl_macQdPtr = &qd; /* setup QuickDraw globals */
- Tcl_MacSetEventProc(TkMacConvertEvent); /* setup event handler */
-}
-#endif
-
-/*---- initialization ----*/
-void
-Init_tcltklib()
-{
- VALUE lib = rb_define_module("TclTkLib");
- VALUE ip = rb_define_class("TclTkIp", rb_cObject);
-
-#if defined USE_TCL_STUBS && defined USE_TK_STUBS
- extern int ruby_tcltk_stubs();
- int ret = ruby_tcltk_stubs();
- if (ret)
- rb_raise(rb_eLoadError, "tcltklib: tcltk_stubs init error(%d)", ret);
-#endif
-
- eTkCallbackBreak = rb_define_class("TkCallbackBreak", rb_eStandardError);
- eTkCallbackContinue = rb_define_class("TkCallbackContinue",rb_eStandardError);
-
- rb_define_module_function(lib, "mainloop", lib_mainloop, 0);
-
- rb_define_singleton_method(ip, "new", ip_new, 0);
- rb_define_method(ip, "_eval", ip_eval, 1);
- rb_define_method(ip, "_toUTF8",ip_toUTF8,2);
- rb_define_method(ip, "_fromUTF8",ip_fromUTF8,2);
- rb_define_method(ip, "_invoke", ip_invoke, -1);
- rb_define_method(ip, "_return_value", ip_retval, 0);
- rb_define_method(ip, "mainloop", lib_mainloop, 0);
- rb_define_method(ip, "restart", lib_restart, 0);
-
- main_thread = rb_thread_current();
-#ifdef __MACOS__
- _macinit();
-#endif
-
- /*---- initialize tcl/tk libraries ----*/
- /* from Tk_Main() */
- DUMP1("Tcl_FindExecutable");
- Tcl_FindExecutable(RSTRING(rb_argv0)->ptr);
-}
-
-/* eof */
diff --git a/ext/tk/.cvsignore b/ext/tk/.cvsignore
deleted file mode 100644
index fc802ff1c2..0000000000
--- a/ext/tk/.cvsignore
+++ /dev/null
@@ -1,2 +0,0 @@
-Makefile
-mkmf.log
diff --git a/ext/tk/MANIFEST b/ext/tk/MANIFEST
deleted file mode 100644
index 9689186bf0..0000000000
--- a/ext/tk/MANIFEST
+++ /dev/null
@@ -1,25 +0,0 @@
-MANIFEST
-extconf.rb
-depend
-tkutil.c
-lib/tk.rb
-lib/tkafter.rb
-lib/tkbgerror.rb
-lib/tkcanvas.rb
-lib/tkclass.rb
-lib/tkdialog.rb
-lib/tkentry.rb
-lib/tkfont.rb
-lib/tkmenubar.rb
-lib/tkmngfocus.rb
-lib/tkpalette.rb
-lib/tkscrollbox.rb
-lib/tktext.rb
-lib/tkvirtevent.rb
-sample/tkbiff.rb
-sample/tkbrowse.rb
-sample/tkdialog.rb
-sample/tkfrom.rb
-sample/tkhello.rb
-sample/tkline.rb
-sample/tktimer.rb
diff --git a/ext/tk/depend b/ext/tk/depend
deleted file mode 100644
index fd63e230f0..0000000000
--- a/ext/tk/depend
+++ /dev/null
@@ -1 +0,0 @@
-tkutil.o: tkutil.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h
diff --git a/ext/tk/extconf.rb b/ext/tk/extconf.rb
deleted file mode 100644
index f769b06e30..0000000000
--- a/ext/tk/extconf.rb
+++ /dev/null
@@ -1,2 +0,0 @@
-require 'mkmf'
-create_makefile("tkutil")
diff --git a/ext/tk/lib/README b/ext/tk/lib/README
deleted file mode 100644
index 87b59f4972..0000000000
--- a/ext/tk/lib/README
+++ /dev/null
@@ -1,15 +0,0 @@
-README this file
-tk.rb Tk interface
-tkafter.rb handles Tcl after
-tkbgerror.rb Tk error module
-tkcanvas.rb Tk canvas interface
-tkclass.rb provides generic names for Tk classes
-tkdialog.rb Tk dialog class
-tkentry.rb Tk entry class
-tkfont.rb Tk font support
-tkmenubar.rb TK menubar utility
-tkmngfocus.rb focus manager
-tkpalette.rb pallete support
-tkscrollbox.rb scroll box, also example of compound widget
-tktext.rb text classes
-tkvirtevent.rb virtual event support
diff --git a/ext/tk/lib/tk.rb b/ext/tk/lib/tk.rb
deleted file mode 100644
index bac2ae35f9..0000000000
--- a/ext/tk/lib/tk.rb
+++ /dev/null
@@ -1,3592 +0,0 @@
-#
-# tk.rb - Tk interface module using tcltklib
-# $Date$
-# by Yukihiro Matsumoto <matz@netlab.jp>
-
-# use Shigehiro's tcltklib
-require "tcltklib"
-require "tkutil"
-
-module TkComm
- WidgetClassNames = {}
-
- None = Object.new
- def None.to_s
- 'None'
- end
-
- Tk_CMDTBL = {}
- Tk_WINDOWS = {}
-
- def error_at
- frames = caller()
- frames.delete_if do |c|
- c =~ %r!/tk(|core|thcore|canvas|text|entry|scrollbox)\.rb:\d+!
- end
- frames
- end
- private :error_at
-
- def _genobj_for_tkwidget(path)
- return TkRoot.new if path == '.'
-
- begin
- tk_class = TkCore::INTERP._invoke('winfo', 'class', path)
- rescue
- return path
- end
-
- ruby_class = WidgetClassNames[tk_class]
- gen_class_name = ruby_class.name + 'GeneratedOnTk'
- unless Object.const_defined? gen_class_name
- eval "class #{gen_class_name}<#{ruby_class.name}
- def initialize(path)
- @path=path
- Tk_WINDOWS[@path] = self
- end
- end"
- end
- eval "#{gen_class_name}.new('#{path}')"
- end
-
- def tk_tcl2ruby(val)
- if val =~ /^rb_out (c\d+)/
- return Tk_CMDTBL[$1]
- end
- if val.include? ?\s
- return val.split.collect{|v| tk_tcl2ruby(v)}
- end
- case val
- when /^@font/
- TkFont.get_obj(val)
- when /^-?\d+$/
- val.to_i
- when /^\./
- Tk_WINDOWS[val] ? Tk_WINDOWS[val] : _genobj_for_tkwidget(val)
- when / /
- val.split.collect{|elt|
- tk_tcl2ruby(elt)
- }
- when /^-?\d+\.\d*$/
- val.to_f
- else
- val
- end
- end
-
- def tk_split_list(str)
- return [] if str == ""
- idx = str.index('{')
- while idx and idx > 0 and str[idx-1] == ?\\
- idx = str.index('{', idx+1)
- end
- return tk_tcl2ruby(str) unless idx
-
- list = tk_tcl2ruby(str[0,idx])
- list = [] if list == ""
- str = str[idx+1..-1]
- i = -1
- brace = 1
- str.each_byte {|c|
- i += 1
- brace += 1 if c == ?{
- brace -= 1 if c == ?}
- break if brace == 0
- }
- if str[0, i] == ' '
- list.push ' '
- else
- list.push tk_split_list(str[0, i])
- end
- list += tk_split_list(str[i+1..-1])
- list
- end
-
- def tk_split_simplelist(str)
- return [] if str == ""
- idx = str.index('{')
- while idx and idx > 0 and str[idx-1] == ?\\
- idx = str.index('{', idx+1)
- end
- return str.split unless idx
-
- list = str[0,idx].split
- str = str[idx+1..-1]
- i = -1
- brace = 1
- str.each_byte {|c|
- i += 1
- brace += 1 if c == ?{
- brace -= 1 if c == ?}
- break if brace == 0
- }
- if i == 0
- list.push ''
- elsif str[0, i] == ' '
- list.push ' '
- else
- list.push str[0..i-1]
- end
- list += tk_split_simplelist(str[i+1..-1])
- list
- end
- private :tk_tcl2ruby, :tk_split_list, :tk_split_simplelist
-
- def hash_kv(keys)
- conf = []
- if keys and keys != None
- for k, v in keys
- conf.push("-#{k}")
- conf.push(v)
- end
- end
- conf
- end
- private :hash_kv
-
- def array2tk_list(ary)
- ary.collect{|e|
- if e.kind_of? Array
- "{#{array2tk_list(e)}}"
- elsif e.kind_of? Hash
- "{#{e.to_a.collect{|ee| array2tk_list(ee)}.join(' ')}}"
- else
- s = _get_eval_string(e)
- (s.index(/\s/))? "{#{s}}": s
- end
- }.join(" ")
- end
- private :array2tk_list
-
- def bool(val)
- case val
- when "1", 1, 'yes', 'true'
- TRUE
- else
- FALSE
- end
- end
- def number(val)
- case val
- when /^-?\d+$/
- val.to_i
- when /^-?\d+\.\d*$/
- val.to_f
- else
- val
- end
- end
- def string(val)
- if val == "{}"
- ''
- elsif val[0] == ?{
- val[1..-2]
- else
- val
- end
- end
- def list(val)
- tk_split_list(val).to_a
- end
- def window(val)
- Tk_WINDOWS[val]
- end
- def procedure(val)
- if val =~ /^rb_out (c\d+)/
- Tk_CMDTBL[$1]
- else
- nil
- end
- end
- private :bool, :number, :string, :list, :window, :procedure
-
- def _get_eval_string(str)
- return nil if str == None
- if str.kind_of?(String)
- # do nothing
- elsif str.kind_of?(Hash)
- str = hash_kv(str).join(" ")
- elsif str.kind_of?(Array)
- str = array2tk_list(str)
- elsif str.kind_of?(Proc)
- str = install_cmd(str)
- elsif str == nil
- str = ""
- elsif str == false
- str = "0"
- elsif str == true
- str = "1"
- elsif (str.respond_to?(:to_eval))
- str = str.to_eval()
- else
- str = str.to_s()
- end
- return str
- end
- private :_get_eval_string
-
- def ruby2tcl(v)
- if v.kind_of?(Hash)
- v = hash_kv(v)
- v.flatten!
- v.collect{|e|ruby2tcl(e)}
- else
- _get_eval_string(v)
- end
- end
- private :ruby2tcl
-
- Tk_IDs = [0, 0] # [0]-cmdid, [1]-winid
- def _curr_cmd_id
- id = format("c%.4d", Tk_IDs[0])
- end
- def _next_cmd_id
- id = _curr_cmd_id
- Tk_IDs[0] += 1
- id
- end
- def install_cmd(cmd)
- return '' if cmd == ''
- id = _next_cmd_id
- Tk_CMDTBL[id] = cmd
- @cmdtbl = [] unless @cmdtbl
- @cmdtbl.push id
- return format("rb_out %s", id);
- end
- def uninstall_cmd(id)
- id = $1 if /rb_out (c\d+)/ =~ id
- Tk_CMDTBL[id] = nil
- end
- private :install_cmd, :uninstall_cmd
-
- def install_win(ppath)
- id = format("w%.4d", Tk_IDs[1])
- Tk_IDs[1] += 1
- if !ppath or ppath == "."
- @path = format(".%s", id);
- else
- @path = format("%s.%s", ppath, id)
- end
- Tk_WINDOWS[@path] = self
- end
-
- def uninstall_win()
- Tk_WINDOWS[@path] = nil
- end
-
- class Event
- def initialize(seq,a,b,c,d,f,h,k,m,o,p,s,t,w,x,y,
- aa,bb,dd,ee,kk,nn,rr,ss,tt,ww,xx,yy)
- @serial = seq
- @above = a
- @num = b
- @count = c
- @detail = d
- @focus = (f == 1)
- @height = h
- @keycode = k
- @mode = m
- @override = (o == 1)
- @place = p
- @state = s
- @time = t
- @width = w
- @x = x
- @y = y
- @char = aa
- @borderwidth = bb
- @wheel_delta = dd
- @send_event = (ee == 1)
- @keysym = kk
- @keysym_num = nn
- @rootwin_id = rr
- @subwindow = ss
- @type = tt
- @widget = ww
- @x_root = xx
- @y_root = yy
- end
- attr :serial
- attr :above
- attr :num
- attr :count
- attr :detail
- attr :focus
- attr :height
- attr :keycode
- attr :mode
- attr :override
- attr :place
- attr :state
- attr :time
- attr :width
- attr :x
- attr :y
- attr :char
- attr :borderwidth
- attr :wheel_delta
- attr :send_event
- attr :keysym
- attr :keysym_num
- attr :rootwin_id
- attr :subwindow
- attr :type
- attr :widget
- attr :x_root
- attr :y_root
- end
-
- def install_bind(cmd, args=nil)
- if args
- id = install_cmd(proc{|*arg|
- TkUtil.eval_cmd cmd, *arg
- })
- id + " " + args
- else
- id = install_cmd(proc{|arg|
- TkUtil.eval_cmd cmd, Event.new(*arg)
- })
- id + ' %# %a %b %c %d %f %h %k %m %o %p %s %t %w %x %y' +
- ' %A %B %D %E %K %N %R %S %T %W %X %Y'
- end
- end
-
- def tk_event_sequence(context)
- if context.kind_of? TkVirtualEvent
- context = context.path
- end
- if context.kind_of? Array
- context = context.collect{|ev|
- if ev.kind_of? TkVirtualEvent
- ev.path
- else
- ev
- end
- }.join("><")
- end
- if /,/ =~ context
- context = context.split(/\s*,\s*/).join("><")
- else
- context
- end
- end
-
- def _bind_core(mode, what, context, cmd, args=nil)
- id = install_bind(cmd, args) if cmd
- begin
- tk_call(*(what + ["<#{tk_event_sequence(context)}>", mode + id]))
- rescue
- uninstall_cmd(id) if cmd
- fail
- end
- end
-
- def _bind(what, context, cmd, args=nil)
- _bind_core('', what, context, cmd, args)
- end
-
- def _bind_append(what, context, cmd, args=nil)
- _bind_core('+', what, context, cmd, args)
- end
-
- def _bind_remove(what, context)
- tk_call(*(what + ["<#{tk_event_sequence(context)}>", '']))
- end
-
- def _bindinfo(what, context=nil)
- if context
- tk_call(*what+["<#{tk_event_sequence(context)}>"]).collect {|cmdline|
- if cmdline =~ /^rb_out (c\d+)\s+(.*)$/
- [Tk_CMDTBL[$1], $2]
- else
- cmdline
- end
- }
- else
- tk_split_simplelist(tk_call(*what)).collect!{|seq|
- l = seq.scan(/<*[^<>]+>*/).collect!{|subseq|
- case (subseq)
- when /^<<[^<>]+>>$/
- TkVirtualEvent.getobj(subseq[1..-2])
- when /^<[^<>]+>$/
- subseq[1..-2]
- else
- subseq.split('')
- end
- }.flatten
- (l.size == 1) ? l[0] : l
- }
- end
- end
- private :install_bind, :tk_event_sequence,
- :_bind_core, :_bind, :_bind_append, :_bind_remove, :_bindinfo
-
- def bind(tagOrClass, context, cmd=Proc.new, args=nil)
- _bind(["bind", tagOrClass], context, cmd, args)
- end
-
- def bind_append(tagOrClass, context, cmd=Proc.new, args=nil)
- _bind_append(["bind", tagOrClass], context, cmd, args)
- end
-
- def bind_remove(tagOrClass, context)
- _bind_remove(['bind', tagOrClass], context)
- end
-
- def bindinfo(tagOrClass, context=nil)
- _bindinfo(['bind', tagOrClass], context)
- end
-
- def bind_all(context, cmd=Proc.new, args=nil)
- _bind(['bind', 'all'], context, cmd, args)
- end
-
- def bind_append_all(context, cmd=Proc.new, args=nil)
- _bind_append(['bind', 'all'], context, cmd, args)
- end
-
- def bindinfo_all(context=nil)
- _bindinfo(['bind', 'all'], context)
- end
-
- def pack(*args)
- TkPack.configure(*args)
- end
-
- def grid(*args)
- TkGrid.configure(*args)
- end
-
- def update(idle=nil)
- if idle
- tk_call 'update', 'idletasks'
- else
- tk_call 'update'
- end
- end
-
-end
-
-module TkCore
- include TkComm
- extend TkComm
-
- INTERP = TclTkIp.new
-
- INTERP._invoke("proc", "rb_out", "args", <<-'EOL')
- regsub -all {!} $args {\\!} args
- regsub -all "{" $args "\\{" args
- if {[set st [catch {ruby [format "TkCore.callback %%Q!%s!" $args]} ret]] != 0} {
- return -code $st $ret
- } {
- return $ret
- }
- EOL
-
- def callback_break
- fail TkCallbackBreak, "Tk callback returns 'break' status"
- end
-
- def callback_continue
- fail TkCallbackContinue, "Tk callback returns 'continue' status"
- end
-
- def after(ms, cmd=Proc.new)
- myid = _curr_cmd_id
- cmdid = install_cmd(cmd)
- tk_call("after",ms,cmdid)
-# return
-# if false #defined? Thread
-# Thread.start do
-# ms = Float(ms)/1000
-# ms = 10 if ms == 0
-# sleep ms/1000
-# cmd.call
-# end
-# else
-# cmdid = install_cmd(cmd)
-# tk_call("after",ms,cmdid)
-# end
- end
-
- def after_idle(cmd=Proc.new)
- myid = _curr_cmd_id
- cmdid = install_cmd(cmd)
- tk_call('after','idle',cmdid)
- end
-
- def clock_clicks(ms=nil)
- if ms
- tk_call('clock','clicks','-milliseconds').to_i
- else
- tk_call('clock','clicks').to_i
- end
- end
-
- def clock_format(clk, form=nil)
- if form
- tk_call('clock','format',clk,'-format',form).to_i
- else
- tk_call('clock','format',clk).to_i
- end
- end
-
- def clock_formatGMT(clk, form=nil)
- if form
- tk_call('clock','format',clk,'-format',form,'-gmt','1').to_i
- else
- tk_call('clock','format',clk,'-gmt','1').to_i
- end
- end
-
- def clock_scan(str, base=nil)
- if base
- tk_call('clock','scan',str,'-base',base).to_i
- else
- tk_call('clock','scan',str).to_i
- end
- end
-
- def clock_scanGMT(str, base=nil)
- if base
- tk_call('clock','scan',str,'-base',base,'-gmt','1').to_i
- else
- tk_call('clock','scan',str,'-gmt','1').to_i
- end
- end
-
- def clock_seconds
- tk_call('clock','seconds').to_i
- end
-
- def TkCore.callback(arg)
- arg = Array(tk_split_list(arg))
- _get_eval_string(TkUtil.eval_cmd(Tk_CMDTBL[arg.shift], *arg))
- end
-
- def scaling(scale=nil)
- if scale
- tk_call('tk', 'scaling', scale)
- else
- Float(number(tk_call('tk', 'scaling')))
- end
- end
- def scaling_displayof(win, scale=nil)
- if scale
- tk_call('tk', 'scaling', '-displayof', win, scale)
- else
- Float(number(tk_call('tk', '-displayof', win, 'scaling')))
- end
- end
-
- def appname(name=None)
- tk_call('tk', 'appname', name)
- end
-
- def appsend(interp, async, *args)
- if async
- tk_call('send', '-async', '--', interp, *args)
- else
- tk_call('send', '--', interp, *args)
- end
- end
-
- def rb_appsend(interp, async, *args)
- args = args.collect!{|c| _get_eval_string(c).gsub(/[][$"]/, '\\\\\&')}
- args.push(').to_s"')
- appsend(interp, async, 'ruby "(', *args)
- end
-
- def appsend_displayof(interp, win, async, *args)
- win = '.' if win == nil
- if async
- tk_call('send', '-async', '-displayof', win, '--', interp, *args)
- else
- tk_call('send', '-displayor', win, '--', interp, *args)
- end
- end
-
- def rb_appsend_displayof(interp, win, async, *args)
- args = args.collect!{|c| _get_eval_string(c).gsub(/[][$"]/, '\\\\\&')}
- args.push(').to_s"')
- appsend_displayof(interp, win, async, 'ruby "(', *args)
- end
-
- def info(*args)
- tk_call('info', *args)
- end
-
- def mainloop
- TclTkLib.mainloop
- end
-
- def restart
- TkCore::INTERP.restart
- TkComm::Tk_WINDOWS.clear
- nil
- end
-
- def event_generate(window, context, keys=nil)
- window = window.path if window.kind_of? TkObject
- if keys
- tk_call('event', 'generate', window,
- "<#{tk_event_sequence(context)}>", *hash_kv(keys))
- else
- tk_call('event', 'generate', window, "<#{tk_event_sequence(context)}>")
- end
- end
-
- def messageBox(keys)
- tk_call 'tk_messageBox', *hash_kv(keys)
- end
-
- def getOpenFile(keys = nil)
- tk_call 'tk_getOpenFile', *hash_kv(keys)
- end
-
- def getSaveFile(keys = nil)
- tk_call 'tk_getSaveFile', *hash_kv(keys)
- end
-
- def chooseColor(keys = nil)
- tk_call 'tk_chooseColor', *hash_kv(keys)
- end
-
- def chooseDirectory(keys = nil)
- tk_call 'tk_chooseDirectory', *hash_kv(keys)
- end
-
- def tk_call(*args)
- puts args.inspect if $DEBUG
- args.collect! {|x|ruby2tcl(x)}
- args.compact!
- args.flatten!
- print "=> ", args.join(" ").inspect, "\n" if $DEBUG
- begin
- res = INTERP._invoke(*args)
- rescue NameError
- err = $!
- begin
- args.unshift "unknown"
- res = INTERP._invoke(*args)
- rescue
- fail unless /^invalid command/ =~ $!
- fail err
- end
- end
- if INTERP._return_value() != 0
- fail RuntimeError, res, error_at
- end
- print "==> ", res.inspect, "\n" if $DEBUG
- return res
- end
-end
-
-module TkPackage
- include TkCore
- extend TkPackage
-
- def add_path(path)
- Tk::AUTO_PATH.value = Tk::AUTO_PATH.to_a << path
- end
-
- def forget(package)
- tk_call('package', 'forget', package)
- nil
- end
-
- def names
- tk_split_simplelist(tk_call('package', 'names'))
- end
-
- def provide(package, version=nil)
- if version
- tk_call('package', 'provide', package, version)
- nil
- else
- tk_call('package', 'provide', package)
- end
- end
-
- def present(package, version=None)
- tk_call('package', 'present', package, version)
- end
-
- def present_exact(package, version)
- tk_call('package', 'present', '-exact', package, version)
- end
-
- def require(package, version=None)
- tk_call('package', 'require', package, version)
- end
-
- def require_exact(package, version)
- tk_call('package', 'require', '-exact', package, version)
- end
-
- def versions(package)
- tk_split_simplelist(tk_call('package', 'versions', package))
- end
-
- def vcompare(version1, version2)
- Integer(tk_call('package', 'vcompare', version1, version2))
- end
-
- def vsatisfies(version1, version2)
- bool(tk_call('package', 'vsatisfies', version1, version2))
- end
-end
-
-module Tk
- include TkCore
- extend Tk
-
- TCL_VERSION = INTERP._invoke("info", "tclversion")
- TK_VERSION = INTERP._invoke("set", "tk_version")
-
- TCL_PATCHLEVEL = INTERP._invoke("info", "patchlevel")
- TK_PATCHLEVEL = INTERP._invoke("set", "tk_patchLevel")
-
- TCL_LIBRARY = INTERP._invoke("set", "tcl_library")
- TK_LIBRARY = INTERP._invoke("set", "tk_library")
- LIBRARY = INTERP._invoke("info", "library")
-
- PLATFORM = Hash[*tk_split_simplelist(INTERP._eval('array get tcl_platform'))]
-
- JAPANIZED_TK = (INTERP._invoke("info", "commands", "kanji") != "")
-
- def root
- TkRoot.new
- end
-
- def bell
- tk_call 'bell'
- end
-
- def Tk.focus(display=nil)
- if display == nil
- r = tk_call('focus')
- else
- r = tk_call('focus', '-displayof', display)
- end
- tk_tcl2ruby(r)
- end
-
- def Tk.focus_lastfor(win)
- tk_tcl2ruby(tk_call('focus', '-lastfor', win))
- end
-
- def Tk.strictMotif(bool=None)
- bool(tk_call('set', 'tk_strictMotif', bool))
- end
-
- def Tk.show_kinsoku(mode='both')
- begin
- if /^8\.*/ === TK_VERSION && JAPANIZED_TK
- tk_split_simplelist(tk_call('kinsoku', 'show', mode))
- end
- rescue
- end
- end
- def Tk.add_kinsoku(chars, mode='both')
- begin
- if /^8\.*/ === TK_VERSION && JAPANIZED_TK
- tk_split_simplelist(tk_call('kinsoku', 'add', mode,
- *(chars.split(''))))
- else
- []
- end
- rescue
- []
- end
- end
- def Tk.delete_kinsoku(chars, mode='both')
- begin
- if /^8\.*/ === TK_VERSION && JAPANIZED_TK
- tk_split_simplelist(tk_call('kinsoku', 'delete', mode,
- *(chars.split(''))))
- end
- rescue
- end
- end
-
- def Tk.toUTF8(str,encoding)
- INTERP._toUTF8(str,encoding)
- end
-
- def Tk.fromUTF8(str,encoding)
- INTERP._fromUTF8(str,encoding)
- end
-
- module Scrollable
- def xscrollcommand(cmd=Proc.new)
- configure_cmd 'xscrollcommand', cmd
- end
- def yscrollcommand(cmd=Proc.new)
- configure_cmd 'yscrollcommand', cmd
- end
- def xview(*index)
- v = tk_send('xview', *index)
- list(v) if index.size == 0
- end
- def yview(*index)
- v = tk_send('yview', *index)
- list(v) if index.size == 0
- end
- def xscrollbar(bar=nil)
- if bar
- @xscrollbar = bar
- @xscrollbar.orient 'horizontal'
- self.xscrollcommand {|arg| @xscrollbar.set(*arg)}
- @xscrollbar.command {|arg| self.xview(*arg)}
- end
- @xscrollbar
- end
- def yscrollbar(bar=nil)
- if bar
- @yscrollbar = bar
- @yscrollbar.orient 'vertical'
- self.yscrollcommand {|arg| @yscrollbar.set(*arg)}
- @yscrollbar.command {|arg| self.yview(*arg)}
- end
- @yscrollbar
- end
- end
-
- module Wm
- include TkComm
- def aspect(*args)
- w = tk_call('wm', 'aspect', path, *args)
- list(w) if args.length == 0
- end
- def client(name=None)
- tk_call 'wm', 'client', path, name
- end
- def colormapwindows(*args)
- list(tk_call('wm', 'colormapwindows', path, *args))
- end
- def wm_command(value=None)
- string(tk_call('wm', 'command', path, value))
- end
- def deiconify
- tk_call 'wm', 'deiconify', path
- end
- def focusmodel(*args)
- tk_call 'wm', 'focusmodel', path, *args
- end
- def frame
- tk_call('wm', 'frame', path)
- end
- def geometry(*args)
- tk_call('wm', 'geometry', path, *args)
- end
- def grid(*args)
- w = tk_call('wm', 'grid', path, *args)
- list(w) if args.size == 0
- end
- def group(*args)
- w = tk_call 'wm', 'group', path, *args
- window(w) if args.size == 0
- end
- def iconbitmap(*args)
- tk_call 'wm', 'iconbitmap', path, *args
- end
- def iconify
- tk_call 'wm', 'iconify', path
- end
- def iconmask(*args)
- tk_call 'wm', 'iconmask', path, *args
- end
- def iconname(*args)
- tk_call 'wm', 'iconname', path, *args
- end
- def iconposition(*args)
- w = tk_call('wm', 'iconposition', path, *args)
- list(w) if args.size == 0
- end
- def iconwindow(*args)
- w = tk_call('wm', 'iconwindow', path, *args)
- window(w) if args.size == 0
- end
- def maxsize(*args)
- w = tk_call('wm', 'maxsize', path, *args)
- list(w) if args.size == 0
- end
- def minsize(*args)
- w = tk_call('wm', 'minsize', path, *args)
- list(w) if args.size == 0
- end
- def overrideredirect(bool=None)
- if bool == None
- bool(tk_call('wm', 'overrideredirect', path))
- else
- tk_call 'wm', 'overrideredirect', path, bool
- end
- end
- def positionfrom(*args)
- tk_call 'wm', 'positionfrom', path, *args
- end
- def protocol(name=nil, cmd=nil)
- if cmd
- tk_call('wm', 'protocol', path, name, cmd)
- elsif name
- result = tk_call('wm', 'protocol', path, name)
- (result == "")? nil : tk_tcl2ruby(result)
- else
- tk_split_simplelist(tk_call('wm', 'protocol', path))
- end
- end
- def resizable(*args)
- w = tk_call('wm', 'resizable', path, *args)
- if args.length == 0
- list(w).collect{|e| bool(e)}
- end
- end
- def sizefrom(*args)
- tk_call('wm', 'sizefrom', path, *args)
- end
- def state(state=None)
- tk_call 'wm', 'state', path, state
- end
- def title(*args)
- tk_call 'wm', 'title', path, *args
- end
- def transient(*args)
- window(tk_call 'wm', 'transient', path, *args)
- end
- def withdraw
- tk_call 'wm', 'withdraw', path
- end
- end
-end
-
-###########################################
-# convert kanji string to/from utf-8
-###########################################
-if /^8\.[1-9]/ =~ Tk::TCL_VERSION && !Tk::JAPANIZED_TK
- class TclTkIp
- # from tkencoding.rb by ttate@jaist.ac.jp
- alias __eval _eval
- alias __invoke _invoke
- private :__eval
- private :__invoke
-
- attr_accessor :encoding
-
- def _eval(cmd)
- if @encoding
- _fromUTF8(__eval(_toUTF8(cmd, @encoding)), @encoding)
- else
- __eval(cmd)
- end
- end
-
- def _invoke(*cmds)
- if @encoding
- cmds = cmds.collect{|cmd| _toUTF8(cmd, @encoding)}
- _fromUTF8(__invoke(*cmds), @encoding)
- else
- __invoke(*cmds)
- end
- end
- end
-
- module Tk
- def encoding=(name)
- INTERP.encoding = name
- end
-
- def encoding
- INTERP.encoding
- end
-
- def encoding_names
- tk_split_simplelist(tk_call('encoding', 'names'))
- end
-
- def encoding_system
- tk_call('encoding', 'system')
- end
-
- def encoding_system=(enc)
- tk_call('encoding', 'system', enc)
- end
- end
-
- # estimate encoding
- case $KCODE
- when /^e/i # EUC
- Tk.encoding = 'euc-jp'
- when /^s/i # SJIS
- Tk.encoding = 'shiftjis'
- when /^u/i # UTF8
- Tk.encoding = 'utf-8'
- else # NONE
- begin
- Tk.encoding = Tk.encoding_system
- rescue StandardError, NameError
- Tk.encoding = 'utf-8'
- end
- end
-
-else
- # dummy methods
- module Tk
- def encoding=(name)
- nil
- end
- def encoding
- nil
- end
- def encoding_names
- nil
- end
- def encoding_system
- nil
- end
- def encoding_system=(enc)
- nil
- end
- end
-end
-
-module TkBindCore
- def bind(context, cmd=Proc.new, args=nil)
- Tk.bind(to_eval, context, cmd, args)
- end
-
- def bind_append(context, cmd=Proc.new, args=nil)
- Tk.bind_append(to_eval, context, cmd, args)
- end
-
- def bind_remove(context)
- Tk.bind_remove(to_eval, context)
- end
-
- def bindinfo(context=nil)
- Tk.bindinfo(to_eval, context)
- end
-end
-
-class TkBindTag
- include TkBindCore
-
- BTagID_TBL = {}
- Tk_BINDTAG_ID = ["btag00000"]
-
- def TkBindTag.id2obj(id)
- BTagID_TBL[id]? BTagID_TBL[id]: id
- end
-
- ALL = self.new
- ALL.instance_eval {
- @id = 'all'
- BTagID_TBL[@id] = self
- }
-
- def initialize(*args)
- @id = Tk_BINDTAG_ID[0]
- Tk_BINDTAG_ID[0] = Tk_BINDTAG_ID[0].succ
- BTagID_TBL[@id] = self
- bind(*args) if args != []
- end
-
- def to_eval
- @id
- end
-
- def inspect
- format "#<TkBindTag: %s>", @id
- end
-end
-
-class TkBindTagAll<TkBindTag
- def TkBindTagAll.new(*args)
- $stderr.puts "Warning: TkBindTagALL is obsolete. Use TkBindTag::ALL\n"
-
- TkBindTag::ALL.bind(*args) if args != []
- TkBindTag::ALL
- end
-end
-
-class TkVariable
- include Tk
- extend TkCore
-
- TkVar_CB_TBL = {}
- Tk_VARIABLE_ID = ["v00000"]
-
- INTERP._invoke("proc", "rb_var", "args", "ruby [format \"TkVariable.callback %%Q!%s!\" $args]")
-
- def TkVariable.callback(args)
- name1,name2,op = tk_split_list(args)
- if TkVar_CB_TBL[name1]
- _get_eval_string(TkVar_CB_TBL[name1].trace_callback(name2,op))
- else
- ''
- end
- end
-
- def initialize(val="")
- @id = Tk_VARIABLE_ID[0]
- Tk_VARIABLE_ID[0] = Tk_VARIABLE_ID[0].succ
- if val == []
- INTERP._eval(format('global %s; set %s(0) 0; unset %s(0)',
- @id, @id, @id))
- elsif val.kind_of?(Array)
- a = []
- val.each_with_index{|e,i| a.push(i); a.push(array2tk_list(e))}
- s = '"' + a.join(" ").gsub(/[][$"]/, '\\\\\&') + '"'
- INTERP._eval(format('global %s; array set %s %s', @id, @id, s))
- elsif val.kind_of?(Hash)
- s = '"' + val.to_a.collect{|e| array2tk_list(e)}.join(" ")\
- .gsub(/[][$"]/, '\\\\\&') + '"'
- INTERP._eval(format('global %s; array set %s %s', @id, @id, s))
- else
- s = '"' + _get_eval_string(val).gsub(/[][$"]/, '\\\\\&') + '"'
- INTERP._eval(format('global %s; set %s %s', @id, @id, s))
- end
- end
-
- def wait
- INTERP._eval("tkwait variable #{@id}")
- end
-
- def id
- @id
- end
-
- def value
- begin
- INTERP._eval(format('global %s; set %s', @id, @id))
- rescue
- if INTERP._eval(format('global %s; array exists %s', @id, @id)) != "1"
- fail
- else
- Hash[*tk_split_simplelist(INTERP._eval(format('global %s; array get %s',
- @id, @id)))]
- end
- end
- end
-
- def value=(val)
- begin
- s = '"' + _get_eval_string(val).gsub(/[][$"]/, '\\\\\&') + '"'
- INTERP._eval(format('global %s; set %s %s', @id, @id, s))
- rescue
- if INTERP._eval(format('global %s; array exists %s', @id, @id)) != "1"
- fail
- else
- if val == []
- INTERP._eval(format('global %s; unset %s; set %s(0) 0; unset %s(0)',
- @id, @id, @id, @id))
- elsif val.kind_of?(Array)
- a = []
- val.each_with_index{|e,i| a.push(i); a.push(array2tk_list(e))}
- s = '"' + a.join(" ").gsub(/[][$"]/, '\\\\\&') + '"'
- INTERP._eval(format('global %s; unset %s; array set %s %s',
- @id, @id, @id, s))
- elsif val.kind_of?(Hash)
- s = '"' + val.to_a.collect{|e| array2tk_list(e)}.join(" ")\
- .gsub(/[][$"]/, '\\\\\&') + '"'
- INTERP._eval(format('global %s; unset %s; array set %s %s',
- @id, @id, @id, s))
- else
- fail
- end
- end
- end
- end
-
- def [](index)
- INTERP._eval(format('global %s; set %s(%s)',
- @id, @id, _get_eval_string(index)))
- end
-
- def []=(index,val)
- INTERP._eval(format('global %s; set %s(%s) %s', @id, @id,
- _get_eval_string(index), _get_eval_string(val)))
- end
-
- def to_i
- number(value).to_i
- end
-
- def to_f
- number(value).to_f
- end
-
- def to_s
- string(value).to_s
- end
-
- def inspect
- format "#<TkVariable: %s>", @id
- end
-
- def ==(other)
- case other
- when TkVariable
- self.equal(self)
- when String
- self.to_s == other
- when Integer
- self.to_i == other
- when Float
- self.to_f == other
- when Array
- self.to_a == other
- else
- false
- end
- end
-
- def to_a
- list(value)
- end
-
- def to_eval
- @id
- end
-
- def unset(elem=nil)
- if elem
- INTERP._eval(format('global %s; unset %s(%s)',
- @id, @id, tk_tcl2ruby(elem)))
- else
- INTERP._eval(format('global %s; unset %s', @id, @id))
- end
- end
- alias remove unset
-
- def trace_callback(elem, op)
- if @trace_var.kind_of? Array
- @trace_var.each{|m,e| e.call(self,elem,op) if m.index(op)}
- end
- if elem.kind_of? String
- if @trace_elem[elem].kind_of? Array
- @trace_elem[elem].each{|m,e| e.call(self,elem,op) if m.index(op)}
- end
- end
- end
-
- def trace(opts, cmd)
- @trace_var = [] if @trace_var == nil
- opts = ['r','w','u'].find_all{|c| opts.index(c)}.join('')
- @trace_var.unshift([opts,cmd])
- if @trace_opts == nil
- TkVar_CB_TBL[@id] = self
- @trace_opts = opts
- Tk.tk_call('trace', 'variable', @id, @trace_opts, 'rb_var')
- else
- newopts = @trace_opts.dup
- opts.each_byte{|c| newopts += c.chr unless newopts.index(c)}
- if newopts != @trace_opts
- Tk.tk_call('trace', 'vdelete', @id, @trace_opts, 'rb_var')
- @trace_opts.replace(newopts)
- Tk.tk_call('trace', 'variable', @id, @trace_opts, 'rb_var')
- end
- end
- end
-
- def trace_element(elem, opts, cmd)
- @trace_elem = {} if @trace_elem == nil
- @trace_elem[elem] = [] if @trace_elem[elem] == nil
- opts = ['r','w','u'].find_all{|c| opts.index(c)}.join('')
- @trace_elem[elem].unshift([opts,cmd])
- if @trace_opts == nil
- TkVar_CB_TBL[@id] = self
- @trace_opts = opts
- Tk.tk_call('trace', 'variable', @id, @trace_opts, 'rb_var')
- else
- newopts = @trace_opts.dup
- opts.each_byte{|c| newopts += c.chr unless newopts.index(c)}
- if newopts != @trace_opts
- Tk.tk_call('trace', 'vdelete', @id, @trace_opts, 'rb_var')
- @trace_opts.replace(newopts)
- Tk.tk_call('trace', 'variable', @id, @trace_opts, 'rb_var')
- end
- end
- end
-
- def trace_vinfo
- return [] unless @trace_var
- @trace_var.dup
- end
- def trace_vinfo_for_element(elem)
- return [] unless @trace_elem
- return [] unless @trace_elem[elem]
- @trace_elem[elem].dup
- end
-
- def trace_vdelete(opts,cmd)
- return unless @trace_var.kind_of? Array
- opts = ['r','w','u'].find_all{|c| opts.index(c)}.join('')
- idx = -1
- newopts = ''
- @trace_var.each_with_index{|e,i|
- if idx < 0 && e[0] == opts && e[1] == cmd
- idx = i
- next
- end
- e[0].each_byte{|c| newopts += c.chr unless newopts.index(c)}
- }
- if idx >= 0
- @trace_var.delete_at(idx)
- else
- return
- end
-
- @trace_elem.each{|elem|
- @trace_elem[elem].each{|e|
- e[0].each_byte{|c| newopts += c.chr unless newopts.index(c)}
- }
- }
-
- newopts = ['r','w','u'].find_all{|c| newopts.index(c)}.join('')
- if newopts != @trace_opts
- Tk.tk_call('trace', 'vdelete', @id, @trace_opts, 'rb_var')
- @trace_opts.replace(newopts)
- if @trace_opts != ''
- Tk.tk_call('trace', 'variable', @id, @trace_opts, 'rb_var')
- end
- end
- end
-
- def trace_vdelete_for_element(elem,opts,cmd)
- return unless @trace_elem.kind_of? Hash
- return unless @trace_elem[elem].kind_of? Array
- opts = ['r','w','u'].find_all{|c| opts.index(c)}.join('')
- idx = -1
- @trace_elem[elem].each_with_index{|e,i|
- if idx < 0 && e[0] == opts && e[1] == cmd
- idx = i
- next
- end
- }
- if idx >= 0
- @trace_elem[elem].delete_at(idx)
- else
- return
- end
-
- newopts = ''
- @trace_var.each{|e|
- e[0].each_byte{|c| newopts += c.chr unless newopts.index(c)}
- }
- @trace_elem.each{|elem|
- @trace_elem[elem].each{|e|
- e[0].each_byte{|c| newopts += c.chr unless newopts.index(c)}
- }
- }
-
- newopts = ['r','w','u'].find_all{|c| newopts.index(c)}.join('')
- if newopts != @trace_opts
- Tk.tk_call('trace', 'vdelete', @id, @trace_opts, 'rb_var')
- @trace_opts.replace(newopts)
- if @trace_opts != ''
- Tk.tk_call('trace', 'variable', @id, @trace_opts, 'rb_var')
- end
- end
- end
-end
-
-class TkVarAccess<TkVariable
- def initialize(varname, val=nil)
- @id = varname
- if val
- s = '"' + _get_eval_string(val).gsub(/[][$"]/, '\\\\\&') + '"' #"
- INTERP._eval(format('global %s; set %s %s', @id, @id, s))
- end
- end
-end
-
-module Tk
- begin
- auto_path = INTERP._invoke('set', 'auto_path')
- rescue
- begin
- auto_path = INTERP._invoke('set', 'env(TCLLIBPATH)')
- rescue
- auto_path = Tk::LIBRARY
- end
- end
- AUTO_PATH = TkVarAccess.new('auto_path', auto_path)
-
- TCL_PACKAGE_PATH = TkVarAccess.new('tcl_pkgPath')
-end
-
-module TkSelection
- include Tk
- extend Tk
- def clear(win=Tk.root)
- tk_call 'selection', 'clear', win.path
- end
- def get(type=None)
- tk_call 'selection', 'get', type
- end
- def TkSelection.handle(win, func, type=None, format=None)
- tk_call 'selection', 'handle', win.path, func, type, format
- end
- def handle(func, type=None, format=None)
- TkSelection.handle self, func, type, format
- end
- def TkSelection.own(win=None, func=None)
- window(tk_call 'selection', 'own', win, func)
- end
- def own(func=None)
- TkSelection.own self, func
- end
-
- module_function :clear, :get
-end
-
-module TkKinput
- include Tk
- extend Tk
-
- def TkKinput.start(window, style=None)
- tk_call 'kinput_start', window.path, style
- end
- def kinput_start(style=None)
- TkKinput.start(self, style)
- end
-
- def TkKinput.send_spot(window)
- tk_call 'kinput_send_spot', window.path
- end
- def kinput_send_spot
- TkKinput.send_spot(self)
- end
-
- def TkKinput.input_start(window, keys=nil)
- tk_call 'kanjiInput', 'start', window.path, *hash_kv(keys)
- end
- def kanji_input_start(keys=nil)
- TkKinput.input_start(self, keys)
- end
-
- def TkKinput.attribute_config(window, slot, value=None)
- if slot.kind_of? Hash
- tk_call 'kanjiInput', 'attribute', window.path, *hash_kv(slot)
- else
- tk_call 'kanjiInput', 'attribute', window.path, "-#{slot}", value
- end
- end
- def kinput_attribute_config(slot, value=None)
- TkKinput.attribute_config(self, slot, value)
- end
-
- def TkKinput.attribute_info(window, slot=nil)
- if slot
- conf = tk_split_list(tk_call('kanjiInput', 'attribute',
- window.path, "-#{slot}"))
- conf[0] = conf[0][1..-1]
- conf
- else
- tk_split_list(tk_call('kanjiInput', 'attribute',
- window.path)).collect{|conf|
- conf[0] = conf[0][1..-1]
- conf
- }
- end
- end
- def kinput_attribute_info(slot=nil)
- TkKinput.attribute_info(self, slot)
- end
-
- def TkKinput.input_end(window)
- tk_call 'kanjiInput', 'end', window.path
- end
- def kanji_input_end
- TkKinput.input_end(self)
- end
-end
-
-module TkXIM
- include Tk
- extend Tk
-
- def TkXIM.useinputmethods(window=nil, value=nil)
- if window
- if value
- tk_call 'tk', 'useinputmethods', '-displayof', window.path, value
- else
- tk_call 'tk', 'useinputmethods', '-displayof', window.path
- end
- else
- if value
- tk_call 'tk', 'useinputmethods', value
- else
- tk_call 'tk', 'useinputmethods'
- end
- end
- end
-
- def TkXIM.configure(window, slot, value=None)
- begin
- if /^8\.*/ === Tk::TK_VERSION && JAPANIZED_TK
- if slot.kind_of? Hash
- tk_call 'imconfigure', window.path, *hash_kv(slot)
- else
- tk_call 'imconfigure', window.path, "-#{slot}", value
- end
- end
- rescue
- end
- end
-
- def TkXIM.configinfo(window, slot=nil)
- begin
- if /^8\.*/ === Tk::TK_VERSION && JAPANIZED_TK
- if slot
- conf = tk_split_list(tk_call('imconfigure', window.path, "-#{slot}"))
- conf[0] = conf[0][1..-1]
- conf
- else
- tk_split_list(tk_call('imconfigure', window.path)).collect{|conf|
- conf[0] = conf[0][1..-1]
- conf
- }
- end
- else
- []
- end
- rescue
- []
- end
- end
-
- def useinputmethods(value=nil)
- TkXIM.useinputmethods(self, value)
- end
-
- def imconfigure(window, slot, value=None)
- TkXIM.configinfo(window, slot, value)
- end
-
- def imconfiginfo(slot=nil)
- TkXIM.configinfo(window, slot)
- end
-end
-
-module TkWinfo
- include Tk
- extend Tk
- def TkWinfo.atom(name)
- number(tk_call 'winfo', 'atom', name)
- end
- def winfo_atom(name)
- TkWinfo.atom name
- end
- def TkWinfo.atomname(id)
- tk_call 'winfo', 'atomname', id
- end
- def winfo_atomname(id)
- TkWinfo.atomname id
- end
- def TkWinfo.cells(window)
- number(tk_call('winfo', 'cells', window.path))
- end
- def winfo_cells
- TkWinfo.cells self
- end
- def TkWinfo.children(window)
- c = tk_call('winfo', 'children', window.path)
- list(c)
- end
- def winfo_children
- TkWinfo.children self
- end
- def TkWinfo.classname(window)
- tk_call 'winfo', 'class', window.path
- end
- def winfo_classname
- TkWinfo.classname self
- end
- def TkWinfo.colormapfull(window)
- bool(tk_call('winfo', 'colormapfull', window.path))
- end
- def winfo_colormapfull
- TkWinfo.colormapfull self
- end
- def TkWinfo.containing(rootX, rootY)
- path = tk_call('winfo', 'containing', rootX, rootY)
- window(path)
- end
- def winfo_containing(x, y)
- TkWinfo.containing x, y
- end
- def TkWinfo.depth(window)
- number(tk_call('winfo', 'depth', window.path))
- end
- def winfo_depth
- TkWinfo.depth self
- end
- def TkWinfo.exist?(window)
- bool(tk_call('winfo', 'exists', window.path))
- end
- def winfo_exist?
- TkWinfo.exist? self
- end
- def TkWinfo.fpixels(window, number)
- number(tk_call('winfo', 'fpixels', window.path, number))
- end
- def winfo_fpixels(number)
- TkWinfo.fpixels self, number
- end
- def TkWinfo.geometry(window)
- tk_call('winfo', 'geometry', window.path)
- end
- def winfo_geometry
- TkWinfo.geometry self
- end
- def TkWinfo.height(window)
- number(tk_call('winfo', 'height', window.path))
- end
- def winfo_height
- TkWinfo.height self
- end
- def TkWinfo.id(window)
- tk_call('winfo', 'id', window.path)
- end
- def winfo_id
- TkWinfo.id self
- end
- def TkWinfo.interps(window=nil)
- if window
- tk_split_simplelist(tk_call('winfo', 'interps',
- '-displayof', window.path))
- else
- tk_split_simplelist(tk_call('winfo', 'interps'))
- end
- end
- def winfo_interps
- TkWinfo.interps self
- end
- def TkWinfo.mapped?(window)
- bool(tk_call('winfo', 'ismapped', window.path))
- end
- def winfo_mapped?
- TkWinfo.mapped? self
- end
- def TkWinfo.manager(window)
- tk_call('winfo', 'manager', window.path)
- end
- def winfo_manager
- TkWinfo.manager self
- end
- def TkWinfo.appname(window)
- tk_call('winfo', 'name', window.path)
- end
- def winfo_appname
- TkWinfo.appname self
- end
- def TkWinfo.parent(window)
- window(tk_call('winfo', 'parent', window.path))
- end
- def winfo_parent
- TkWinfo.parent self
- end
- def TkWinfo.widget(id)
- window(tk_call('winfo', 'pathname', id))
- end
- def winfo_widget(id)
- TkWinfo.widget id
- end
- def TkWinfo.pixels(window, number)
- number(tk_call('winfo', 'pixels', window.path, number))
- end
- def winfo_pixels(number)
- TkWinfo.pixels self, number
- end
- def TkWinfo.reqheight(window)
- number(tk_call('winfo', 'reqheight', window.path))
- end
- def winfo_reqheight
- TkWinfo.reqheight self
- end
- def TkWinfo.reqwidth(window)
- number(tk_call('winfo', 'reqwidth', window.path))
- end
- def winfo_reqwidth
- TkWinfo.reqwidth self
- end
- def TkWinfo.rgb(window, color)
- list(tk_call('winfo', 'rgb', window.path, color))
- end
- def winfo_rgb(color)
- TkWinfo.rgb self, color
- end
- def TkWinfo.rootx(window)
- number(tk_call('winfo', 'rootx', window.path))
- end
- def winfo_rootx
- TkWinfo.rootx self
- end
- def TkWinfo.rooty(window)
- number(tk_call('winfo', 'rooty', window.path))
- end
- def winfo_rooty
- TkWinfo.rooty self
- end
- def TkWinfo.screen(window)
- tk_call 'winfo', 'screen', window.path
- end
- def winfo_screen
- TkWinfo.screen self
- end
- def TkWinfo.screencells(window)
- number(tk_call('winfo', 'screencells', window.path))
- end
- def winfo_screencells
- TkWinfo.screencells self
- end
- def TkWinfo.screendepth(window)
- number(tk_call('winfo', 'screendepth', window.path))
- end
- def winfo_screendepth
- TkWinfo.screendepth self
- end
- def TkWinfo.screenheight (window)
- number(tk_call('winfo', 'screenheight', window.path))
- end
- def winfo_screenheight
- TkWinfo.screenheight self
- end
- def TkWinfo.screenmmheight(window)
- number(tk_call('winfo', 'screenmmheight', window.path))
- end
- def winfo_screenmmheight
- TkWinfo.screenmmheight self
- end
- def TkWinfo.screenmmwidth(window)
- number(tk_call('winfo', 'screenmmwidth', window.path))
- end
- def winfo_screenmmwidth
- TkWinfo.screenmmwidth self
- end
- def TkWinfo.screenvisual(window)
- tk_call 'winfo', 'screenvisual', window.path
- end
- def winfo_screenvisual
- TkWinfo.screenvisual self
- end
- def TkWinfo.screenwidth(window)
- number(tk_call('winfo', 'screenwidth', window.path))
- end
- def winfo_screenwidth
- TkWinfo.screenwidth self
- end
- def TkWinfo.server(window)
- tk_call 'winfo', 'server', window.path
- end
- def winfo_server
- TkWinfo.server self
- end
- def TkWinfo.toplevel(window)
- window(tk_call('winfo', 'toplevel', window.path))
- end
- def winfo_toplevel
- TkWinfo.toplevel self
- end
- def TkWinfo.visual(window)
- tk_call 'winfo', 'visual', window.path
- end
- def winfo_visual
- TkWinfo.visual self
- end
- def TkWinfo.visualid(window)
- tk_call 'winfo', 'visualid', window.path
- end
- def winfo_visualid
- TkWinfo.visualid self
- end
- def TkWinfo.visualsavailable(window, includeids=false)
- if includeids
- v = tk_call('winfo', 'visualsavailable', window.path, "includeids")
- else
- v = tk_call('winfo', 'visualsavailable', window.path)
- end
- list(v)
- end
- def winfo_visualsavailable(includeids=false)
- TkWinfo.visualsavailable self, includeids
- end
- def TkWinfo.vrootheight(window)
- number(tk_call('winfo', 'vrootheight', window.path))
- end
- def winfo_vrootheight
- TkWinfo.vrootheight self
- end
- def TkWinfo.vrootwidth(window)
- number(tk_call('winfo', 'vrootwidth', window.path))
- end
- def winfo_vrootwidth
- TkWinfo.vrootwidth self
- end
- def TkWinfo.vrootx(window)
- number(tk_call('winfo', 'vrootx', window.path))
- end
- def winfo_vrootx
- TkWinfo.vrootx self
- end
- def TkWinfo.vrooty(window)
- number(tk_call('winfo', 'vrooty', window.path))
- end
- def winfo_vrooty
- TkWinfo.vrooty self
- end
- def TkWinfo.width(window)
- number(tk_call('winfo', 'width', window.path))
- end
- def winfo_width
- TkWinfo.width self
- end
- def TkWinfo.x(window)
- number(tk_call('winfo', 'x', window.path))
- end
- def winfo_x
- TkWinfo.x self
- end
- def TkWinfo.y(window)
- number(tk_call('winfo', 'y', window.path))
- end
- def winfo_y
- TkWinfo.y self
- end
- def TkWinfo.viewable(window)
- bool(tk_call 'winfo', 'viewable', window.path)
- end
- def winfo_viewable
- TkWinfo.viewable self
- end
- def TkWinfo.pointerx(window)
- number(tk_call('winfo', 'pointerx', window.path))
- end
- def winfo_pointerx
- TkWinfo.pointerx self
- end
- def TkWinfo.pointery(window)
- number(tk_call('winfo', 'pointery', window.path))
- end
- def winfo_pointery
- TkWinfo.pointery self
- end
- def TkWinfo.pointerxy(window)
- list(tk_call('winfo', 'pointerxy', window.path))
- end
- def winfo_pointerxy
- TkWinfo.pointerxy self
- end
-end
-
-module TkPack
- include Tk
- extend Tk
- def configure(win, *args)
- if args[-1].kind_of?(Hash)
- keys = args.pop
- end
- wins = [win.epath]
- for i in args
- wins.push i.epath
- end
- tk_call "pack", 'configure', *(wins+hash_kv(keys))
- end
-
- def forget(*args)
- tk_call 'pack', 'forget' *args
- end
-
- def info(slave)
- ilist = list(tk_call('pack', 'info', slave.epath))
- info = {}
- while key = ilist.shift
- info[key[1..-1]] = ilist.shift
- end
- return info
- end
-
- def propagate(master, bool=None)
- if bool == None
- bool(tk_call('pack', 'propagate', master.epath))
- else
- tk_call('pack', 'propagate', master.epath, bool)
- end
- end
-
- def slaves(master)
- list(tk_call('pack', 'slaves', master.epath))
- end
-
- module_function :configure, :forget, :info, :propagate, :slaves
-end
-
-module TkGrid
- include Tk
- extend Tk
-
- def bbox(*args)
- list(tk_call('grid', 'bbox', *args))
- end
-
- def configure(widget, *args)
- if args[-1].kind_of?(Hash)
- keys = args.pop
- end
- wins = [widget.epath]
- for i in args
- wins.push i.epath
- end
- tk_call "grid", 'configure', *(wins+hash_kv(keys))
- end
-
- def columnconfigure(master, index, args)
- tk_call "grid", 'columnconfigure', master, index, *hash_kv(args)
- end
-
- def rowconfigure(master, index, args)
- tk_call "grid", 'rowconfigure', master, index, *hash_kv(args)
- end
-
- def columnconfiginfo(master, index, slot=nil)
- if slot
- tk_call 'grid', 'columnconfigure', master, index, "-#{slot}"
- else
- ilist = list(tk_call('grid', 'columnconfigure', master, index))
- info = {}
- while key = ilist.shift
- info[key[1..-1]] = ilist.shift
- end
- info
- end
- end
-
- def rowconfiginfo(master, index, slot=nil)
- if slot
- tk_call 'grid', 'rowconfigure', master, index, "-#{slot}"
- else
- ilist = list(tk_call('grid', 'rowconfigure', master, index))
- info = {}
- while key = ilist.shift
- info[key[1..-1]] = ilist.shift
- end
- info
- end
- end
-
- def add(widget, *args)
- configure(widget, *args)
- end
-
- def forget(*args)
- tk_call 'grid', 'forget', *args
- end
-
- def info(slave)
- list(tk_call('grid', 'info', slave))
- end
-
- def location(master, x, y)
- list(tk_call('grid', 'location', master, x, y))
- end
-
- def propagate(master, bool=None)
- if bool == None
- bool(tk_call('grid', 'propagate', master.epath))
- else
- tk_call('grid', 'propagate', master.epath, bool)
- end
- end
-
- def remove(*args)
- tk_call 'grid', 'remove', *args
- end
-
- def size(master)
- tk_call 'grid', 'size', master
- end
-
- def slaves(master, args)
- list(tk_call('grid', 'slaves', master, *hash_kv(args)))
- end
-
- module_function :bbox, :forget, :propagate, :info
- module_function :remove, :size, :slaves, :location
- module_function :configure, :columnconfigure, :rowconfigure
- module_function :columnconfiginfo, :rowconfiginfo
-end
-
-module TkPlace
- include Tk
- extend Tk
-
- def configure(win, slot, value=None)
- if slot.kind_of? Hash
- tk_call 'place', 'configure', win.epath, *hash_kv(slot)
- else
- tk_call 'place', 'configure', win.epath, "-#{slot}", value
- end
- end
-
- def configinfo(win, slot = nil)
- # for >= Tk8.4a2 ?
- if slot
- conf = tk_split_list(tk_call('place', 'configure',
- win.epath, "-#{slot}") )
- conf[0] = conf[0][1..-1]
- conf
- else
- tk_split_simplelist(tk_call('place', 'configure',
- win.epath)).collect{|conflist|
- conf = tk_split_simplelist(conflist)
- conf[0] = conf[0][1..-1]
- conf
- }
- end
- end
-
- def forget(win)
- tk_call 'place', 'forget', win
- end
-
- def info(win)
- ilist = list(tk_call('place', 'info', win.epath))
- info = {}
- while key = ilist.shift
- info[key[1..-1]] = ilist.shift
- end
- return info
- end
-
- def slaves(master)
- list(tk_call('place', 'slaves', master.epath))
- end
-
- module_function :configure, :configinfo, :forget, :info, :slaves
-end
-
-module TkOption
- include Tk
- extend Tk
- def add pat, value, pri=None
- tk_call 'option', 'add', pat, value, pri
- end
- def clear
- tk_call 'option', 'clear'
- end
- def get win, name, klass
- tk_call 'option', 'get', win ,name, klass
- end
- def readfile file, pri=None
- tk_call 'option', 'readfile', file, pri
- end
- module_function :add, :clear, :get, :readfile
-end
-
-module TkTreatFont
- def font_configinfo
- ret = TkFont.used_on(self.path)
- if ret == nil
- ret = TkFont.init_widget_font(self.path, self.path, 'configure')
- end
- ret
- end
- alias fontobj font_configinfo
-
- def font_configure(slot)
- if (fnt = slot.delete('font'))
- if fnt.kind_of? TkFont
- return fnt.call_font_configure(self.path, self.path,'configure',slot)
- else
- latinfont_configure(fnt) if fnt
- end
- end
- if (ltn = slot.delete('latinfont'))
- latinfont_configure(ltn) if ltn
- end
- if (ltn = slot.delete('asciifont'))
- latinfont_configure(ltn) if ltn
- end
- if (knj = slot.delete('kanjifont'))
- kanjifont_configure(knj) if knj
- end
-
- tk_call(self.path, 'configure', *hash_kv(slot)) if slot != {}
- self
- end
-
- def latinfont_configure(ltn, keys=nil)
- fobj = fontobj
- if ltn.kind_of? TkFont
- conf = {}
- ltn.latin_configinfo.each{|key,val| conf[key] = val}
- if keys
- fobj.latin_configure(conf.update(keys))
- else
- fobj.latin_configure(conf)
- end
- else
- fobj.latin_replace(ltn)
- end
- end
- alias asciifont_configure latinfont_configure
-
- def kanjifont_configure(knj, keys=nil)
- fobj = fontobj
- if knj.kind_of? TkFont
- conf = {}
- knj.kanji_configinfo.each{|key,val| conf[key] = val}
- if keys
- fobj.kanji_configure(conf.update(keys))
- else
- fobj.kanji_configure(cond)
- end
- else
- fobj.kanji_replace(knj)
- end
- end
-
- def font_copy(window, tag=nil)
- if tag
- window.tagfontobj(tag).configinfo.each{|key,value|
- fontobj.configure(key,value)
- }
- fontobj.replace(window.tagfontobj(tag).latin_font,
- window.tagfontobj(tag).kanji_font)
- else
- window.fontobj.configinfo.each{|key,value|
- fontobj.configure(key,value)
- }
- fontobj.replace(window.fontobj.latin_font, window.fontobj.kanji_font)
- end
- end
-
- def latinfont_copy(window, tag=nil)
- if tag
- fontobj.latin_replace(window.tagfontobj(tag).latin_font)
- else
- fontobj.latin_replace(window.fontobj.latin_font)
- end
- end
- alias asciifont_copy latinfont_copy
-
- def kanjifont_copy(window, tag=nil)
- if tag
- fontobj.kanji_replace(window.tagfontobj(tag).kanji_font)
- else
- fontobj.kanji_replace(window.fontobj.kanji_font)
- end
- end
-end
-
-module TkTreatItemFont
- def __conf_cmd(idx)
- raise NotImplementError, "need to define `__conf_cmd'"
- end
- def __item_pathname(tagOrId)
- raise NotImplementError, "need to define `__item_pathname'"
- end
- private :__conf_cmd, :__item_pathname
-
- def tagfont_configinfo(tagOrId)
- pathname = __item_pathname(tagOrId)
- ret = TkFont.used_on(pathname)
- if ret == nil
- ret = TkFont.init_widget_font(pathname, self.path,
- __conf_cmd(0), __conf_cmd(1), tagOrId)
- end
- ret
- end
- alias tagfontobj tagfont_configinfo
-
- def tagfont_configure(tagOrId, slot)
- pathname = __item_pathname(tagOrId)
- if (fnt = slot.delete('font'))
- if fnt.kind_of? TkFont
- return fnt.call_font_configure(pathname, self.path,
- __conf_cmd(0), __conf_cmd(1),
- tagOrId, slot)
- else
- latintagfont_configure(tagOrId, fnt) if fnt
- end
- end
- if (ltn = slot.delete('latinfont'))
- latintagfont_configure(tagOrId, ltn) if ltn
- end
- if (ltn = slot.delete('asciifont'))
- latintagfont_configure(tagOrId, ltn) if ltn
- end
- if (knj = slot.delete('kanjifont'))
- kanjitagfont_configure(tagOrId, knj) if knj
- end
-
- tk_call(self.path, __conf_cmd(0), __conf_cmd(1),
- tagOrId, *hash_kv(slot)) if slot != {}
- self
- end
-
- def latintagfont_configure(tagOrId, ltn, keys=nil)
- fobj = tagfontobj(tagOrId)
- if ltn.kind_of? TkFont
- conf = {}
- ltn.latin_configinfo.each{|key,val| conf[key] = val if val != []}
- if conf == {}
- fobj.latin_replace(ltn)
- fobj.latin_configure(keys) if keys
- elsif keys
- fobj.latin_configure(conf.update(keys))
- else
- fobj.latin_configure(conf)
- end
- else
- fobj.latin_replace(ltn)
- end
- end
- alias asciitagfont_configure latintagfont_configure
-
- def kanjitagfont_configure(tagOrId, knj, keys=nil)
- fobj = tagfontobj(tagOrId)
- if knj.kind_of? TkFont
- conf = {}
- knj.kanji_configinfo.each{|key,val| conf[key] = val if val != []}
- if conf == {}
- fobj.kanji_replace(knj)
- fobj.kanji_configure(keys) if keys
- elsif keys
- fobj.kanji_configure(conf.update(keys))
- else
- fobj.kanji_configure(conf)
- end
- else
- fobj.kanji_replace(knj)
- end
- end
-
- def tagfont_copy(tagOrId, window, wintag=nil)
- if wintag
- window.tagfontobj(wintag).configinfo.each{|key,value|
- tagfontobj(tagOrId).configure(key,value)
- }
- tagfontobj(tagOrId).replace(window.tagfontobj(wintag).latin_font,
- window.tagfontobj(wintag).kanji_font)
- else
- window.tagfont(wintag).configinfo.each{|key,value|
- tagfontobj(tagOrId).configure(key,value)
- }
- tagfontobj(tagOrId).replace(window.fontobj.latin_font,
- window.fontobj.kanji_font)
- end
- end
-
- def latintagfont_copy(tagOrId, window, wintag=nil)
- if wintag
- tagfontobj(tagOrId).latin_replace(window.tagfontobj(wintag).latin_font)
- else
- tagfontobj(tagOrId).latin_replace(window.fontobj.latin_font)
- end
- end
- alias asciitagfont_copy latintagfont_copy
-
- def kanjitagfont_copy(tagOrId, window, wintag=nil)
- if wintag
- tagfontobj(tagOrId).kanji_replace(window.tagfontobj(wintag).kanji_font)
- else
- tagfontobj(tagOrId).kanji_replace(window.fontobj.kanji_font)
- end
- end
-end
-
-class TkObject<TkKernel
- include Tk
- include TkTreatFont
- include TkBindCore
-
- def path
- return @path
- end
-
- def epath
- return @path
- end
-
- def to_eval
- @path
- end
-
- def tk_send(cmd, *rest)
- tk_call path, cmd, *rest
- end
- private :tk_send
-
- def method_missing(id, *args)
- name = id.id2name
- case args.length
- when 1
- configure name, args[0]
- when 0
- begin
- cget name
- rescue
- fail NameError, "undefined local variable or method `#{name}' for #{self.to_s}", error_at
- end
- else
- fail NameError, "undefined method `#{name}' for #{self.to_s}", error_at
- end
- end
-
- def [](id)
- cget id
- end
-
- def []=(id, val)
- configure id, val
- end
-
- def cget(slot)
- case slot
- when 'text', 'label', 'show', 'data', 'file'
- tk_call path, 'cget', "-#{slot}"
- else
- tk_tcl2ruby tk_call path, 'cget', "-#{slot}"
- end
- end
-
- def configure(slot, value=None)
- if slot.kind_of? Hash
- if (slot['font'] || slot['kanjifont'] ||
- slot['latinfont'] || slot['asciifont'] )
- font_configure(slot.dup)
- else
- tk_call path, 'configure', *hash_kv(slot)
- end
-
- else
- if (slot == 'font' || slot == 'kanjifont' ||
- slot == 'latinfont' || slot == 'asciifont')
- if value == None
- fontobj
- else
- font_configure({slot=>value})
- end
- else
- tk_call path, 'configure', "-#{slot}", value
- end
- end
- end
-
- def configure_cmd(slot, value)
- configure slot, install_cmd(value)
- end
-
- def configinfo(slot = nil)
- if slot == 'font' || slot == 'kanjifont'
- fontobj
- else
- if slot
- case slot
- when 'text', 'label', 'show', 'data', 'file'
- conf = tk_split_simplelist(tk_send('configure', "-#{slot}") )
- else
- conf = tk_split_list(tk_send('configure', "-#{slot}") )
- end
- conf[0] = conf[0][1..-1]
- conf
- else
- ret = tk_split_simplelist(tk_send('configure') ).collect{|conflist|
- conf = tk_split_simplelist(conflist)
- conf[0] = conf[0][1..-1]
- case conf[0]
- when 'text', 'label', 'show', 'data', 'file'
- else
- if conf[3]
- if conf[3].index('{')
- conf[3] = tk_split_list(conf[3])
- else
- conf[3] = tk_tcl2ruby(conf[3])
- end
- end
- if conf[4]
- if conf[4].index('{')
- conf[4] = tk_split_list(conf[4])
- else
- conf[4] = tk_tcl2ruby(conf[4])
- end
- end
- end
- conf
- }
- fontconf = ret.assoc('font')
- if fontconf
- ret.delete_if{|item| item[0] == 'font' || item[0] == 'kanjifont'}
- fontconf[4] = fontobj
- ret.push(fontconf)
- else
- ret
- end
- end
- end
- end
-
- def event_generate(context, keys=nil)
- if keys
- tk_call('event', 'generate', path,
- "<#{tk_event_sequence(context)}>", *hash_kv(keys))
- else
- tk_call('event', 'generate', path, "<#{tk_event_sequence(context)}>")
- end
- end
-
- def tk_trace_variable(v)
- unless v.kind_of?(TkVariable)
- fail ArgumentError, format("requires TkVariable given %s", v.type)
- end
- v
- end
- private :tk_trace_variable
-
- def destroy
- tk_call 'trace', 'vdelete', @tk_vn, 'w', @var_id if @var_id
- end
-end
-
-class TkWindow<TkObject
- extend TkBindCore
-
- def initialize(parent=nil, keys=nil)
- install_win(if parent then parent.path end)
- if self.method(:create_self).arity == 0
- p 'create_self has no arg' if $DEBUG
- create_self
- if keys
- # tk_call @path, 'configure', *hash_kv(keys)
- configure(keys)
- end
- else
- p 'create_self has an arg' if $DEBUG
- fontkeys = {}
- if keys
- keys = keys.dup
- ['font', 'kanjifont', 'latinfont', 'asciifont'].each{|key|
- fontkeys[key] = keys.delete(key) if keys.key?(key)
- }
- end
- create_self(keys)
- font_configure(fontkeys) unless fontkeys.empty?
- end
- end
-
- def create_self
- end
- private :create_self
-
- def pack(keys = nil)
- tk_call 'pack', epath, *hash_kv(keys)
- self
- end
-
- def unpack
- tk_call 'pack', 'forget', epath
- self
- end
- alias pack_forget unpack
-
- def pack_config(slot, value=None)
- if slot.kind_of? Hash
- tk_call 'pack', 'configure', epath, *hash_kv(slot)
- else
- tk_call 'pack', 'configure', epath, "-#{slot}", value
- end
- end
-
- def pack_info()
- ilist = list(tk_call('pack', 'info', epath))
- info = {}
- while key = ilist.shift
- info[key[1..-1]] = ilist.shift
- end
- return info
- end
-
- def pack_propagate(mode = nil)
- if mode
- tk_call('pack', 'propagate', epath, mode)
- else
- bool(tk_call('pack', 'propagate', epath))
- end
- end
-
- def pack_slaves()
- list(tk_call('pack', 'slaves', epath))
- end
-
- def grid(keys = nil)
- tk_call 'grid', epath, *hash_kv(keys)
- self
- end
-
- def ungrid
- tk_call 'grid', 'forget', epath
- self
- end
- alias grid_forget ungrid
-
- def grid_bbox(*args)
- list(tk_call('grid', 'bbox', epath, *args))
- end
-
- def grid_config(slot, value=None)
- if slot.kind_of? Hash
- tk_call 'grid', 'configure', epath, *hash_kv(slot)
- else
- tk_call 'grid', 'configure', epath, "-#{slot}", value
- end
- end
-
- def grid_columnconfig(index, keys)
- tk_call('grid', 'columnconfigure', epath, index, *hash_kv(keys))
- end
-
- def grid_rowconfig(index, keys)
- tk_call('grid', 'rowconfigure', epath, index, *hash_kv(keys))
- end
-
- def grid_columnconfiginfo(index, slot=nil)
- if slot
- tk_call('grid', 'columnconfigure', epath, index, "-#{slot}")
- else
- ilist = list(tk_call('grid', 'columnconfigure', epath, index))
- info = {}
- while key = ilist.shift
- info[key[1..-1]] = ilist.shift
- end
- info
- end
- end
-
- def grid_rowconfiginfo(index, slot=nil)
- if slot
- tk_call('grid', 'rowconfigure', epath, index, "-#{slot}")
- else
- ilist = list(tk_call('grid', 'rowconfigure', epath, index))
- info = {}
- while key = ilist.shift
- info[key[1..-1]] = ilist.shift
- end
- info
- end
- end
-
- def grid_info()
- list(tk_call('grid', 'info', epath))
- end
-
- def grid_location(x, y)
- list(tk_call('grid', 'location', epath, x, y))
- end
-
- def grid_propagate(mode=nil)
- if mode
- tk_call('grid', 'propagate', epath, mode)
- else
- bool(tk_call('grid', 'propagate', epath))
- end
- end
-
- def grid_remove()
- tk_call 'grid', 'remove', epath
- end
-
- def grid_size()
- tk_call 'grid', 'size', epath
- end
-
- def grid_slaves(args)
- list(tk_call('grid', 'slaves', epath, *hash_kv(args)))
- end
-
- def place(keys = nil)
- tk_call 'place', epath, *hash_kv(keys)
- self
- end
-
- def unplace
- tk_call 'place', 'forget', epath
- self
- end
- alias place_forget unplace
-
- def place_config(slot, value=None)
- if slot.kind_of? Hash
- tk_call 'place', 'configure', epath, *hash_kv(slot)
- else
- tk_call 'place', 'configure', epath, "-#{slot}", value
- end
- end
-
- def place_configinfo(slot = nil)
- # for >= Tk8.4a2 ?
- if slot
- conf = tk_split_list(tk_call('place', 'configure', epath, "-#{slot}") )
- conf[0] = conf[0][1..-1]
- conf
- else
- tk_split_simplelist(tk_call('place',
- 'configure', epath)).collect{|conflist|
- conf = tk_split_simplelist(conflist)
- conf[0] = conf[0][1..-1]
- conf
- }
- end
- end
-
- def place_info()
- ilist = list(tk_call('place', 'info', epath))
- info = {}
- while key = ilist.shift
- info[key[1..-1]] = ilist.shift
- end
- return info
- end
-
- def place_slaves()
- list(tk_call('place', 'slaves', epath))
- end
-
- def focus(force=false)
- if force
- tk_call 'focus', '-force', path
- else
- tk_call 'focus', path
- end
- self
- end
-
- def grab(*args)
- if !args or args.length == 0
- tk_call 'grab', 'set', path
- elsif args.length == 1
- case args[0]
- when 'global'
- return(tk_call 'grab', 'set', '-global', path)
- when 'release'
- return(tk_call 'grab', 'release', path)
- else
- val = tk_call('grab', args[0], path)
- end
- case args[0]
- when 'current'
- return window(val)
- when 'status'
- return val
- end
- else
- fail ArgumentError, 'wrong # of args'
- end
- end
-
- def lower(below=None)
- tk_call 'lower', epath, below
- self
- end
- def raise(above=None)
- tk_call 'raise', epath, above
- self
- end
-
- def command(cmd=Proc.new)
- configure_cmd 'command', cmd
- end
-
- def colormodel model=None
- tk_call 'tk', 'colormodel', path, model
- self
- end
-
- def destroy
- tk_call 'destroy', epath
- if @cmdtbl
- for id in @cmdtbl
- uninstall_cmd id
- end
- end
- uninstall_win
- end
-
- def wait_visibility
- tk_call 'tkwait', 'visibility', path
- end
- alias wait wait_visibility
-
- def wait_destroy
- tk_call 'tkwait', 'window', epath
- end
-
- def bindtags(taglist=nil)
- if taglist
- fail ArgumentError unless taglist.kind_of? Array
- tk_call('bindtags', path, taglist)
- else
- list(tk_call('bindtags', path)).collect{|tag|
- if tag.kind_of?(String)
- if cls = WidgetClassNames[tag]
- cls
- elsif btag = TkBindTag.id2obj(tag)
- btag
- else
- tag
- end
- else
- tag
- end
- }
- end
- end
-end
-
-class TkRoot<TkWindow
- include Wm
- ROOT = []
- def TkRoot.new
- return ROOT[0] if ROOT[0]
- new = super
- ROOT[0] = new
- Tk_WINDOWS["."] = new
- end
-
- WidgetClassName = 'Tk'.freeze
- WidgetClassNames[WidgetClassName] = self
- def self.to_eval
- WidgetClassName
- end
-
- def create_self
- @path = '.'
- end
- def path
- "."
- end
-end
-
-class TkToplevel<TkWindow
- include Wm
-
- WidgetClassName = 'Toplevel'.freeze
- WidgetClassNames[WidgetClassName] = self
- def self.to_eval
- WidgetClassName
- end
-
-################# old version
-# def initialize(parent=nil, screen=nil, classname=nil, keys=nil)
-# if screen.kind_of? Hash
-# keys = screen.dup
-# else
-# @screen = screen
-# end
-# @classname = classname
-# if keys.kind_of? Hash
-# keys = keys.dup
-# @classname = keys.delete('classname') if keys.key?('classname')
-# @colormap = keys.delete('colormap') if keys.key?('colormap')
-# @container = keys.delete('container') if keys.key?('container')
-# @screen = keys.delete('screen') if keys.key?('screen')
-# @use = keys.delete('use') if keys.key?('use')
-# @visual = keys.delete('visual') if keys.key?('visual')
-# end
-# super(parent, keys)
-# end
-#
-# def create_self
-# s = []
-# s << "-class" << @classname if @classname
-# s << "-colormap" << @colormap if @colormap
-# s << "-container" << @container if @container
-# s << "-screen" << @screen if @screen
-# s << "-use" << @use if @use
-# s << "-visual" << @visual if @visual
-# tk_call 'toplevel', @path, *s
-# end
-#################
-
- def initialize(parent=nil, screen=nil, classname=nil, keys=nil)
- if screen.kind_of? Hash
- keys = screen
- else
- @screen = screen
- end
- @classname = classname
- if keys.kind_of? Hash
- if keys.key?('classname')
- keys = keys.dup
- keys['class'] = keys.delete('classname')
- end
- @classname = keys['class']
- @colormap = keys['colormap']
- @container = keys['container']
- @screen = keys['screen']
- @use = keys['use']
- @visual = keys['visual']
- end
- super(parent, keys)
- end
-
- def create_self(keys)
- if keys and keys != None
- tk_call 'toplevel', @path, *hash_kv(keys)
- else
- tk_call 'toplevel', @path
- end
- end
-
- def specific_class
- @classname
- end
-end
-
-class TkFrame<TkWindow
- WidgetClassName = 'Frame'.freeze
- WidgetClassNames[WidgetClassName] = self
- def self.to_eval
- WidgetClassName
- end
-
-################# old version
-# def initialize(parent=nil, keys=nil)
-# if keys.kind_of? Hash
-# keys = keys.dup
-# @classname = keys.delete('classname') if keys.key?('classname')
-# @colormap = keys.delete('colormap') if keys.key?('colormap')
-# @container = keys.delete('container') if keys.key?('container')
-# @visual = keys.delete('visual') if keys.key?('visual')
-# end
-# super(parent, keys)
-# end
-#
-# def create_self
-# s = []
-# s << "-class" << @classname if @classname
-# s << "-colormap" << @colormap if @colormap
-# s << "-container" << @container if @container
-# s << "-visual" << @visual if @visual
-# tk_call 'frame', @path, *s
-# end
-#################
-
- def initialize(parent=nil, keys=nil)
- if keys.kind_of? Hash
- if keys.key?('classname')
- keys = keys.dup
- keys['class'] = keys.delete('classname')
- end
- @classname = keys['class']
- @colormap = keys['colormap']
- @container = keys['container']
- @visual = keys['visual']
- end
- super(parent, keys)
- end
-
- def create_self(keys)
- if keys and keys != None
- tk_call 'frame', @path, *hash_kv(keys)
- else
- tk_call 'frame', @path
- end
- end
-end
-
-class TkLabel<TkWindow
- WidgetClassName = 'Label'.freeze
- WidgetClassNames[WidgetClassName] = self
- def self.to_eval
- WidgetClassName
- end
- def create_self(keys)
- if keys and keys != None
- tk_call 'label', @path, *hash_kv(keys)
- else
- tk_call 'label', @path
- end
- end
- def textvariable(v)
- configure 'textvariable', tk_trace_variable(v)
- end
-end
-
-class TkButton<TkLabel
- WidgetClassNames['Button'] = self
- def TkButton.to_eval
- 'Button'
- end
- def create_self(keys)
- if keys and keys != None
- tk_call 'button', @path, *hash_kv(keys)
- else
- tk_call 'button', @path
- end
- end
- def invoke
- tk_send 'invoke'
- end
- def flash
- tk_send 'flash'
- end
-end
-
-class TkRadioButton<TkButton
- WidgetClassNames['Radiobutton'] = self
- def TkRadioButton.to_eval
- 'Radiobutton'
- end
- def create_self(keys)
- if keys and keys != None
- tk_call 'radiobutton', @path, *hash_kv(keys)
- else
- tk_call 'radiobutton', @path
- end
- end
- def deselect
- tk_send 'deselect'
- end
- def select
- tk_send 'select'
- end
- def variable(v)
- configure 'variable', tk_trace_variable(v)
- end
-end
-TkRadiobutton = TkRadioButton
-
-class TkCheckButton<TkRadioButton
- WidgetClassNames['Checkbutton'] = self
- def TkCheckButton.to_eval
- 'Checkbutton'
- end
- def create_self(keys)
- if keys and keys != None
- tk_call 'checkbutton', @path, *hash_kv(keys)
- else
- tk_call 'checkbutton', @path
- end
- end
- def toggle
- tk_send 'toggle'
- end
-end
-TkCheckbutton = TkCheckButton
-
-class TkMessage<TkLabel
- WidgetClassNames['Message'] = self
- def TkMessage.to_eval
- 'Message'
- end
- def create_self(keys)
- if keys and keys != None
- tk_call 'message', @path, *hash_kv(keys)
- else
- tk_call 'message', @path
- end
- end
-end
-
-class TkScale<TkWindow
- WidgetClassName = 'Scale'.freeze
- WidgetClassNames[WidgetClassName] = self
- def self.to_eval
- WidgetClassName
- end
-
- def create_self(keys)
- if keys and keys != None
- tk_call 'scale', @path, *hash_kv(keys)
- else
- tk_call 'scale', @path
- end
- end
-
- def get(x=None, y=None)
- number(tk_send('get', x, y))
- end
-
- def coords(val=None)
- tk_split_list(tk_send('coords', val))
- end
-
- def identify(x, y)
- tk_send('identify', x, y)
- end
-
- def set(val)
- tk_send "set", val
- end
-
- def value
- get
- end
-
- def value= (val)
- set val
- end
-end
-
-class TkScrollbar<TkWindow
- WidgetClassName = 'Scrollbar'.freeze
- WidgetClassNames[WidgetClassName] = self
- def self.to_eval
- WidgetClassName
- end
-
- def create_self(keys)
- if keys and keys != None
- tk_call 'scrollbar', @path, *hash_kv(keys)
- else
- tk_call 'scrollbar', @path
- end
- end
-
- def delta(deltax=None, deltay=None)
- number(tk_send('delta', deltax, deltay))
- end
-
- def fraction(x=None, y=None)
- number(tk_send('fraction', x, y))
- end
-
- def identify(x, y)
- tk_send('identify', x, y)
- end
-
- def get
- ary1 = tk_send('get').split
- ary2 = []
- for i in ary1
- ary2.push number(i)
- end
- ary2
- end
-
- def set(first, last)
- tk_send "set", first, last
- end
-
- def activate(element=None)
- tk_send('activate', element)
- end
-end
-
-class TkTextWin<TkWindow
- def create_self
- fail TypeError, "TkTextWin is abstract class"
- end
-
- def bbox(index)
- tk_send 'bbox', index
- end
- def delete(first, last=None)
- tk_send 'delete', first, last
- end
- def get(*index)
- tk_send 'get', *index
- end
- def index(index)
- tk_send 'index', index
- end
- def insert(index, chars, *args)
- tk_send 'insert', index, chars, *args
- end
- def scan_mark(x, y)
- tk_send 'scan', 'mark', x, y
- end
- def scan_dragto(x, y)
- tk_send 'scan', 'dragto', x, y
- end
- def see(index)
- tk_send 'see', index
- end
-end
-
-module TkTreatListItemFont
- include TkTreatItemFont
-
- ItemCMD = ['itemconfigure', TkComm::None]
- def __conf_cmd(idx)
- ItemCMD[idx]
- end
-
- def __item_pathname(tagOrId)
- self.path + ';' + tagOrId.to_s
- end
-end
-
-class TkListbox<TkTextWin
- include TkTreatListItemFont
- include Scrollable
-
- WidgetClassNames['Listbox'] = self
- def TkListbox.to_eval
- 'Listbox'
- end
- def create_self(keys)
- if keys and keys != None
- tk_call 'listbox', @path, *hash_kv(keys)
- else
- tk_call 'listbox', @path
- end
- end
-
- def activate(y)
- tk_send 'activate', y
- end
- def curselection
- list(tk_send('curselection'))
- end
- def get(*index)
- v = tk_send('get', *index)
- if index.size == 1
- v
- else
- tk_split_simplelist(v)
- end
- end
- def nearest(y)
- tk_send('nearest', y).to_i
- end
- def size
- tk_send('size').to_i
- end
- def selection_anchor(index)
- tk_send 'selection', 'anchor', index
- end
- def selection_clear(first, last=None)
- tk_send 'selection', 'clear', first, last
- end
- def selection_includes(index)
- bool(tk_send('selection', 'includes', index))
- end
- def selection_set(first, last=None)
- tk_send 'selection', 'set', first, last
- end
-
- def itemcget(index, key)
- case key
- when 'text', 'label', 'show'
- tk_send 'itemcget', index, "-#{key}"
- else
- tk_tcl2ruby tk_send 'itemcget', index, "-#{key}"
- end
- end
- def itemconfigure(index, key, val=None)
- if key.kind_of? Hash
- if (key['font'] || key['kanjifont'] ||
- key['latinfont'] || key['asciifont'])
- tagfont_configure(index, key.dup)
- else
- tk_send 'itemconfigure', index, *hash_kv(key)
- end
-
- else
- if (key == 'font' || key == 'kanjifont' ||
- key == 'latinfont' || key == 'asciifont' )
- tagfont_configure(index, {key=>val})
- else
- tk_call 'itemconfigure', index, "-#{key}", val
- end
- end
- end
-
- def itemconfiginfo(index, key=nil)
- if key
- case key
- when 'text', 'label', 'show'
- conf = tk_split_simplelist(tk_send('itemconfigure',index,"-#{key}"))
- else
- conf = tk_split_list(tk_send('itemconfigure',index,"-#{key}"))
- end
- conf[0] = conf[0][1..-1]
- conf
- else
- tk_split_simplelist(tk_send('itemconfigure', index)).collect{|conflist|
- conf = tk_split_simplelist(conflist)
- conf[0] = conf[0][1..-1]
- case conf[0]
- when 'text', 'label', 'show'
- else
- if conf[3]
- if conf[3].index('{')
- conf[3] = tk_split_list(conf[3])
- else
- conf[3] = tk_tcl2ruby(conf[3])
- end
- end
- if conf[4]
- if conf[4].index('{')
- conf[4] = tk_split_list(conf[4])
- else
- conf[4] = tk_tcl2ruby(conf[4])
- end
- end
- end
- conf
- }
- end
- end
-end
-
-module TkTreatMenuEntryFont
- include TkTreatItemFont
-
- ItemCMD = ['entryconfigure', TkComm::None]
- def __conf_cmd(idx)
- ItemCMD[idx]
- end
-
- def __item_pathname(tagOrId)
- self.path + ';' + tagOrId.to_s
- end
-end
-
-class TkMenu<TkWindow
- include TkTreatMenuEntryFont
-
- WidgetClassName = 'Menu'.freeze
- WidgetClassNames[WidgetClassName] = self
- def self.to_eval
- WidgetClassName
- end
- def create_self(keys)
- if keys and keys != None
- tk_call 'menu', @path, *hash_kv(keys)
- else
- tk_call 'menu', @path
- end
- end
- def activate(index)
- tk_send 'activate', index
- end
- def add(type, keys=nil)
- tk_send 'add', type, *hash_kv(keys)
- end
- def index(index)
- tk_send 'index', index
- end
- def invoke(index)
- tk_send 'invoke', index
- end
- def insert(index, type, keys=nil)
- tk_send 'insert', index, type, *hash_kv(keys)
- end
- def delete(index, last=None)
- tk_send 'delete', index, last
- end
- def popup(x, y, index=None)
- tk_call 'tk_popup', path, x, y, index
- end
- def post(x, y)
- tk_send 'post', x, y
- end
- def postcascade(index)
- tk_send 'postcascade', index
- end
- def postcommand(cmd=Proc.new)
- configure_cmd 'postcommand', cmd
- end
- def tearoffcommand(cmd=Proc.new)
- configure_cmd 'tearoffcommand', cmd
- end
- def menutype(index)
- tk_send 'type', index
- end
- def unpost
- tk_send 'unpost'
- end
- def yposition(index)
- number(tk_send('yposition', index))
- end
- def entrycget(index, key)
- case key
- when 'text', 'label', 'show'
- tk_send 'entrycget', index, "-#{key}"
- else
- tk_tcl2ruby tk_send 'entrycget', index, "-#{key}"
- end
- end
- def entryconfigure(index, key, val=None)
- if key.kind_of? Hash
- if (key['font'] || key['kanjifont'] ||
- key['latinfont'] || key['asciifont'])
- tagfont_configure(index, key.dup)
- else
- tk_send 'entryconfigure', index, *hash_kv(key)
- end
-
- else
- if (key == 'font' || key == 'kanjifont' ||
- key == 'latinfont' || key == 'asciifont' )
- tagfont_configure({key=>val})
- else
- tk_call 'entryconfigure', index, "-#{key}", val
- end
- end
- end
-
- def entryconfiginfo(index, key=nil)
- if key
- case key
- when 'text', 'label', 'show'
- conf = tk_split_simplelist(tk_send('entryconfigure',index,"-#{key}"))
- else
- conf = tk_split_list(tk_send('entryconfigure',index,"-#{key}"))
- end
- conf[0] = conf[0][1..-1]
- conf
- else
- tk_split_simplelist(tk_send('entryconfigure', index)).collect{|conflist|
- conf = tk_split_simplelist(conflist)
- conf[0] = conf[0][1..-1]
- case conf[0]
- when 'text', 'label', 'show'
- else
- if conf[3]
- if conf[3].index('{')
- conf[3] = tk_split_list(conf[3])
- else
- conf[3] = tk_tcl2ruby(conf[3])
- end
- end
- if conf[4]
- if conf[4].index('{')
- conf[4] = tk_split_list(conf[4])
- else
- conf[4] = tk_tcl2ruby(conf[4])
- end
- end
- end
- conf
- }
- end
- end
-end
-
-class TkMenuClone<TkMenu
- def initialize(parent, type=None)
- unless parent.kind_of?(TkMenu)
- fail ArgumentError, "parent must be TkMenu"
- end
- @parent = parent
- install_win(@parent.path)
- tk_call @parent.path, 'clone', @path, type
- end
-end
-
-module TkSystemMenu
- def initialize(parent, keys=nil)
- fail unless parent.kind_of? TkMenu
- @path = format("%s.%s", parent.path, self.type::SYSMENU_NAME)
- TkComm::Tk_WINDOWS[@path] = self
- if self.method(:create_self).arity == 0
- p 'create_self has no arg' if $DEBUG
- create_self
- configure(keys) if keys
- else
- p 'create_self has an arg' if $DEBUG
- create_self(keys)
- end
- end
-end
-
-class TkSysMenu_Help<TkMenu
- # for all platform
- include TkSystemMenu
- SYSMENU_NAME = 'help'
-end
-
-class TkSysMenu_System<TkMenu
- # for Windows
- include TkSystemMenu
- SYSMENU_NAME = 'system'
-end
-
-class TkSysMenu_Apple<TkMenu
- # for Machintosh
- include TkSystemMenu
- SYSMENU_NAME = 'apple'
-end
-
-class TkMenubutton<TkLabel
- WidgetClassNames['Menubutton'] = self
- def TkMenubutton.to_eval
- 'Menubutton'
- end
- def create_self(keys)
- if keys and keys != None
- tk_call 'menubutton', @path, *hash_kv(keys)
- else
- tk_call 'menubutton', @path
- end
- end
-end
-
-class TkOptionMenubutton<TkMenubutton
- class OptionMenu<TkMenu
- def initialize(parent)
- @path = parent.path + '.menu'
- TkComm::Tk_WINDOWS[@path] = self
- end
- end
-
- def initialize(parent=nil, var=TkVariable.new, firstval=nil, *vals)
- fail unless var.kind_of? TkVariable
- @variable = var
- firstval = @variable.value unless firstval
- @variable.value = firstval
- install_win(if parent then parent.path end)
- @menu = OptionMenu.new(self)
- tk_call 'tk_optionMenu', @path, @variable.id, firstval, *vals
- end
-
- def value
- @variable.value
- end
-
- def activate(index)
- @menu.activate(index)
- end
- def add(value)
- @menu.add('radiobutton', 'variable'=>@variable,
- 'label'=>value, 'value'=>value)
- end
- def index(index)
- @menu.index(index)
- end
- def invoke(index)
- @menu.invoke(index)
- end
- def insert(index, value)
- @menu.add(index, 'radiobutton', 'variable'=>@variable,
- 'label'=>value, 'value'=>value)
- end
- def delete(index, last=None)
- @menu.delete(index, last)
- end
- def yposition(index)
- @menu.yposition(index)
- end
- def menucget(index, key)
- @menu.cget(index, key)
- end
- def menuconfigure(index, key, val=None)
- @menu.configure(index, key, val)
- end
- def menuconfiginfo(index, key=nil)
- @menu.configinfo(index, key)
- end
- def entrycget(index, key)
- @menu.entrycget(index, key)
- end
- def entryconfigure(index, key, val=None)
- @menu.entryconfigure(index, key, val)
- end
- def entryconfiginfo(index, key=nil)
- @menu.entryconfiginfo(index, key)
- end
-end
-
-module TkComposite
- include Tk
- extend Tk
-
- def initialize(parent=nil, *args)
- @frame = TkFrame.new(parent)
- @path = @epath = @frame.path
- initialize_composite(*args)
- end
-
- def epath
- @epath
- end
-
- def initialize_composite(*args) end
- private :initialize_composite
-
- def delegate(option, *wins)
- unless @delegates
- @delegates = {}
- @delegates['DEFAULT'] = @frame
- end
- if @delegates[option].kind_of?(Array)
- for i in wins
- @delegates[option].push(i)
- end
- else
- @delegates[option] = wins
- end
- end
-
- def configure(slot, value=None)
- if slot.kind_of? Hash
- slot.each{|slot,value| configure slot, value}
- else
- if @delegates and @delegates[slot]
- for i in @delegates[slot]
- if not i
- i = @delegates['DEFALUT']
- redo
- else
- last = i.configure(slot, value)
- end
- end
- last
- else
- super
- end
- end
- end
-end
-
-module TkClipboard
- include Tk
- extend Tk
-
- def clear
- tk_call 'clipboard', 'clear'
- end
- def get
- begin
- tk_call 'selection', 'get', '-selection', 'CLIPBOARD'
- rescue
- ''
- end
- end
- def set(data)
- clear
- append(data)
- end
- def append(data)
- tk_call 'clipboard', 'append', data
- end
-
- module_function :clear, :set, :get, :append
-end
-
-autoload :TkCanvas, 'tkcanvas'
-autoload :TkImage, 'tkcanvas'
-autoload :TkBitmapImage, 'tkcanvas'
-autoload :TkPhotoImage, 'tkcanvas'
-autoload :TkEntry, 'tkentry'
-autoload :TkSpinbox, 'tkentry'
-autoload :TkText, 'tktext'
-autoload :TkDialog, 'tkdialog'
-autoload :TkWarning, 'tkdialog'
-autoload :TkMenubar, 'tkmenubar'
-autoload :TkAfter, 'tkafter'
-autoload :TkPalette, 'tkpalette'
-autoload :TkFont, 'tkfont'
-autoload :TkVirtualEvent, 'tkvirtevent'
-autoload :TkBgError, 'tkbgerror'
-autoload :TkManageFocus, 'tkmngfocus'
-autoload :TkPalette, 'tkpalette'
-autoload :TkWinDDE, 'tkwinpkg'
-autoload :TkWinRegistry, 'tkwinpkg'
-autoload :TkMacResource, 'tkmacpkg'
diff --git a/ext/tk/lib/tkafter.rb b/ext/tk/lib/tkafter.rb
deleted file mode 100644
index fe3ee38740..0000000000
--- a/ext/tk/lib/tkafter.rb
+++ /dev/null
@@ -1,316 +0,0 @@
-#
-# tkafter.rb : methods for Tcl/Tk after command
-# 2000/08/01 by Hidetoshi Nagai <nagai@ai.kyutech.ac.jp>
-#
-require 'tk'
-
-class TkAfter
- include TkCore
- extend TkCore
-
- Tk_CBID = [0]
- Tk_CBTBL = {}
-
- INTERP._invoke("proc", "rb_after", "args", "ruby [format \"TkAfter.callback %%Q!%s!\" $args]")
-
- ###############################
- # class methods
- ###############################
- def TkAfter.callback(arg)
- @after_id = nil
- arg = Array(tk_split_list(arg))
- obj_id = arg.shift
- ex_obj = Tk_CBTBL[obj_id]
- return nil if ex_obj == nil; # canceled
- _get_eval_string(ex_obj.do_callback(*arg))
- end
-
- def TkAfter.info
- tk_call('after', 'info').split(' ').collect!{|id|
- ret = Tk_CBTBL.find{|key,val| val.after_id == id}
- (ret == nil)? id: ret[1]
- }
- end
-
- ###############################
- # instance methods
- ###############################
- def do_callback(*args)
- @in_callback = true
- begin
- ret = @current_proc.call(*args)
- rescue StandardError, NameError
- if @cancel_on_exception
- cancel
- return nil
- else
- fail $!
- end
- end
- if @set_next
- set_next_callback(*args)
- else
- @set_next = true
- end
- @in_callback = false
- ret
- end
-
- def set_callback(sleep, args=nil)
- @after_script = "rb_after #{@id} #{_get_eval_string(args)}"
- @after_id = tk_call('after', sleep, @after_script)
- @current_script = [sleep, @after_script]
- end
-
- def set_next_callback(*args)
- if @running == false || @proc_max == 0 || @do_loop == 0
- Tk_CBTBL[@id] = nil ;# for GC
- @running = false
- return
- end
- if @current_pos >= @proc_max
- if @do_loop < 0 || (@do_loop -= 1) > 0
- @current_pos = 0
- else
- Tk_CBTBL[@id] = nil ;# for GC
- @running = false
- return
- end
- end
-
- @current_args = args
-
- if @sleep_time.kind_of? Proc
- sleep = @sleep_time.call(*args)
- else
- sleep = @sleep_time
- end
- @current_sleep = sleep
-
- cmd, *cmd_args = @loop_proc[@current_pos]
- @current_pos += 1
- @current_proc = cmd
-
- if cmd_args[0].kind_of? Proc
- #c = cmd_args.shift
- #cb_args = c.call(*(cmd_args + args))
- cb_args = cmd_args[0].call(*args)
- else
- cb_args = cmd_args
- end
-
- set_callback(sleep, cb_args)
- end
-
- def initialize(*args)
- @id = format("a%.4d", Tk_CBID[0])
- Tk_CBID[0] += 1
-
- @set_next = true
-
- @init_sleep = 0
- @init_proc = nil
- @init_args = []
-
- @current_script = []
- @current_proc = nil
- @current_args = nil
-
- @sleep_time = 0
- @current_sleep = 0
- @loop_exec = 0
- @do_loop = 0
- @loop_proc = []
- @proc_max = 0
- @current_pos = 0
-
- @after_id = nil
- @after_script = nil
-
- @cancel_on_exception = true
-
- set_procs(*args) if args != []
-
- @running = false
- end
-
- attr :after_id
- attr :after_script
- attr :current_proc
- attr :current_sleep
-
- attr_accessor :loop_exec
-
- def get_procs
- [@init_sleep, @init_proc, @init_args, @sleep_time, @loop_exec, @loop_proc]
- end
-
- def current_status
- [@running, @current_sleep, @current_proc, @current_args,
- @do_loop, @cancel_on_exception]
- end
-
- def cancel_on_exception?
- @cancel_on_exception
- end
-
- def cancel_on_exception=(mode)
- @cancel_on_exception = mode
- end
-
- def running?
- @running
- end
-
- def loop_rest
- @do_loop
- end
-
- def loop_rest=(rest)
- @do_loop = rest
- end
-
- def set_procs(interval, loop_exec, *procs)
- if !interval == 'idle' \
- && !interval.kind_of?(Integer) && !interval.kind_of?(Proc)
- fail format("%s need to be Integer or Proc", interval.inspect)
- end
- @sleep_time = interval
-
- @loop_proc = []
- procs.each{|e|
- if e.kind_of? Proc
- @loop_proc.push([e])
- else
- @loop_proc.push(e)
- end
- }
- @proc_max = @loop_proc.size
- @current_pos = 0
-
- @do_loop = 0
- if loop_exec
- if loop_exec.kind_of?(Integer) && loop_exec < 0
- @loop_exec = -1
- elsif loop_exec == nil || loop_exec == false || loop_exec == 0
- @loop_exec = 1
- else
- if not loop_exec.kind_of?(Integer)
- fail format("%s need to be Integer", loop_exec.inspect)
- end
- @loop_exec = loop_exec
- end
- @do_loop = @loop_exec
- end
-
- self
- end
-
- def add_procs(*procs)
- procs.each{|e|
- if e.kind_of? Proc
- @loop_proc.push([e])
- else
- @loop_proc.push(e)
- end
- }
- @proc_max = @loop_proc.size
-
- self
- end
-
- def set_start_proc(sleep, init_proc, *init_args)
- if !sleep == 'idle' && !sleep.kind_of?(Integer)
- fail format("%s need to be Integer", sleep.inspect)
- end
- @init_sleep = sleep
- @init_proc = init_proc
- @init_args = init_args
- self
- end
-
- def start(*init_args)
- return nil if @running
-
- Tk_CBTBL[@id] = self
- @do_loop = @loop_exec
- @current_pos = 0
-
- argc = init_args.size
- if argc > 0
- sleep = init_args.shift
- if !sleep == 'idle' && !sleep.kind_of?(Integer)
- fail format("%s need to be Integer", sleep.inspect)
- end
- @init_sleep = sleep
- end
- @init_proc = init_args.shift if argc > 1
- @init_args = init_args if argc > 0
-
- @current_sleep = @init_sleep
- @running = true
- if @init_proc
- if not @init_proc.kind_of? Proc
- fail format("%s need to be Proc", @init_proc.inspect)
- end
- @current_proc = @init_proc
- set_callback(sleep, @init_args)
- @set_next = false if @in_callback
- else
- set_next_callback(*@init_args)
- end
-
- self
- end
-
- def restart(*restart_args)
- cancel if @running
- if restart_args == []
- start(@init_sleep, @init_proc, *@init_args)
- else
- start(*restart_args)
- end
- end
-
- def cancel
- @running = false
- tk_call 'after', 'cancel', @after_id if @after_id
- @after_id = nil
- Tk_CBTBL[@id] = nil ;# for GC
- self
- end
- alias stop cancel
-
- def continue(wait=nil)
- sleep, cmd = @current_script
- return nil if cmd == nil || @running == true
- if wait
- if not wait.kind_of? Integer
- fail format("%s need to be Integer", wait.inspect)
- end
- sleep = wait
- end
- Tk_CBTBL[@id] = self
- @running = true
- @after_id = tk_call('after', sleep, cmd)
- self
- end
-
- def skip
- return nil if @running == false
- cancel
- Tk_CBTBL[@id] = self
- @running = true
- set_next_callback(@current_args)
- self
- end
-
- def info
- if @after_id
- inf = tk_split_list(tk_call('after', 'info', @after_id))
- [Tk_CBTBL[inf[0][1]], inf[1]]
- else
- nil
- end
- end
-end
diff --git a/ext/tk/lib/tkbgerror.rb b/ext/tk/lib/tkbgerror.rb
deleted file mode 100644
index 8022077a3f..0000000000
--- a/ext/tk/lib/tkbgerror.rb
+++ /dev/null
@@ -1,17 +0,0 @@
-#
-# tkbgerror -- bgerror ( tkerror ) module
-# 1998/07/16 by Hidetoshi Nagai <nagai@ai.kyutech.ac.jp>
-#
-require 'tk'
-
-module TkBgError
- extend Tk
-
- def bgerror(message)
- tk_call 'bgerror', message
- end
- alias tkerror bgerror
- alias show bgerror
-
- module_function :bgerror, :tkerror, :show
-end
diff --git a/ext/tk/lib/tkcanvas.rb b/ext/tk/lib/tkcanvas.rb
deleted file mode 100644
index 94376072d3..0000000000
--- a/ext/tk/lib/tkcanvas.rb
+++ /dev/null
@@ -1,863 +0,0 @@
-
-# tkcanvas.rb - Tk canvas classes
-# $Date$
-# by Yukihiro Matsumoto <matz@caelum.co.jp>
-# $Date$
-# by Hidetoshi Nagai <nagai@ai.kyutech.ac.jp>
-
-require "tk"
-require 'tkfont'
-
-module TkTreatCItemFont
- include TkTreatItemFont
-
- ItemCMD = ['itemconfigure', TkComm::None]
- def __conf_cmd(idx)
- ItemCMD[idx]
- end
-
- def __item_pathname(tagOrId)
- if tagOrId.kind_of?(TkcItem) || tagOrId.kind_of?(TkcTag)
- self.path + ';' + tagOrId.id.to_s
- else
- self.path + ';' + tagOrId.to_s
- end
- end
-end
-
-class TkCanvas<TkWindow
- include TkTreatCItemFont
- include Scrollable
-
- WidgetClassName = 'Canvas'.freeze
- WidgetClassNames[WidgetClassName] = self
- def self.to_eval
- WidgetClassName
- end
-
- def create_self(keys)
- if keys and keys != None
- tk_call 'canvas', @path, *hash_kv(keys)
- else
- tk_call 'canvas', @path
- end
- end
-
- def tagid(tag)
- if tag.kind_of?(TkcItem) || tag.kind_of?(TkcTag)
- tag.id
- else
- tag
- end
- end
- private :tagid
-
- def addtag(tag, mode, *args)
- tk_send 'addtag', tagid(tag), mode, *args
- end
- def addtag_above(tagOrId, target)
- addtag(tagOrId, 'above', tagid(target))
- end
- def addtag_all(tagOrId)
- addtag(tagOrId, 'all')
- end
- def addtag_below(tagOrId, target)
- addtag(tagOrId, 'below', tagid(target))
- end
- def addtag_closest(tagOrId, x, y, halo=None, start=None)
- addtag(tagOrId, 'closest', x, y, halo, start)
- end
- def addtag_enclosed(tagOrId, x1, y1, x2, y2)
- addtag(tagOrId, 'enclosed', x1, y1, x2, y2)
- end
- def addtag_overlapping(tagOrId, x1, y1, x2, y2)
- addtag(tagOrId, 'overlapping', x1, y1, x2, y2)
- end
- def addtag_withtag(tagOrId, tag)
- addtag(tagOrId, 'withtag', tagid(tag))
- end
-
- def bbox(tagOrId, *tags)
- list(tk_send('bbox', tagid(tagOrId), *tags.collect{|t| tagid(t)}))
- end
-
- def itembind(tag, context, cmd=Proc.new, args=nil)
- _bind([path, "bind", tagid(tag)], context, cmd, args)
- end
-
- def itembind_append(tag, context, cmd=Proc.new, args=nil)
- _bind_append([path, "bind", tagid(tag)], context, cmd, args)
- end
-
- def itembindinfo(tag, context=nil)
- _bindinfo([path, "bind", tagid(tag)], context)
- end
-
- def canvasx(x, *args)
- tk_tcl2ruby(tk_send 'canvasx', x, *args)
- end
- def canvasy(y, *args)
- tk_tcl2ruby(tk_send 'canvasy', y, *args)
- end
-
- def coords(tag, *args)
- if args == []
- tk_split_list(tk_send('coords', tagid(tag)))
- else
- tk_send('coords', tagid(tag), *args)
- end
- end
-
- def dchars(tag, first, last=None)
- tk_send 'dchars', tagid(tag), first, last
- end
-
- def delete(*args)
- tk_send 'delete', *args.collect{|t| tagid(t)}
- end
- alias remove delete
-
- def dtag(tag, tag_to_del=None)
- tk_send 'dtag', tagid(tag), tag_to_del
- end
-
- def find(mode, *args)
- list(tk_send 'find', mode, *args).collect!{|id|
- TkcItem.id2obj(self, id)
- }
- end
- def find_above(target)
- find('above', tagid(target))
- end
- def find_all
- find('all')
- end
- def find_below(target)
- find('below', tagid(target))
- end
- def find_closest(x, y, halo=None, start=None)
- find('closest', x, y, halo, start)
- end
- def find_enclosed(x1, y1, x2, y2)
- find('enclosed', x1, y1, x2, y2)
- end
- def find_overlapping(x1, y1, x2, y2)
- find('overlapping', x1, y1, x2, y2)
- end
- def find_withtag(tag)
- find('withtag', tag)
- end
-
- def itemfocus(tagOrId=nil)
- if tagOrId
- tk_send 'focus', tagid(tagOrId)
- else
- ret = tk_send('focus')
- if ret == ""
- nil
- else
- TkcItem.id2obj(self, ret)
- end
- end
- end
-
- def gettags(tagOrId)
- list(tk_send('gettags', tagid(tagOrId))).collect{|tag|
- TkcTag.id2obj(self, tag)
- }
- end
-
- def icursor(tagOrId, index)
- tk_send 'icursor', tagid(tagOrId), index
- end
-
- def index(tagOrId, index)
- tk_send 'index', tagid(tagOrId), index
- end
-
- def insert(tagOrId, index, string)
- tk_send 'insert', tagid(tagOrId), index, string
- end
-
- def itemcget(tagOrId, option)
- case option
- when 'dash', 'activedash', 'disableddash'
- conf = tk_send('itemcget', tagid(tagOrId), "-#{option}")
- if conf =~ /^[0-9]/
- list(conf)
- else
- conf
- end
- when 'text', 'label', 'show', 'data', 'file', 'maskdata', 'maskfile'
- tk_send 'itemcget', tagid(tagOrId), "-#{option}"
- else
- tk_tcl2ruby tk_send 'itemcget', tagid(tagOrId), "-#{option}"
- end
- end
-
- def itemconfigure(tagOrId, key, value=None)
- if key.kind_of? Hash
- if ( key['font'] || key['kanjifont'] \
- || key['latinfont'] || key['asciifont'] )
- tagfont_configure(tagOrId, key.dup)
- else
- tk_send 'itemconfigure', tagid(tagOrId), *hash_kv(key)
- end
-
- else
- if ( key == 'font' || key == 'kanjifont' \
- || key == 'latinfont' || key == 'asciifont' )
- tagfont_configure(tagid(tagOrId), {key=>value})
- else
- tk_send 'itemconfigure', tagid(tagOrId), "-#{key}", value
- end
- end
- end
-# def itemconfigure(tagOrId, key, value=None)
-# if key.kind_of? Hash
-# tk_send 'itemconfigure', tagid(tagOrId), *hash_kv(key)
-# else
-# tk_send 'itemconfigure', tagid(tagOrId), "-#{key}", value
-# end
-# end
-# def itemconfigure(tagOrId, keys)
-# tk_send 'itemconfigure', tagid(tagOrId), *hash_kv(keys)
-# end
-
- def itemconfiginfo(tagOrId, key=nil)
- if key
- case key
- when 'dash', 'activedash', 'disableddash'
- conf = tk_split_simplelist(tk_send 'itemconfigure',
- tagid(tagOrId), "-#{key}")
- if conf[3] && conf[3] =~ /^[0-9]/
- conf[3] = list(conf[3])
- end
- if conf[4] && conf[4] =~ /^[0-9]/
- conf[4] = list(conf[4])
- end
- when 'text', 'label', 'show', 'data', 'file', 'maskdata', 'maskfile'
- conf = tk_split_simplelist(tk_send 'itemconfigure',
- tagid(tagOrId), "-#{key}")
- else
- conf = tk_split_list(tk_send 'itemconfigure',
- tagid(tagOrId), "-#{key}")
- end
- conf[0] = conf[0][1..-1]
- conf
- else
- tk_split_simplelist(tk_send 'itemconfigure',
- tagid(tagOrId)).collect{|conflist|
- conf = tk_split_simplelist(conflist)
- conf[0] = conf[0][1..-1]
- case conf[0]
- when 'text', 'label', 'show', 'data', 'file', 'maskdata', 'maskfile'
- when 'dash', 'activedash', 'disableddash'
- if conf[3] && conf[3] =~ /^[0-9]/
- conf[3] = list(conf[3])
- end
- if conf[4] && conf[4] =~ /^[0-9]/
- conf[4] = list(conf[4])
- end
- else
- if conf[3]
- if conf[3].index('{')
- conf[3] = tk_split_list(conf[3])
- else
- conf[3] = tk_tcl2ruby(conf[3])
- end
- end
- if conf[4]
- if conf[4].index('{')
- conf[4] = tk_split_list(conf[4])
- else
- conf[4] = tk_tcl2ruby(conf[4])
- end
- end
- end
- conf
- }
- end
- end
-
- def lower(tag, below=None)
- tk_send 'lower', tagid(tag), tagid(below)
- end
-
- def move(tag, x, y)
- tk_send 'move', tagid(tag), x, y
- end
-
- def postscript(keys)
- tk_send "postscript", *hash_kv(keys)
- end
-
- def raise(tag, above=None)
- tk_send 'raise', tagid(tag), tagid(above)
- end
-
- def scale(tag, x, y, xs, ys)
- tk_send 'scale', tagid(tag), x, y, xs, ys
- end
-
- def scan_mark(x, y)
- tk_send 'scan', 'mark', x, y
- end
- def scan_dragto(x, y)
- tk_send 'scan', 'dragto', x, y
- end
-
- def select(mode, *args)
- tk_send 'select', mode, *args
- end
- def select_adjust(tagOrId, index)
- select('adjust', tagid(tagOrId), index)
- end
- def select_clear
- select('clear')
- end
- def select_from(tagOrId, index)
- select('from', tagid(tagOrId), index)
- end
- def select_item
- select('item')
- end
- def select_to(tagOrId, index)
- select('to', tagid(tagOrId), index)
- end
-
- def itemtype(tag)
- TkcItem.type2class(tk_send 'type', tagid(tag))
- end
-end
-
-module TkcTagAccess
- include TkComm
- include TkTreatTagFont
-
- def addtag(tag)
- @c.addtag(tag, 'with', @id)
- end
-
- def bbox
- @c.bbox(@id)
- end
-
- def bind(seq, cmd=Proc.new, args=nil)
- @c.itembind @id, seq, cmd, args
- end
-
- def bindinfo(seq=nil)
- @c.itembindinfo @id, seq
- end
-
- def cget(option)
- @c.itemcget @id, option
- end
-
- def configure(key, value=None)
- @c.itemconfigure @id, key, value
- end
-# def configure(keys)
-# @c.itemconfigure @id, keys
-# end
-
- def configinfo(key=nil)
- @c.itemconfiginfo @id, key
- end
-
- def coords(*args)
- @c.coords @id, *args
- end
-
- def dchars(first, last=None)
- @c.dchars @id, first, last
- end
-
- def dtag(tag_to_del=None)
- @c.dtag @id, tag_to_del
- end
-
- def find
- @c.find 'withtag', @id
- end
- alias list find
-
- def focus
- @c.itemfocus @id
- end
-
- def gettags
- @c.gettags @id
- end
-
- def icursor(index)
- @c.icursor @id, index
- end
-
- def index(index)
- @c.index @id, index
- end
-
- def insert(beforethis, string)
- @c.insert @id, beforethis, string
- end
-
- def lower(belowthis=None)
- @c.lower @id, belowthis
- end
-
- def move(xamount, yamount)
- @c.move @id, xamount, yamount
- end
-
- def raise(abovethis=None)
- @c.raise @id, abovethis
- end
-
- def scale(xorigin, yorigin, xscale, yscale)
- @c.scale @id, xorigin, yorigin, xscale, yscale
- end
-
- def select_adjust(index)
- @c.select('adjust', @id, index)
- end
- def select_from(index)
- @c.select('from', @id, index)
- end
- def select_to(index)
- @c.select('to', @id, index)
- end
-
- def itemtype
- @c.itemtype @id
- end
-
- # Followings operators supports logical expressions of canvas tags
- # (for Tk8.3+).
- # If tag1.path is 't1' and tag2.path is 't2', then
- # ltag = tag1 & tag2; ltag.path => "(t1)&&(t2)"
- # ltag = tag1 | tag2; ltag.path => "(t1)||(t2)"
- # ltag = tag1 ^ tag2; ltag.path => "(t1)^(t2)"
- # ltag = - tag1; ltag.path => "!(t1)"
- def & (tag)
- if tag.kind_of? TkObject
- TkcTagString.new(@c, '(' + @id + ')&&(' + tag.path + ')')
- else
- TkcTagString.new(@c, '(' + @id + ')&&(' + tag.to_s + ')')
- end
- end
-
- def | (tag)
- if tag.kind_of? TkObject
- TkcTagString.new(@c, '(' + @id + ')||(' + tag.path + ')')
- else
- TkcTagString.new(@c, '(' + @id + ')||(' + tag.to_s + ')')
- end
- end
-
- def ^ (tag)
- if tag.kind_of? TkObject
- TkcTagString.new(@c, '(' + @id + ')^(' + tag.path + ')')
- else
- TkcTagString.new(@c, '(' + @id + ')^(' + tag.to_s + ')')
- end
- end
-
- def -@
- TkcTagString.new(@c, '!(' + @id + ')')
- end
-end
-
-class TkcTag<TkObject
- include TkcTagAccess
-
- CTagID_TBL = {}
-
- def TkcTag.id2obj(canvas, id)
- cpath = canvas.path
- return id unless CTagID_TBL[cpath]
- CTagID_TBL[cpath][id]? CTagID_TBL[cpath][id]: id
- end
-
- Tk_CanvasTag_ID = ['ctag0000']
- def initialize(parent, mode=nil, *args)
- if not parent.kind_of?(TkCanvas)
- fail format("%s need to be TkCanvas", parent.inspect)
- end
- @c = parent
- @cpath = parent.path
- @path = @id = Tk_CanvasTag_ID[0]
- CTagID_TBL[@cpath] = {} unless CTagID_TBL[@cpath]
- CTagID_TBL[@cpath][@id] = self
- Tk_CanvasTag_ID[0] = Tk_CanvasTag_ID[0].succ
- if mode
- tk_call @c.path, "addtag", @id, mode, *args
- end
- end
- def id
- return @id
- end
-
- def delete
- @c.delete @id
- CTagID_TBL[@path][@id] = nil if CTagID_TBL[@path]
- end
- alias remove delete
- alias destroy delete
-
- def set_to_above(target)
- @c.addtag_above(@id, target)
- end
- alias above set_to_above
-
- def set_to_all
- @c.addtag_all(@id)
- end
- alias all set_to_all
-
- def set_to_below(target)
- @c.addtag_below(@id, target)
- end
- alias below set_to_below
-
- def set_to_closest(x, y, halo=None, start=None)
- @c.addtag_closest(@id, x, y, halo, start)
- end
- alias closest set_to_closest
-
- def set_to_enclosed(x1, y1, x2, y2)
- @c.addtag_enclosed(@id, x1, y1, x2, y2)
- end
- alias enclosed set_to_enclosed
-
- def set_to_overlapping(x1, y1, x2, y2)
- @c.addtag_overlapping(@id, x1, y1, x2, y2)
- end
- alias overlapping set_to_overlapping
-
- def set_to_withtag(target)
- @c.addtag_withtag(@id, target)
- end
- alias withtag set_to_withtag
-end
-
-class TkcTagString<TkcTag
- def self.new(parent, name, *args)
- if CTagID_TBL[parent.path] && CTagID_TBL[parent.path][name]
- return CTagID_TBL[parent.path][name]
- else
- super(parent, name, *args)
- end
- end
-
- def initialize(parent, name, mode=nil, *args)
- if not parent.kind_of?(TkCanvas)
- fail format("%s need to be TkCanvas", parent.inspect)
- end
- @c = parent
- @cpath = parent.path
- @path = @id = name
- CTagID_TBL[@cpath] = {} unless CTagID_TBL[@cpath]
- CTagID_TBL[@cpath][@id] = self
- if mode
- tk_call @c.path, "addtag", @id, mode, *args
- end
- end
-end
-
-class TkcTagAll<TkcTag
- def initialize(parent)
- if not parent.kind_of?(TkCanvas)
- fail format("%s need to be TkCanvas", parent.inspect)
- end
- @c = parent
- @cpath = parent.path
- @path = @id = 'all'
- CTagID_TBL[@cpath] = {} unless CTagID_TBL[@cpath]
- CTagID_TBL[@cpath][@id] = self
- end
-end
-
-class TkcTagCurrent<TkcTag
- def initialize(parent)
- if not parent.kind_of?(TkCanvas)
- fail format("%s need to be TkCanvas", parent.inspect)
- end
- @c = parent
- @cpath = parent.path
- @path = @id = 'current'
- CTagID_TBL[@cpath] = {} unless CTagID_TBL[@cpath]
- CTagID_TBL[@cpath][@id] = self
- end
-end
-
-class TkcGroup<TkcTag
- Tk_cGroup_ID = ['tkcg00000']
- def create_self(parent, *args)
- if not parent.kind_of?(TkCanvas)
- fail format("%s need to be TkCanvas", parent.inspect)
- end
- @c = parent
- @cpath = parent.path
- @path = @id = Tk_cGroup_ID[0]
- CTagID_TBL[@cpath] = {} unless CTagID_TBL[@cpath]
- CTagID_TBL[@cpath][@id] = self
- Tk_cGroup_ID[0] = Tk_cGroup_ID[0].succ
- add(*args) if args != []
- end
-
- def include(*tags)
- for i in tags
- i.addtag @id
- end
- end
-
- def exclude(*tags)
- for i in tags
- i.delete @id
- end
- end
-end
-
-class TkcItem<TkObject
- include TkcTagAccess
-
- CItemTypeToClass = {}
- CItemID_TBL = {}
-
- def TkcItem.type2class(type)
- CItemTypeToClass[type]
- end
-
- def TkcItem.id2obj(canvas, id)
- cpath = canvas.path
- return id unless CItemID_TBL[cpath]
- CItemID_TBL[cpath][id]? CItemID_TBL[cpath][id]: id
- end
-
- def initialize(parent, *args)
- if not parent.kind_of?(TkCanvas)
- fail format("%s need to be TkCanvas", parent.inspect)
- end
- @parent = @c = parent
- @path = parent.path
- fontkeys = {}
- if args[-1].kind_of? Hash
- args = args.dup
- keys = args.pop
- ['font', 'kanjifont', 'latinfont', 'asciifont'].each{|key|
- fontkeys[key] = keys.delete(key) if keys.key?(key)
- }
- args += hash_kv(keys)
- end
- @id = create_self(*args).to_i ;# 'canvas item id' is integer number
- CItemID_TBL[@path] = {} unless CItemID_TBL[@path]
- CItemID_TBL[@path][@id] = self
- font_configure(fontkeys) unless fontkeys.empty?
-
-######## old version
-# if args[-1].kind_of? Hash
-# keys = args.pop
-# end
-# @id = create_self(*args).to_i ;# 'canvas item id' is integer number
-# CItemID_TBL[@path] = {} unless CItemID_TBL[@path]
-# CItemID_TBL[@path][@id] = self
-# if keys
-# # tk_call @path, 'itemconfigure', @id, *hash_kv(keys)
-# configure(keys) if keys
-# end
-########
- end
- def create_self(*args); end
- private :create_self
- def id
- return @id
- end
-
- def delete
- @c.delete @id
- CItemID_TBL[@path][@id] = nil if CItemID_TBL[@path]
- end
- alias remove delete
- alias destroy delete
-end
-
-class TkcArc<TkcItem
- CItemTypeToClass['arc'] = self
- def create_self(*args)
- tk_call(@path, 'create', 'arc', *args)
- end
-end
-class TkcBitmap<TkcItem
- CItemTypeToClass['bitmap'] = self
- def create_self(*args)
- tk_call(@path, 'create', 'bitmap', *args)
- end
-end
-class TkcImage<TkcItem
- CItemTypeToClass['image'] = self
- def create_self(*args)
- tk_call(@path, 'create', 'image', *args)
- end
-end
-class TkcLine<TkcItem
- CItemTypeToClass['line'] = self
- def create_self(*args)
- tk_call(@path, 'create', 'line', *args)
- end
-end
-class TkcOval<TkcItem
- CItemTypeToClass['oval'] = self
- def create_self(*args)
- tk_call(@path, 'create', 'oval', *args)
- end
-end
-class TkcPolygon<TkcItem
- CItemTypeToClass['polygon'] = self
- def create_self(*args)
- tk_call(@path, 'create', 'polygon', *args)
- end
-end
-class TkcRectangle<TkcItem
- CItemTypeToClass['rectangle'] = self
- def create_self(*args)
- tk_call(@path, 'create', 'rectangle', *args)
- end
-end
-class TkcText<TkcItem
- CItemTypeToClass['text'] = self
- def create_self(*args)
- tk_call(@path, 'create', 'text', *args)
- end
-end
-class TkcWindow<TkcItem
- CItemTypeToClass['window'] = self
- def create_self(*args)
- tk_call(@path, 'create', 'window', *args)
- end
-end
-
-class TkImage<TkObject
- include Tk
-
- Tk_IMGTBL = {}
-
- Tk_Image_ID = ['i00000']
- def initialize(keys=nil)
- @path = Tk_Image_ID[0]
- Tk_Image_ID[0] = Tk_Image_ID[0].succ
- tk_call 'image', 'create', @type, @path, *hash_kv(keys)
- Tk_IMGTBL[@path] = self
- end
-
- def delete
- Tk_IMGTBL[@id] = nil if @id
- tk_call('image', 'delete', @path)
- end
- def height
- number(tk_call('image', 'height', @path))
- end
- def inuse
- bool(tk_call('image', 'inuse', @path))
- end
- def itemtype
- tk_call('image', 'type', @path)
- end
- def width
- number(tk_call('image', 'width', @path))
- end
-
- def TkImage.names
- Tk.tk_call('image', 'names').split.collect!{|id|
- (Tk_IMGTBL[id])? Tk_IMGTBL[id] : id
- }
- end
-
- def TkImage.types
- Tk.tk_call('image', 'types').split
- end
-end
-
-class TkBitmapImage<TkImage
- def initialize(*args)
- @type = 'bitmap'
- super
- end
-end
-
-class TkPhotoImage<TkImage
- def initialize(*args)
- @type = 'photo'
- super
- end
-
- def blank
- tk_send 'blank'
- end
-
- def cget(option)
- case option
- when 'data', 'file'
- tk_send 'cget', option
- else
- tk_tcl2ruby tk_send 'cget', option
- end
- end
-
- def copy(source, *opts)
- args = opts.collect{|term|
- if term.kind_of?(String) && term.include?(?\s)
- term.split
- else
- term
- end
- }.flatten
-
- tk_send 'copy', source, *args
- end
-
- def data(keys=nil)
- tk_send 'data', *hash_kv(keys)
- end
-
- def get(x, y)
- tk_send 'get', x, y
- end
-
- def put(data, *to)
- if to == []
- tk_send 'put', data
- else
- tk_send 'put', data, '-to', *to
- end
- end
-
- def read(file, *opts)
- args = opts.collect{|term|
- if term.kind_of?(String) && term.include?(?\s)
- term.split
- else
- term
- end
- }.flatten
-
- tk_send 'read', file, *args
- end
-
- def redither
- tk_send 'redither'
- end
-
- def write(file, *opts)
- args = opts.collect{|term|
- if term.kind_of?(String) && term.include?(?\s)
- term.split
- else
- term
- end
- }.flatten
-
- tk_send 'write', file, *args
- end
-end
diff --git a/ext/tk/lib/tkclass.rb b/ext/tk/lib/tkclass.rb
deleted file mode 100644
index 0b33d4ec8b..0000000000
--- a/ext/tk/lib/tkclass.rb
+++ /dev/null
@@ -1,38 +0,0 @@
-#
-# tkclass.rb - Tk classes
-# $Date$
-# by Yukihiro Matsumoto <matz@caelum.co.jp>
-
-require "tk"
-
-TopLevel = TkToplevel
-Frame = TkFrame
-Label = TkLabel
-Button = TkButton
-Radiobutton = TkRadioButton
-Checkbutton = TkCheckButton
-Message = TkMessage
-Entry = TkEntry
-Text = TkText
-Scale = TkScale
-Scrollbar = TkScrollbar
-Listbox = TkListbox
-Menu = TkMenu
-Menubutton = TkMenubutton
-Canvas = TkCanvas
-Arc = TkcArc
-Bitmap = TkcBitmap
-Line = TkcLine
-Oval = TkcOval
-Polygon = TkcPolygon
-Rectangle = TkcRectangle
-TextItem = TkcText
-WindowItem = TkcWindow
-Selection = TkSelection
-Winfo = TkWinfo
-Pack = TkPack
-Variable = TkVariable
-
-def Mainloop
- Tk.mainloop
-end
diff --git a/ext/tk/lib/tkdialog.rb b/ext/tk/lib/tkdialog.rb
deleted file mode 100644
index 1133db6ae9..0000000000
--- a/ext/tk/lib/tkdialog.rb
+++ /dev/null
@@ -1,141 +0,0 @@
-require "tk"
-
-class TkDialog < TkWindow
- extend Tk
-
- # initialize tk_dialog
- def initialize(keys = nil)
- super()
- @var = TkVariable.new
- id = @var.id
-
- @title = title
-
- @message = message
- @message_config = message_config
-
- @bitmap = bitmap
- @bitmap_config = message_config
-
- @default_button = default_button
-
- @buttons = buttons
- @button_configs = proc{|num| button_configs num}
-
- if keys.kind_of? Hash
- @title = keys['title'] if keys['title']
- @message = keys['message'] if keys['message']
- @bitmap = keys['bitmap'] if keys['bitmap']
- @default_button = keys['default'] if keys['default']
- @buttons = keys['buttons'] if keys['buttons']
-
- @command = keys['prev_command']
-
- @message_config = keys['message_config'] if keys['message_config']
- @bitmap_config = keys['bitmap_config'] if keys['bitmap_config']
- @button_configs = keys['button_configs'] if keys['button_configs']
- end
-
- if @title.include? ?\s
- @title = '{' + @title + '}'
- end
-
- @buttons = tk_split_list(@buttons) if @buttons.kind_of? String
- @buttons = @buttons.collect{|s|
- if s.kind_of? Array
- s = s.join(' ')
- end
- if s.include? ?\s
- '{' + s + '}'
- else
- s
- end
- }
-
- config = ""
- if @message_config.kind_of? Hash
- config << format("%s.msg configure %s\n",
- @path, hash_kv(@message_config).join(' '))
- end
- if @bitmap_config.kind_of? Hash
- config << format("%s.msg configure %s\n",
- @path, hash_kv(@bitmap_config).join(' '))
- end
- if @button_configs.kind_of? Proc
- @buttons.each_index{|i|
- if (c = @button_configs.call(i)).kind_of? Hash
- config << format("%s.button%s configure %s\n",
- @path, i, hash_kv(c).join(' '))
- end
- }
- end
- config = 'after idle {' + config + '};' if config != ""
-
- if @command.kind_of? Proc
- @command.call(self)
- end
-
- INTERP._eval('eval {global '+id+';'+config+
- 'set '+id+' [tk_dialog '+
- @path+" "+@title+" {#{@message}} "+@bitmap+" "+
- String(@default_button)+" "+@buttons.join(' ')+']}')
- end
- def value
- return @var.value.to_i
- end
- ######################################################
- # #
- # these methods must be overridden for each dialog #
- # #
- ######################################################
- def title
- return "DIALOG"
- end
- def message
- return "MESSAGE"
- end
- def message_config
- return nil
- end
- def bitmap
- return "info"
- end
- def bitmap_config
- return nil
- end
- def default_button
- return 0
- end
- def buttons
- #return "BUTTON1 BUTTON2"
- return ["BUTTON1", "BUTTON2"]
- end
- def button_configs(num)
- return nil
- end
-end
-
-#
-# dialog for warning
-#
-class TkWarning < TkDialog
- def initialize(mes)
- @mes = mes
- super()
- end
- def message
- return @mes
- end
- def title
- return "WARNING";
- end
- def bitmap
- return "warning";
- end
- def default_button
- return 0;
- end
- def buttons
- return "OK";
- end
-end
diff --git a/ext/tk/lib/tkentry.rb b/ext/tk/lib/tkentry.rb
deleted file mode 100644
index f301bbdace..0000000000
--- a/ext/tk/lib/tkentry.rb
+++ /dev/null
@@ -1,221 +0,0 @@
-#
-# tkentry.rb - Tk entry classes
-# $Date$
-# by Yukihiro Matsumoto <matz@caelum.co.jp>
-
-require 'tk.rb'
-
-class TkEntry<TkLabel
- include Scrollable
-
- WidgetClassName = 'Entry'.freeze
- WidgetClassNames[WidgetClassName] = self
- def self.to_eval
- WidgetClassName
- end
-
- class ValidateCmd
- include TkComm
-
- class ValidateArgs
- def initialize(d,i,s,v,pp,ss,vv,ww)
- @action = d
- @index = i
- @current = s
- @type = v
- @value = pp
- @string = ss
- @triggered = vv
- @widget = ww
- end
- attr :action
- attr :index
- attr :current
- attr :type
- attr :value
- attr :string
- attr :triggered
- attr :widget
- end
-
- def initialize(cmd = Proc.new, args=nil)
- if args
- @id = install_cmd(proc{|*arg|
- TkUtil.eval_cmd cmd, *arg
- }) + " " + args
- else
- @id = install_cmd(proc{|arg|
- TkUtil.eval_cmd cmd, ValidateArgs.new(*arg)
- }) + ' %d %i %s %v %P %S %V %W'
- end
- end
-
- def to_eval
- @id
- end
- end
-
- def create_self(keys)
- if keys and keys != None
- tk_call 'entry', @path, *hash_kv(keys)
- else
- tk_call 'entry', @path
- end
- end
-
- def bbox(index)
- tk_send 'bbox', index
- end
-
- def delete(s, e=None)
- tk_send 'delete', s, e
- end
-
- def configure(slot, value=None)
- if slot.kind_of? Hash
- if slot['vcmd'].kind_of? Array
- cmd, *args = slot['vcmd']
- slot['vcmd'] = ValidateCmd.new(cmd, args.join(' '))
- elsif slot['vcmd'].kind_of? Proc
- slot['vcmd'] = ValidateCmd.new(slot['vcmd'])
- end
- if slot['validatecommand'].kind_of? Array
- cmd, *args = slot['validatecommand']
- slot['validatecommand'] = ValidateCmd.new(cmd, args.join(' '))
- elsif slot['validatecommand'].kind_of? Proc
- slot['validatecommand'] = ValidateCmd.new(slot['validatecommand'])
- end
- if slot['invcmd'].kind_of? Array
- cmd, *args = slot['invcmd']
- slot['invcmd'] = ValidateCmd.new(cmd, args.join(' '))
- elsif slot['invcmd'].kind_of? Proc
- slot['invcmd'] = ValidateCmd.new(slot['invcmd'])
- end
- if slot['invalidcommand'].kind_of? Array
- cmd, *args = slot['invalidcommand']
- slot['invalidcommand'] = ValidateCmd.new(cmd, args.join(' '))
- elsif slot['invalidcommand'].kind_of? Proc
- slot['invalidcommand'] = ValidateCmd.new(slot['invalidcommand'])
- end
- super(slot)
- else
- if (slot == 'vcmd' || slot == 'validatecommand' ||
- slot == 'invcmd' || slot == 'invalidcommand')
- if value.kind_of? Array
- cmd, *args = value
- value = ValidateCmd.new(cmd, args.join(' '))
- elsif value.kind_of? Proc
- value = ValidateCmd.new(value)
- end
- end
- super(slot, value)
- end
- end
-
- def cursor
- tk_send 'index', 'insert'
- end
- def cursor=(index)
- tk_send 'icursor', index
- end
- def index(index)
- number(tk_send('index', index))
- end
- def insert(pos,text)
- tk_send 'insert', pos, text
- end
- def mark(pos)
- tk_send 'scan', 'mark', pos
- end
- def dragto(pos)
- tk_send 'scan', 'dragto', pos
- end
- def selection_adjust(index)
- tk_send 'selection', 'adjust', index
- end
- def selection_clear
- tk_send 'selection', 'clear'
- end
- def selection_from(index)
- tk_send 'selection', 'from', index
- end
- def selection_present()
- bool(tk_send('selection', 'present'))
- end
- def selection_range(s, e)
- tk_send 'selection', 'range', s, e
- end
- def selection_to(index)
- tk_send 'selection', 'to', index
- end
-
- def validate(mode = nil)
- if mode
- configure 'validate', mode
- else
- if tk_send('validate') == '0'
- false
- else
- true
- end
- end
- end
-
- def validatecommand(cmd = ValidateCmd.new, args = nil)
- if cmd.kind_of?(ValidateCmd)
- configure('validatecommand', cmd)
- else
- configure('validatecommand', ValidateCmd.new(cmd, args))
- end
- end
- alias vcmd validatecommand
-
- def invalidcommand(cmd = ValidateCmd.new, args = nil)
- if cmd.kind_of?(ValidateCmd)
- configure('invalidcommand', cmd)
- else
- configure('invalidcommand', ValidateCmd.new(cmd, args))
- end
- end
- alias invcmd invalidcommand
-
- def value
- tk_send 'get'
- end
- def value= (val)
- tk_send 'delete', 0, 'end'
- tk_send 'insert', 0, val
- end
-end
-
-class TkSpinbox<TkEntry
- WidgetClassName = 'Spinbox'.freeze
- WidgetClassNames[WidgetClassName] = self
- def self.to_eval
- WidgetClassName
- end
-
- def create_self(keys)
- if keys and keys != None
- tk_call 'spinbox', @path, *hash_kv(keys)
- else
- tk_call 'spinbox', @path
- end
- end
-
- def identify(x, y)
- tk_send 'identify', x, y
- end
-
- def spinup
- tk_send 'invoke', 'spinup'
- end
-
- def spindown
- tk_send 'invoke', 'spindown'
- end
-
- def set(str)
- tk_send 'set', str
- end
-end
diff --git a/ext/tk/lib/tkfont.rb b/ext/tk/lib/tkfont.rb
deleted file mode 100644
index c84d0960ed..0000000000
--- a/ext/tk/lib/tkfont.rb
+++ /dev/null
@@ -1,1042 +0,0 @@
-#
-# tkfont.rb - the class to treat fonts on Ruby/Tk
-#
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-require 'tk'
-
-class TkFont
- include Tk
- extend TkCore
-
- Tk_FontID = [0]
- Tk_FontNameTBL = {}
- Tk_FontUseTBL = {}
-
- # set default font
- case Tk::TK_VERSION
- when /^4\.*/
- DEFAULT_LATIN_FONT_NAME = 'a14'.freeze
- DEFAULT_KANJI_FONT_NAME = 'k14'.freeze
- when /^8\.*/
- if JAPANIZED_TK
- begin
- fontnames = tk_call('font', 'names')
- case fontnames
- when /defaultgui/
- # Tcl/Tk-JP for Windows
- ltn = 'defaultgui'
- knj = 'defaultgui'
- when /Mincho:Helvetica-12/
- # Tcl/Tk-JP for UNIX/X
- ltn, knj = tk_split_simplelist(tk_call('font', 'configure',
- 'Mincho:Helvetica-12',
- '-compound'))
- else
- # unknown Tcl/Tk-JP
- platform = tk_call('set', 'tcl_platform(platform)')
- case platform
- when 'unix'
- ltn = {'family'=>'Helvetica'.freeze, 'size'=>-12}
- knj = 'k14'
- #knj = '-misc-fixed-medium-r-normal--14-*-*-*-c-*-jisx0208.1983-0'
- when 'windows'
- ltn = {'family'=>'MS Sans Serif'.freeze, 'size'=>8}
- knj = 'mincho'
- when 'macintosh'
- ltn = 'system'
- knj = 'mincho'
- else # unknown
- ltn = 'Helvetica'
- knj = 'mincho'
- end
- end
- rescue
- ltn = 'Helvetica'
- knj = 'mincho'
- end
-
- else # not JAPANIZED_TK
- begin
- platform = tk_call('set', 'tcl_platform(platform)')
- case platform
- when 'unix'
- ltn = {'family'=>'Helvetica'.freeze, 'size'=>-12}
- knj = 'k14'
- #knj = '-misc-fixed-medium-r-normal--14-*-*-*-c-*-jisx0208.1983-0'
- when 'windows'
- ltn = {'family'=>'MS Sans Serif'.freeze, 'size'=>8}
- knj = 'mincho'
- when 'macintosh'
- ltn = 'system'
- knj = 'mincho'
- else # unknown
- ltn = 'Helvetica'
- knj = 'mincho'
- end
- rescue
- ltn = 'Helvetica'
- knj = 'mincho'
- end
- end
-
- DEFAULT_LATIN_FONT_NAME = ltn.freeze
- DEFAULT_KANJI_FONT_NAME = knj.freeze
-
- else # unknown version
- DEFAULT_LATIN_FONT_NAME = 'Helvetica'.freeze
- DEFAULT_KANJI_FONT_NAME = 'mincho'.freeze
-
- end
-
- if $DEBUG
- print "default latin font = "; p DEFAULT_LATIN_FONT_NAME
- print "default kanji font = "; p DEFAULT_KANJI_FONT_NAME
- end
-
- ###################################
- # class methods
- ###################################
- def TkFont.families(window=nil)
- case (Tk::TK_VERSION)
- when /^4\.*/
- ['fixed']
-
- when /^8\.*/
- if window
- tk_split_simplelist(tk_call('font', 'families', '-displayof', window))
- else
- tk_split_simplelist(tk_call('font', 'families'))
- end
- end
- end
-
- def TkFont.names
- case (Tk::TK_VERSION)
- when /^4\.*/
- r = ['fixed']
- r += ['a14', 'k14'] if JAPANIZED_TK
- Tk_FontNameTBL.each_value{|obj| r.push(obj)}
- r | []
-
- when /^8\.*/
- tk_split_simplelist(tk_call('font', 'names'))
-
- end
- end
-
- def TkFont.create_copy(font)
- fail 'source-font need to be TkFont' unless font.kind_of? TkFont
- keys = {}
- font.configinfo.each{|key,value| keys[key] = value }
- TkFont.new(font.latin_font, font.kanji_font, keys)
- end
-
- def TkFont.get_obj(name)
- if name =~ /^(@font[0-9]+)(|c|l|k)$/
- Tk_FontNameTBL[$1]
- else
- nil
- end
- end
-
- def TkFont.init_widget_font(path, *args)
- case (Tk::TK_VERSION)
- when /^4\.*/
- conf = tk_split_simplelist(tk_call(*args)).
- find_all{|prop| prop[0..5]=='-font ' || prop[0..10]=='-kanjifont '}.
- collect{|prop| tk_split_simplelist(prop)}
- if font_inf = conf.assoc('-font')
- ltn = font_inf[4]
- ltn = nil if ltn == []
- else
- #ltn = nil
- raise RuntimeError, "unknown option '-font'"
- end
- if font_inf = conf.assoc('-kanjifont')
- knj = font_inf[4]
- knj = nil if knj == []
- else
- knj = nil
- end
- TkFont.new(ltn, knj).call_font_configure(path, *(args + [{}]))
-
- when /^8\.*/
- font_prop = tk_split_simplelist(tk_call(*args)).find{|prop|
- prop[0..5] == '-font '
- }
- unless font_prop
- raise RuntimeError, "unknown option '-font'"
- end
- fnt = tk_split_simplelist(font_prop)[4]
- if fnt == ""
- TkFont.new(nil, nil).call_font_configure(path, *(args + [{}]))
- else
- begin
- compound = Hash[*tk_split_simplelist(tk_call('font', 'configure',
- fnt))].collect{|key,value|
- [key[1..-1], value]
- }.assoc('compound')[1]
- rescue
- compound = []
- end
- if compound == []
- TkFont.new(fnt, DEFAULT_KANJI_FONT_NAME) \
- .call_font_configure(path, *(args + [{}]))
- else
- TkFont.new(compound[0], compound[1]) \
- .call_font_configure(path, *(args + [{}]))
- end
- end
- end
- end
-
- def TkFont.used_on(path=nil)
- if path
- Tk_FontUseTBL[path]
- else
- Tk_FontUseTBL.values | []
- end
- end
-
- def TkFont.failsafe(font)
- begin
- if /^8\.*/ === Tk::TK_VERSION && JAPANIZED_TK
- tk_call('font', 'failsafe', font)
- end
- rescue
- end
- end
-
- ###################################
- private
- ###################################
- def initialize(ltn=DEFAULT_LATIN_FONT_NAME, knj=nil, keys=nil)
- @id = format("@font%.4d", Tk_FontID[0])
- Tk_FontID[0] += 1
- Tk_FontNameTBL[@id] = self
- knj = DEFAULT_KANJI_FONT_NAME if JAPANIZED_TK && !knj
- create_compoundfont(ltn, knj, keys)
- end
-
- def _get_font_info_from_hash(font)
- foundry = (info = font['foundry'] .to_s)? info: '*'
- family = (info = font['family'] .to_s)? info: '*'
- weight = (info = font['weight'] .to_s)? info: '*'
- slant = (info = font['slant'] .to_s)? info: '*'
- swidth = (info = font['swidth'] .to_s)? info: '*'
- adstyle = (info = font['adstyle'] .to_s)? info: '*'
- pixels = (info = font['pixels'] .to_s)? info: '*'
- points = (info = font['points'] .to_s)? info: '*'
- resx = (info = font['resx'] .to_s)? info: '*'
- resy = (info = font['resy'] .to_s)? info: '*'
- space = (info = font['space'] .to_s)? info: '*'
- avgWidth = (info = font['avgWidth'].to_s)? info: '*'
- charset = (info = font['charset'] .to_s)? info: '*'
- encoding = (info = font['encoding'].to_s)? info: '*'
-
- [foundry, family, weight, slant, swidth, adstyle,
- pixels, points, resx, resy, space, avgWidth, charset, encoding]
- end
-
- def create_latinfont_tk4x(font)
- if font.kind_of? Hash
- @latinfont = '-' + _get_font_info_from_hash(font).join('-') + '-'
-
- elsif font.kind_of? Array
- finfo = {}
- finfo['family'] = font[0].to_s
- if font[1]
- fsize = font[1].to_s
- if fsize != '0' && fsize =~ /^(|\+|-)([0-9]+)$/
- if $1 == '-'
- finfo['pixels'] = $2
- else
- finfo['points'] = $2
- end
- else
- finfo['points'] = '13'
- end
- end
- font[2..-1].each{|style|
- case (style)
- when 'normal'
- finfo['weight'] = style
- when 'bold'
- finfo['weight'] = style
- when 'roman'
- finfo['slant'] = 'r'
- when 'italic'
- finfo['slant'] = 'i'
- end
- }
-
- @latinfont = '-' + _get_font_info_from_hash(finfo).join('-') + '-'
-
- elsif font.kind_of? TkFont
- @latinfont = font.latin_font
-
- else
- if font
- @latinfont = font
- else
- @latinfont = DEFAULT_LATIN_FONT_NAME
- end
-
- end
- end
-
- def create_kanjifont_tk4x(font)
- unless JAPANIZED_TK
- @kanjifont = ""
- return
- end
-
- if font.kind_of? Hash
- @kanjifont = '-' + _get_font_info_from_hash(font).join('-') + '-'
-
- elsif font.kind_of? Array
- finfo = {}
- finfo['family'] = font[0].to_s
- if font[1]
- fsize = font[1].to_s
- if fsize != '0' && fsize =~ /^(|\+|-)([0-9]+)$/
- if $1 == '-'
- finfo['pixels'] = $2
- else
- finfo['points'] = $2
- end
- else
- finfo['points'] = '13'
- end
- end
- font[2..-1].each{|style|
- case (style)
- when 'normal'
- finfo['weight'] = style
- when 'bold'
- finfo['weight'] = style
- when 'roman'
- finfo['slant'] = 'r'
- when 'italic'
- finfo['slant'] = 'i'
- end
- }
-
- @kanjifont = '-' + _get_font_info_from_hash(finfo).join('-') + '-'
- elsif font.kind_of? TkFont
- @kanjifont = font.kanji_font
- else
- if font
- @kanjifont = font
- else
- @kanjifont = DEFAULT_KANJI_FONT_NAME
- end
- end
- end
-
- def create_compoundfont_tk4x(ltn, knj, keys)
- create_latinfont(ltn)
- create_kanjifont(knj)
-
- if JAPANIZED_TK
- @compoundfont = [[@latinfont], [@kanjifont]]
- @fontslot = {'font'=>@latinfont, 'kanjifont'=>@kanjifont}
- else
- @compoundfont = @latinfont
- @fontslot = {'font'=>@latinfont}
- end
- end
-
- def create_latinfont_tk8x(font)
- @latinfont = @id + 'l'
-
- if JAPANIZED_TK
- if font.kind_of? Hash
- if font['charset']
- tk_call('font', 'create', @latinfont, *hash_kv(font))
- else
- tk_call('font', 'create', @latinfont,
- '-charset', 'iso8859', *hash_kv(font))
- end
- elsif font.kind_of? Array
- tk_call('font', 'create', @latinfont, '-copy', array2tk_list(font))
- tk_call('font', 'configure', @latinfont, '-charset', 'iso8859')
- elsif font.kind_of? TkFont
- tk_call('font', 'create', @latinfont, '-copy', font.latin_font)
- elsif font
- tk_call('font', 'create', @latinfont, '-copy', font,
- '-charset', 'iso8859')
- else
- tk_call('font', 'create', @latinfont, '-charset', 'iso8859')
- end
- else
- if font.kind_of? Hash
- tk_call('font', 'create', @latinfont, *hash_kv(font))
- else
- keys = {}
- if font.kind_of? Array
- actual_core(array2tk_list(font)).each{|key,val| keys[key] = val}
- elsif font.kind_of? TkFont
- actual_core(font.latin_font).each{|key,val| keys[key] = val}
- elsif font
- actual_core(font).each{|key,val| keys[key] = val}
- end
- tk_call('font', 'create', @latinfont, *hash_kv(keys))
- end
-
- if font && @compoundfont
- keys = {}
- actual_core(@latinfont).each{|key,val| keys[key] = val}
- tk_call('font', 'configure', @compoundfont, *hash_kv(keys))
- end
- end
- end
-
- def create_kanjifont_tk8x(font)
- @kanjifont = @id + 'k'
-
- if JAPANIZED_TK
- if font.kind_of? Hash
- if font['charset']
- tk_call('font', 'create', @kanjifont, *hash_kv(font))
- else
- tk_call('font', 'create', @kanjifont,
- '-charset', 'jisx0208.1983', *hash_kv(font))
- end
- elsif font.kind_of? Array
- tk_call('font', 'create', @kanjifont, '-copy', array2tk_list(font))
- tk_call('font', 'configure', @kanjifont, '-charset', 'jisx0208.1983')
- elsif font.kind_of? TkFont
- tk_call('font', 'create', @kanjifont, '-copy', font.kanji_font)
- elsif font
- tk_call('font', 'create', @kanjifont, '-copy', font,
- '-charset', 'jisx0208.1983')
- else
- tk_call('font', 'create', @kanjifont, '-charset', 'jisx0208.1983')
- end
- # end of JAPANIZED_TK
-
- else
- if font.kind_of? Hash
- tk_call('font', 'create', @kanjifont, *hash_kv(font))
- else
- keys = {}
- if font.kind_of? Array
- actual_core(array2tk_list(font)).each{|key,val| keys[key] = val}
- elsif font.kind_of? TkFont
- actual_core(font.kanji_font).each{|key,val| keys[key] = val}
- elsif font
- actual_core(font).each{|key,val| keys[key] = val}
- end
- tk_call('font', 'create', @kanjifont, *hash_kv(keys))
- end
-
- if font && @compoundfont
- keys = {}
- actual_core(@kanjifont).each{|key,val| keys[key] = val}
- tk_call('font', 'configure', @compoundfont, *hash_kv(keys))
- end
- end
- end
-
- def create_compoundfont_tk8x(ltn, knj, keys)
- create_latinfont(ltn)
- create_kanjifont(knj)
-
- @compoundfont = @id + 'c'
- if JAPANIZED_TK
- @fontslot = {'font'=>@compoundfont}
- tk_call('font', 'create', @compoundfont,
- '-compound', [@latinfont, @kanjifont], *hash_kv(keys))
- else
- tk_call('font', 'create', @compoundfont)
-
- latinkeys = {}
- begin
- actual_core(@latinfont).each{|key,val| latinkeys[key] = val}
- rescue
- latinkeys {}
- end
- if latinkeys != {}
- tk_call('font', 'configure', @compoundfont, *hash_kv(latinkeys))
- end
-
- if knj
- kanjikeys = {}
- begin
- actual_core(@kanjifont).each{|key,val| kanjikeys[key] = val}
- rescue
- kanjikeys {}
- end
- if kanjikeys != {}
- tk_call('font', 'configure', @compoundfont, *hash_kv(kanjikeys))
- end
- end
-
- @fontslot = {'font'=>@compoundfont}
- tk_call('font', 'configure', @compoundfont, *hash_kv(keys))
- end
- end
-
- def actual_core_tk4x(font, window=nil, option=nil)
- # dummy
- if option
- ""
- else
- [['family',[]], ['size',[]], ['weight',[]], ['slant',[]],
- ['underline',[]], ['overstrike',[]], ['charset',[]],
- ['pointadjust',[]]]
- end
- end
-
- def actual_core_tk8x(font, window=nil, option=nil)
- if option == 'compound'
- ""
- elsif option
- if window
- tk_call('font', 'actual', font, "-displayof", window, "-#{option}")
- else
- tk_call('font', 'actual', font, "-#{option}")
- end
- else
- l = tk_split_simplelist(if window
- tk_call('font', 'actual', font,
- "-displayof", window)
- else
- tk_call('font', 'actual', font)
- end)
- r = []
- while key=l.shift
- if key == '-compound'
- l.shift
- else
- r.push [key[1..-1], l.shift]
- end
- end
- r
- end
- end
-
- def configure_core_tk4x(font, slot, value=None)
- ""
- end
-
- def configinfo_core_tk4x(font, option=nil)
- # dummy
- if option
- ""
- else
- [['family',[]], ['size',[]], ['weight',[]], ['slant',[]],
- ['underline',[]], ['overstrike',[]], ['charset',[]],
- ['pointadjust',[]]]
- end
- end
-
- def configure_core_tk8x(font, slot, value=None)
- if slot.kind_of? Hash
- tk_call 'font', 'configure', font, *hash_kv(slot)
- else
- tk_call 'font', 'configure', font, "-#{slot}", value
- end
- end
-
- def configinfo_core_tk8x(font, option=nil)
- if option == 'compound'
- ""
- elsif option
- tk_call('font', 'configure', font, "-#{option}")
- else
- l = tk_split_simplelist(tk_call('font', 'configure', font))
- r = []
- while key=l.shift
- if key == '-compound'
- l.shift
- else
- r.push [key[1..-1], l.shift]
- end
- end
- r
- end
- end
-
- def delete_core_tk4x
- Tk_FontNameTBL[@id] = nil
- Tk_FontUseTBL.delete_if{|key,value| value == self}
- end
-
- def delete_core_tk8x
- begin
- tk_call('font', 'delete', @latinfont)
- rescue
- end
- begin
- tk_call('font', 'delete', @kanjifont)
- rescue
- end
- begin
- tk_call('font', 'delete', @compoundfont)
- rescue
- end
- Tk_FontNameTBL[@id] = nil
- Tk_FontUseTBL.delete_if{|key,value| value == self}
- end
-
- def latin_replace_core_tk4x(ltn)
- create_latinfont_tk4x(ltn)
- @compoundfont[0] = [@latinfont] if JAPANIZED_TK
- @fontslot['font'] = @latinfont
- Tk_FontUseTBL.dup.each{|w, fobj|
- if self == fobj
- begin
- if w.include?(';')
- win, tag = w.split(';')
- winobj = tk_tcl2ruby(win)
-# winobj.tagfont_configure(tag, {'font'=>@latinfont})
- if winobj.kind_of? TkText
- tk_call(win, 'tag', 'configure', tag, '-font', @latinfont)
- elsif winobj.kind_of? TkCanvas
- tk_call(win, 'itemconfigure', tag, '-font', @latinfont)
- elsif winobj.kind_of? TkMenu
- tk_call(win, 'entryconfigure', tag, '-font', @latinfont)
- else
- raise RuntimeError, "unknown widget type"
- end
- else
-# tk_tcl2ruby(w).font_configure('font'=>@latinfont)
- tk_call(w, 'configure', '-font', @latinfont)
- end
- rescue
- Tk_FontUseTBL[w] = nil
- end
- end
- }
- self
- end
-
- def kanji_replace_core_tk4x(knj)
- return self unless JAPANIZED_TK
-
- create_kanjifont_tk4x(knj)
- @compoundfont[1] = [@kanjifont]
- @fontslot['kanjifont'] = @kanjifont
- Tk_FontUseTBL.dup.each{|w, fobj|
- if self == fobj
- begin
- if w.include?(';')
- win, tag = w.split(';')
- winobj = tk_tcl2ruby(win)
-# winobj.tagfont_configure(tag, {'kanjifont'=>@kanjifont})
- if winobj.kind_of? TkText
- tk_call(win, 'tag', 'configure', tag, '-kanjifont', @kanjifont)
- elsif winobj.kind_of? TkCanvas
- tk_call(win, 'itemconfigure', tag, '-kanjifont', @kanjifont)
- elsif winobj.kind_of? TkMenu
- tk_call(win, 'entryconfigure', tag, '-kanjifont', @latinfont)
- else
- raise RuntimeError, "unknown widget type"
- end
- else
-# tk_tcl2ruby(w).font_configure('kanjifont'=>@kanjifont)
- tk_call(w, 'configure', '-kanjifont', @kanjifont)
- end
- rescue
- Tk_FontUseTBL[w] = nil
- end
- end
- }
- self
- end
-
- def latin_replace_core_tk8x(ltn)
- begin
- tk_call('font', 'delete', @latinfont)
- rescue
- end
- create_latinfont(ltn)
- self
- end
-
- def kanji_replace_core_tk8x(knj)
- begin
- tk_call('font', 'delete', @kanjifont)
- rescue
- end
- create_kanjifont(knj)
- self
- end
-
- def measure_core_tk4x(window, text)
- 0
- end
-
- def measure_core_tk8x(window, text)
- if window
- number(tk_call('font', 'measure', @compoundfont,
- '-displayof', window, text))
- else
- number(tk_call('font', 'measure', @compoundfont, text))
- end
- end
-
- def metrics_core_tk4x(font, window, option=nil)
- # dummy
- if option
- ""
- else
- [['ascent',[]], ['descent',[]], ['linespace',[]], ['fixed',[]]]
- end
- end
-
- def metrics_core_tk8x(font, window, option=nil)
- if option
- if window
- number(tk_call('font', 'metrics', font,
- "-displayof", window, "-#{option}"))
- else
- number(tk_call('font', 'metrics', font, "-#{option}"))
- end
- else
- l = tk_split_list(if window
- tk_call('font','metrics',font,"-displayof",window)
- else
- tk_call('font','metrics',font)
- end)
- r = []
- while key=l.shift
- r.push [key[1..-1], l.shift.to_i]
- end
- r
- end
- end
-
- ###################################
- # private alias
- ###################################
- case (Tk::TK_VERSION)
- when /^4\.*/
- alias create_latinfont create_latinfont_tk4x
- alias create_kanjifont create_kanjifont_tk4x
- alias create_compoundfont create_compoundfont_tk4x
- alias actual_core actual_core_tk4x
- alias configure_core configure_core_tk4x
- alias configinfo_core configinfo_core_tk4x
- alias delete_core delete_core_tk4x
- alias latin_replace_core latin_replace_core_tk4x
- alias kanji_replace_core kanji_replace_core_tk4x
- alias measure_core measure_core_tk4x
- alias metrics_core metrics_core_tk4x
-
- when /^8\.[0123]/
- alias create_latinfont create_latinfont_tk8x
- alias create_kanjifont create_kanjifont_tk8x
- alias create_compoundfont create_compoundfont_tk8x
- alias actual_core actual_core_tk8x
- alias configure_core configure_core_tk8x
- alias configinfo_core configinfo_core_tk8x
- alias delete_core delete_core_tk8x
- alias latin_replace_core latin_replace_core_tk8x
- alias kanji_replace_core kanji_replace_core_tk8x
- alias measure_core measure_core_tk8x
- alias metrics_core metrics_core_tk8x
-
- when /^8\.*/
- alias create_latinfont create_latinfont_tk8x
- alias create_kanjifont create_kanjifont_tk8x
- alias create_compoundfont create_compoundfont_tk8x
- alias actual_core actual_core_tk8x
- alias configure_core configure_core_tk8x
- alias configinfo_core configinfo_core_tk8x
- alias delete_core delete_core_tk8x
- alias latin_replace_core latin_replace_core_tk8x
- alias kanji_replace_core kanji_replace_core_tk8x
- alias measure_core measure_core_tk8x
- alias metrics_core metrics_core_tk8x
-
- end
-
- ###################################
- public
- ###################################
- def method_missing(id, *args)
- name = id.id2name
- case args.length
- when 1
- configure name, args[0]
- when 0
- begin
- configinfo name
- rescue
- fail NameError, "undefined local variable or method `#{name}' for #{self.to_s}", error_at
- end
- else
- fail NameError, "undefined method `#{name}' for #{self.to_s}", error_at
- end
- end
-
- def call_font_configure(path, *args)
- args += hash_kv(args.pop.update(@fontslot))
- tk_call(*args)
- Tk_FontUseTBL[path] = self
- self
- end
-
- def used
- ret = []
- Tk_FontUseTBL.each{|key,value|
- if key.include?(';')
- win, tag = key.split(';')
- winobj = tk_tcl2ruby(win)
- if winobj.kind_of? TkText
- ret.push([winobj, winobj.tagid2obj(tag)])
- elsif winobj.kind_of? TkCanvas
- if (tagobj = TkcTag.id2obj(winobj, tag)).kind_of? TkcTag
- ret.push([winobj, tagobj])
- elsif (tagobj = TkcItem.id2obj(tag)).kind_of? TkcItem
- ret.push([winobj, tagobj])
- else
- ret.push([winobj, tag])
- end
- elsif winobj.kind_of? TkMenu
- ret.push([winobj, tag])
- else
- ret.push([win, tag])
- end
- else
- ret.push(tk_tcl2ruby(key)) if value == self
- end
- }
- ret
- end
-
- def id
- @id
- end
-
- def to_eval
- font
- end
-
- def font
- @compoundfont
- end
-
- def latin_font
- @latinfont
- end
-
- def kanji_font
- @kanjifont
- end
-
- def actual(option=nil)
- actual_core(@compoundfont, nil, option)
- end
-
- def actual_displayof(window, option=nil)
- window = '.' unless window
- actual_core(@compoundfont, window, option)
- end
-
- def latin_actual(option=nil)
- actual_core(@latinfont, nil, option)
- end
-
- def latin_actual_displayof(window, option=nil)
- window = '.' unless window
- actual_core(@latinfont, window, option)
- end
-
- def kanji_actual(option=nil)
- #if JAPANIZED_TK
- if @kanjifont != ""
- actual_core(@kanjifont, nil, option)
- else
- actual_core_tk4x(nil, nil, option)
- end
- end
-
- def kanji_actual_displayof(window, option=nil)
- #if JAPANIZED_TK
- if @kanjifont != ""
- window = '.' unless window
- actual_core(@kanjifont, window, option)
- else
- actual_core_tk4x(nil, window, option)
- end
- end
-
- def [](slot)
- configinfo slot
- end
-
- def []=(slot, val)
- configure slot, val
- end
-
- def configure(slot, value=None)
- configure_core(@compoundfont, slot, value)
- end
-
- def configinfo(slot=nil)
- configinfo_core(@compoundfont, slot)
- end
-
- def delete
- delete_core
- end
-
- def latin_configure(slot, value=None)
- if JAPANIZED_TK
- configure_core(@latinfont, slot, value)
- else
- configure(slot, value)
- end
- end
-
- def latin_configinfo(slot=nil)
- if JAPANIZED_TK
- configinfo_core(@latinfont, slot)
- else
- configinfo(slot)
- end
- end
-
- def kanji_configure(slot, value=None)
- #if JAPANIZED_TK
- if @kanjifont != ""
- configure_core(@kanjifont, slot, value)
- configure('size'=>configinfo('size')) # to reflect new configuration
- else
- #""
- configure(slot, value)
- end
- end
-
- def kanji_configinfo(slot=nil)
- #if JAPANIZED_TK
- if @kanjifont != ""
- configinfo_core(@kanjifont, slot)
- else
- #[]
- configinfo(slot)
- end
- end
-
- def replace(ltn, knj)
- latin_replace(ltn)
- kanji_replace(knj)
- self
- end
-
- def latin_replace(ltn)
- latin_replace_core(ltn)
- reset_pointadjust
- end
-
- def kanji_replace(knj)
- kanji_replace_core(knj)
- reset_pointadjust
- end
-
- def measure(text)
- measure_core(nil, text)
- end
-
- def measure_displayof(window, text)
- window = '.' unless window
- measure_core(window, text)
- end
-
- def metrics(option=nil)
- metrics_core(@compoundfont, nil, option)
- end
-
- def metrics_displayof(window, option=nil)
- window = '.' unless window
- metrics_core(@compoundfont, window, option)
- end
-
- def latin_metrics(option=nil)
- metrics_core(@latinfont, nil, option)
- end
-
- def latin_metrics_displayof(window, option=nil)
- window = '.' unless window
- metrics_core(@latinfont, window, option)
- end
-
- def kanji_metrics(option=nil)
- if JAPANIZED_TK
- metrics_core(@kanjifont, nil, option)
- else
- metrics_core_tk4x(nil, nil, option)
- end
- end
-
- def kanji_metrics_displayof(window, option=nil)
- if JAPANIZED_TK
- window = '.' unless window
- metrics_core(@kanjifont, window, option)
- else
- metrics_core_tk4x(nil, window, option)
- end
- end
-
- def reset_pointadjust
- begin
- if /^8\.*/ === Tk::TK_VERSION && JAPANIZED_TK
- configure('pointadjust' => latin_actual.assoc('size')[1].to_f /
- kanji_actual.assoc('size')[1].to_f )
- end
- rescue
- end
- self
- end
-
- ###################################
- # public alias
- ###################################
- alias ascii_font latin_font
- alias create_asciifont create_latinfont
- alias ascii_actual latin_actual
- alias ascii_actual_displayof latin_actual_displayof
- alias ascii_configure latin_configure
- alias ascii_configinfo latin_configinfo
- alias ascii_replace latin_replace
- alias ascii_metrics latin_metrics
-
-end
-
-module TkTreatTagFont
- def font_configinfo
- @parent.tagfont_configinfo(@id)
- end
-# alias font font_configinfo
-
- def font_configure(slot)
- @parent.tagfont_configure(@id, slot)
- end
-
- def latinfont_configure(ltn, keys=nil)
- @parent.latintagfont_configure(@id, ltn, keys)
- end
- alias asciifont_configure latinfont_configure
-
- def kanjifont_configure(knj, keys=nil)
- @parent.kanjitagfont_configure(@id, ltn, keys)
- end
-
- def font_copy(window, wintag=nil)
- @parent.tagfont_copy(@id, window, wintag)
- end
-
- def latinfont_copy(window, wintag=nil)
- @parent.latintagfont_copy(@id, window, wintag)
- end
- alias asciifont_copy latinfont_copy
-
- def kanjifont_copy(window, wintag=nil)
- @parent.kanjitagfont_copy(@id, window, wintag)
- end
-end
diff --git a/ext/tk/lib/tkmenubar.rb b/ext/tk/lib/tkmenubar.rb
deleted file mode 100644
index 441f3f5c03..0000000000
--- a/ext/tk/lib/tkmenubar.rb
+++ /dev/null
@@ -1,137 +0,0 @@
-#
-# tkmenubar.rb
-#
-# Copyright (C) 1998 maeda shugo. All rights reserved.
-# This file can be distributed under the terms of the Ruby.
-
-# Usage:
-#
-# menu_spec = [
-# [['File', 0],
-# ['Open', proc{puts('Open clicked')}, 0],
-# '---',
-# ['Quit', proc{exit}, 0]],
-# [['Edit', 0],
-# ['Cut', proc{puts('Cut clicked')}, 2],
-# ['Copy', proc{puts('Copy clicked')}, 0],
-# ['Paste', proc{puts('Paste clicked')}, 0]]
-# ]
-# menubar = TkMenubar.new(nil, menu_spec,
-# 'tearoff'=>false,
-# 'foreground'=>'grey40',
-# 'activeforeground'=>'red',
-# 'font'=>'-adobe-helvetica-bold-r-*--12-*-iso8859-1')
-# menubar.pack('side'=>'top', 'fill'=>'x')
-#
-#
-# OR
-#
-#
-# menubar = TkMenubar.new
-# menubar.add_menu([['File', 0],
-# ['Open', proc{puts('Open clicked')}, 0],
-# '---',
-# ['Quit', proc{exit}, 0]])
-# menubar.add_menu([['Edit', 0],
-# ['Cut', proc{puts('Cut clicked')}, 2],
-# ['Copy', proc{puts('Copy clicked')}, 0],
-# ['Paste', proc{puts('Paste clicked')}, 0]])
-# menubar.configure('tearoff', false)
-# menubar.configure('foreground', 'grey40')
-# menubar.configure('activeforeground', 'red')
-# menubar.configure('font', '-adobe-helvetica-bold-r-*--12-*-iso8859-1')
-# menubar.pack('side'=>'top', 'fill'=>'x')
-
-# The format of the menu_spec is:
-# [
-# [
-# [button text, underline, accelerator],
-# [menu label, command, underline, accelerator],
-# '---', # separator
-# ...
-# ],
-# ...
-# ]
-
-# underline and accelerator are optional parameters.
-# Hashes are OK instead of Arrays.
-
-# To use add_menu, configuration must be done by calling configure after
-# adding all menus by add_menu, not by the constructor arguments.
-
-require "tk"
-
-class TkMenubar<TkFrame
-
- include TkComposite
-
- def initialize(parent = nil, spec = nil, options = nil)
- super(parent, options)
-
- @menus = []
-
- if spec
- for menu_info in spec
- add_menu(menu_info)
- end
- end
-
- if options
- for key, value in options
- configure(key, value)
- end
- end
- end
-
- def add_menu(menu_info)
- btn_info = menu_info.shift
- mbtn = TkMenubutton.new(@frame)
-
- if btn_info.kind_of?(Hash)
- for key, value in btn_info
- mbtn.configure(key, value)
- end
- elsif btn_info.kind_of?(Array)
- mbtn.configure('text', btn_info[0]) if btn_info[0]
- mbtn.configure('underline', btn_info[1]) if btn_info[1]
- mbtn.configure('accelerator', btn_info[2]) if btn_info[2]
- else
- mbtn.configure('text', btn_info)
- end
-
- menu = TkMenu.new(mbtn)
-
- for item_info in menu_info
- if item_info.kind_of?(Hash)
- menu.add('command', item_info)
- elsif item_info.kind_of?(Array)
- options = {}
- options['label'] = item_info[0] if item_info[0]
- options['command'] = item_info[1] if item_info[1]
- options['underline'] = item_info[2] if item_info[2]
- options['accelerator'] = item_info[3] if item_info[3]
- menu.add('command', options)
- elsif /^-+$/ =~ item_info
- menu.add('sep')
- else
- menu.add('command', 'label' => item_info)
- end
- end
-
- mbtn.menu(menu)
- @menus.push([mbtn, menu])
- delegate('tearoff', menu)
- delegate('foreground', mbtn, menu)
- delegate('background', mbtn, menu)
- delegate('disabledforeground', mbtn, menu)
- delegate('activeforeground', mbtn, menu)
- delegate('activebackground', mbtn, menu)
- delegate('font', mbtn, menu)
- delegate('kanjifont', mbtn, menu)
- mbtn.pack('side' => 'left')
- end
-
- def [](index)
- return @menus[index]
- end
-end
diff --git a/ext/tk/lib/tkmngfocus.rb b/ext/tk/lib/tkmngfocus.rb
deleted file mode 100644
index 921fb646e7..0000000000
--- a/ext/tk/lib/tkmngfocus.rb
+++ /dev/null
@@ -1,27 +0,0 @@
-#
-# tkmngfocus.rb : methods for Tcl/Tk standard library 'focus.tcl'
-# 1998/07/16 by Hidetoshi Nagai <nagai@ai.kyutech.ac.jp>
-#
-require 'tk'
-
-module TkManageFocus
- extend Tk
-
- def TkManageFocus.followsMouse
- tk_call 'tk_focusFollowsMouse'
- end
-
- def TkManageFocus.next(window)
- tk_call 'tk_focusNext', window
- end
- def focusNext
- TkManageFocus.next(self)
- end
-
- def TkManageFocus.prev(window)
- tk_call 'tk_focusPrev', window
- end
- def focusPrev
- TkManageFocus.prev(self)
- end
-end
diff --git a/ext/tk/lib/tkpalette.rb b/ext/tk/lib/tkpalette.rb
deleted file mode 100644
index a2dc7c87cb..0000000000
--- a/ext/tk/lib/tkpalette.rb
+++ /dev/null
@@ -1,48 +0,0 @@
-#
-# tkpalette.rb : methods for Tcl/Tk standard library 'palette.tcl'
-# 1998/06/21 by Hidetoshi Nagai <nagai@ai.kyutech.ac.jp>
-#
-require 'tk'
-
-module TkPalette
- include Tk
- extend Tk
-
- def TkPalette.set(*args)
- args = args.to_a.flatten if args.kind_of? Hash
- tk_call 'tk_setPalette', *args
- end
- def TkPalette.setPalette(*args)
- TkPalette.set(*args)
- end
-
- def TkPalette.bisque
- tk_call 'tk_bisque'
- end
-
- def TkPalette.darken(color, percent)
- tk_call 'tkDarken', color, percent
- end
-
- def TkPalette.recolorTree(window, colors)
- if not colors.kind_of?(Hash)
- fail "2nd arg need to be Hash"
- end
-
- colors.each{|key, value|
- begin
- if window.cget(key) == tk_call('set', "tkPalette(#{key})")
- window[key] = colors[key]
- end
- rescue
- # ignore
- end
- }
-
- TkWinfo.children(window).each{|w| TkPalette.recolorTree(w, colors)}
- end
-
- def recolorTree(colors)
- TkPalette.recolorTree(self, colors)
- end
-end
diff --git a/ext/tk/lib/tkscrollbox.rb b/ext/tk/lib/tkscrollbox.rb
deleted file mode 100644
index 6236430491..0000000000
--- a/ext/tk/lib/tkscrollbox.rb
+++ /dev/null
@@ -1,29 +0,0 @@
-#
-# tkscrollbox.rb - Tk Listbox with Scrollbar
-# as an example of Composite Widget
-# $Date$
-# by Yukihiro Matsumoto <matz@netlab.co.jp>
-
-require 'tk.rb'
-
-class TkScrollbox<TkListbox
- include TkComposite
- def initialize_composite(keys=nil)
- list = TkListbox.new(@frame)
- scroll = TkScrollbar.new(@frame)
- @path = list.path
-
- list.configure 'yscroll', scroll.path+" set"
- list.pack 'side'=>'left','fill'=>'both','expand'=>'yes'
- scroll.configure 'command', list.path+" yview"
- scroll.pack 'side'=>'right','fill'=>'y'
-
- delegate('DEFAULT', list)
- delegate('foreground', list)
- delegate('background', list, scroll)
- delegate('borderwidth', @frame)
- delegate('relief', @frame)
-
- configure keys if keys
- end
-end
diff --git a/ext/tk/lib/tktext.rb b/ext/tk/lib/tktext.rb
deleted file mode 100644
index 75b28d8477..0000000000
--- a/ext/tk/lib/tktext.rb
+++ /dev/null
@@ -1,1000 +0,0 @@
-#
-# tktext.rb - Tk text classes
-# $Date$
-# by Yukihiro Matsumoto <matz@caelum.co.jp>
-
-require 'tk.rb'
-require 'tkfont'
-
-module TkTreatTextTagFont
- include TkTreatItemFont
-
- ItemCMD = ['tag', 'configure']
- def __conf_cmd(idx)
- ItemCMD[idx]
- end
-
- def __item_pathname(tagOrId)
- if tagOrId.kind_of?(TkTextTag)
- self.path + ';' + tagOrId.id
- else
- self.path + ';' + tagOrId
- end
- end
-end
-
-class TkText<TkTextWin
- ItemConfCMD = ['tag', 'configure']
- include TkTreatTextTagFont
- include Scrollable
-
- WidgetClassName = 'Text'.freeze
- WidgetClassNames[WidgetClassName] = self
-
- def self.to_eval
- WidgetClassName
- end
-
- def self.new(*args, &block)
- obj = super(*args){}
- obj.init_instance_variable
- obj.instance_eval(&block) if defined? yield
- obj
- end
-
- def init_instance_variable
- @tags = {}
- end
-
- def create_self(keys)
- if keys and keys != None
- tk_call 'text', @path, *hash_kv(keys)
- else
- tk_call 'text', @path
- end
- init_instance_variable
- end
-
- def index(index)
- tk_send 'index', index
- end
-
- def value
- tk_send 'get', "1.0", "end - 1 char"
- end
-
- def value= (val)
- tk_send 'delete', "1.0", 'end'
- tk_send 'insert', "1.0", val
- end
-
- def _addcmd(cmd)
- @cmdtbl.push cmd
- end
-
- def _addtag(name, obj)
- @tags[name] = obj
- end
-
- def tagid2obj(tagid)
- if not @tags[tagid]
- tagid
- else
- @tags[tagid]
- end
- end
-
- def tag_names(index=None)
- tk_split_list(tk_send('tag', 'names', index)).collect{|elt|
- tagid2obj(elt)
- }
- end
-
- def mark_names
- tk_split_list(tk_send('mark', 'names')).collect{|elt|
- tagid2obj(elt)
- }
- end
-
- def mark_next(index)
- tagid2obj(tk_send('mark', 'next', index))
- end
-
- def mark_previous(index)
- tagid2obj(tk_send('mark', 'previous', index))
- end
-
- def window_names
- tk_send('window', 'names').collect{|elt|
- tagid2obj(elt)
- }
- end
-
- def image_names
- tk_send('image', 'names').collect{|elt|
- tagid2obj(elt)
- }
- end
-
- def set_insert(index)
- tk_send 'mark', 'set', 'insert', index
- end
-
- def set_current(index)
- tk_send 'mark', 'set', 'current', index
- end
-
- def insert(index, chars, *tags)
- super index, chars, tags.collect{|x|_get_eval_string(x)}.join(' ')
- end
-
- def destroy
- @tags = {} unless @tags
- @tags.each_value do |t|
- t.destroy
- end
- super
- end
-
- def backspace
- self.delete 'insert'
- end
-
- def compare(idx1, op, idx2)
- bool(tk_send('compare', idx1, op, idx2))
- end
-
- def debug
- bool(tk_send('debug'))
- end
- def debug=(boolean)
- tk_send 'debug', boolean
- end
-
- def bbox(index)
- inf = tk_send('bbox', index)
- (inf == "")? [0,0,0,0]: inf
- end
- def dlineinfo(index)
- inf = tk_send('dlineinfo', index)
- (inf == "")? [0,0,0,0,0]: inf
- end
-
- def yview_pickplace(*what)
- tk_send 'yview', '-pickplace', *what
- end
-
- def xview_pickplace(*what)
- tk_send 'xview', '-pickplace', *what
- end
-
- def tag_add(tag, index1, index2=None)
- tk_send 'tag', 'add', tag, index1, index2
- end
-
- def tag_bind(tag, seq, cmd=Proc.new, args=nil)
- _bind(['tag', 'bind', tag], seq, cmd, args)
- end
-
- def tag_bind_append(tag, seq, cmd=Proc.new, args=nil)
- _bind_append(['tag', 'bind', tag], seq, cmd, args)
- end
-
- def tag_bindinfo(tag, context=nil)
- _bindinfo(['tag', 'bind', tag], context)
- end
-
- def tag_cget(tag, key)
- case key
- when 'text', 'label', 'show', 'data', 'file'
- tk_call @path, 'tag', 'cget', tag, "-#{key}"
- else
- tk_tcl2ruby tk_call @path, 'tag', 'cget', tag, "-#{key}"
- end
- end
-
- def tag_configure(tag, key, val=None)
- if key.kind_of? Hash
- if ( key['font'] || key['kanjifont'] \
- || key['latinfont'] || key['asciifont'] )
- tagfont_configure(tag, key.dup)
- else
- tk_send 'tag', 'configure', tag, *hash_kv(key)
- end
-
- else
- if key == 'font' || key == 'kanjifont' ||
- key == 'latinfont' || key == 'asciifont'
- tagfont_configure(tag, {key=>val})
- else
- tk_send 'tag', 'configure', tag, "-#{key}", val
- end
- end
- end
-
- def tag_configinfo(tag, key=nil)
- if key
- case key
- when 'text', 'label', 'show', 'data', 'file'
- conf = tk_split_simplelist(tk_send('tag','configure',tag,"-#{key}"))
- else
- conf = tk_split_list(tk_send('tag','configure',tag,"-#{key}"))
- end
- conf[0] = conf[0][1..-1]
- conf
- else
- tk_split_simplelist(tk_send('tag', 'configure', tag)).collect{|conflist|
- conf = tk_split_simplelist(conflist)
- conf[0] = conf[0][1..-1]
- case conf[0]
- when 'text', 'label', 'show', 'data', 'file'
- else
- if conf[3]
- if conf[3].index('{')
- conf[3] = tk_split_list(conf[3])
- else
- conf[3] = tk_tcl2ruby(conf[3])
- end
- end
- if conf[4]
- if conf[4].index('{')
- conf[4] = tk_split_list(conf[4])
- else
- conf[4] = tk_tcl2ruby(conf[4])
- end
- end
- end
- conf
- }
- end
- end
-
- def tag_raise(tag, above=None)
- tk_send 'tag', 'raise', tag, above
- end
-
- def tag_lower(tag, below=None)
- tk_send 'tag', 'lower', tag, below
- end
-
- def tag_remove(tag, *index)
- tk_send 'tag', 'remove', tag, *index
- end
-
- def tag_ranges(tag)
- l = tk_split_simplelist(tk_send('tag', 'ranges', tag))
- r = []
- while key=l.shift
- r.push [key, l.shift]
- end
- r
- end
-
- def tag_nextrange(tag, first, last=None)
- tk_split_simplelist(tk_send('tag', 'nextrange', tag, first, last))
- end
-
- def tag_prevrange(tag, first, last=None)
- tk_split_simplelist(tk_send('tag', 'prevrange', tag, first, last))
- end
-
- def _ktext_length(txt)
- if $KCODE !~ /n/i
- return txt.gsub(/[^\Wa-zA-Z_\d]/, ' ').length
- end
-
- # $KCODE == 'NONE'
- if JAPANIZED_TK
- tk_call('kstring', 'length', txt).to_i
- else
- begin
- tk_call('encoding', 'convertto', 'ascii', txt).length
- rescue StandardError, NameError
- # sorry, I have no plan
- txt.length
- end
- end
- end
- private :_ktext_length
-
- def search_with_length(pat,start,stop=None)
- pat = pat.chr if pat.kind_of? Integer
- if stop != None
- return ["", 0] if compare(start,'>=',stop)
- txt = get(start,stop)
- if (pos = txt.index(pat))
- match = $&
- #pos = txt[0..(pos-1)].split('').length if pos > 0
- pos = _ktext_length(txt[0..(pos-1)]) if pos > 0
- if pat.kind_of? String
- #return [index(start + " + #{pos} chars"), pat.split('').length]
- return [index(start + " + #{pos} chars"),
- _ktext_length(pat), pat.dup]
- else
- #return [index(start + " + #{pos} chars"), $&.split('').length]
- return [index(start + " + #{pos} chars"),
- _ktext_length(match), match]
- end
- else
- return ["", 0]
- end
- else
- txt = get(start,'end - 1 char')
- if (pos = txt.index(pat))
- match = $&
- #pos = txt[0..(pos-1)].split('').length if pos > 0
- pos = _ktext_length(txt[0..(pos-1)]) if pos > 0
- if pat.kind_of? String
- #return [index(start + " + #{pos} chars"), pat.split('').length]
- return [index(start + " + #{pos} chars"),
- _ktext_length(pat), pat.dup]
- else
- #return [index(start + " + #{pos} chars"), $&.split('').length]
- return [index(start + " + #{pos} chars"),
- _ktext_length(match), match]
- end
- else
- txt = get('1.0','end - 1 char')
- if (pos = txt.index(pat))
- match = $&
- #pos = txt[0..(pos-1)].split('').length if pos > 0
- pos = _ktext_length(txt[0..(pos-1)]) if pos > 0
- if pat.kind_of? String
- #return [index("1.0 + #{pos} chars"), pat.split('').length]
- return [index("1.0 + #{pos} chars"),
- _ktext_length(pat), pat.dup]
- else
- #return [index("1.0 + #{pos} chars"), $&.split('').length]
- return [index("1.0 + #{pos} chars"), _ktext_length(match), match]
- end
- else
- return ["", 0]
- end
- end
- end
- end
-
- def search(pat,start,stop=None)
- search_with_length(pat,start,stop)[0]
- end
-
- def rsearch_with_length(pat,start,stop=None)
- pat = pat.chr if pat.kind_of? Integer
- if stop != None
- return ["", 0] if compare(start,'<=',stop)
- txt = get(stop,start)
- if (pos = txt.rindex(pat))
- match = $&
- #pos = txt[0..(pos-1)].split('').length if pos > 0
- pos = _ktext_length(txt[0..(pos-1)]) if pos > 0
- if pat.kind_of? String
- #return [index(stop + " + #{pos} chars"), pat.split('').length]
- return [index(stop + " + #{pos} chars"), _ktext_length(pat), pat.dup]
- else
- #return [index(stop + " + #{pos} chars"), $&.split('').length]
- return [index(stop + " + #{pos} chars"), _ktext_length(match), match]
- end
- else
- return ["", 0]
- end
- else
- txt = get('1.0',start)
- if (pos = txt.rindex(pat))
- match = $&
- #pos = txt[0..(pos-1)].split('').length if pos > 0
- pos = _ktext_length(txt[0..(pos-1)]) if pos > 0
- if pat.kind_of? String
- #return [index("1.0 + #{pos} chars"), pat.split('').length]
- return [index("1.0 + #{pos} chars"), _ktext_length(pat), pat.dup]
- else
- #return [index("1.0 + #{pos} chars"), $&.split('').length]
- return [index("1.0 + #{pos} chars"), _ktext_length(match), match]
- end
- else
- txt = get('1.0','end - 1 char')
- if (pos = txt.rindex(pat))
- match = $&
- #pos = txt[0..(pos-1)].split('').length if pos > 0
- pos = _ktext_length(txt[0..(pos-1)]) if pos > 0
- if pat.kind_of? String
- #return [index("1.0 + #{pos} chars"), pat.split('').length]
- return [index("1.0 + #{pos} chars"), _ktext_length(pat), pat.dup]
- else
- #return [index("1.0 + #{pos} chars"), $&.split('').length]
- return [index("1.0 + #{pos} chars"), _ktext_length(match), match]
- end
- else
- return ["", 0]
- end
- end
- end
- end
-
- def rsearch(pat,start,stop=None)
- rsearch_with_length(pat,start,stop)[0]
- end
-
- def dump(type_info, *index, &block)
- args = type_info.collect{|inf| '-' + inf}
- args << '-command' << Proc.new(&block) if iterator?
- str = tk_send('dump', *(args + index))
- result = []
- sel = nil
- i = 0
- while i < str.size
- # retrieve key
- idx = str.index(/ /, i)
- result.push str[i..(idx-1)]
- i = idx + 1
-
- # retrieve value
- case result[-1]
- when 'text'
- if str[i] == ?{
- # text formed as {...}
- val, i = _retrieve_braced_text(str, i)
- result.push val
- else
- # text which may contain backslahes
- val, i = _retrieve_backslashed_text(str, i)
- result.push val
- end
- else
- idx = str.index(/ /, i)
- val = str[i..(idx-1)]
- case result[-1]
- when 'mark'
- case val
- when 'insert'
- result.push TkTextMarkInsert.new(self)
- when 'current'
- result.push TkTextMarkCurrent.new(self)
- when 'anchor'
- result.push TkTextMarkAnchor.new(self)
- else
- result.push tk_tcl2ruby(val)
- end
- when 'tagon'
- if val == 'sel'
- if sel
- result.push sel
- else
- result.push TkTextTagSel.new(self)
- end
- else
- result.push tk_tcl2ruby(val)
- end
- when 'tagoff'
- result.push tk_tcl2ruby(sel)
- when 'window'
- result.push tk_tcl2ruby(val)
- end
- i = idx + 1
- end
-
- # retrieve index
- idx = str.index(/ /, i)
- if idx
- result.push str[i..(idx-1)]
- i = idx + 1
- else
- result.push str[i..-1]
- break
- end
- end
-
- kvis = []
- until result.empty?
- kvis.push [result.shift, result.shift, result.shift]
- end
- kvis # result is [[key1, value1, index1], [key2, value2, index2], ...]
- end
-
- def _retrieve_braced_text(str, i)
- cnt = 0
- idx = i
- while idx < str.size
- case str[idx]
- when ?{
- cnt += 1
- when ?}
- cnt -= 1
- if cnt == 0
- break
- end
- end
- idx += 1
- end
- return str[i+1..idx-1], idx + 2
- end
- private :_retrieve_braced_text
-
- def _retrieve_backslashed_text(str, i)
- j = i
- idx = nil
- loop {
- idx = str.index(/ /, j)
- if str[idx-1] == ?\\
- j += 1
- else
- break
- end
- }
- val = str[i..(idx-1)]
- val.gsub!(/\\( |\{|\})/, '\1')
- return val, idx + 1
- end
- private :_retrieve_backslashed_text
-
- def dump_all(*index, &block)
- dump(['all'], *index, &block)
- end
- def dump_mark(*index, &block)
- dump(['mark'], *index, &block)
- end
- def dump_tag(*index, &block)
- dump(['tag'], *index, &block)
- end
- def dump_text(*index, &block)
- dump(['text'], *index, &block)
- end
- def dump_window(*index, &block)
- dump(['window'], *index, &block)
- end
- def dump_image(*index, &block)
- dump(['image'], *index, &block)
- end
-end
-
-class TkTextTag<TkObject
- include TkTreatTagFont
-
- Tk_TextTag_ID = ['tag0000']
-
- def initialize(parent, *args)
- if not parent.kind_of?(TkText)
- fail format("%s need to be TkText", parent.inspect)
- end
- @parent = @t = parent
- @path = @id = Tk_TextTag_ID[0]
- Tk_TextTag_ID[0] = Tk_TextTag_ID[0].succ
- #tk_call @t.path, "tag", "configure", @id, *hash_kv(keys)
- if args != [] then
- keys = args.pop
- if keys.kind_of? Hash then
- add(*args) if args != []
- configure(keys)
- else
- args.push keys
- add(*args)
- end
- end
- @t._addtag id, self
- end
-
- def id
- return @id
- end
-
- def first
- @id + '.first'
- end
-
- def last
- @id + '.last'
- end
-
- def add(*index)
- tk_call @t.path, 'tag', 'add', @id, *index
- end
-
- def remove(*index)
- tk_call @t.path, 'tag', 'remove', @id, *index
- end
-
- def ranges
- l = tk_split_simplelist(tk_call(@t.path, 'tag', 'ranges', @id))
- r = []
- while key=l.shift
- r.push [key, l.shift]
- end
- r
- end
-
- def nextrange(first, last=None)
- tk_split_simplelist(tk_call(@t.path, 'tag', 'nextrange', @id, first, last))
- end
-
- def prevrange(first, last=None)
- tk_split_simplelist(tk_call(@t.path, 'tag', 'prevrange', @id, first, last))
- end
-
- def [](key)
- cget key
- end
-
- def []=(key,val)
- configure key, val
- end
-
- def cget(key)
- case key
- when 'text', 'label', 'show', 'data', 'file'
- tk_call @t.path, 'tag', 'cget', @id, "-#{key}"
- else
- tk_tcl2ruby tk_call @t.path, 'tag', 'cget', @id, "-#{key}"
- end
- end
-
- def configure(key, val=None)
- @t.tag_configure @id, key, val
- end
-# def configure(key, val=None)
-# if key.kind_of? Hash
-# tk_call @t.path, 'tag', 'configure', @id, *hash_kv(key)
-# else
-# tk_call @t.path, 'tag', 'configure', @id, "-#{key}", val
-# end
-# end
-# def configure(key, value)
-# if value == FALSE
-# value = "0"
-# elsif value.kind_of? Proc
-# value = install_cmd(value)
-# end
-# tk_call @t.path, 'tag', 'configure', @id, "-#{key}", value
-# end
-
- def configinfo(key=nil)
- @t.tag_configinfo @id, key
- end
-
- def bind(seq, cmd=Proc.new, args=nil)
- _bind([@t.path, 'tag', 'bind', @id], seq, cmd, args)
- end
-
- def bind_append(seq, cmd=Proc.new, args=nil)
- _bind_append([@t.path, 'tag', 'bind', @id], seq, cmd, args)
- end
-
- def bindinfo(context=nil)
- _bindinfo([@t.path, 'tag', 'bind', @id], context)
- end
-
- def raise(above=None)
- tk_call @t.path, 'tag', 'raise', @id, above
- end
-
- def lower(below=None)
- tk_call @t.path, 'tag', 'lower', @id, below
- end
-
- def destroy
- tk_call @t.path, 'tag', 'delete', @id
- end
-end
-
-class TkTextTagSel<TkTextTag
- def initialize(parent, keys=nil)
- if not parent.kind_of?(TkText)
- fail format("%s need to be TkText", parent.inspect)
- end
- @t = parent
- @path = @id = 'sel'
- #tk_call @t.path, "tag", "configure", @id, *hash_kv(keys)
- configure(keys) if keys
- @t._addtag id, self
- end
-end
-
-class TkTextMark<TkObject
- Tk_TextMark_ID = ['mark0000']
- def initialize(parent, index)
- if not parent.kind_of?(TkText)
- fail format("%s need to be TkText", parent.inspect)
- end
- @t = parent
- @path = @id = Tk_TextMark_ID[0]
- Tk_TextMark_ID[0] = Tk_TextMark_ID[0].succ
- tk_call @t.path, 'mark', 'set', @id, index
- @t._addtag id, self
- end
- def id
- return @id
- end
-
- def set(where)
- tk_call @t.path, 'mark', 'set', @id, where
- end
-
- def unset
- tk_call @t.path, 'mark', 'unset', @id
- end
- alias destroy unset
-
- def gravity
- tk_call @t.path, 'mark', 'gravity', @id
- end
-
- def gravity=(direction)
- tk_call @t.path, 'mark', 'gravity', @id, direction
- end
-
- def next(index = nil)
- if index
- @t.tagid2obj(tk_call(@t.path, 'mark', 'next', index))
- else
- @t.tagid2obj(tk_call(@t.path, 'mark', 'next', @id))
- end
- end
-
- def previous(index = nil)
- if index
- @t.tagid2obj(tk_call(@t.path, 'mark', 'previous', index))
- else
- @t.tagid2obj(tk_call(@t.path, 'mark', 'previous', @id))
- end
- end
-end
-
-class TkTextMarkInsert<TkTextMark
- def initialize(parent, index=nil)
- if not parent.kind_of?(TkText)
- fail format("%s need to be TkText", parent.inspect)
- end
- @t = parent
- @path = @id = 'insert'
- tk_call @t.path, 'mark', 'set', @id, index if index
- @t._addtag id, self
- end
-end
-
-class TkTextMarkCurrent<TkTextMark
- def initialize(parent,index=nil)
- if not parent.kind_of?(TkText)
- fail format("%s need to be TkText", parent.inspect)
- end
- @t = parent
- @path = @id = 'current'
- tk_call @t.path, 'mark', 'set', @id, index if index
- @t._addtag id, self
- end
-end
-
-class TkTextMarkAnchor<TkTextMark
- def initialize(parent,index=nil)
- if not parent.kind_of?(TkText)
- fail format("%s need to be TkText", parent.inspect)
- end
- @t = parent
- @path = @id = 'anchor'
- tk_call @t.path, 'mark', 'set', @id, index if index
- @t._addtag id, self
- end
-end
-
-class TkTextWindow<TkObject
- def initialize(parent, index, keys)
- if not parent.kind_of?(TkText)
- fail format("%s need to be TkText", parent.inspect)
- end
- @t = parent
- if index == 'end'
- @path = TkTextMark.new(@t, tk_call(@t.path, 'index', 'end - 1 chars'))
- elsif index.kind_of? TkTextMark
- if tk_call(@t.path,'index',index.path) == tk_call(@t.path,'index','end')
- @path = TkTextMark.new(@t, tk_call(@t.path, 'index', 'end - 1 chars'))
- else
- @path = TkTextMark.new(@t, tk_call(@t.path, 'index', index.path))
- end
- else
- @path = TkTextMark.new(@t, tk_call(@t.path, 'index', index))
- end
- @path.gravity = 'left'
- @index = @path.path
- @id = keys['window']
- if keys['create']
- @p_create = keys['create']
- if @p_create.kind_of? Proc
- keys['create'] = install_cmd(proc{@id = @p_create.call; @id.path})
- end
- end
- tk_call @t.path, 'window', 'create', @index, *hash_kv(keys)
- end
-
- def [](slot)
- cget(slot)
- end
- def []=(slot, value)
- configure(slot, value)
- end
-
- def cget(slot)
- case slot
- when 'text', 'label', 'show', 'data', 'file'
- tk_call @t.path, 'window', 'cget', @index, "-#{slot}"
- else
- tk_tcl2ruby tk_call @t.path, 'window', 'cget', @index, "-#{slot}"
- end
- end
-
- def configure(slot, value=None)
- if slot.kind_of? Hash
- @id = slot['window'] if slot['window']
- if slot['create']
- self.create=value
- slot['create']=nil
- end
- if slot.size > 0
- tk_call @t.path, 'window', 'configure', @index, *hash_kv(slot)
- end
- else
- @id = value if slot == 'window'
- if slot == 'create'
- self.create=value
- else
- tk_call @t.path, 'window', 'configure', @index, "-#{slot}", value
- end
- end
- end
-
- def window
- @id
- end
-
- def window=(value)
- tk_call @t.path, 'window', 'configure', @index, '-window', value
- @id = value
- end
-
- def create
- @p_create
- end
-
- def create=(value)
- @p_create = value
- if @p_create.kind_of? Proc
- value = install_cmd(proc{@id = @p_create.call})
- end
- tk_call @t.path, 'window', 'configure', @index, '-create', value
- end
-
- def configinfo(slot = nil)
- if slot
- case slot
- when 'text', 'label', 'show', 'data', 'file'
- conf = tk_split_simplelist(tk_call @t.path, 'window', 'configure',
- @index, "-#{slot}")
- else
- conf = tk_split_list(tk_call @t.path, 'window', 'configure',
- @index, "-#{slot}")
- end
- conf[0] = conf[0][1..-1]
- conf
- else
- tk_split_simplelist(tk_call @t.path, 'window', 'configure',
- @index).collect{|conflist|
- conf = tk_split_simplelist(conflist)
- conf[0] = conf[0][1..-1]
- case conf[0]
- when 'text', 'label', 'show', 'data', 'file'
- else
- if conf[3]
- if conf[3].index('{')
- conf[3] = tk_split_list(conf[3])
- else
- conf[3] = tk_tcl2ruby(conf[3])
- end
- end
- if conf[4]
- if conf[4].index('{')
- conf[4] = tk_split_list(conf[4])
- else
- conf[4] = tk_tcl2ruby(conf[4])
- end
- end
- end
- conf
- }
- end
- end
-
-end
-
-class TkTextImage<TkObject
- def initialize(parent, index, keys)
- if not parent.kind_of?(TkText)
- fail format("%s need to be TkText", parent.inspect)
- end
- @t = parent
- if index == 'end'
- @path = TkTextMark.new(@t, tk_call(@t.path, 'index', 'end - 1 chars'))
- elsif index.kind_of? TkTextMark
- if tk_call(@t.path,'index',index.path) == tk_call(@t.path,'index','end')
- @path = TkTextMark.new(@t, tk_call(@t.path, 'index', 'end - 1 chars'))
- else
- @path = TkTextMark.new(@t, tk_call(@t.path, 'index', index.path))
- end
- else
- @path = TkTextMark.new(@t, tk_call(@t.path, 'index', index))
- end
- @path.gravity = 'left'
- @index = @path.path
- @id = tk_call(@t.path, 'image', 'create', @index, *hash_kv(keys))
- end
-
- def [](slot)
- cget(slot)
- end
- def []=(slot, value)
- configure(slot, value)
- end
-
- def cget(slot)
- case slot
- when 'text', 'label', 'show', 'data', 'file'
- tk_call @t.path, 'image', 'cget', @index, "-#{slot}"
- else
- tk_tcl2ruby tk_call @t.path, 'image', 'cget', @index, "-#{slot}"
- end
- end
-
- def configure(slot, value=None)
- if slot.kind_of? Hash
- tk_call @t.path, 'image', 'configure', @index, *hash_kv(slot)
- else
- tk_call @t.path, 'image', 'configure', @index, "-#{slot}", value
- end
- end
-# def configure(slot, value)
-# tk_call @t.path, 'image', 'configure', @index, "-#{slot}", value
-# end
-
- def image
- tk_call @t.path, 'image', 'configure', @index, '-image'
- end
-
- def image=(value)
- tk_call @t.path, 'image', 'configure', @index, '-image', value
- end
-
- def configinfo(slot = nil)
- if slot
- case slot
- when 'text', 'label', 'show', 'data', 'file'
- conf = tk_split_simplelist(tk_call @t.path, 'image', 'configure',
- @index, "-#{slot}")
- else
- conf = tk_split_list(tk_call @t.path, 'image', 'configure',
- @index, "-#{slot}")
- end
- conf[0] = conf[0][1..-1]
- conf
- else
- tk_split_simplelist(tk_call @t.path, 'image', 'configure',
- @index).collect{|conflist|
- conf = tk_split_simplelist(conflist)
- conf[0] = conf[0][1..-1]
- case conf[0]
- when 'text', 'label', 'show', 'data', 'file'
- else
- if conf[3]
- if conf[3].index('{')
- conf[3] = tk_split_list(conf[3])
- else
- conf[3] = tk_tcl2ruby(conf[3])
- end
- end
- if conf[4]
- if conf[4].index('{')
- conf[4] = tk_split_list(conf[4])
- else
- conf[4] = tk_tcl2ruby(conf[4])
- end
- end
- end
- conf
- }
- end
- end
-end
diff --git a/ext/tk/lib/tkvirtevent.rb b/ext/tk/lib/tkvirtevent.rb
deleted file mode 100644
index d3721e362e..0000000000
--- a/ext/tk/lib/tkvirtevent.rb
+++ /dev/null
@@ -1,81 +0,0 @@
-#
-# tkvirtevent.rb : treats virtual events
-# 1998/07/16 by Hidetoshi Nagai <nagai@ai.kyutech.ac.jp>
-#
-require 'tk'
-
-class TkVirtualEvent<TkObject
- extend Tk
-
- TkVirtualEventID = [0]
- TkVirtualEventTBL = {}
-
- class PreDefVirtEvent<self
- def initialize(event)
- @path = @id = event
- TkVirtualEvent::TkVirtualEventTBL[@id] = self
- end
- end
-
- def TkVirtualEvent.getobj(event)
- obj = TkVirtualEventTBL[event]
- if obj
- obj
- else
- if tk_call('event', 'info').index("<#{event}>")
- PreDefVirtEvent.new(event)
- else
- fail ArgumentError, "undefined virtual event '<#{event}>'"
- end
- end
- end
-
- def TkVirtualEvent.info
- tk_call('event', 'info').split(/\s+/).collect!{|seq|
- TkVirtualEvent.getobj(seq[1..-2])
- }
- end
-
- def initialize(*sequences)
- @path = @id = format("<VirtEvent%.4d>", TkVirtualEventID[0])
- TkVirtualEventID[0] += 1
- add(*sequences)
- end
-
- def add(*sequences)
- if sequences != []
- tk_call('event', 'add', "<#{@id}>",
- *(sequences.collect{|seq| "<#{tk_event_sequence(seq)}>"}) )
- TkVirtualEventTBL[@id] = self
- end
- self
- end
-
- def delete(*sequences)
- if sequences == []
- tk_call('event', 'delete', "<#{@id}>")
- TkVirtualEventTBL[@id] = nil
- else
- tk_call('event', 'delete', "<#{@id}>",
- *(sequences.collect{|seq| "<#{tk_event_sequence(seq)}>"}) )
- TkVirtualEventTBL[@id] = nil if info == []
- end
- self
- end
-
- def info
- tk_call('event', 'info', "<#{@id}>").split(/\s+/).collect!{|seq|
- l = seq.scan(/<*[^<>]+>*/).collect!{|subseq|
- case (subseq)
- when /^<<[^<>]+>>$/
- TkVirtualEvent.getobj(subseq[1..-2])
- when /^<[^<>]+>$/
- subseq[1..-2]
- else
- subseq.split('')
- end
- }.flatten
- (l.size == 1) ? l[0] : l
- }
- end
-end
diff --git a/ext/tk/sample/tkbiff.rb b/ext/tk/sample/tkbiff.rb
deleted file mode 100644
index ac27184437..0000000000
--- a/ext/tk/sample/tkbiff.rb
+++ /dev/null
@@ -1,149 +0,0 @@
-#! /usr/local/bin/ruby
-
-if ARGV[0] != '-d'
- unless $DEBUG
- exit if fork
- end
-else
- ARGV.shift
-end
-
-if ARGV.length == 0
- if ENV['MAIL']
- $spool = ENV['MAIL']
- else
- $spool = '/usr/spool/mail/' + ENV['USER']
- end
-else
- $spool = ARGV[0]
-end
-
-require "parsedate"
-require "base64"
-
-include ParseDate
-
-class Mail
- def Mail.new(f)
- if !f.kind_of?(IO)
- f = open(f, "r")
- me = super
- f.close
- else
- me = super
- end
- return me
- end
-
- def initialize(f)
- @header = {}
- @body = []
- while line = f.gets()
- line.chop!
- next if /^From / =~ line # skip From-line
- break if /^$/ =~ line # end of header
- if /^(\S+):\s*(.*)/ =~ line
- @header[attr = $1.capitalize] = $2
- elsif attr
- sub(/^\s*/, '')
- @header[attr] += "\n" + $_
- end
- end
-
- return unless $_
-
- while line = f.gets()
- break if /^From / =~ line
- @body.push($_)
- end
- end
-
- def header
- return @header
- end
-
- def body
- return @body
- end
-
-end
-
-require "tkscrollbox"
-
-$top = TkRoot.new
-$top.withdraw
-$list = TkScrollbox.new($top) {
- relief 'raised'
- width 80
- height 8
- setgrid 'yes'
- pack
-}
-TkButton.new($top) {
- text 'Dismiss'
- command proc {$top.withdraw}
- pack('fill'=>'both','expand'=>'yes')
-}
-$top.bind "Control-c", proc{exit}
-$top.bind "Control-q", proc{exit}
-$top.bind "space", proc{exit}
-
-$spool_size = 0
-$check_time = Time.now
-
-def check
- $check_time = Time.now
- size = File.size($spool)
- if size and size != $spool_size
- $spool_size = size
- pop_up if size > 0
- end
- Tk.after 5000, proc{check}
-end
-
-if defined? Thread
- Thread.start do
- loop do
- sleep 600
- if Time.now - $check_time > 200
- Tk.after 5000, proc{check}
- end
- end
- end
-end
-
-def pop_up
- outcount = 0;
- $list.delete 0, 'end'
- f = open($spool, "r")
- while !f.eof?
- mail = Mail.new(f)
- date, from, subj = mail.header['Date'], mail.header['From'], mail.header['Subject']
- next if !date
- y = m = d = 0
- y, m, d = parsedate(date) if date
- from = "sombody@somewhere" if ! from
- subj = "(nil)" if ! subj
- from = decode_b(from)
- subj = decode_b(subj)
- $list.insert 'end', format('%-02d/%02d/%02d [%-28.28s] %s',y,m,d,from,subj)
- outcount += 1
- end
- f.close
- if outcount == 0
- $list.insert 'end', "You have no mail."
- else
- $list.see 'end'
- end
- $top.deiconify
- Tk.after 2000, proc{$top.withdraw}
-end
-
-$list.insert 'end', "You have no mail."
-check
-Tk.after 2000, proc{$top.withdraw}
-begin
- Tk.mainloop
-rescue
- `echo #$! > /tmp/tkbiff`
-end
diff --git a/ext/tk/sample/tkbrowse.rb b/ext/tk/sample/tkbrowse.rb
deleted file mode 100644
index 882f0a489b..0000000000
--- a/ext/tk/sample/tkbrowse.rb
+++ /dev/null
@@ -1,79 +0,0 @@
-#!/usr/local/bin/ruby
-#
-# This script generates a directory browser, which lists the working
-# directory and allows you to open files or subdirectories by
-# double-clicking.
-
-# Create a scrollbar on the right side of the main window and a listbox
-# on the left side.
-
-require "tkscrollbox"
-
-# The procedure below is invoked to open a browser on a given file; if the
-# file is a directory then another instance of this program is invoked; if
-# the file is a regular file then the Mx editor is invoked to display
-# the file.
-
-$dirlist = {}
-
-def browsedir (dir)
- if $dirlist.key? dir
- $dirlist[dir]
- else
- top = if $dirlist.size > 0 then TkToplevel.new else nil end
- list = TkScrollbox.new(top) {
- relief 'raised'
- width 20
- height 20
- setgrid 'yes'
- pack
- }
- list.insert 'end', *`ls #{dir}`.split
-
- # Set up bindings for the browser.
-
- list.focus
- list.bind "Control-q", proc{exit}
- list.bind "Control-c", proc{exit}
- list.bind "Control-p", proc{
- print "selection <", TkSelection.get, ">\n"
- }
-
- list.bind "Double-Button-1", proc{
- for i in TkSelection.get.split
- print "clicked ", i, "\n"
- browse dir, i
- end
- }
- $dirlist[dir] = list
- end
-end
-
-def browse (dir, file)
- file="#{dir}/#{file}"
- if File.directory? file
- browsedir(file)
- else
- if File.file? file
- if ENV['EDITOR']
- system format("%s %s&", ENV['EDITOR'], file)
- else
- system "xedit #{file}&"
- end
- else
- STDERR.print "\"#{file}\" isn't a directory or regular file"
- end
- end
-end
-
-# Fill the listbox with a list of all the files in the directory (run
-# the "ls" command to get that information).
-
-if ARGV.length>0
- dir = ARGV[0]
-else
- dir="."
-end
-
-browsedir(dir)
-Tk.mainloop
diff --git a/ext/tk/sample/tkdialog.rb b/ext/tk/sample/tkdialog.rb
deleted file mode 100644
index e83e16d0a8..0000000000
--- a/ext/tk/sample/tkdialog.rb
+++ /dev/null
@@ -1,62 +0,0 @@
-#! /usr/local/bin/ruby
-require "tk"
-
-root = TkFrame.new
-top = TkFrame.new(root) {
- relief 'raised'
- border 1
-}
-msg = TkMessage.new(top) {
- text "File main.c hasn't been saved to disk since \
-it was last modified. What should I do?"
- justify 'center'
- aspect 200
- font '-Adobe-helvetica-medium-r-normal--*-240*'
- pack('padx'=>5, 'pady'=>5, 'expand'=>'yes')
-}
-top.pack('fill'=>'both')
-root.pack
-
-bot = TkFrame.new(root) {
- relief 'raised'
- border 1
-}
-
-TkFrame.new(bot) { |left|
- relief 'sunken'
- border 1
- pack('side'=>'left', 'expand'=>'yes', 'padx'=>10, 'pady'=> 10)
- TkButton.new(left) {
- text "Save File"
- command "quit 'save'"
- pack('expand'=>'yes','padx'=>6,'pady'=> 6)
- top.bind "Enter", proc{state 'active'}
- msg.bind "Enter", proc{state 'active'}
- bot.bind "Enter", proc{state 'active'}
- top.bind "Leave", proc{state 'normal'}
- msg.bind "Leave", proc{state 'normal'}
- bot.bind "Leave", proc{state 'normal'}
- Tk.root.bind "ButtonRelease-1", proc{quit 'save'}
- Tk.root.bind "Return", proc{quit 'save'}
- }
-}
-TkButton.new(bot) {
- text "Quit Anyway"
- command "quit 'quit'"
- pack('side'=>'left', 'expand'=>'yes', 'padx'=>10)
-}
-TkButton.new(bot) {
- text "Return To Editor"
- command "quit 'return'"
- pack('side'=>'left', 'expand'=>'yes', 'padx'=>10)
-}
-bot.pack
-root.pack('side'=>'top', 'fill'=>'both', 'expand'=>'yes')
-
-def quit(button)
- print "aaa\n"
- print "You pressed the \"#{button}\" button; bye-bye!\n"
- exit
-end
-
-Tk.mainloop
diff --git a/ext/tk/sample/tkfrom.rb b/ext/tk/sample/tkfrom.rb
deleted file mode 100644
index 8c3efb8137..0000000000
--- a/ext/tk/sample/tkfrom.rb
+++ /dev/null
@@ -1,132 +0,0 @@
-#! /usr/local/bin/ruby
-
-require "parsedate"
-require "base64"
-
-include ParseDate
-
-class Mail
- def Mail.new(f)
- if !f.kind_of?(IO)
- f = open(f, "r")
- me = super(f)
- f.close
- else
- me = super
- end
- return me
- end
-
- def initialize(f)
- @header = {}
- @body = []
- while line = f.gets()
- $_.chop!
- next if /^From / =~ line # skip From-line
- break if /^$/ =~ line # end of header
- if /^(\S+):\s*(.*)/ =~ line
- @header[attr = $1.capitalize] = $2
- elsif attr
- sub(/^\s*/, '')
- @header[attr] += "\n" + $_
- end
- end
-
- return unless $_
-
- while line = f.gets()
- break if /^From / =~ line
- @body.push($_)
- end
- end
-
- def header
- return @header
- end
-
- def body
- return @body
- end
-
-end
-
-if ARGV.length == 0
- if ENV['MAIL']
- ARGV[0] = ENV['MAIL']
- elsif ENV['USER']
- ARGV[0] = '/usr/spool/mail/' + ENV['USER']
- elsif ENV['LOGNAME']
- ARGV[0] = '/usr/spool/mail/' + ENV['LOGNAME']
- end
-end
-
-require "tk"
-list = scroll = nil
-TkFrame.new{|f|
- list = TkListbox.new(f) {
- yscroll proc{|idx|
- scroll.set *idx
- }
- relief 'raised'
-# geometry "80x5"
- width 80
- height 5
- setgrid 'yes'
- pack('side'=>'left','fill'=>'both','expand'=>'yes')
- }
- scroll = TkScrollbar.new(f) {
- command proc{|idx|
- list.yview *idx
- }
- pack('side'=>'right','fill'=>'y')
- }
- pack
-}
-root = Tk.root
-TkButton.new(root) {
- text 'Dismiss'
- command proc {exit}
- pack('fill'=>'both','expand'=>'yes')
-}
-root.bind "Control-c", proc{exit}
-root.bind "Control-q", proc{exit}
-root.bind "space", proc{exit}
-
-$outcount = 0;
-for file in ARGV
- next if File.exist?(file)
- atime = File.atime(file)
- mtime = File.mtime(file)
- f = open(file, "r")
- begin
- until f.eof
- mail = Mail.new(f)
- date = mail.header['Date']
- next unless date
- from = mail.header['From']
- subj = mail.header['Subject']
- y = m = d = 0
- y, m, d = parsedate(date) if date
- from = "sombody@somewhere" unless from
- subj = "(nil)" unless subj
- from = decode_b(from)
- subj = decode_b(subj)
- list.insert 'end', format('%-02d/%02d/%02d [%-28.28s] %s',y,m,d,from,subj)
- $outcount += 1
- end
- ensure
- f.close
- File.utime(atime, mtime, file)
- list.see 'end'
- end
-end
-
-limit = 10000
-if $outcount == 0
- list.insert 'end', "You have no mail."
- limit = 2000
-end
-Tk.after limit, proc{
- exit
-}
-Tk.mainloop
diff --git a/ext/tk/sample/tkhello.rb b/ext/tk/sample/tkhello.rb
deleted file mode 100644
index 5188fe1c8c..0000000000
--- a/ext/tk/sample/tkhello.rb
+++ /dev/null
@@ -1,10 +0,0 @@
-require "tk"
-
-TkButton.new(nil,
- 'text' => 'hello',
- 'command' => proc{print "hello\n"}).pack('fill'=>'x')
-TkButton.new(nil,
- 'text' => 'quit',
- 'command' => 'exit').pack('fill'=>'x')
-
-Tk.mainloop
diff --git a/ext/tk/sample/tkline.rb b/ext/tk/sample/tkline.rb
deleted file mode 100644
index 2406b0749f..0000000000
--- a/ext/tk/sample/tkline.rb
+++ /dev/null
@@ -1,45 +0,0 @@
-
-require "tkclass"
-
-$tkline_init = FALSE
-def start_random
- return if $tkline_init
- $tkline_init = TRUE
- if defined? Thread
- Thread.start do
- loop do
- sleep 2
- Line.new($c, rand(400), rand(200), rand(400), rand(200))
- end
- end
- end
-end
-
-$c = Canvas.new
-$c.pack
-$start_x = start_y = 0
-
-def do_press(x, y)
- $start_x = x
- $start_y = y
- $current_line = Line.new($c, x, y, x, y)
- start_random
-end
-def do_motion(x, y)
- if $current_line
- $current_line.coords $start_x, $start_y, x, y
- end
-end
-
-def do_release(x, y)
- if $current_line
- $current_line.coords $start_x, $start_y, x, y
- $current_line.fill 'black'
- $current_line = nil
- end
-end
-
-$c.bind("1", proc{|e| do_press e.x, e.y})
-$c.bind("B1-Motion", proc{|x, y| do_motion x, y}, "%x %y")
-$c.bind("ButtonRelease-1", proc{|x, y| do_release x, y}, "%x %y")
-Tk.mainloop
diff --git a/ext/tk/sample/tktimer.rb b/ext/tk/sample/tktimer.rb
deleted file mode 100644
index 34377e2f39..0000000000
--- a/ext/tk/sample/tktimer.rb
+++ /dev/null
@@ -1,50 +0,0 @@
-#!/usr/local/bin/ruby
-# This script generates a counter with start and stop buttons.
-
-require "tk"
-$label = TkLabel.new {
- text '0.00'
- relief 'raised'
- width 10
- pack('side'=>'bottom', 'fill'=>'both')
-}
-
-TkButton.new {
- text 'Start'
- command proc {
- if $stopped
- $stopped = FALSE
- tick
- end
- }
- pack('side'=>'left','fill'=>'both','expand'=>'yes')
-}
-TkButton.new {
- text 'Stop'
- command proc{
- exit if $stopped
- $stopped = TRUE
- }
- pack('side'=>'right','fill'=>'both','expand'=>'yes')
-}
-
-$seconds=0
-$hundredths=0
-$stopped=TRUE
-
-def tick
- if $stopped then return end
- Tk.after 50, proc{tick}
- $hundredths+=5
- if $hundredths >= 100
- $hundredths=0
- $seconds+=1
- end
- $label.text format("%d.%02d", $seconds, $hundredths)
-end
-
-root = Tk.root
-root.bind "Control-c", proc{root.destroy}
-root.bind "Control-q", proc{root.destroy}
-Tk.root.focus
-Tk.mainloop
diff --git a/ext/tk/tkutil.c b/ext/tk/tkutil.c
deleted file mode 100644
index b42069e234..0000000000
--- a/ext/tk/tkutil.c
+++ /dev/null
@@ -1,45 +0,0 @@
-/************************************************
-
- tk.c -
-
- $Author$
- $Date$
- created at: Fri Nov 3 00:47:54 JST 1995
-
-************************************************/
-
-#include "ruby.h"
-
-static VALUE
-tk_eval_cmd(argc, argv)
- int argc;
- VALUE argv[];
-{
- VALUE cmd, rest;
-
- rb_scan_args(argc, argv, "1*", &cmd, &rest);
- return rb_eval_cmd(cmd, rest, 0);
-}
-
-static VALUE
-tk_s_new(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- VALUE obj = rb_class_new_instance(argc, argv, klass);
-
- if (rb_block_given_p()) rb_obj_instance_eval(0, 0, obj);
- return obj;
-}
-
-void
-Init_tkutil()
-{
- VALUE mTK = rb_define_module("TkUtil");
- VALUE cTK = rb_define_class("TkKernel", rb_cObject);
-
- rb_define_singleton_method(mTK, "eval_cmd", tk_eval_cmd, -1);
-
- rb_define_singleton_method(cTK, "new", tk_s_new, -1);
-}
diff --git a/file.c b/file.c
deleted file mode 100644
index 1735012584..0000000000
--- a/file.c
+++ /dev/null
@@ -1,2651 +0,0 @@
-/**********************************************************************
-
- file.c -
-
- $Author$
- $Date$
- created at: Mon Nov 15 12:24:34 JST 1993
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
- Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
- Copyright (C) 2000 Information-technology Promotion Agency, Japan
-
-**********************************************************************/
-
-#ifdef NT
-#include "missing/file.h"
-#endif
-
-#include "ruby.h"
-#include "rubyio.h"
-#include "rubysig.h"
-#include "util.h"
-#include "dln.h"
-
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-
-#ifdef HAVE_SYS_FILE_H
-# include <sys/file.h>
-#else
-int flock _((int, int));
-#endif
-
-#ifdef HAVE_SYS_PARAM_H
-# include <sys/param.h>
-#else
-# define MAXPATHLEN 1024
-#endif
-
-#include <time.h>
-#ifdef HAVE_SYS_TIME_H
-# include <sys/time.h>
-#else
-#ifndef NT
-struct timeval {
- long tv_sec; /* seconds */
- long tv_usec; /* and microseconds */
-};
-#endif /* NT */
-#endif
-
-VALUE rb_time_new _((time_t, time_t));
-
-#ifdef HAVE_UTIME_H
-#include <utime.h>
-#endif
-
-#ifdef HAVE_PWD_H
-#include <pwd.h>
-#endif
-
-#ifndef HAVE_STRING_H
-char *strrchr _((const char*,const char));
-#endif
-
-#include <sys/types.h>
-#include <sys/stat.h>
-
-#ifdef HAVE_SYS_MKDEV_H
-#include <sys/mkdev.h>
-#endif
-
-#ifndef HAVE_LSTAT
-#define lstat(path,st) stat(path,st)
-#endif
-
-VALUE rb_cFile;
-VALUE rb_mFileTest;
-static VALUE rb_cStat;
-
-static int
-apply2files(func, vargs, arg)
- void (*func)();
- VALUE vargs;
- void *arg;
-{
- int i;
- VALUE path;
- struct RArray *args = RARRAY(vargs);
-
- for (i=0; i<args->len; i++) {
- path = args->ptr[i];
- SafeStringValue(path);
- (*func)(RSTRING(path)->ptr, arg);
- }
-
- return args->len;
-}
-
-static VALUE
-rb_file_path(obj)
- VALUE obj;
-{
- OpenFile *fptr;
-
- GetOpenFile(obj, fptr);
- if (!fptr->path) return Qnil;
- return rb_str_new2(fptr->path);
-}
-
-#ifdef NT
-#include "missing/file.h"
-#endif
-
-static VALUE
-stat_new_0(klass, st)
- VALUE klass;
- struct stat *st;
-{
- struct stat *nst = 0;
-
- if (st) {
- nst = ALLOC(struct stat);
- *nst = *st;
- }
- return Data_Wrap_Struct(klass, NULL, free, nst);
-}
-
-static VALUE
-stat_new(st)
- struct stat *st;
-{
- return stat_new_0(rb_cStat, st);
-}
-
-static struct stat*
-get_stat(self)
- VALUE self;
-{
- struct stat* st;
- Data_Get_Struct(self, struct stat, st);
- if (!st) rb_raise(rb_eTypeError, "uninitialized File::Stat");
- return st;
-}
-
-static VALUE
-rb_stat_cmp(self, other)
- VALUE self, other;
-{
- if (rb_obj_is_kind_of(other, rb_obj_class(self))) {
- time_t t1 = get_stat(self)->st_mtime;
- time_t t2 = get_stat(other)->st_mtime;
- if (t1 == t2)
- return INT2FIX(0);
- else if (t1 < t2)
- return INT2FIX(-1);
- else
- return INT2FIX(1);
- }
- rb_raise(rb_eTypeError, "operand is not File::Stat");
-}
-
-static VALUE
-rb_stat_dev(self)
- VALUE self;
-{
- return INT2NUM(get_stat(self)->st_dev);
-}
-
-static VALUE
-rb_stat_ino(self)
- VALUE self;
-{
- return ULONG2NUM(get_stat(self)->st_ino);
-}
-
-static VALUE
-rb_stat_mode(self)
- VALUE self;
-{
- return UINT2NUM(get_stat(self)->st_mode);
-}
-
-static VALUE
-rb_stat_nlink(self)
- VALUE self;
-{
- return UINT2NUM(get_stat(self)->st_nlink);
-}
-
-static VALUE
-rb_stat_uid(self)
- VALUE self;
-{
- return UINT2NUM(get_stat(self)->st_uid);
-}
-
-static VALUE
-rb_stat_gid(self)
- VALUE self;
-{
- return UINT2NUM(get_stat(self)->st_gid);
-}
-
-static VALUE
-rb_stat_rdev(self)
- VALUE self;
-{
-#ifdef HAVE_ST_RDEV
- return ULONG2NUM(get_stat(self)->st_rdev);
-#else
- return INT2FIX(0);
-#endif
-}
-
-static VALUE
-rb_stat_rdev_major(self)
- VALUE self;
-{
-#if defined(HAVE_ST_RDEV) && defined(major)
- long rdev = get_stat(self)->st_rdev;
- return ULONG2NUM(major(rdev));
-#else
- return INT2FIX(0);
-#endif
-}
-
-static VALUE
-rb_stat_rdev_minor(self)
- VALUE self;
-{
-#if defined(HAVE_ST_RDEV) && defined(minor)
- long rdev = get_stat(self)->st_rdev;
- return ULONG2NUM(minor(rdev));
-#else
- return INT2FIX(0);
-#endif
-}
-
-static VALUE
-rb_stat_size(self)
- VALUE self;
-{
- return OFFT2NUM(get_stat(self)->st_size);
-}
-
-static VALUE
-rb_stat_blksize(self)
- VALUE self;
-{
-#ifdef HAVE_ST_BLKSIZE
- return ULONG2NUM(get_stat(self)->st_blksize);
-#else
- return INT2FIX(0);
-#endif
-}
-
-static VALUE
-rb_stat_blocks(self)
- VALUE self;
-{
-#ifdef HAVE_ST_BLOCKS
- return ULONG2NUM(get_stat(self)->st_blocks);
-#else
- return INT2FIX(0);
-#endif
-}
-
-static VALUE
-rb_stat_atime(self)
- VALUE self;
-{
- return rb_time_new(get_stat(self)->st_atime, 0);
-}
-
-static VALUE
-rb_stat_mtime(self)
- VALUE self;
-{
- return rb_time_new(get_stat(self)->st_mtime, 0);
-}
-
-static VALUE
-rb_stat_ctime(self)
- VALUE self;
-{
- return rb_time_new(get_stat(self)->st_ctime, 0);
-}
-
-static VALUE
-rb_stat_inspect(self)
- VALUE self;
-{
- VALUE str;
- int i;
- struct {
- char *name;
- VALUE (*func)();
- } member[] = {
- {"dev", rb_stat_dev},
- {"ino", rb_stat_ino},
- {"mode", rb_stat_mode},
- {"nlink", rb_stat_nlink},
- {"uid", rb_stat_uid},
- {"gid", rb_stat_gid},
- {"rdev", rb_stat_rdev},
- {"size", rb_stat_size},
- {"blksize", rb_stat_blksize},
- {"blocks", rb_stat_blocks},
- {"atime", rb_stat_atime},
- {"mtime", rb_stat_mtime},
- {"ctime", rb_stat_ctime},
- };
-
- str = rb_str_buf_new2("#<");
- rb_str_buf_cat2(str, rb_class2name(CLASS_OF(self)));
- rb_str_buf_cat2(str, " ");
-
- for (i = 0; i < sizeof(member)/sizeof(member[0]); i++) {
- VALUE v;
-
- if (i > 0) {
- rb_str_buf_cat2(str, ", ");
- }
- rb_str_buf_cat2(str, member[i].name);
- rb_str_buf_cat2(str, "=");
- v = (*member[i].func)(self);
- if (i == 2) { /* mode */
- char buf[32];
-
- sprintf(buf, "0%o", NUM2INT(v));
- rb_str_buf_cat2(str, buf);
- }
- else if (i == 0 || i == 6) { /* dev/rdev */
- char buf[32];
-
- sprintf(buf, "0x%x", NUM2ULONG(v));
- rb_str_buf_cat2(str, buf);
- }
- else {
- rb_str_append(str, rb_inspect(v));
- }
- }
- rb_str_buf_cat2(str, ">");
- OBJ_INFECT(str, self);
-
- return str;
-}
-
-static int
-rb_stat(file, st)
- VALUE file;
- struct stat *st;
-{
- if (TYPE(file) == T_FILE) {
- OpenFile *fptr;
-
- rb_secure(2);
- GetOpenFile(file, fptr);
- return fstat(fileno(fptr->f), st);
- }
- SafeStringValue(file);
-#if defined DJGPP
- if (RSTRING(file)->len == 0) return -1;
-#endif
- return stat(RSTRING(file)->ptr, st);
-}
-
-static VALUE
-rb_file_s_stat(klass, fname)
- VALUE klass, fname;
-{
- struct stat st;
-
- SafeStringValue(fname);
- if (stat(RSTRING(fname)->ptr, &st) == -1) {
- rb_sys_fail(RSTRING(fname)->ptr);
- }
- return stat_new(&st);
-}
-
-static VALUE
-rb_io_stat(obj)
- VALUE obj;
-{
- OpenFile *fptr;
- struct stat st;
-
- GetOpenFile(obj, fptr);
- if (fstat(fileno(fptr->f), &st) == -1) {
- rb_sys_fail(fptr->path);
- }
- return stat_new(&st);
-}
-
-static VALUE
-rb_file_s_lstat(klass, fname)
- VALUE klass, fname;
-{
-#ifdef HAVE_LSTAT
- struct stat st;
-
- SafeStringValue(fname);
- if (lstat(RSTRING(fname)->ptr, &st) == -1) {
- rb_sys_fail(RSTRING(fname)->ptr);
- }
- return stat_new(&st);
-#else
- return rb_file_s_stat(klass, fname);
-#endif
-}
-
-static VALUE
-rb_file_lstat(obj)
- VALUE obj;
-{
-#ifdef HAVE_LSTAT
- OpenFile *fptr;
- struct stat st;
-
- rb_secure(2);
- GetOpenFile(obj, fptr);
- if (!fptr->path) return Qnil;
- if (lstat(fptr->path, &st) == -1) {
- rb_sys_fail(fptr->path);
- }
- return stat_new(&st);
-#else
- return rb_io_stat(obj);
-#endif
-}
-
-static int
-group_member(gid)
- GETGROUPS_T gid;
-{
-#if !defined(NT)
- if (getgid() == gid)
- return Qtrue;
-
-# ifdef HAVE_GETGROUPS
-# ifndef NGROUPS
-# ifdef NGROUPS_MAX
-# define NGROUPS NGROUPS_MAX
-# else
-# define NGROUPS 32
-# endif
-# endif
- {
- GETGROUPS_T gary[NGROUPS];
- int anum;
-
- anum = getgroups(NGROUPS, gary);
- while (--anum >= 0)
- if (gary[anum] == gid)
- return Qtrue;
- }
-# endif
-#endif
- return Qfalse;
-}
-
-#ifndef S_IXUGO
-# define S_IXUGO (S_IXUSR | S_IXGRP | S_IXOTH)
-#endif
-
-int
-eaccess(path, mode)
- const char *path;
- int mode;
-{
-#ifdef S_IXGRP
- struct stat st;
- int euid;
-
- if (stat(path, &st) < 0) return -1;
-
- euid = geteuid();
-
- if (euid == 0) {
- /* Root can read or write any file. */
- if (!(mode & X_OK))
- return 0;
-
- /* Root can execute any file that has any one of the execute
- bits set. */
- if (st.st_mode & S_IXUGO)
- return 0;
-
- return -1;
- }
-
- if (st.st_uid == euid) /* owner */
- mode <<= 6;
- else if (getegid() == st.st_gid || group_member(st.st_gid))
- mode <<= 3;
-
- if ((st.st_mode & mode) == mode) return 0;
-
- return -1;
-#else
- return access(path, mode);
-#endif
-}
-
-static VALUE
-test_d(obj, fname)
- VALUE obj, fname;
-{
-#ifndef S_ISDIR
-# define S_ISDIR(m) ((m & S_IFMT) == S_IFDIR)
-#endif
-
- struct stat st;
-
- if (rb_stat(fname, &st) < 0) return Qfalse;
- if (S_ISDIR(st.st_mode)) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-test_p(obj, fname)
- VALUE obj, fname;
-{
-#ifdef S_IFIFO
-# ifndef S_ISFIFO
-# define S_ISFIFO(m) ((m & S_IFMT) == S_IFIFO)
-# endif
-
- struct stat st;
-
- if (rb_stat(fname, &st) < 0) return Qfalse;
- if (S_ISFIFO(st.st_mode)) return Qtrue;
-
-#endif
- return Qfalse;
-}
-
-static VALUE
-test_l(obj, fname)
- VALUE obj, fname;
-{
-#ifndef S_ISLNK
-# ifdef _S_ISLNK
-# define S_ISLNK(m) _S_ISLNK(m)
-# else
-# ifdef _S_IFLNK
-# define S_ISLNK(m) ((m & S_IFMT) == _S_IFLNK)
-# else
-# ifdef S_IFLNK
-# define S_ISLNK(m) ((m & S_IFMT) == S_IFLNK)
-# endif
-# endif
-# endif
-#endif
-
-#ifdef S_ISLNK
- struct stat st;
-
- SafeStringValue(fname);
- if (lstat(RSTRING(fname)->ptr, &st) < 0) return Qfalse;
- if (S_ISLNK(st.st_mode)) return Qtrue;
-#endif
-
- return Qfalse;
-}
-
-static VALUE
-test_S(obj, fname)
- VALUE obj, fname;
-{
-#ifndef S_ISSOCK
-# ifdef _S_ISSOCK
-# define S_ISSOCK(m) _S_ISSOCK(m)
-# else
-# ifdef _S_IFSOCK
-# define S_ISSOCK(m) ((m & S_IFMT) == _S_IFSOCK)
-# else
-# ifdef S_IFSOCK
-# define S_ISSOCK(m) ((m & S_IFMT) == S_IFSOCK)
-# endif
-# endif
-# endif
-#endif
-
-#ifdef S_ISSOCK
- struct stat st;
-
- if (rb_stat(fname, &st) < 0) return Qfalse;
- if (S_ISSOCK(st.st_mode)) return Qtrue;
-
-#endif
- return Qfalse;
-}
-
-static VALUE
-test_b(obj, fname)
- VALUE obj, fname;
-{
-#ifndef S_ISBLK
-# ifdef S_IFBLK
-# define S_ISBLK(m) ((m & S_IFMT) == S_IFBLK)
-# else
-# define S_ISBLK(m) (0) /* anytime false */
-# endif
-#endif
-
-#ifdef S_ISBLK
- struct stat st;
-
- if (rb_stat(fname, &st) < 0) return Qfalse;
- if (S_ISBLK(st.st_mode)) return Qtrue;
-
-#endif
- return Qfalse;
-}
-
-static VALUE
-test_c(obj, fname)
- VALUE obj, fname;
-{
-#ifndef S_ISCHR
-# define S_ISCHR(m) ((m & S_IFMT) == S_IFCHR)
-#endif
-
- struct stat st;
-
- if (rb_stat(fname, &st) < 0) return Qfalse;
- if (S_ISCHR(st.st_mode)) return Qtrue;
-
- return Qfalse;
-}
-
-static VALUE
-test_e(obj, fname)
- VALUE obj, fname;
-{
- struct stat st;
-
- if (rb_stat(fname, &st) < 0) return Qfalse;
- return Qtrue;
-}
-
-static VALUE
-test_r(obj, fname)
- VALUE obj, fname;
-{
- SafeStringValue(fname);
- if (eaccess(RSTRING(fname)->ptr, R_OK) < 0) return Qfalse;
- return Qtrue;
-}
-
-static VALUE
-test_R(obj, fname)
- VALUE obj, fname;
-{
- SafeStringValue(fname);
- if (access(RSTRING(fname)->ptr, R_OK) < 0) return Qfalse;
- return Qtrue;
-}
-
-static VALUE
-test_w(obj, fname)
- VALUE obj, fname;
-{
- SafeStringValue(fname);
- if (eaccess(RSTRING(fname)->ptr, W_OK) < 0) return Qfalse;
- return Qtrue;
-}
-
-static VALUE
-test_W(obj, fname)
- VALUE obj, fname;
-{
- SafeStringValue(fname);
- if (access(RSTRING(fname)->ptr, W_OK) < 0) return Qfalse;
- return Qtrue;
-}
-
-static VALUE
-test_x(obj, fname)
- VALUE obj, fname;
-{
- SafeStringValue(fname);
- if (eaccess(RSTRING(fname)->ptr, X_OK) < 0) return Qfalse;
- return Qtrue;
-}
-
-static VALUE
-test_X(obj, fname)
- VALUE obj, fname;
-{
- SafeStringValue(fname);
- if (access(RSTRING(fname)->ptr, X_OK) < 0) return Qfalse;
- return Qtrue;
-}
-
-#ifndef S_ISREG
-# define S_ISREG(m) ((m & S_IFMT) == S_IFREG)
-#endif
-
-static VALUE
-test_f(obj, fname)
- VALUE obj, fname;
-{
- struct stat st;
-
- if (rb_stat(fname, &st) < 0) return Qfalse;
- if (S_ISREG(st.st_mode)) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-test_z(obj, fname)
- VALUE obj, fname;
-{
- struct stat st;
-
- if (rb_stat(fname, &st) < 0) return Qfalse;
- if (st.st_size == 0) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-test_s(obj, fname)
- VALUE obj, fname;
-{
- struct stat st;
-
- if (rb_stat(fname, &st) < 0) return Qnil;
- if (st.st_size == 0) return Qnil;
- return OFFT2NUM(st.st_size);
-}
-
-static VALUE
-test_owned(obj, fname)
- VALUE obj, fname;
-{
- struct stat st;
-
- if (rb_stat(fname, &st) < 0) return Qfalse;
- if (st.st_uid == geteuid()) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-test_rowned(obj, fname)
- VALUE obj, fname;
-{
- struct stat st;
-
- if (rb_stat(fname, &st) < 0) return Qfalse;
- if (st.st_uid == getuid()) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-test_grpowned(obj, fname)
- VALUE obj, fname;
-{
-#ifndef NT
- struct stat st;
-
- if (rb_stat(fname, &st) < 0) return Qfalse;
- if (st.st_gid == getegid()) return Qtrue;
-#endif
- return Qfalse;
-}
-
-#if defined(S_ISUID) || defined(S_ISGID) || defined(S_ISVTX)
-static VALUE
-check3rdbyte(fname, mode)
- VALUE fname;
- int mode;
-{
- struct stat st;
-
- SafeStringValue(fname);
- if (stat(RSTRING(fname)->ptr, &st) < 0) return Qfalse;
- if (st.st_mode & mode) return Qtrue;
- return Qfalse;
-}
-#endif
-
-static VALUE
-test_suid(obj, fname)
- VALUE obj, fname;
-{
-#ifdef S_ISUID
- return check3rdbyte(fname, S_ISUID);
-#else
- return Qfalse;
-#endif
-}
-
-static VALUE
-test_sgid(obj, fname)
- VALUE obj, fname;
-{
-#ifdef S_ISGID
- return check3rdbyte(fname, S_ISGID);
-#else
- return Qfalse;
-#endif
-}
-
-static VALUE
-test_sticky(obj, fname)
- VALUE obj, fname;
-{
-#ifdef S_ISVTX
- return check3rdbyte(fname, S_ISVTX);
-#else
- return Qnil;
-#endif
-}
-
-static VALUE
-rb_file_s_size(klass, fname)
- VALUE klass, fname;
-{
- struct stat st;
-
- if (rb_stat(fname, &st) < 0)
- rb_sys_fail(RSTRING(fname)->ptr);
- return rb_int2inum(st.st_size);
-}
-
-static VALUE
-rb_file_ftype(st)
- struct stat *st;
-{
- char *t;
-
- if (S_ISREG(st->st_mode)) {
- t = "file";
- }
- else if (S_ISDIR(st->st_mode)) {
- t = "directory";
- }
- else if (S_ISCHR(st->st_mode)) {
- t = "characterSpecial";
- }
-#ifdef S_ISBLK
- else if (S_ISBLK(st->st_mode)) {
- t = "blockSpecial";
- }
-#endif
-#ifdef S_ISFIFO
- else if (S_ISFIFO(st->st_mode)) {
- t = "fifo";
- }
-#endif
-#ifdef S_ISLNK
- else if (S_ISLNK(st->st_mode)) {
- t = "link";
- }
-#endif
-#ifdef S_ISSOCK
- else if (S_ISSOCK(st->st_mode)) {
- t = "socket";
- }
-#endif
- else {
- t = "unknown";
- }
-
- return rb_str_new2(t);
-}
-
-static VALUE
-rb_file_s_ftype(klass, fname)
- VALUE klass, fname;
-{
- struct stat st;
-
- SafeStringValue(fname);
- if (lstat(RSTRING(fname)->ptr, &st) == -1) {
- rb_sys_fail(RSTRING(fname)->ptr);
- }
-
- return rb_file_ftype(&st);
-}
-
-static VALUE
-rb_file_s_atime(klass, fname)
- VALUE klass, fname;
-{
- struct stat st;
-
- if (rb_stat(fname, &st) < 0)
- rb_sys_fail(RSTRING(fname)->ptr);
- return rb_time_new(st.st_atime, 0);
-}
-
-static VALUE
-rb_file_atime(obj)
- VALUE obj;
-{
- OpenFile *fptr;
- struct stat st;
-
- GetOpenFile(obj, fptr);
- if (fstat(fileno(fptr->f), &st) == -1) {
- rb_sys_fail(fptr->path);
- }
- return rb_time_new(st.st_atime, 0);
-}
-
-static VALUE
-rb_file_s_mtime(klass, fname)
- VALUE klass, fname;
-{
- struct stat st;
-
- if (rb_stat(fname, &st) < 0)
- rb_sys_fail(RSTRING(fname)->ptr);
- return rb_time_new(st.st_mtime, 0);
-}
-
-static VALUE
-rb_file_mtime(obj)
- VALUE obj;
-{
- OpenFile *fptr;
- struct stat st;
-
- GetOpenFile(obj, fptr);
- if (fstat(fileno(fptr->f), &st) == -1) {
- rb_sys_fail(fptr->path);
- }
- return rb_time_new(st.st_mtime, 0);
-}
-
-static VALUE
-rb_file_s_ctime(klass, fname)
- VALUE klass, fname;
-{
- struct stat st;
-
- if (rb_stat(fname, &st) < 0)
- rb_sys_fail(RSTRING(fname)->ptr);
- return rb_time_new(st.st_ctime, 0);
-}
-
-static VALUE
-rb_file_ctime(obj)
- VALUE obj;
-{
- OpenFile *fptr;
- struct stat st;
-
- GetOpenFile(obj, fptr);
- if (fstat(fileno(fptr->f), &st) == -1) {
- rb_sys_fail(fptr->path);
- }
- return rb_time_new(st.st_ctime, 0);
-}
-
-static void
-chmod_internal(path, mode)
- const char *path;
- int mode;
-{
- if (chmod(path, mode) < 0)
- rb_sys_fail(path);
-}
-
-static VALUE
-rb_file_s_chmod(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE vmode;
- VALUE rest;
- int mode, n;
-
- rb_secure(2);
- rb_scan_args(argc, argv, "1*", &vmode, &rest);
- mode = NUM2INT(vmode);
-
- n = apply2files(chmod_internal, rest, mode);
- return INT2FIX(n);
-}
-
-static VALUE
-rb_file_chmod(obj, vmode)
- VALUE obj, vmode;
-{
- OpenFile *fptr;
- int mode;
-
- rb_secure(2);
- mode = NUM2INT(vmode);
-
- GetOpenFile(obj, fptr);
-#ifdef HAVE_FCHMOD
- if (fchmod(fileno(fptr->f), mode) == -1)
- rb_sys_fail(fptr->path);
-#else
- if (!fptr->path) return Qnil;
- if (chmod(fptr->path, mode) == -1)
- rb_sys_fail(fptr->path);
-#endif
-
- return INT2FIX(0);
-}
-
-#if defined(HAVE_LCHMOD)
-static void
-lchmod_internal(path, mode)
- const char *path;
- int mode;
-{
- if (lchmod(path, mode) < 0)
- rb_sys_fail(path);
-}
-
-static VALUE
-rb_file_s_lchmod(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE vmode;
- VALUE rest;
- int mode, n;
-
- rb_secure(2);
- rb_scan_args(argc, argv, "1*", &vmode, &rest);
- mode = NUM2INT(vmode);
-
- n = apply2files(lchmod_internal, rest, mode);
- return INT2FIX(n);
-}
-#else
-static VALUE
-rb_file_s_lchmod(argc, argv)
- int argc;
- VALUE *argv;
-{
- rb_notimplement();
-}
-#endif
-
-struct chown_args {
- int owner, group;
-};
-
-static void
-chown_internal(path, args)
- const char *path;
- struct chown_args *args;
-{
- if (chown(path, args->owner, args->group) < 0)
- rb_sys_fail(path);
-}
-
-static VALUE
-rb_file_s_chown(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE o, g, rest;
- struct chown_args arg;
- int n;
-
- rb_secure(2);
- rb_scan_args(argc, argv, "2*", &o, &g, &rest);
- if (NIL_P(o)) {
- arg.owner = -1;
- }
- else {
- arg.owner = NUM2INT(o);
- }
- if (NIL_P(g)) {
- arg.group = -1;
- }
- else {
- arg.group = NUM2INT(g);
- }
-
- n = apply2files(chown_internal, rest, &arg);
- return INT2FIX(n);
-}
-
-static VALUE
-rb_file_chown(obj, owner, group)
- VALUE obj, owner, group;
-{
- OpenFile *fptr;
-
- rb_secure(2);
- GetOpenFile(obj, fptr);
-#if defined(DJGPP) || defined(__CYGWIN32__) || defined(NT) || defined(__EMX__)
- if (!fptr->path) return Qnil;
- if (chown(fptr->path, NUM2INT(owner), NUM2INT(group)) == -1)
- rb_sys_fail(fptr->path);
-#else
- if (fchown(fileno(fptr->f), NUM2INT(owner), NUM2INT(group)) == -1)
- rb_sys_fail(fptr->path);
-#endif
-
- return INT2FIX(0);
-}
-
-#if defined(HAVE_LCHOWN) && !defined(__CHECKER__)
-static void
-lchown_internal(path, args)
- const char *path;
- struct chown_args *args;
-{
- if (lchown(path, args->owner, args->group) < 0)
- rb_sys_fail(path);
-}
-
-static VALUE
-rb_file_s_lchown(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE o, g, rest;
- struct chown_args arg;
- int n;
-
- rb_secure(2);
- rb_scan_args(argc, argv, "2*", &o, &g, &rest);
- if (NIL_P(o)) {
- arg.owner = -1;
- }
- else {
- arg.owner = NUM2INT(o);
- }
- if (NIL_P(g)) {
- arg.group = -1;
- }
- else {
- arg.group = NUM2INT(g);
- }
-
- n = apply2files(lchown_internal, rest, &arg);
- return INT2FIX(n);
-}
-#else
-static VALUE
-rb_file_s_lchown(argc, argv)
- int argc;
- VALUE *argv;
-{
- rb_notimplement();
-}
-#endif
-
-struct timeval rb_time_timeval();
-
-#if defined(HAVE_UTIMES) && !defined(__CHECKER__)
-
-static void
-utime_internal(path, tvp)
- char *path;
- struct timeval tvp[];
-{
- if (utimes(path, tvp) < 0)
- rb_sys_fail(path);
-}
-
-static VALUE
-rb_file_s_utime(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE atime, mtime, rest;
- struct timeval tvp[2];
- int n;
-
- rb_scan_args(argc, argv, "2*", &atime, &mtime, &rest);
-
- tvp[0] = rb_time_timeval(atime);
- tvp[1] = rb_time_timeval(mtime);
-
- n = apply2files(utime_internal, rest, tvp);
- return INT2FIX(n);
-}
-
-#else
-
-#ifndef HAVE_UTIME_H
-# ifdef NT
-# if defined(__BORLANDC__)
-# include <utime.h>
-# else
-# include <sys/utime.h>
-# endif
-# if defined(_MSC_VER) || defined __MINGW32__
-# define utimbuf _utimbuf
-# endif
-# else
-struct utimbuf {
- long actime;
- long modtime;
-};
-# endif
-#endif
-
-static void
-utime_internal(path, utp)
- const char *path;
- struct utimbuf *utp;
-{
- if (utime(path, utp) < 0)
- rb_sys_fail(path);
-}
-
-static VALUE
-rb_file_s_utime(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE atime, mtime, rest;
- int n;
- struct timeval tv;
- struct utimbuf utbuf;
-
- rb_scan_args(argc, argv, "2*", &atime, &mtime, &rest);
-
- tv = rb_time_timeval(atime);
- utbuf.actime = tv.tv_sec;
- tv = rb_time_timeval(mtime);
- utbuf.modtime = tv.tv_sec;
-
- n = apply2files(utime_internal, rest, &utbuf);
- return INT2FIX(n);
-}
-
-#endif
-
-static VALUE
-rb_file_s_link(klass, from, to)
- VALUE klass, from, to;
-{
- SafeStringValue(from);
- SafeStringValue(to);
-
- if (link(RSTRING(from)->ptr, RSTRING(to)->ptr) < 0)
- rb_sys_fail(RSTRING(from)->ptr);
- return INT2FIX(0);
-}
-
-static VALUE
-rb_file_s_symlink(klass, from, to)
- VALUE klass, from, to;
-{
-#ifdef HAVE_SYMLINK
- SafeStringValue(from);
- SafeStringValue(to);
-
- if (symlink(RSTRING(from)->ptr, RSTRING(to)->ptr) < 0)
- rb_sys_fail(RSTRING(from)->ptr);
- return INT2FIX(0);
-#else
- rb_notimplement();
- return Qnil; /* not reached */
-#endif
-}
-
-static VALUE
-rb_file_s_readlink(klass, path)
- VALUE klass, path;
-{
-#ifdef HAVE_READLINK
- char *buf;
- int size = 100;
- int rv;
- VALUE v;
-
- SafeStringValue(path);
- buf = xmalloc(size);
- if ((rv = readlink(RSTRING(path)->ptr, buf, size)) == size) {
- size *= 2;
- buf = xrealloc(buf, size);
- }
- if (rv < 0) rb_sys_fail(RSTRING(path)->ptr);
- v = rb_tainted_str_new(buf, rv);
- free(buf);
-
- return v;
-#else
- rb_notimplement();
- return Qnil; /* not reached */
-#endif
-}
-
-static void
-unlink_internal(path)
- const char *path;
-{
- if (unlink(path) < 0)
- rb_sys_fail(path);
-}
-
-static VALUE
-rb_file_s_unlink(klass, args)
- VALUE klass, args;
-{
- int n;
-
- rb_secure(2);
- n = apply2files(unlink_internal, args, 0);
- return INT2FIX(n);
-}
-
-static VALUE
-rb_file_s_rename(klass, from, to)
- VALUE klass, from, to;
-{
- SafeStringValue(from);
- SafeStringValue(to);
-
- if (rename(RSTRING(from)->ptr, RSTRING(to)->ptr) < 0) {
-#if defined __CYGWIN__
- extern unsigned long __attribute__((stdcall)) GetLastError();
- errno = GetLastError(); /* This is a Cygwin bug */
-#endif
- rb_sys_fail(RSTRING(from)->ptr);
- }
-
- return INT2FIX(0);
-}
-
-static VALUE
-rb_file_s_umask(argc, argv)
- int argc;
- VALUE *argv;
-{
- int omask = 0;
-
- rb_secure(2);
- if (argc == 0) {
- omask = umask(0);
- umask(omask);
- }
- else if (argc == 1) {
- omask = umask(NUM2INT(argv[0]));
- }
- else {
- rb_raise(rb_eArgError, "wrong number of argument");
- }
- return INT2FIX(omask);
-}
-
-#if defined DOSISH
-#define isdirsep(x) ((x) == '/' || (x) == '\\')
-#else
-#define isdirsep(x) ((x) == '/')
-#endif
-#ifndef CharNext /* defined as CharNext[AW] on Windows. */
-# if defined(DJGPP)
-# define CharNext(p) ((p) + mblen(p, MB_CUR_MAX))
-# else
-# define CharNext(p) ((p) + 1)
-# endif
-#endif
-
-static char *
-strrdirsep(path)
- char *path;
-{
- char *last = NULL;
- while (*path) {
- if (isdirsep(*path)) {
- last = path++;
- }
- else {
- path = CharNext(path);
- }
- }
- return last;
-}
-
-#define BUFCHECK(cond) while (cond) {\
- long bdiff = p - buf;\
- buflen *= 2;\
- rb_str_resize(result, buflen);\
- buf = RSTRING(result)->ptr;\
- p = buf + bdiff;\
- pend = buf + buflen;\
-}
-
-VALUE
-rb_file_s_expand_path(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE fname, dname, result;
- char *s, *buf, *b, *p, *pend;
- long buflen = MAXPATHLEN;
- int tainted;
-
- rb_scan_args(argc, argv, "11", &fname, &dname);
- result = rb_str_new(0, buflen + 2);
-
- s = StringValuePtr(fname);
- p = buf = RSTRING(result)->ptr;
- pend = p + buflen;
- tainted = OBJ_TAINTED(fname);
-
- if (s[0] == '~') {
- if (isdirsep(s[1]) || s[1] == '\0') {
- char *dir = getenv("HOME");
-
- if (!dir) {
- rb_raise(rb_eArgError, "couldn't find HOME environment -- expanding `%s'", s);
- }
- BUFCHECK (strlen(dir) > buflen);
- strcpy(buf, dir);
- p = buf + strlen(dir);
- s++;
- tainted = 1;
- }
- else {
-#ifdef HAVE_PWD_H
- struct passwd *pwPtr;
- s++;
-#endif
- b = s;
- while (*s && !isdirsep(*s)) {
- s = CharNext(s);
- }
- BUFCHECK (p + (s-b) >= pend);
- memcpy(p, b, s-b);
- p += s-b;
- *p = '\0';
-#ifdef HAVE_PWD_H
- pwPtr = getpwnam(buf);
- if (!pwPtr) {
- endpwent();
- rb_raise(rb_eArgError, "user %s doesn't exist", buf);
- }
- BUFCHECK (strlen(pwPtr->pw_dir) > buflen);
- strcpy(buf, pwPtr->pw_dir);
- p = buf + strlen(pwPtr->pw_dir);
- endpwent();
-#endif
- }
- }
-#if defined DOSISH
- /* skip drive letter */
- else if (ISALPHA(s[0]) && s[1] == ':' && isdirsep(s[2])) {
- b = s;
- while (*s && !isdirsep(*s)) {
- s = CharNext(s);
- }
- BUFCHECK (p + (s-b) >= pend);
- memcpy(p, b, s-b);
- p += s-b;
- }
-#endif
- else if (!isdirsep(*s)) {
- if (!NIL_P(dname)) {
- dname = rb_file_s_expand_path(1, &dname);
- if (OBJ_TAINTED(dname)) tainted = 1;
- BUFCHECK (RSTRING(dname)->len > buflen);
- memcpy(buf, RSTRING(dname)->ptr, RSTRING(dname)->len);
- p += RSTRING(dname)->len;
- }
- else {
- char *dir = my_getcwd();
-
- tainted = 1;
- BUFCHECK (strlen(dir) > buflen);
- strcpy(buf, dir);
- free(dir);
- p = &buf[strlen(buf)];
- }
- while (p > buf && *(p - 1) == '/') p--;
- }
- else {
- while (*s && isdirsep(*s)) {
- *p++ = '/';
- BUFCHECK (p >= pend);
- s++;
- }
- if (p > buf && *s) p--;
- }
- *p = '/';
-
- b = s;
- while (*s) {
- switch (*s) {
- case '.':
- if (b == s++) { /* beginning of path element */
- switch (*s) {
- case '\0':
- b = s;
- break;
- case '.':
- if (*(s+1) == '\0' || isdirsep(*(s+1))) {
- /* We must go back to the parent */
- *p = '\0';
- if (!(b = strrdirsep(buf))) {
- *p = '/';
- }
- else {
- p = b;
- }
- b = ++s;
- }
- break;
- case '/':
-#if defined DOSISH
- case '\\':
-#endif
- b = ++s;
- break;
- default:
- /* ordinary path element, beginning don't move */
- break;
- }
- }
- break;
- case '/':
-#if defined DOSISH
- case '\\':
-#endif
- if (s > b) {
- BUFCHECK (p + (s-b+1) >= pend);
- memcpy(++p, b, s-b);
- p += s-b;
- *p = '/';
- }
- b = ++s;
- break;
- default:
- s = CharNext(s);
- break;
- }
- }
-
- if (s > b) {
- BUFCHECK (p + (s-b) >= pend);
- memcpy(++p, b, s-b);
- p += s-b;
- }
-#if defined(DOSISH)
- else if (ISALPHA(buf[0]) && (buf[1] == ':') && isdirsep(buf[2])) {
- /* root directory needs a trailing backslash,
- otherwise it mean the current directory of the drive */
- if (p == (buf+2)) p++;
- }
- else if (isdirsep(buf[0]) && isdirsep(buf[1])) {
- if (p == (buf+1)) p++;
- }
-#endif
-
- if (tainted) OBJ_TAINT(result);
- RSTRING(result)->len = p - buf;
- *p = '\0';
- return result;
-}
-
-static int
-rmext(p, e)
- const char *p, *e;
-{
- int l1, l2;
-
- l1 = strlen(p);
- if (!e) return 0;
-
- l2 = strlen(e);
- if (l2 == 2 && e[1] == '*') {
- e = strrchr(p, *e);
- if (!e) return 0;
- return e - p;
- }
- if (l1 < l2) return l1;
-
- if (strcmp(p+l1-l2, e) == 0) {
- return l1-l2;
- }
- return 0;
-}
-
-static VALUE
-rb_file_s_basename(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE fname, fext, basename;
- char *name, *p, *ext;
- int f;
-
- if (rb_scan_args(argc, argv, "11", &fname, &fext) == 2) {
- ext = StringValuePtr(fext);
- }
- name = StringValuePtr(fname);
- p = strrdirsep(name);
- if (!p) {
- if (NIL_P(fext) || !(f = rmext(name, ext)))
- return fname;
- basename = rb_str_new(name, f);
- }
- else {
- p++; /* skip last / */
- if (NIL_P(fext) || !(f = rmext(p, ext))) {
- basename = rb_str_new2(p);
- }
- else {
- basename = rb_str_new(p, f);
- }
- }
- OBJ_INFECT(basename, fname);
- return basename;
-}
-
-static VALUE
-rb_file_s_dirname(klass, fname)
- VALUE klass, fname;
-{
- char *name, *p;
- VALUE dirname;
-
- name = StringValuePtr(fname);
- p = strrdirsep(name);
- if (!p) {
- return rb_str_new2(".");
- }
- if (p == name)
- p++;
- dirname = rb_str_new(name, p - name);
- if (OBJ_TAINTED(fname)) OBJ_TAINT(dirname);
- return dirname;
-}
-
-static VALUE
-rb_file_s_split(klass, path)
- VALUE klass, path;
-{
- return rb_assoc_new(rb_file_s_dirname(Qnil, path), rb_file_s_basename(1,&path));
-}
-
-static VALUE separator;
-
-static VALUE
-rb_file_s_join(klass, args)
- VALUE klass, args;
-{
- return rb_ary_join(args, separator);
-}
-
-static VALUE
-rb_file_s_truncate(klass, path, len)
- VALUE klass, path, len;
-{
- rb_secure(2);
- SafeStringValue(path);
-
-#ifdef HAVE_TRUNCATE
- if (truncate(RSTRING(path)->ptr, NUM2INT(len)) < 0)
- rb_sys_fail(RSTRING(path)->ptr);
-#else
-# ifdef HAVE_CHSIZE
- {
- int tmpfd;
-
-# if defined(NT)
- if ((tmpfd = open(RSTRING(path)->ptr, O_RDWR)) < 0) {
- rb_sys_fail(RSTRING(path)->ptr);
- }
-# else
- if ((tmpfd = open(RSTRING(path)->ptr, 0)) < 0) {
- rb_sys_fail(RSTRING(path)->ptr);
- }
-# endif
- if (chsize(tmpfd, NUM2INT(len)) < 0) {
- close(tmpfd);
- rb_sys_fail(RSTRING(path)->ptr);
- }
- close(tmpfd);
- }
-# else
- rb_notimplement();
-# endif
-#endif
- return INT2FIX(0);
-}
-
-static VALUE
-rb_file_truncate(obj, len)
- VALUE obj, len;
-{
- OpenFile *fptr;
-
- rb_secure(2);
- GetOpenFile(obj, fptr);
- if (!(fptr->mode & FMODE_WRITABLE)) {
- rb_raise(rb_eIOError, "not opened for writing");
- }
-#ifdef HAVE_TRUNCATE
- if (ftruncate(fileno(fptr->f), NUM2INT(len)) < 0)
- rb_sys_fail(fptr->path);
-#else
-# ifdef HAVE_CHSIZE
- if (chsize(fileno(fptr->f), NUM2INT(len)) < 0)
- rb_sys_fail(fptr->path);
-# else
- rb_notimplement();
-# endif
-#endif
- return INT2FIX(0);
-}
-
-# ifndef LOCK_SH
-# define LOCK_SH 1
-# endif
-# ifndef LOCK_EX
-# define LOCK_EX 2
-# endif
-# ifndef LOCK_NB
-# define LOCK_NB 4
-# endif
-# ifndef LOCK_UN
-# define LOCK_UN 8
-# endif
-
-#if 0
-static int
-rb_thread_flock(fd, op, fptr)
- int fd, op;
- OpenFile *fptr;
-{
- if (rb_thread_alone() || (op & LOCK_NB)) {
- return flock(fd, op);
- }
- op |= LOCK_NB;
- while (flock(fd, op) < 0) {
- switch (errno) {
- case EAGAIN:
- case EACCES:
-#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
- case EWOULDBLOCK:
-#endif
- rb_thread_polling(); /* busy wait */
- rb_io_check_closed(fptr);
- continue;
- default:
- return -1;
- }
- }
- return 0;
-}
-#define flock(fd, op) rb_thread_flock(fd, op, fptr)
-#endif
-
-static VALUE
-rb_file_flock(obj, operation)
- VALUE obj;
- VALUE operation;
-{
-#ifndef __CHECKER__
- OpenFile *fptr;
- int ret;
-
- rb_secure(2);
- GetOpenFile(obj, fptr);
-
- if (fptr->mode & FMODE_WRITABLE) {
- fflush(GetWriteFile(fptr));
- }
- TRAP_BEG;
- ret = flock(fileno(fptr->f), NUM2INT(operation));
- TRAP_END;
- if (ret < 0) {
- switch (errno) {
- case EAGAIN:
- case EACCES:
-#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
- case EWOULDBLOCK:
-#endif
- return Qfalse;
- }
- rb_sys_fail(fptr->path);
- }
-#endif
- return INT2FIX(0);
-}
-#undef flock
-
-static void
-test_check(n, argc, argv)
- int n, argc;
- VALUE *argv;
-{
- int i;
-
- n+=1;
- if (n != argc) rb_raise(rb_eArgError, "wrong number of arguments(%d for %d)", argc, n);
- for (i=1; i<n; i++) {
- switch (TYPE(argv[i])) {
- case T_STRING:
- SafeStringValue(argv[i]);
- break;
- case T_FILE:
- break;
- default:
- Check_Type(argv[i], T_STRING);
- break;
- }
- }
-}
-
-#define CHECK(n) test_check((n), argc, argv)
-
-static VALUE
-rb_f_test(argc, argv)
- int argc;
- VALUE *argv;
-{
- int cmd;
-
- if (argc == 0) rb_raise(rb_eArgError, "wrong number of arguments");
-#if 0 /* 1.7 behavior? */
- if (argc == 1) {
- return RTEST(argv[0]) ? Qtrue : Qfalse;
- }
-#endif
- cmd = NUM2CHR(argv[0]);
- if (cmd == 0) return Qfalse;
- if (strchr("bcdefgGkloOprRsSuwWxXz", cmd)) {
- CHECK(1);
- switch (cmd) {
- case 'b':
- return test_b(0, argv[1]);
-
- case 'c':
- return test_c(0, argv[1]);
-
- case 'd':
- return test_d(0, argv[1]);
-
- case 'a':
- case 'e':
- return test_e(0, argv[1]);
-
- case 'f':
- return test_f(0, argv[1]);
-
- case 'g':
- return test_sgid(0, argv[1]);
-
- case 'G':
- return test_grpowned(0, argv[1]);
-
- case 'k':
- return test_sticky(0, argv[1]);
-
- case 'l':
- return test_l(0, argv[1]);
-
- case 'o':
- return test_owned(0, argv[1]);
-
- case 'O':
- return test_rowned(0, argv[1]);
-
- case 'p':
- return test_p(0, argv[1]);
-
- case 'r':
- return test_r(0, argv[1]);
-
- case 'R':
- return test_R(0, argv[1]);
-
- case 's':
- return test_s(0, argv[1]);
-
- case 'S':
- return test_S(0, argv[1]);
-
- case 'u':
- return test_suid(0, argv[1]);
-
- case 'w':
- return test_w(0, argv[1]);
-
- case 'W':
- return test_W(0, argv[1]);
-
- case 'x':
- return test_x(0, argv[1]);
-
- case 'X':
- return test_X(0, argv[1]);
-
- case 'z':
- return test_z(0, argv[1]);
- }
- }
-
- if (strchr("MAC", cmd)) {
- struct stat st;
-
- CHECK(1);
- if (rb_stat(argv[1], &st) == -1) {
- rb_sys_fail(RSTRING(argv[1])->ptr);
- }
-
- switch (cmd) {
- case 'A':
- return rb_time_new(st.st_atime, 0);
- case 'M':
- return rb_time_new(st.st_mtime, 0);
- case 'C':
- return rb_time_new(st.st_ctime, 0);
- }
- }
-
- if (strchr("-=<>", cmd)) {
- struct stat st1, st2;
-
- CHECK(2);
- if (rb_stat(argv[1], &st1) < 0) return Qfalse;
- if (rb_stat(argv[2], &st2) < 0) return Qfalse;
-
- switch (cmd) {
- case '-':
- if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
- return Qtrue;
- return Qfalse;
-
- case '=':
- if (st1.st_mtime == st2.st_mtime) return Qtrue;
- return Qfalse;
-
- case '>':
- if (st1.st_mtime > st2.st_mtime) return Qtrue;
- return Qfalse;
-
- case '<':
- if (st1.st_mtime < st2.st_mtime) return Qtrue;
- return Qfalse;
- }
- }
- /* unknown command */
- rb_raise(rb_eArgError, "unknown command ?%c", cmd);
- return Qnil; /* not reached */
-}
-
-static VALUE
-rb_stat_s_alloc(klass)
- VALUE klass;
-{
- return stat_new_0(klass, 0);
-}
-
-static VALUE
-rb_stat_init(obj, fname)
- VALUE obj, fname;
-{
- struct stat st, *nst;
-
- SafeStringValue(fname);
-
- if (stat(RSTRING(fname)->ptr, &st) == -1) {
- rb_sys_fail(RSTRING(fname)->ptr);
- }
- nst = ALLOC(struct stat);
- *nst = st;
- DATA_PTR(obj) = nst;
-
- return Qnil;
-}
-
-static VALUE
-rb_stat_clone(obj)
- VALUE obj;
-{
- struct stat st, *nst;
-
- VALUE clone;
-
- clone = rb_obj_alloc(RBASIC(obj)->klass);
- CLONESETUP(clone,obj);
- if (DATA_PTR(obj)) {
- nst = ALLOC(struct stat);
- *nst = *(struct stat*)DATA_PTR(obj);
- DATA_PTR(clone) = nst;
- }
-
- return clone;
-}
-
-static VALUE
-rb_stat_ftype(obj)
- VALUE obj;
-{
- return rb_file_ftype(get_stat(obj));
-}
-
-static VALUE
-rb_stat_d(obj)
- VALUE obj;
-{
- if (S_ISDIR(get_stat(obj)->st_mode)) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-rb_stat_p(obj)
- VALUE obj;
-{
-#ifdef S_IFIFO
- if (S_ISFIFO(get_stat(obj)->st_mode)) return Qtrue;
-
-#endif
- return Qfalse;
-}
-
-static VALUE
-rb_stat_l(obj)
- VALUE obj;
-{
-#ifdef S_ISLNK
- if (S_ISLNK(get_stat(obj)->st_mode)) return Qtrue;
-#endif
- return Qfalse;
-}
-
-static VALUE
-rb_stat_S(obj)
- VALUE obj;
-{
-#ifdef S_ISSOCK
- if (S_ISSOCK(get_stat(obj)->st_mode)) return Qtrue;
-
-#endif
- return Qfalse;
-}
-
-static VALUE
-rb_stat_b(obj)
- VALUE obj;
-{
-#ifdef S_ISBLK
- if (S_ISBLK(get_stat(obj)->st_mode)) return Qtrue;
-
-#endif
- return Qfalse;
-}
-
-static VALUE
-rb_stat_c(obj)
- VALUE obj;
-{
- if (S_ISCHR(get_stat(obj)->st_mode)) return Qtrue;
-
- return Qfalse;
-}
-
-static VALUE
-rb_stat_owned(obj)
- VALUE obj;
-{
- if (get_stat(obj)->st_uid == geteuid()) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-rb_stat_rowned(obj)
- VALUE obj;
-{
- if (get_stat(obj)->st_uid == getuid()) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-rb_stat_grpowned(obj)
- VALUE obj;
-{
-#ifndef NT
- if (get_stat(obj)->st_gid == getegid()) return Qtrue;
-#endif
- return Qfalse;
-}
-
-static VALUE
-rb_stat_r(obj)
- VALUE obj;
-{
- struct stat *st = get_stat(obj);
-
-#ifdef S_IRUSR
- if (rb_stat_owned(obj))
- return st->st_mode & S_IRUSR ? Qtrue : Qfalse;
-#endif
-#ifdef S_IRGRP
- if (rb_stat_grpowned(obj))
- return st->st_mode & S_IRGRP ? Qtrue : Qfalse;
-#endif
-#ifdef S_IROTH
- if (!(st->st_mode & S_IROTH)) return Qfalse;
-#endif
- return Qtrue;
-}
-
-static VALUE
-rb_stat_R(obj)
- VALUE obj;
-{
- struct stat *st = get_stat(obj);
-
-#ifdef S_IRUSR
- if (rb_stat_rowned(obj))
- return st->st_mode & S_IRUSR ? Qtrue : Qfalse;
-#endif
-#ifdef S_IRGRP
- if (group_member(get_stat(obj)->st_gid))
- return st->st_mode & S_IRGRP ? Qtrue : Qfalse;
-#endif
-#ifdef S_IROTH
- if (!(st->st_mode & S_IROTH)) return Qfalse;
-#endif
- return Qtrue;
-}
-
-static VALUE
-rb_stat_w(obj)
- VALUE obj;
-{
- struct stat *st = get_stat(obj);
-
-#ifdef S_IWUSR
- if (rb_stat_owned(obj))
- return st->st_mode & S_IWUSR ? Qtrue : Qfalse;
-#endif
-#ifdef S_IWGRP
- if (rb_stat_grpowned(obj))
- return st->st_mode & S_IWGRP ? Qtrue : Qfalse;
-#endif
-#ifdef S_IWOTH
- if (!(st->st_mode & S_IWOTH)) return Qfalse;
-#endif
- return Qtrue;
-}
-
-static VALUE
-rb_stat_W(obj)
- VALUE obj;
-{
- struct stat *st = get_stat(obj);
-
-#ifdef S_IWUSR
- if (rb_stat_rowned(obj))
- return st->st_mode & S_IWUSR ? Qtrue : Qfalse;
-#endif
-#ifdef S_IWGRP
- if (group_member(get_stat(obj)->st_gid))
- return st->st_mode & S_IWGRP ? Qtrue : Qfalse;
-#endif
-#ifdef S_IWOTH
- if (!(st->st_mode & S_IWOTH)) return Qfalse;
-#endif
- return Qtrue;
-}
-
-static VALUE
-rb_stat_x(obj)
- VALUE obj;
-{
- struct stat *st = get_stat(obj);
-
-#ifdef S_IXUSR
- if (rb_stat_owned(obj))
- return st->st_mode & S_IXUSR ? Qtrue : Qfalse;
-#endif
-#ifdef S_IXGRP
- if (rb_stat_grpowned(obj))
- return st->st_mode & S_IXGRP ? Qtrue : Qfalse;
-#endif
-#ifdef S_IXOTH
- if (!(st->st_mode & S_IXOTH)) return Qfalse;
-#endif
- return Qtrue;
-}
-
-static VALUE
-rb_stat_X(obj)
- VALUE obj;
-{
- struct stat *st = get_stat(obj);
-
-#ifdef S_IXUSR
- if (rb_stat_rowned(obj))
- return st->st_mode & S_IXUSR ? Qtrue : Qfalse;
-#endif
-#ifdef S_IXGRP
- if (group_member(get_stat(obj)->st_gid))
- return st->st_mode & S_IXGRP ? Qtrue : Qfalse;
-#endif
-#ifdef S_IXOTH
- if (!(st->st_mode & S_IXOTH)) return Qfalse;
-#endif
- return Qtrue;
-}
-
-static VALUE
-rb_stat_f(obj)
- VALUE obj;
-{
- if (S_ISREG(get_stat(obj)->st_mode)) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-rb_stat_z(obj)
- VALUE obj;
-{
- if (get_stat(obj)->st_size == 0) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-rb_stat_s(obj)
- VALUE obj;
-{
- int size = get_stat(obj)->st_size;
-
- if (size == 0) return Qnil;
- return INT2FIX(size);
-}
-
-static VALUE
-rb_stat_suid(obj)
- VALUE obj;
-{
-#ifdef S_ISUID
- if (get_stat(obj)->st_mode & S_ISUID) return Qtrue;
-#endif
- return Qfalse;
-}
-
-static VALUE
-rb_stat_sgid(obj)
- VALUE obj;
-{
-#ifdef S_ISGID
- if (get_stat(obj)->st_mode & S_ISGID) return Qtrue;
-#endif
- return Qfalse;
-}
-
-static VALUE
-rb_stat_sticky(obj)
- VALUE obj;
-{
-#ifdef S_ISVTX
- if (get_stat(obj)->st_mode & S_ISVTX) return Qtrue;
-#endif
- return Qfalse;
-}
-
-static VALUE rb_mFConst;
-
-void
-rb_file_const(name, value)
- const char *name;
- VALUE value;
-{
- rb_define_const(rb_mFConst, name, value);
- rb_define_const(rb_cIO, name, value);
- rb_define_const(rb_cFile, name, value);
-}
-
-static int
-is_absolute_path(path)
- const char *path;
-{
-#ifdef DOSISH
- if (ISALPHA(path[0]) && path[1] == ':' && isdirsep(path[2])) return 1;
- if (isdirsep(path[0]) && isdirsep(path[1])) return 1;
-#else
- if (path[0] == '/') return 1;
-#endif
- return 0;
-}
-
-static int
-path_check_1(path)
- VALUE path;
-{
- struct stat st;
- char *p0 = RSTRING(path)->ptr;
- char *p = 0, *s;
-
- if (!is_absolute_path(p0)) {
- char *buf = my_getcwd();
- VALUE newpath;
-
- newpath = rb_str_new2(buf);
- free(buf);
-
- rb_str_cat2(newpath, "/");
- rb_str_cat2(newpath, p0);
- return path_check_1(newpath);
- }
- for (;;) {
-#ifndef S_IWOTH
-# define S_IWOTH 002
-#endif
- if (stat(p0, &st) == 0 && S_ISDIR(st.st_mode) && (st.st_mode & S_IWOTH)
-#ifdef S_ISVTX
- && (!p || !(st.st_mode & S_ISVTX))
-#endif
- ) {
- rb_warn("Unsecure world writeable dir %s , mode 0%o", p0, st.st_mode);
- if (p) *p = '/';
- return 0;
- }
- s = strrdirsep(p0);
- if (p) *p = '/';
- if (!s || s == p0) return 1;
- p = s;
- *p = '\0';
- }
-}
-
-int
-rb_path_check(path)
- char *path;
-{
- char *p0, *p, *pend;
- const char sep = PATH_SEP_CHAR;
-
- if (!path) return 1;
-
- pend = path + strlen(path);
- p0 = path;
- p = strchr(path, sep);
- if (!p) p = pend;
-
- for (;;) {
- if (!path_check_1(rb_str_new(p0, p - p0))) {
- return 0; /* not safe */
- }
- p0 = p + 1;
- if (p0 > pend) break;
- p = strchr(p0, sep);
- if (!p) p = pend;
- }
- return 1;
-}
-
-#if defined(__MACOS__) || defined(riscos)
-static int
-is_macos_native_path(path)
- const char *path;
-{
- if (strchr(path, ':')) return 1;
- return 0;
-}
-#endif
-
-static int
-file_load_ok(file)
- char *file;
-{
- FILE *f;
-
- if (!file) return 0;
- f = fopen(file, "r");
- if (f == NULL) return 0;
- fclose(f);
- return 1;
-}
-
-extern VALUE rb_load_path;
-
-int
-rb_find_file_ext(filep, ext)
- VALUE *filep;
- const char * const *ext;
-{
- char *path, *e, *found;
- char *f = RSTRING(*filep)->ptr;
- VALUE fname;
- int i, j;
-
- if (f[0] == '~') {
- fname = rb_file_s_expand_path(1, filep);
- if (rb_safe_level() >= 2 && OBJ_TAINTED(fname)) {
- rb_raise(rb_eSecurityError, "loading from unsafe file %s", f);
- }
- f = StringValuePtr(fname);
- *filep = fname;
- }
-
- if (is_absolute_path(f)) {
- for (i=0; ext[i]; i++) {
- fname = rb_str_dup(*filep);
- rb_str_cat2(fname, ext[i]);
- if (file_load_ok(RSTRING(fname)->ptr)) {
- *filep = fname;
- return i+1;
- }
- }
- return 0;
- }
-
- if (!rb_load_path) return 0;
-
- Check_Type(rb_load_path, T_ARRAY);
- for (i=0;i<RARRAY(rb_load_path)->len;i++) {
- VALUE str = RARRAY(rb_load_path)->ptr[i];
-
- SafeStringValue(str);
- path = RSTRING(str)->ptr;
- for (j=0; ext[j]; j++) {
- fname = rb_str_dup(*filep);
- rb_str_cat2(fname, ext[j]);
- found = dln_find_file(RSTRING(fname)->ptr, path);
- if (found && file_load_ok(found)) {
- *filep = fname;
- return j+1;
- }
- }
- }
- return 0;
-}
-
-VALUE
-rb_find_file(path)
- VALUE path;
-{
- VALUE tmp, fname;
- char *f = RSTRING(path)->ptr;
- char *lpath;
- struct stat st;
-
- if (f[0] == '~') {
- path = rb_file_s_expand_path(1, &path);
- if (rb_safe_level() >= 2 && OBJ_TAINTED(path)) {
- rb_raise(rb_eSecurityError, "loading from unsafe file %s", f);
- }
- f = StringValuePtr(path);
- }
-
-#if defined(__MACOS__) || defined(riscos)
- if (is_macos_native_path(f)) {
- if (rb_safe_level() >= 2 && !rb_path_check(f)) {
- rb_raise(rb_eSecurityError, "loading from unsafe file %s", f);
- }
- if (file_load_ok(f)) return path;
- }
-#endif
-
- if (is_absolute_path(f)) {
- if (rb_safe_level() >= 2 && !rb_path_check(f)) {
- rb_raise(rb_eSecurityError, "loading from unsafe file %s", f);
- }
- if (file_load_ok(f)) return path;
- }
-
- if (rb_load_path) {
- int i;
-
- Check_Type(rb_load_path, T_ARRAY);
- tmp = rb_ary_new();
- for (i=0;i<RARRAY(rb_load_path)->len;i++) {
- VALUE str = RARRAY(rb_load_path)->ptr[i];
- SafeStringValue(str);
- if (RSTRING(str)->len > 0) {
- rb_ary_push(tmp, str);
- }
- }
- tmp = rb_ary_join(tmp, rb_str_new2(PATH_SEP));
- lpath = StringValuePtr(tmp);
- if (rb_safe_level() >= 2 && !rb_path_check(lpath)) {
- rb_raise(rb_eSecurityError, "loading from unsafe path %s", lpath);
- }
- }
- else {
- lpath = 0;
- }
-
- f = dln_find_file(f, lpath);
- if (file_load_ok(f)) {
- return rb_str_new2(f);
- }
- return 0;
-}
-
-static void
-define_filetest_function(name, func, argc)
- const char *name;
- VALUE (*func)();
- int argc;
-{
- rb_define_module_function(rb_mFileTest, name, func, argc);
- rb_define_singleton_method(rb_cFile, name, func, argc);
-}
-
-void
-Init_File()
-{
- rb_mFileTest = rb_define_module("FileTest");
- rb_cFile = rb_define_class("File", rb_cIO);
-
- define_filetest_function("directory?", test_d, 1);
- define_filetest_function("exist?", test_e, 1);
- define_filetest_function("exists?", test_e, 1); /* temporary */
- define_filetest_function("readable?", test_r, 1);
- define_filetest_function("readable_real?", test_R, 1);
- define_filetest_function("writable?", test_w, 1);
- define_filetest_function("writable_real?", test_W, 1);
- define_filetest_function("executable?", test_x, 1);
- define_filetest_function("executable_real?", test_X, 1);
- define_filetest_function("file?", test_f, 1);
- define_filetest_function("zero?", test_z, 1);
- define_filetest_function("size?", test_s, 1);
- define_filetest_function("size", rb_file_s_size, 1);
- define_filetest_function("owned?", test_owned, 1);
- define_filetest_function("grpowned?", test_grpowned, 1);
-
- define_filetest_function("pipe?", test_p, 1);
- define_filetest_function("symlink?", test_l, 1);
- define_filetest_function("socket?", test_S, 1);
-
- define_filetest_function("blockdev?", test_b, 1);
- define_filetest_function("chardev?", test_c, 1);
-
- define_filetest_function("setuid?", test_suid, 1);
- define_filetest_function("setgid?", test_sgid, 1);
- define_filetest_function("sticky?", test_sticky, 1);
-
- rb_define_singleton_method(rb_cFile, "stat", rb_file_s_stat, 1);
- rb_define_singleton_method(rb_cFile, "lstat", rb_file_s_lstat, 1);
- rb_define_singleton_method(rb_cFile, "ftype", rb_file_s_ftype, 1);
-
- rb_define_singleton_method(rb_cFile, "atime", rb_file_s_atime, 1);
- rb_define_singleton_method(rb_cFile, "mtime", rb_file_s_mtime, 1);
- rb_define_singleton_method(rb_cFile, "ctime", rb_file_s_ctime, 1);
-
- rb_define_singleton_method(rb_cFile, "utime", rb_file_s_utime, -1);
- rb_define_singleton_method(rb_cFile, "chmod", rb_file_s_chmod, -1);
- rb_define_singleton_method(rb_cFile, "chown", rb_file_s_chown, -1);
- rb_define_singleton_method(rb_cFile, "lchmod", rb_file_s_lchmod, -1);
- rb_define_singleton_method(rb_cFile, "lchown", rb_file_s_lchown, -1);
-
- rb_define_singleton_method(rb_cFile, "link", rb_file_s_link, 2);
- rb_define_singleton_method(rb_cFile, "symlink", rb_file_s_symlink, 2);
- rb_define_singleton_method(rb_cFile, "readlink", rb_file_s_readlink, 1);
-
- rb_define_singleton_method(rb_cFile, "unlink", rb_file_s_unlink, -2);
- rb_define_singleton_method(rb_cFile, "delete", rb_file_s_unlink, -2);
- rb_define_singleton_method(rb_cFile, "rename", rb_file_s_rename, 2);
- rb_define_singleton_method(rb_cFile, "umask", rb_file_s_umask, -1);
- rb_define_singleton_method(rb_cFile, "truncate", rb_file_s_truncate, 2);
- rb_define_singleton_method(rb_cFile, "expand_path", rb_file_s_expand_path, -1);
- rb_define_singleton_method(rb_cFile, "basename", rb_file_s_basename, -1);
- rb_define_singleton_method(rb_cFile, "dirname", rb_file_s_dirname, 1);
-
- separator = rb_obj_freeze(rb_str_new2("/"));
- rb_define_const(rb_cFile, "Separator", separator);
- rb_define_const(rb_cFile, "SEPARATOR", separator);
- rb_define_singleton_method(rb_cFile, "split", rb_file_s_split, 1);
- rb_define_singleton_method(rb_cFile, "join", rb_file_s_join, -2);
-
-#if defined DOSISH && !defined __CYGWIN__
- rb_define_const(rb_cFile, "ALT_SEPARATOR", rb_obj_freeze(rb_str_new2("\\")));
-#else
- rb_define_const(rb_cFile, "ALT_SEPARATOR", Qnil);
-#endif
- rb_define_const(rb_cFile, "PATH_SEPARATOR", rb_obj_freeze(rb_str_new2(PATH_SEP)));
-
- rb_define_method(rb_cIO, "stat", rb_io_stat, 0); /* this is IO's method */
- rb_define_method(rb_cFile, "lstat", rb_file_lstat, 0);
-
- rb_define_method(rb_cFile, "atime", rb_file_atime, 0);
- rb_define_method(rb_cFile, "mtime", rb_file_mtime, 0);
- rb_define_method(rb_cFile, "ctime", rb_file_ctime, 0);
-
- rb_define_method(rb_cFile, "chmod", rb_file_chmod, 1);
- rb_define_method(rb_cFile, "chown", rb_file_chown, 2);
- rb_define_method(rb_cFile, "truncate", rb_file_truncate, 1);
-
- rb_define_method(rb_cFile, "flock", rb_file_flock, 1);
-
- rb_mFConst = rb_define_module_under(rb_cFile, "Constants");
- rb_include_module(rb_cFile, rb_mFConst);
- rb_file_const("LOCK_SH", INT2FIX(LOCK_SH));
- rb_file_const("LOCK_EX", INT2FIX(LOCK_EX));
- rb_file_const("LOCK_UN", INT2FIX(LOCK_UN));
- rb_file_const("LOCK_NB", INT2FIX(LOCK_NB));
-
- rb_define_method(rb_cFile, "path", rb_file_path, 0);
- rb_define_global_function("test", rb_f_test, -1);
-
- rb_cStat = rb_define_class_under(rb_cFile, "Stat", rb_cObject);
- rb_define_singleton_method(rb_cStat, "allocate", rb_stat_s_alloc, 0);
- rb_define_method(rb_cStat, "initialize", rb_stat_init, 1);
- rb_define_method(rb_cStat, "clone", rb_stat_clone, 0);
-
- rb_include_module(rb_cStat, rb_mComparable);
-
- rb_define_method(rb_cStat, "<=>", rb_stat_cmp, 1);
-
- rb_define_method(rb_cStat, "dev", rb_stat_dev, 0);
- rb_define_method(rb_cStat, "ino", rb_stat_ino, 0);
- rb_define_method(rb_cStat, "mode", rb_stat_mode, 0);
- rb_define_method(rb_cStat, "nlink", rb_stat_nlink, 0);
- rb_define_method(rb_cStat, "uid", rb_stat_uid, 0);
- rb_define_method(rb_cStat, "gid", rb_stat_gid, 0);
- rb_define_method(rb_cStat, "rdev", rb_stat_rdev, 0);
- rb_define_method(rb_cStat, "rdev_major", rb_stat_rdev_major, 0);
- rb_define_method(rb_cStat, "rdev_minor", rb_stat_rdev_minor, 0);
- rb_define_method(rb_cStat, "size", rb_stat_size, 0);
- rb_define_method(rb_cStat, "blksize", rb_stat_blksize, 0);
- rb_define_method(rb_cStat, "blocks", rb_stat_blocks, 0);
- rb_define_method(rb_cStat, "atime", rb_stat_atime, 0);
- rb_define_method(rb_cStat, "mtime", rb_stat_mtime, 0);
- rb_define_method(rb_cStat, "ctime", rb_stat_ctime, 0);
-
- rb_define_method(rb_cStat, "inspect", rb_stat_inspect, 0);
-
- rb_define_method(rb_cStat, "ftype", rb_stat_ftype, 0);
-
- rb_define_method(rb_cStat, "directory?", rb_stat_d, 0);
- rb_define_method(rb_cStat, "readable?", rb_stat_r, 0);
- rb_define_method(rb_cStat, "readable_real?", rb_stat_R, 0);
- rb_define_method(rb_cStat, "writable?", rb_stat_w, 0);
- rb_define_method(rb_cStat, "writable_real?", rb_stat_W, 0);
- rb_define_method(rb_cStat, "executable?", rb_stat_x, 0);
- rb_define_method(rb_cStat, "executable_real?", rb_stat_X, 0);
- rb_define_method(rb_cStat, "file?", rb_stat_f, 0);
- rb_define_method(rb_cStat, "zero?", rb_stat_z, 0);
- rb_define_method(rb_cStat, "size?", rb_stat_s, 0);
- rb_define_method(rb_cStat, "owned?", rb_stat_owned, 0);
- rb_define_method(rb_cStat, "grpowned?", rb_stat_grpowned, 0);
-
- rb_define_method(rb_cStat, "pipe?", rb_stat_p, 0);
- rb_define_method(rb_cStat, "symlink?", rb_stat_l, 0);
- rb_define_method(rb_cStat, "socket?", rb_stat_S, 0);
-
- rb_define_method(rb_cStat, "blockdev?", rb_stat_b, 0);
- rb_define_method(rb_cStat, "chardev?", rb_stat_c, 0);
-
- rb_define_method(rb_cStat, "setuid?", rb_stat_suid, 0);
- rb_define_method(rb_cStat, "setgid?", rb_stat_sgid, 0);
- rb_define_method(rb_cStat, "sticky?", rb_stat_sticky, 0);
-}
diff --git a/gc.c b/gc.c
deleted file mode 100644
index e95f38e6b3..0000000000
--- a/gc.c
+++ /dev/null
@@ -1,1561 +0,0 @@
-/**********************************************************************
-
- gc.c -
-
- $Author$
- $Date$
- created at: Tue Oct 5 09:44:46 JST 1993
-
- Copyright (C) 1993-2002 Yukihiro Matsumoto
- Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
- Copyright (C) 2000 Information-technology Promotion Agency, Japan
-
-**********************************************************************/
-
-#include "ruby.h"
-#include "rubysig.h"
-#include "st.h"
-#include "node.h"
-#include "env.h"
-#include "re.h"
-#include <stdio.h>
-#include <setjmp.h>
-#include <sys/types.h>
-
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#endif
-
-#ifdef HAVE_SYS_RESOURCE_H
-#include <sys/resource.h>
-#endif
-
-void re_free_registers _((struct re_registers*));
-void rb_io_fptr_finalize _((struct OpenFile*));
-
-#ifndef setjmp
-#ifdef HAVE__SETJMP
-#define setjmp(env) _setjmp(env)
-#define longjmp(env,val) _longjmp(env,val)
-#endif
-#endif
-
-/* Make alloca work the best possible way. */
-#ifndef __GNUC__
-# if HAVE_ALLOCA_H
-# include <alloca.h>
-# else
-# ifdef _AIX
-# pragma alloca
-# else
-# ifndef alloca /* predefined by HP cc +Olibcalls */
-void *alloca ();
-# endif
-# endif
-# endif
-#endif
-
-static void run_final();
-
-#ifndef GC_MALLOC_LIMIT
-#if defined(MSDOS) || defined(__human68k__)
-#define GC_MALLOC_LIMIT 200000
-#else
-#define GC_MALLOC_LIMIT 8000000
-#endif
-#endif
-
-static unsigned long malloc_memories = 0;
-
-static void
-mem_error(mesg)
- char *mesg;
-{
- static int recurse = 0;
-
- if (rb_safe_level() >= 4) {
- rb_raise(rb_eNoMemError, mesg);
- }
- if (recurse == 0) {
- recurse++;
- rb_fatal(mesg);
- }
- fprintf(stderr, "[FATAL] failed to allocate memory\n");
- exit(1);
-}
-
-void *
-ruby_xmalloc(size)
- long size;
-{
- void *mem;
-
- if (size < 0) {
- rb_raise(rb_eNoMemError, "negative allocation size (or too big)");
- }
- if (size == 0) size = 1;
- malloc_memories += size;
-
- if (malloc_memories > GC_MALLOC_LIMIT) {
- rb_gc();
- }
- RUBY_CRITICAL(mem = malloc(size));
- if (!mem) {
- rb_gc();
- RUBY_CRITICAL(mem = malloc(size));
- if (!mem) {
- if (size >= 10 * 1024 * 1024) {
- mem_error("tried to allocate too big memory");
- }
- mem_error("failed to allocate memory");
- }
- }
-
- return mem;
-}
-
-void *
-ruby_xcalloc(n, size)
- long n, size;
-{
- void *mem;
-
- mem = xmalloc(n * size);
- memset(mem, 0, n * size);
-
- return mem;
-}
-
-void *
-ruby_xrealloc(ptr, size)
- void *ptr;
- long size;
-{
- void *mem;
-
- if (size < 0) {
- rb_raise(rb_eArgError, "negative re-allocation size");
- }
- if (!ptr) return xmalloc(size);
- if (size == 0) size = 1;
- malloc_memories += size;
- RUBY_CRITICAL(mem = realloc(ptr, size));
- if (!mem) {
- rb_gc();
- RUBY_CRITICAL(mem = realloc(ptr, size));
- if (!mem) {
- if (size >= 10 * 1024 * 1024) {
- rb_raise(rb_eNoMemError, "tried to re-allocate too big memory");
- }
- mem_error("failed to allocate memory(realloc)");
- }
- }
-
- return mem;
-}
-
-void
-ruby_xfree(x)
- void *x;
-{
- if (x)
- RUBY_CRITICAL(free(x));
-}
-
-extern int ruby_in_compile;
-static int dont_gc;
-static int during_gc;
-static int need_call_final = 0;
-static st_table *finalizer_table = 0;
-
-VALUE
-rb_gc_enable()
-{
- int old = dont_gc;
-
- dont_gc = Qfalse;
- return old;
-}
-
-VALUE
-rb_gc_disable()
-{
- int old = dont_gc;
-
- dont_gc = Qtrue;
- return old;
-}
-
-VALUE rb_mGC;
-
-static struct gc_list {
- VALUE *varptr;
- struct gc_list *next;
-} *global_List = 0;
-
-void
-rb_gc_register_address(addr)
- VALUE *addr;
-{
- struct gc_list *tmp;
-
- tmp = ALLOC(struct gc_list);
- tmp->next = global_List;
- tmp->varptr = addr;
- global_List = tmp;
-}
-
-void
-rb_gc_unregister_address(addr)
- VALUE *addr;
-{
- struct gc_list *tmp = global_List;
-
- if (tmp->varptr == addr) {
- global_List = tmp->next;
- RUBY_CRITICAL(free(tmp));
- return;
- }
- while (tmp->next) {
- if (tmp->next->varptr == addr) {
- struct gc_list *t = tmp->next;
-
- tmp->next = tmp->next->next;
- RUBY_CRITICAL(free(t));
- break;
- }
- tmp = tmp->next;
- }
-}
-
-void
-rb_global_variable(var)
- VALUE *var;
-{
- rb_gc_register_address(var);
-}
-
-typedef struct RVALUE {
- union {
- struct {
- unsigned long flags; /* always 0 for freed obj */
- struct RVALUE *next;
- } free;
- struct RBasic basic;
- struct RObject object;
- struct RClass klass;
- struct RFloat flonum;
- struct RString string;
- struct RArray array;
- struct RRegexp regexp;
- struct RHash hash;
- struct RData data;
- struct RStruct rstruct;
- struct RBignum bignum;
- struct RFile file;
- struct RNode node;
- struct RMatch match;
- struct RVarmap varmap;
- struct SCOPE scope;
- } as;
-} RVALUE;
-
-static RVALUE *freelist = 0;
-static RVALUE *deferred_final_list = 0;
-
-#define HEAPS_INCREMENT 10
-static RVALUE **heaps;
-static int heaps_length = 0;
-static int heaps_used = 0;
-
-#define HEAP_MIN_SLOTS 10000
-static int *heaps_limits;
-static int heap_slots = HEAP_MIN_SLOTS;
-
-#define FREE_MIN 4096
-
-static RVALUE *himem, *lomem;
-
-static void
-add_heap()
-{
- RVALUE *p, *pend;
-
- if (heaps_used == heaps_length) {
- /* Realloc heaps */
- heaps_length += HEAPS_INCREMENT;
- RUBY_CRITICAL(heaps = (heaps_used>0)?
- (RVALUE**)realloc(heaps, heaps_length*sizeof(RVALUE*)):
- (RVALUE**)malloc(heaps_length*sizeof(RVALUE*)));
- if (heaps == 0) mem_error("heaps: can't alloc memory");
- RUBY_CRITICAL(heaps_limits = (heaps_used>0)?
- (int*)realloc(heaps_limits, heaps_length*sizeof(int)):
- (int*)malloc(heaps_length*sizeof(int)));
- if (heaps_limits == 0) mem_error("heaps_limits: can't alloc memory");
- }
-
- for (;;) {
- RUBY_CRITICAL(p = heaps[heaps_used] = (RVALUE*)malloc(sizeof(RVALUE)*heap_slots));
- heaps_limits[heaps_used] = heap_slots;
- if (p == 0) {
- if (heap_slots == HEAP_MIN_SLOTS) {
- mem_error("add_heap: can't alloc memory");
- }
- heap_slots = HEAP_MIN_SLOTS;
- continue;
- }
- break;
- }
- pend = p + heap_slots;
- if (lomem == 0 || lomem > p) lomem = p;
- if (himem < pend) himem = pend;
- heaps_used++;
- heap_slots *= 1.8;
-
- while (p < pend) {
- p->as.free.flags = 0;
- p->as.free.next = freelist;
- freelist = p;
- p++;
- }
-}
-#define RANY(o) ((RVALUE*)(o))
-
-VALUE
-rb_newobj()
-{
- VALUE obj;
-
- if (!freelist) rb_gc();
-
- obj = (VALUE)freelist;
- freelist = freelist->as.free.next;
- MEMZERO((void*)obj, RVALUE, 1);
- return obj;
-}
-
-VALUE
-rb_data_object_alloc(klass, datap, dmark, dfree)
- VALUE klass;
- void *datap;
- RUBY_DATA_FUNC dmark;
- RUBY_DATA_FUNC dfree;
-{
- NEWOBJ(data, struct RData);
- OBJSETUP(data, klass, T_DATA);
- data->data = datap;
- data->dfree = dfree;
- data->dmark = dmark;
-
- return (VALUE)data;
-}
-
-extern st_table *rb_class_tbl;
-VALUE *rb_gc_stack_start = 0;
-
-#ifdef DJGPP
-static unsigned int STACK_LEVEL_MAX = 65535;
-#else
-#ifdef __human68k__
-extern unsigned int _stacksize;
-# define STACK_LEVEL_MAX (_stacksize - 4096)
-# undef HAVE_GETRLIMIT
-#else
-#ifdef HAVE_GETRLIMIT
-static unsigned int STACK_LEVEL_MAX = 655300;
-#else
-# define STACK_LEVEL_MAX 655300
-#endif
-#endif
-#endif
-
-#ifdef C_ALLOCA
-# define SET_STACK_END VALUE stack_end; alloca(0);
-# define STACK_END (&stack_end)
-#else
-# if defined(__GNUC__) && defined(USE_BUILTIN_FRAME_ADDRESS)
-# define SET_STACK_END VALUE *stack_end = __builtin_frame_address(0);
-# else
-# define SET_STACK_END VALUE *stack_end = alloca(1);
-# endif
-# define STACK_END (stack_end)
-#endif
-#ifdef __sparc__
-# define STACK_LENGTH (rb_gc_stack_start - STACK_END + 0x80)
-#else
-# define STACK_LENGTH ((STACK_END < rb_gc_stack_start) ? rb_gc_stack_start - STACK_END\
- : STACK_END - rb_gc_stack_start)
-#endif
-
-#define CHECK_STACK(ret) do {\
- SET_STACK_END;\
- (ret) = (STACK_LENGTH > STACK_LEVEL_MAX);\
-} while (0)\
-
-int
-ruby_stack_length(p)
- VALUE **p;
-{
- int ret;
-
- SET_STACK_END;
- if (p) *p = STACK_END;
- return STACK_LENGTH;
-}
-
-int
-ruby_stack_check()
-{
- int ret;
-
- CHECK_STACK(ret);
- return ret;
-}
-
-#define MARK_STACK_MAX 1024
-static VALUE mark_stack[MARK_STACK_MAX];
-static VALUE *mark_stack_ptr;
-static int mark_stack_overflow;
-
-static void
-init_mark_stack()
-{
- mark_stack_overflow = 0;
- mark_stack_ptr = mark_stack;
-}
-
-#define MARK_STACK_EMPTY (mark_stack_ptr == mark_stack)
-
-static void rb_gc_mark_children(VALUE ptr);
-
-static st_table *source_filenames;
-
-char *
-rb_source_filename(f)
- const char *f;
-{
- char *name;
-
- if (!st_lookup(source_filenames, f, &name)) {
- long len = strlen(f) + 1;
- char *ptr = name = ALLOC_N(char, len + 1);
- *ptr++ = 0;
- MEMCPY(ptr, f, char, len);
- st_add_direct(source_filenames, ptr, name);
- return ptr;
- }
- return name + 1;
-}
-
-static void
-mark_source_filename(f)
- char *f;
-{
- if (f) {
- f[-1] = 1;
- }
-}
-
-static enum st_retval
-sweep_source_filename(key, value)
- char *key, *value;
-{
- if (*value) {
- *value = 0;
- return ST_CONTINUE;
- }
- else {
- free(value);
- return ST_DELETE;
- }
-}
-
-static void
-gc_mark_all()
-{
- RVALUE *p, *pend;
- int i;
-
- init_mark_stack();
- for (i = 0; i < heaps_used; i++) {
- p = heaps[i]; pend = p + heaps_limits[i];
- while (p < pend) {
- if ((p->as.basic.flags & FL_MARK) &&
- (p->as.basic.flags != FL_MARK)) {
- rb_gc_mark_children((VALUE)p);
- }
- p++;
- }
- }
-}
-
-static void
-gc_mark_rest()
-{
- VALUE tmp_arry[MARK_STACK_MAX];
- VALUE *p;
-
- p = (mark_stack_ptr - mark_stack) + tmp_arry;
- MEMCPY(tmp_arry, mark_stack, VALUE, MARK_STACK_MAX);
-
- init_mark_stack();
-
- while(p != tmp_arry){
- p--;
- rb_gc_mark_children(*p);
- }
-}
-
-static inline int
-is_pointer_to_heap(ptr)
- void *ptr;
-{
- register RVALUE *p = RANY(ptr);
- register RVALUE *heap_org;
- register long i;
-
- if (p < lomem || p > himem) return Qfalse;
-
- /* check if p looks like a pointer */
- for (i=0; i < heaps_used; i++) {
- heap_org = heaps[i];
- if (heap_org <= p && p < heap_org + heaps_limits[i] &&
- ((((char*)p)-((char*)heap_org))%sizeof(RVALUE)) == 0)
- return Qtrue;
- }
- return Qfalse;
-}
-
-static void
-mark_locations_array(x, n)
- register VALUE *x;
- register long n;
-{
- while (n--) {
- if (is_pointer_to_heap(*x)) {
- rb_gc_mark(*x);
- }
- x++;
- }
-}
-
-void
-rb_gc_mark_locations(start, end)
- VALUE *start, *end;
-{
- VALUE *tmp;
- long n;
-
- if (start > end) {
- tmp = start;
- start = end;
- end = tmp;
- }
- n = end - start + 1;
- mark_locations_array(start,n);
-}
-
-static int
-mark_entry(key, value)
- ID key;
- VALUE value;
-{
- rb_gc_mark(value);
- return ST_CONTINUE;
-}
-
-void
-rb_mark_tbl(tbl)
- st_table *tbl;
-{
- if (!tbl) return;
- st_foreach(tbl, mark_entry, 0);
-}
-
-static int
-mark_hashentry(key, value)
- VALUE key;
- VALUE value;
-{
- rb_gc_mark(key);
- rb_gc_mark(value);
- return ST_CONTINUE;
-}
-
-void
-rb_mark_hash(tbl)
- st_table *tbl;
-{
- if (!tbl) return;
- st_foreach(tbl, mark_hashentry, 0);
-}
-
-void
-rb_gc_mark_maybe(obj)
- VALUE obj;
-{
- if (is_pointer_to_heap(obj)) {
- rb_gc_mark(obj);
- }
-}
-
-void
-rb_gc_mark(ptr)
- VALUE ptr;
-{
- int ret;
- register RVALUE *obj = RANY(ptr);
-
- if (rb_special_const_p(ptr)) return; /* special const not marked */
- if (obj->as.basic.flags == 0) return; /* free cell */
- if (obj->as.basic.flags & FL_MARK) return; /* already marked */
-
- obj->as.basic.flags |= FL_MARK;
-
- CHECK_STACK(ret);
- if (ret) {
- if (!mark_stack_overflow) {
- if (mark_stack_ptr - mark_stack < MARK_STACK_MAX) {
- *mark_stack_ptr = ptr;
- mark_stack_ptr++;
- }
- else {
- mark_stack_overflow = 1;
- }
- }
- }
- else {
- rb_gc_mark_children(ptr);
- }
-}
-
-void
-rb_gc_mark_children(ptr)
- VALUE ptr;
-{
- register RVALUE *obj = RANY(ptr);
-
- if (FL_TEST(obj, FL_EXIVAR)) {
- rb_mark_generic_ivar((VALUE)obj);
- }
-
- switch (obj->as.basic.flags & T_MASK) {
- case T_NIL:
- case T_FIXNUM:
- rb_bug("rb_gc_mark() called for broken object");
- break;
-
- case T_NODE:
- mark_source_filename(obj->as.node.nd_file);
- switch (nd_type(obj)) {
- case NODE_IF: /* 1,2,3 */
- case NODE_FOR:
- case NODE_ITER:
- case NODE_CREF:
- case NODE_WHEN:
- case NODE_MASGN:
- case NODE_RESCUE:
- case NODE_RESBODY:
- rb_gc_mark((VALUE)obj->as.node.u2.node);
- /* fall through */
- case NODE_BLOCK: /* 1,3 */
- case NODE_ARRAY:
- case NODE_DSTR:
- case NODE_DXSTR:
- case NODE_EVSTR:
- case NODE_DREGX:
- case NODE_DREGX_ONCE:
- case NODE_FBODY:
- case NODE_ENSURE:
- case NODE_CALL:
- case NODE_DEFS:
- case NODE_OP_ASGN1:
- rb_gc_mark((VALUE)obj->as.node.u1.node);
- /* fall through */
- case NODE_SUPER: /* 3 */
- case NODE_FCALL:
- case NODE_DEFN:
- case NODE_NEWLINE:
- rb_gc_mark((VALUE)obj->as.node.u3.node);
- break;
-
- case NODE_WHILE: /* 1,2 */
- case NODE_UNTIL:
- case NODE_AND:
- case NODE_OR:
- case NODE_CASE:
- case NODE_SCLASS:
- case NODE_DOT2:
- case NODE_DOT3:
- case NODE_FLIP2:
- case NODE_FLIP3:
- case NODE_MATCH2:
- case NODE_MATCH3:
- case NODE_OP_ASGN_OR:
- case NODE_OP_ASGN_AND:
- rb_gc_mark((VALUE)obj->as.node.u1.node);
- /* fall through */
- case NODE_METHOD: /* 2 */
- case NODE_NOT:
- case NODE_GASGN:
- case NODE_LASGN:
- case NODE_DASGN:
- case NODE_DASGN_CURR:
- case NODE_IASGN:
- case NODE_CDECL:
- case NODE_CVDECL:
- case NODE_CVASGN:
- case NODE_MODULE:
- case NODE_COLON3:
- case NODE_OPT_N:
- rb_gc_mark((VALUE)obj->as.node.u2.node);
- break;
-
- case NODE_HASH: /* 1 */
- case NODE_LIT:
- case NODE_STR:
- case NODE_XSTR:
- case NODE_DEFINED:
- case NODE_MATCH:
- case NODE_RETURN:
- case NODE_BREAK:
- case NODE_NEXT:
- case NODE_YIELD:
- case NODE_COLON2:
- case NODE_ARGS:
- rb_gc_mark((VALUE)obj->as.node.u1.node);
- break;
-
- case NODE_SCOPE: /* 2,3 */
- case NODE_CLASS:
- case NODE_BLOCK_PASS:
- rb_gc_mark((VALUE)obj->as.node.u3.node);
- rb_gc_mark((VALUE)obj->as.node.u2.node);
- break;
-
- case NODE_ZARRAY: /* - */
- case NODE_ZSUPER:
- case NODE_CFUNC:
- case NODE_VCALL:
- case NODE_GVAR:
- case NODE_LVAR:
- case NODE_DVAR:
- case NODE_IVAR:
- case NODE_CVAR:
- case NODE_NTH_REF:
- case NODE_BACK_REF:
- case NODE_ALIAS:
- case NODE_VALIAS:
- case NODE_REDO:
- case NODE_RETRY:
- case NODE_UNDEF:
- case NODE_SELF:
- case NODE_NIL:
- case NODE_TRUE:
- case NODE_FALSE:
- case NODE_ATTRSET:
- case NODE_BLOCK_ARG:
- case NODE_POSTEXE:
- break;
-#ifdef C_ALLOCA
- case NODE_ALLOCA:
- mark_locations_array((VALUE*)obj->as.node.u1.value,
- obj->as.node.u3.cnt);
- rb_gc_mark((VALUE)obj->as.node.u2.node);
- break;
-#endif
-
- default:
- if (is_pointer_to_heap(obj->as.node.u1.node)) {
- rb_gc_mark((VALUE)obj->as.node.u1.node);
- }
- if (is_pointer_to_heap(obj->as.node.u2.node)) {
- rb_gc_mark((VALUE)obj->as.node.u2.node);
- }
- if (is_pointer_to_heap(obj->as.node.u3.node)) {
- rb_gc_mark((VALUE)obj->as.node.u3.node);
- }
- }
- return; /* no need to mark class. */
- }
-
- rb_gc_mark(obj->as.basic.klass);
- switch (obj->as.basic.flags & T_MASK) {
- case T_ICLASS:
- case T_CLASS:
- case T_MODULE:
- rb_gc_mark(obj->as.klass.super);
- rb_mark_tbl(obj->as.klass.m_tbl);
- rb_mark_tbl(obj->as.klass.iv_tbl);
- break;
-
- case T_ARRAY:
- {
- int i, len = obj->as.array.len;
- VALUE *ptr = obj->as.array.ptr;
-
- for (i=0; i < len; i++)
- rb_gc_mark(*ptr++);
- }
- if (FL_TEST(obj, ELTS_SHARED))
- rb_gc_mark(obj->as.array.aux.shared);
- break;
-
- case T_HASH:
- rb_mark_hash(obj->as.hash.tbl);
- rb_gc_mark(obj->as.hash.ifnone);
- break;
-
- case T_STRING:
-#define STR_ASSOC FL_USER3 /* copied from string.c */
- if (FL_TEST(obj, ELTS_SHARED|STR_ASSOC)) {
- rb_gc_mark(obj->as.string.aux.shared);
- }
- break;
-
- case T_DATA:
- if (obj->as.data.dmark) (*obj->as.data.dmark)(DATA_PTR(obj));
- break;
-
- case T_OBJECT:
- rb_mark_tbl(obj->as.object.iv_tbl);
- break;
-
- case T_FILE:
- case T_REGEXP:
- case T_FLOAT:
- case T_BIGNUM:
- case T_BLKTAG:
- break;
-
- case T_MATCH:
- if (obj->as.match.str) {
- rb_gc_mark((VALUE)obj->as.match.str);
- }
- break;
-
- case T_VARMAP:
- rb_gc_mark(obj->as.varmap.val);
- rb_gc_mark((VALUE)obj->as.varmap.next);
- break;
-
- case T_SCOPE:
- if (obj->as.scope.local_vars && (obj->as.scope.flags & SCOPE_MALLOC)) {
- int n = obj->as.scope.local_tbl[0]+1;
- VALUE *vars = &obj->as.scope.local_vars[-1];
-
- while (n--) {
- rb_gc_mark(*vars);
- vars++;
- }
- }
- break;
-
- case T_STRUCT:
- {
- int i, len = obj->as.rstruct.len;
- VALUE *ptr = obj->as.rstruct.ptr;
-
- for (i=0; i < len; i++)
- rb_gc_mark(*ptr++);
- }
- break;
-
- default:
- rb_bug("rb_gc_mark(): unknown data type 0x%x(0x%x) %s",
- obj->as.basic.flags & T_MASK, obj,
- is_pointer_to_heap(obj) ? "corrupted object" : "non object");
- }
-}
-
-static void obj_free _((VALUE));
-
-static void
-gc_sweep()
-{
- RVALUE *p, *pend, *final_list;
- int freed = 0;
- int i, used = heaps_used;
-
- if (ruby_in_compile) {
- /* should not reclaim nodes during compilation */
- for (i = 0; i < used; i++) {
- p = heaps[i]; pend = p + heaps_limits[i];
- while (p < pend) {
- if (!(p->as.basic.flags&FL_MARK) && BUILTIN_TYPE(p) == T_NODE)
- rb_gc_mark((VALUE)p);
- p++;
- }
- }
- }
-
- mark_source_filename(ruby_sourcefile);
- st_foreach(source_filenames, sweep_source_filename, 0);
-
- freelist = 0;
- final_list = deferred_final_list;
- deferred_final_list = 0;
- for (i = 0; i < used; i++) {
- int n = 0;
-
- p = heaps[i]; pend = p + heaps_limits[i];
- while (p < pend) {
- if (!(p->as.basic.flags & FL_MARK)) {
- if (p->as.basic.flags) {
- obj_free((VALUE)p);
- }
- if (need_call_final && FL_TEST(p, FL_FINALIZE)) {
- p->as.free.flags = FL_MARK; /* remain marked */
- p->as.free.next = final_list;
- final_list = p;
- }
- else {
- p->as.free.flags = 0;
- p->as.free.next = freelist;
- freelist = p;
- }
- n++;
- }
- else if (RBASIC(p)->flags == FL_MARK) {
- /* objects to be finalized */
- /* do notning remain marked */
- }
- else {
- RBASIC(p)->flags &= ~FL_MARK;
- }
- p++;
- }
- freed += n;
- }
- if (freed < FREE_MIN) {
- add_heap();
- }
- during_gc = 0;
-
- /* clear finalization list */
- if (final_list) {
- RVALUE *tmp;
-
- if (rb_prohibit_interrupt || ruby_in_compile) {
- deferred_final_list = final_list;
- return;
- }
-
- for (p = final_list; p; p = tmp) {
- tmp = p->as.free.next;
- run_final((VALUE)p);
- p->as.free.flags = 0;
- p->as.free.next = freelist;
- freelist = p;
- }
- }
-}
-
-void
-rb_gc_force_recycle(p)
- VALUE p;
-{
- RANY(p)->as.free.flags = 0;
- RANY(p)->as.free.next = freelist;
- freelist = RANY(p);
-}
-
-static void
-obj_free(obj)
- VALUE obj;
-{
- switch (RANY(obj)->as.basic.flags & T_MASK) {
- case T_NIL:
- case T_FIXNUM:
- case T_TRUE:
- case T_FALSE:
- rb_bug("obj_free() called for broken object");
- break;
- }
-
- if (FL_TEST(obj, FL_EXIVAR)) {
- rb_free_generic_ivar((VALUE)obj);
- }
-
- switch (RANY(obj)->as.basic.flags & T_MASK) {
- case T_OBJECT:
- if (RANY(obj)->as.object.iv_tbl) {
- st_free_table(RANY(obj)->as.object.iv_tbl);
- }
- break;
- case T_MODULE:
- case T_CLASS:
- st_free_table(RANY(obj)->as.klass.m_tbl);
- if (RANY(obj)->as.object.iv_tbl) {
- st_free_table(RANY(obj)->as.object.iv_tbl);
- }
- break;
- case T_STRING:
- if (RANY(obj)->as.string.ptr && !FL_TEST(obj, ELTS_SHARED)) {
- RUBY_CRITICAL(free(RANY(obj)->as.string.ptr));
- }
- break;
- case T_ARRAY:
- if (RANY(obj)->as.array.ptr && !FL_TEST(obj, ELTS_SHARED)) {
- RUBY_CRITICAL(free(RANY(obj)->as.array.ptr));
- }
- break;
- case T_HASH:
- if (RANY(obj)->as.hash.tbl) {
- st_free_table(RANY(obj)->as.hash.tbl);
- }
- break;
- case T_REGEXP:
- if (RANY(obj)->as.regexp.ptr) {
- re_free_pattern(RANY(obj)->as.regexp.ptr);
- }
- if (RANY(obj)->as.regexp.str) {
- RUBY_CRITICAL(free(RANY(obj)->as.regexp.str));
- }
- break;
- case T_DATA:
- if (DATA_PTR(obj)) {
- if ((long)RANY(obj)->as.data.dfree == -1) {
- RUBY_CRITICAL(free(DATA_PTR(obj)));
- }
- else if (RANY(obj)->as.data.dfree) {
- (*RANY(obj)->as.data.dfree)(DATA_PTR(obj));
- }
- }
- break;
- case T_MATCH:
- if (RANY(obj)->as.match.regs) {
- re_free_registers(RANY(obj)->as.match.regs);
- RUBY_CRITICAL(free(RANY(obj)->as.match.regs));
- }
- break;
- case T_FILE:
- if (RANY(obj)->as.file.fptr) {
- rb_io_fptr_finalize(RANY(obj)->as.file.fptr);
- RUBY_CRITICAL(free(RANY(obj)->as.file.fptr));
- }
- break;
- case T_ICLASS:
- /* iClass shares table with the module */
- break;
-
- case T_FLOAT:
- case T_VARMAP:
- case T_BLKTAG:
- break;
-
- case T_BIGNUM:
- if (RANY(obj)->as.bignum.digits) {
- RUBY_CRITICAL(free(RANY(obj)->as.bignum.digits));
- }
- break;
- case T_NODE:
- switch (nd_type(obj)) {
- case NODE_SCOPE:
- if (RANY(obj)->as.node.u1.tbl) {
- RUBY_CRITICAL(free(RANY(obj)->as.node.u1.tbl));
- }
- break;
-#ifdef C_ALLOCA
- case NODE_ALLOCA:
- RUBY_CRITICAL(free(RANY(obj)->as.node.u1.node));
- break;
-#endif
- }
- return; /* no need to free iv_tbl */
-
- case T_SCOPE:
- if (RANY(obj)->as.scope.local_vars &&
- RANY(obj)->as.scope.flags != SCOPE_ALLOCA) {
- VALUE *vars = RANY(obj)->as.scope.local_vars-1;
- if (vars[0] == 0)
- RUBY_CRITICAL(free(RANY(obj)->as.scope.local_tbl));
- if (RANY(obj)->as.scope.flags & SCOPE_MALLOC)
- RUBY_CRITICAL(free(vars));
- }
- break;
-
- case T_STRUCT:
- if (RANY(obj)->as.rstruct.ptr) {
- RUBY_CRITICAL(free(RANY(obj)->as.rstruct.ptr));
- }
- break;
-
- default:
- rb_bug("gc_sweep(): unknown data type 0x%x(%d)", obj,
- RANY(obj)->as.basic.flags & T_MASK);
- }
-}
-
-void
-rb_gc_mark_frame(frame)
- struct FRAME *frame;
-{
- mark_locations_array(frame->argv, frame->argc);
- rb_gc_mark(frame->cbase);
-}
-
-#ifdef __GNUC__
-#if defined(__human68k__) || defined(DJGPP)
-#if defined(__human68k__)
-typedef unsigned long rb_jmp_buf[8];
-__asm__ (".even\n\
-_rb_setjmp:\n\
- move.l 4(sp),a0\n\
- movem.l d3-d7/a3-a5,(a0)\n\
- moveq.l #0,d0\n\
- rts");
-#ifdef setjmp
-#undef setjmp
-#endif
-#else
-#if defined(DJGPP)
-typedef unsigned long rb_jmp_buf[6];
-__asm__ (".align 4\n\
-_rb_setjmp:\n\
- pushl %ebp\n\
- movl %esp,%ebp\n\
- movl 8(%ebp),%ebp\n\
- movl %eax,(%ebp)\n\
- movl %ebx,4(%ebp)\n\
- movl %ecx,8(%ebp)\n\
- movl %edx,12(%ebp)\n\
- movl %esi,16(%ebp)\n\
- movl %edi,20(%ebp)\n\
- popl %ebp\n\
- xorl %eax,%eax\n\
- ret");
-#endif
-#endif
-int rb_setjmp (rb_jmp_buf);
-#define jmp_buf rb_jmp_buf
-#define setjmp rb_setjmp
-#endif /* __human68k__ or DJGPP */
-#endif /* __GNUC__ */
-
-void
-rb_gc()
-{
- struct gc_list *list;
- struct FRAME * volatile frame; /* gcc 2.7.2.3 -O2 bug?? */
- jmp_buf save_regs_gc_mark;
-#ifdef C_ALLOCA
- VALUE stack_end;
- alloca(0);
-# define STACK_END (&stack_end)
-#else
-# if defined(__GNUC__) && defined(USE_BUILTIN_FRAME_ADDRESS)
- VALUE *stack_end = __builtin_frame_address(0);
-# else
- VALUE *stack_end = alloca(1);
-# endif
-# define STACK_END (stack_end)
-#endif
-
- if (dont_gc || during_gc) {
- if (!freelist || malloc_memories > GC_MALLOC_LIMIT) {
- malloc_memories = 0;
- add_heap();
- }
- return;
- }
-
- malloc_memories = 0;
-
- if (during_gc) return;
- during_gc++;
-
- init_mark_stack();
-
- /* mark frame stack */
- for (frame = ruby_frame; frame; frame = frame->prev) {
- rb_gc_mark_frame(frame);
- if (frame->tmp) {
- struct FRAME *tmp = frame->tmp;
- while (tmp) {
- rb_gc_mark_frame(tmp);
- tmp = tmp->prev;
- }
- }
- }
- rb_gc_mark((VALUE)ruby_class);
- rb_gc_mark((VALUE)ruby_scope);
- rb_gc_mark((VALUE)ruby_dyna_vars);
- if (finalizer_table) {
- rb_mark_tbl(finalizer_table);
- }
-
- FLUSH_REGISTER_WINDOWS;
- /* This assumes that all registers are saved into the jmp_buf */
- setjmp(save_regs_gc_mark);
- mark_locations_array((VALUE*)save_regs_gc_mark, sizeof(save_regs_gc_mark) / sizeof(VALUE *));
- rb_gc_mark_locations(rb_gc_stack_start, (VALUE*)STACK_END);
-#if defined(__human68k__)
- rb_gc_mark_locations((VALUE*)((char*)rb_gc_stack_start + 2),
- (VALUE*)((char*)STACK_END + 2));
-#endif
- rb_gc_mark_threads();
-
- /* mark protected global variables */
- for (list = global_List; list; list = list->next) {
- rb_gc_mark(*list->varptr);
- }
- rb_mark_end_proc();
- rb_gc_mark_global_tbl();
-
- rb_mark_tbl(rb_class_tbl);
- rb_gc_mark_trap_list();
-
- /* mark generic instance variables for special constants */
- rb_mark_generic_ivar_tbl();
-
- /* gc_mark objects whose marking are not completed*/
- while (!MARK_STACK_EMPTY){
- if (mark_stack_overflow){
- gc_mark_all();
- }
- else {
- gc_mark_rest();
- }
- }
- gc_sweep();
-}
-
-VALUE
-rb_gc_start()
-{
- rb_gc();
- return Qnil;
-}
-
-void
-Init_stack(addr)
- VALUE *addr;
-{
-#if defined(__human68k__)
- extern void *_SEND;
- rb_gc_stack_start = _SEND;
-#else
- VALUE start;
-
- if (!addr) addr = &start;
- rb_gc_stack_start = addr;
-#endif
-#ifdef HAVE_GETRLIMIT
- {
- struct rlimit rlim;
-
- if (getrlimit(RLIMIT_STACK, &rlim) == 0) {
- double space = (double)rlim.rlim_cur*0.2;
-
- if (space > 1024*1024) space = 1024*1024;
- STACK_LEVEL_MAX = (rlim.rlim_cur - space) / sizeof(VALUE);
- }
- }
-#endif
-}
-
-void
-Init_heap()
-{
- if (!rb_gc_stack_start) {
- Init_stack(0);
- }
- add_heap();
-}
-
-static VALUE
-os_live_obj()
-{
- int i;
- int n = 0;
-
- for (i = 0; i < heaps_used; i++) {
- RVALUE *p, *pend;
-
- p = heaps[i]; pend = p + heaps_limits[i];
- for (;p < pend; p++) {
- if (p->as.basic.flags) {
- switch (TYPE(p)) {
- case T_ICLASS:
- case T_VARMAP:
- case T_SCOPE:
- case T_NODE:
- continue;
- case T_CLASS:
- if (FL_TEST(p, FL_SINGLETON)) continue;
- default:
- if (!p->as.basic.klass) continue;
- rb_yield((VALUE)p);
- n++;
- }
- }
- }
- }
-
- return INT2FIX(n);
-}
-
-static VALUE
-os_obj_of(of)
- VALUE of;
-{
- int i;
- int n = 0;
-
- for (i = 0; i < heaps_used; i++) {
- RVALUE *p, *pend;
-
- p = heaps[i]; pend = p + heaps_limits[i];
- for (;p < pend; p++) {
- if (p->as.basic.flags) {
- switch (TYPE(p)) {
- case T_ICLASS:
- case T_VARMAP:
- case T_SCOPE:
- case T_NODE:
- continue;
- case T_CLASS:
- if (FL_TEST(p, FL_SINGLETON)) continue;
- default:
- if (!p->as.basic.klass) continue;
- if (rb_obj_is_kind_of((VALUE)p, of)) {
- rb_yield((VALUE)p);
- n++;
- }
- }
- }
- }
- }
-
- return INT2FIX(n);
-}
-
-static VALUE
-os_each_obj(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE of;
-
- if (rb_scan_args(argc, argv, "01", &of) == 0) {
- return os_live_obj();
- }
- else {
- return os_obj_of(of);
- }
-}
-
-static VALUE finalizers;
-
-static VALUE
-add_final(os, proc)
- VALUE os, proc;
-{
- rb_warn("ObjectSpace::add_finalizer is deprecated; use define_finalizer");
- if (!rb_obj_is_kind_of(proc, rb_cProc)) {
- rb_raise(rb_eArgError, "wrong type argument %s (Proc required)",
- rb_class2name(CLASS_OF(proc)));
- }
- rb_ary_push(finalizers, proc);
- return proc;
-}
-
-static VALUE
-rm_final(os, proc)
- VALUE os, proc;
-{
- rb_warn("ObjectSpace::remove_finalizer is deprecated; use undefine_finalizer");
- rb_ary_delete(finalizers, proc);
- return proc;
-}
-
-static VALUE
-finals()
-{
- rb_warn("ObjectSpace::finalizers is deprecated");
- return finalizers;
-}
-
-static VALUE
-call_final(os, obj)
- VALUE os, obj;
-{
- rb_warn("ObjectSpace::call_final is deprecated; use define_finalizer");
- need_call_final = 1;
- FL_SET(obj, FL_FINALIZE);
- return obj;
-}
-
-static VALUE
-undefine_final(os, obj)
- VALUE os, obj;
-{
- if (finalizer_table) {
- st_delete(finalizer_table, &obj, 0);
- }
- return obj;
-}
-
-static VALUE
-define_final(argc, argv, os)
- int argc;
- VALUE *argv;
- VALUE os;
-{
- VALUE obj, proc, table;
-
- rb_scan_args(argc, argv, "11", &obj, &proc);
- if (argc == 1) {
- proc = rb_f_lambda();
- }
- else if (!rb_obj_is_kind_of(proc, rb_cProc)) {
- rb_raise(rb_eArgError, "wrong type argument %s (Proc required)",
- rb_class2name(CLASS_OF(proc)));
- }
- need_call_final = 1;
- FL_SET(obj, FL_FINALIZE);
-
- if (!finalizer_table) {
- finalizer_table = st_init_numtable();
- }
- if (st_lookup(finalizer_table, obj, &table)) {
- rb_ary_push(table, proc);
- }
- else {
- st_add_direct(finalizer_table, obj, rb_ary_new3(1, proc));
- }
- return proc;
-}
-
-static VALUE
-run_single_final(args)
- VALUE *args;
-{
- rb_eval_cmd(args[0], args[1], 0);
- return Qnil;
-}
-
-static void
-run_final(obj)
- VALUE obj;
-{
- int i, status;
- VALUE args[2], table;
-
- args[1] = rb_ary_new3(1, rb_obj_id(obj)); /* make obj into id */
- for (i=0; i<RARRAY(finalizers)->len; i++) {
- args[0] = RARRAY(finalizers)->ptr[i];
- rb_protect((VALUE(*)_((VALUE)))run_single_final, (VALUE)args, &status);
- }
- if (finalizer_table && st_delete(finalizer_table, &obj, &table)) {
- for (i=0; i<RARRAY(table)->len; i++) {
- args[0] = RARRAY(table)->ptr[i];
- rb_protect((VALUE(*)_((VALUE)))run_single_final, (VALUE)args, &status);
- }
- }
-}
-
-void
-rb_gc_call_finalizer_at_exit()
-{
- RVALUE *p, *pend;
- int i;
-
- /* run finalizers */
- if (need_call_final) {
- if (deferred_final_list) {
- p = deferred_final_list;
- while (p) {
- RVALUE *tmp = p;
- p = p->as.free.next;
- run_final((VALUE)tmp);
- }
- }
- for (i = 0; i < heaps_used; i++) {
- p = heaps[i]; pend = p + heaps_limits[i];
- while (p < pend) {
- if (FL_TEST(p, FL_FINALIZE)) {
- FL_UNSET(p, FL_FINALIZE);
- p->as.basic.klass = 0;
- run_final((VALUE)p);
- }
- p++;
- }
- }
- }
- /* run data object's finaliers */
- for (i = 0; i < heaps_used; i++) {
- p = heaps[i]; pend = p + heaps_limits[i];
- while (p < pend) {
- if (BUILTIN_TYPE(p) == T_DATA &&
- DATA_PTR(p) && RANY(p)->as.data.dfree) {
- p->as.free.flags = 0;
- (*RANY(p)->as.data.dfree)(DATA_PTR(p));
- }
- else if (BUILTIN_TYPE(p) == T_FILE) {
- p->as.free.flags = 0;
- rb_io_fptr_finalize(RANY(p)->as.file.fptr);
- }
- p++;
- }
- }
-}
-
-static VALUE
-id2ref(obj, id)
- VALUE obj, id;
-{
- unsigned long ptr, p0;
-
- rb_secure(4);
- p0 = ptr = NUM2ULONG(id);
- if (ptr == Qtrue) return Qtrue;
- if (ptr == Qfalse) return Qfalse;
- if (ptr == Qnil) return Qnil;
- if (FIXNUM_P(ptr)) return (VALUE)ptr;
- if (SYMBOL_P(ptr) && rb_id2name(SYM2ID((VALUE)ptr)) != 0) {
- return (VALUE)ptr;
- }
-
- ptr = id ^ FIXNUM_FLAG; /* unset FIXNUM_FLAG */
- if (!is_pointer_to_heap(ptr)) {
- rb_raise(rb_eRangeError, "0x%x is not id value", p0);
- }
- if (BUILTIN_TYPE(ptr) == 0) {
- rb_raise(rb_eRangeError, "0x%x is recycled object", p0);
- }
- return (VALUE)ptr;
-}
-
-void
-Init_GC()
-{
- VALUE rb_mObSpace;
-
- rb_mGC = rb_define_module("GC");
- rb_define_singleton_method(rb_mGC, "start", rb_gc_start, 0);
- rb_define_singleton_method(rb_mGC, "enable", rb_gc_enable, 0);
- rb_define_singleton_method(rb_mGC, "disable", rb_gc_disable, 0);
- rb_define_method(rb_mGC, "garbage_collect", rb_gc_start, 0);
-
- rb_mObSpace = rb_define_module("ObjectSpace");
- rb_define_module_function(rb_mObSpace, "each_object", os_each_obj, -1);
- rb_define_module_function(rb_mObSpace, "garbage_collect", rb_gc_start, 0);
- rb_define_module_function(rb_mObSpace, "add_finalizer", add_final, 1);
- rb_define_module_function(rb_mObSpace, "remove_finalizer", rm_final, 1);
- rb_define_module_function(rb_mObSpace, "finalizers", finals, 0);
- rb_define_module_function(rb_mObSpace, "call_finalizer", call_final, 1);
-
- rb_define_module_function(rb_mObSpace, "define_finalizer", define_final, -1);
- rb_define_module_function(rb_mObSpace, "undefine_finalizer", undefine_final, 1);
-
- rb_define_module_function(rb_mObSpace, "_id2ref", id2ref, 1);
-
- rb_gc_register_address(&rb_mObSpace);
- rb_global_variable(&finalizers);
- rb_gc_unregister_address(&rb_mObSpace);
- finalizers = rb_ary_new();
-
- source_filenames = st_init_strtable();
-}
diff --git a/hash.c b/hash.c
deleted file mode 100644
index 170913dc18..0000000000
--- a/hash.c
+++ /dev/null
@@ -1,1654 +0,0 @@
-/**********************************************************************
-
- hash.c -
-
- $Author$
- $Date$
- created at: Mon Nov 22 18:51:18 JST 1993
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
- Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
- Copyright (C) 2000 Information-technology Promotion Agency, Japan
-
-**********************************************************************/
-
-#include "ruby.h"
-#include "st.h"
-#include "util.h"
-#include "rubysig.h"
-
-#define HASH_DELETED FL_USER1
-#define HASH_PROC_DEFAULT FL_USER2
-
-static void
-rb_hash_modify(hash)
- VALUE hash;
-{
- if (OBJ_FROZEN(hash)) rb_error_frozen("hash");
- if (!OBJ_TAINTED(hash) && rb_safe_level() >= 4)
- rb_raise(rb_eSecurityError, "Insecure: can't modify hash");
-}
-
-VALUE
-rb_hash_freeze(hash)
- VALUE hash;
-{
- return rb_obj_freeze(hash);
-}
-
-VALUE rb_cHash;
-
-static VALUE envtbl;
-static ID id_hash, id_yield, id_default;
-
-VALUE
-rb_hash(obj)
- VALUE obj;
-{
- return rb_funcall(obj, id_hash, 0);
-}
-
-static VALUE
-eql(args)
- VALUE *args;
-{
- return (VALUE)rb_eql(args[0], args[1]);
-}
-
-static int
-rb_any_cmp(a, b)
- VALUE a, b;
-{
- VALUE args[2];
- if (FIXNUM_P(a) && FIXNUM_P(b)) {
- return a != b;
- }
- if (TYPE(a) == T_STRING && RBASIC(a)->klass == rb_cString &&
- TYPE(b) == T_STRING && RBASIC(b)->klass == rb_cString) {
- return rb_str_cmp(a, b);
- }
- if (SYMBOL_P(a) && SYMBOL_P(b)) {
- return a != b;
- }
- if (a == Qundef || b == Qundef) return -1;
-
- args[0] = a;
- args[1] = b;
- return !rb_with_disable_interrupt(eql, (VALUE)args);
-}
-
-static int
-rb_any_hash(a)
- VALUE a;
-{
- VALUE hval;
-
- switch (TYPE(a)) {
- case T_FIXNUM:
- case T_SYMBOL:
- return (int)a;
- break;
-
- case T_STRING:
- return rb_str_hash(a);
- break;
-
- default:
- DEFER_INTS;
- hval = rb_funcall(a, id_hash, 0);
- if (FIXNUM_P(hval)) {
- hval %= 536870923;
- }
- else {
- hval = rb_funcall(hval, '%', 1, INT2FIX(536870923));
- }
- ENABLE_INTS;
- return (int)FIX2LONG(hval);
- }
-}
-
-static struct st_hash_type objhash = {
- rb_any_cmp,
- rb_any_hash,
-};
-
-struct rb_hash_foreach_arg {
- VALUE hash;
- enum st_retval (*func)();
- char *arg;
-};
-
-static int
-rb_hash_foreach_iter(key, value, arg)
- VALUE key, value;
- struct rb_hash_foreach_arg *arg;
-{
- int status;
- st_table *tbl = RHASH(arg->hash)->tbl;
- struct st_table_entry **bins = tbl->bins;
-
- if (key == Qundef) return ST_CONTINUE;
- status = (*arg->func)(key, value, arg->arg);
- if (RHASH(arg->hash)->tbl != tbl || RHASH(arg->hash)->tbl->bins != bins){
- rb_raise(rb_eIndexError, "rehash occurred during iteration");
- }
- return status;
-}
-
-static VALUE
-rb_hash_foreach_call(arg)
- struct rb_hash_foreach_arg *arg;
-{
- st_foreach(RHASH(arg->hash)->tbl, rb_hash_foreach_iter, arg);
- return Qnil;
-}
-
-static VALUE
-rb_hash_foreach_ensure(hash)
- VALUE hash;
-{
- RHASH(hash)->iter_lev--;
-
- if (RHASH(hash)->iter_lev == 0) {
- if (FL_TEST(hash, HASH_DELETED)) {
- st_cleanup_safe(RHASH(hash)->tbl, Qundef);
- FL_UNSET(hash, HASH_DELETED);
- }
- }
- return 0;
-}
-
-static int
-rb_hash_foreach(hash, func, farg)
- VALUE hash;
- enum st_retval (*func)();
- char *farg;
-{
- struct rb_hash_foreach_arg arg;
-
- RHASH(hash)->iter_lev++;
- arg.hash = hash;
- arg.func = func;
- arg.arg = farg;
- return rb_ensure(rb_hash_foreach_call, (VALUE)&arg, rb_hash_foreach_ensure, hash);
-}
-
-static VALUE
-rb_hash_s_alloc(klass)
- VALUE klass;
-{
- NEWOBJ(hash, struct RHash);
- OBJSETUP(hash, klass, T_HASH);
-
- hash->ifnone = Qnil;
- hash->tbl = st_init_table(&objhash);
-
- return (VALUE)hash;
-}
-
-VALUE
-rb_hash_new()
-{
- return rb_hash_s_alloc(rb_cHash);
-}
-
-static VALUE
-rb_hash_initialize(argc, argv, hash)
- int argc;
- VALUE *argv;
- VALUE hash;
-{
- VALUE ifnone;
-
- rb_hash_modify(hash);
- if (rb_block_given_p()) {
- if (argc > 0) {
- rb_raise(rb_eArgError, "wrong number of arguments");
- }
- RHASH(hash)->ifnone = rb_f_lambda();
- FL_SET(hash, HASH_PROC_DEFAULT);
- }
- else {
- rb_scan_args(argc, argv, "01", &ifnone);
- RHASH(hash)->ifnone = ifnone;
- }
-
- return hash;
-}
-
-static VALUE
-rb_hash_s_create(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- VALUE hash;
- int i;
-
- if (argc == 1 && TYPE(argv[0]) == T_HASH) {
- VALUE hash = rb_obj_alloc(klass);
-
- RHASH(hash)->ifnone = Qnil;
- RHASH(hash)->tbl = st_copy(RHASH(argv[0])->tbl);
-
- return hash;
- }
-
- if (argc % 2 != 0) {
- rb_raise(rb_eArgError, "odd number args for Hash");
- }
- hash = rb_hash_s_alloc(klass);
-
- for (i=0; i<argc; i+=2) {
- st_insert(RHASH(hash)->tbl, argv[i], argv[i+1]);
- }
-
- return hash;
-}
-
-static VALUE
-rb_hash_clone(hash)
- VALUE hash;
-{
- VALUE clone = rb_obj_clone(hash);
-
- RHASH(clone)->ifnone = RHASH(hash)->ifnone;
- RHASH(clone)->tbl = (st_table*)st_copy(RHASH(hash)->tbl);
-
- return clone;
-}
-
-static VALUE
-to_hash(hash)
- VALUE hash;
-{
- return rb_convert_type(hash, T_HASH, "Hash", "to_hash");
-}
-
-static int
-rb_hash_rehash_i(key, value, tbl)
- VALUE key, value;
- st_table *tbl;
-{
- if (key != Qundef) st_insert(tbl, key, value);
- return ST_CONTINUE;
-}
-
-static VALUE
-rb_hash_rehash(hash)
- VALUE hash;
-{
- st_table *tbl;
-
- tbl = st_init_table_with_size(&objhash, RHASH(hash)->tbl->num_entries);
- st_foreach(RHASH(hash)->tbl, rb_hash_rehash_i, tbl);
- st_free_table(RHASH(hash)->tbl);
- RHASH(hash)->tbl = tbl;
-
- return hash;
-}
-
-VALUE
-rb_hash_aref(hash, key)
- VALUE hash, key;
-{
- VALUE val;
-
- if (!st_lookup(RHASH(hash)->tbl, key, &val)) {
- return rb_funcall(hash, id_default, 1, key);
- }
- return val;
-}
-
-static VALUE
-rb_hash_fetch(argc, argv, hash)
- int argc;
- VALUE *argv;
- VALUE hash;
-{
- VALUE key, if_none;
- VALUE val;
-
- rb_scan_args(argc, argv, "11", &key, &if_none);
-
- if (!st_lookup(RHASH(hash)->tbl, key, &val)) {
- if (rb_block_given_p()) {
- if (argc > 1) {
- rb_raise(rb_eArgError, "wrong number of arguments", argc);
- }
- return rb_yield(key);
- }
- if (argc == 1) {
- rb_raise(rb_eIndexError, "key not found");
- }
- return if_none;
- }
- return val;
-}
-
-static VALUE
-rb_hash_default(argc, argv, hash)
- int argc;
- VALUE *argv;
- VALUE hash;
-{
- VALUE key;
-
- rb_scan_args(argc, argv, "01", &key);
- if (FL_TEST(hash, HASH_PROC_DEFAULT)) {
- return rb_funcall(RHASH(hash)->ifnone, id_yield, 2, hash, key);
- }
- return RHASH(hash)->ifnone;
-}
-
-static VALUE
-rb_hash_set_default(hash, ifnone)
- VALUE hash, ifnone;
-{
- rb_hash_modify(hash);
- RHASH(hash)->ifnone = ifnone;
- FL_UNSET(hash, HASH_PROC_DEFAULT);
- return ifnone;
-}
-
-static int
-index_i(key, value, args)
- VALUE key, value;
- VALUE *args;
-{
- if (rb_equal(value, args[0])) {
- args[1] = key;
- return ST_STOP;
- }
- return ST_CONTINUE;
-}
-
-static VALUE
-rb_hash_index(hash, value)
- VALUE hash, value;
-{
- VALUE args[2];
-
- args[0] = value;
- args[1] = Qnil;
-
- st_foreach(RHASH(hash)->tbl, index_i, args);
-
- return args[1];
-}
-
-static VALUE
-rb_hash_indexes(argc, argv, hash)
- int argc;
- VALUE *argv;
- VALUE hash;
-{
- VALUE indexes;
- int i;
-
- rb_warn("Hash#%s is deprecated; use Hash#select",
- rb_id2name(rb_frame_last_func()));
- indexes = rb_ary_new2(argc);
- for (i=0; i<argc; i++) {
- RARRAY(indexes)->ptr[i] = rb_hash_aref(hash, argv[i]);
- RARRAY(indexes)->len++;
- }
- return indexes;
-}
-
-VALUE
-rb_hash_delete(hash, key)
- VALUE hash, key;
-{
- VALUE val;
-
- rb_hash_modify(hash);
- if (RHASH(hash)->iter_lev > 0) {
- if (st_delete_safe(RHASH(hash)->tbl, &key, &val, Qundef)) {
- FL_SET(hash, HASH_DELETED);
- return val;
- }
- }
- else if (st_delete(RHASH(hash)->tbl, &key, &val))
- return val;
- if (rb_block_given_p()) {
- return rb_yield(key);
- }
- return Qnil;
-}
-
-struct shift_var {
- int stop;
- VALUE key;
- VALUE val;
-};
-
-static int
-shift_i(key, value, var)
- VALUE key, value;
- struct shift_var *var;
-{
- if (key == Qundef) return ST_CONTINUE;
- if (var->stop) return ST_STOP;
- var->stop = 1;
- var->key = key;
- var->val = value;
- return ST_DELETE;
-}
-
-static VALUE
-rb_hash_shift(hash)
- VALUE hash;
-{
- struct shift_var var;
-
- rb_hash_modify(hash);
- var.stop = 0;
- st_foreach(RHASH(hash)->tbl, shift_i, &var);
-
- if (var.stop == 0) return RHASH(hash)->ifnone;
- return rb_assoc_new(var.key, var.val);
-}
-
-static int
-delete_if_i(key, value)
- VALUE key, value;
-{
- if (key == Qundef) return ST_CONTINUE;
- if (RTEST(rb_yield(rb_assoc_new(key, value))))
- return ST_DELETE;
- return ST_CONTINUE;
-}
-
-VALUE
-rb_hash_delete_if(hash)
- VALUE hash;
-{
- rb_hash_modify(hash);
- rb_hash_foreach(hash, delete_if_i, 0);
- return hash;
-}
-
-VALUE
-rb_hash_reject_bang(hash)
- VALUE hash;
-{
- int n = RHASH(hash)->tbl->num_entries;
- rb_hash_delete_if(hash);
- if (n == RHASH(hash)->tbl->num_entries) return Qnil;
- return hash;
-}
-
-static VALUE
-rb_hash_reject(hash)
- VALUE hash;
-{
- return rb_hash_delete_if(rb_obj_dup(hash));
-}
-
-static int
-select_i(key, value, result)
- VALUE key, value;
-{
- VALUE assoc;
-
- if (key == Qundef) return ST_CONTINUE;
- assoc = rb_assoc_new(key, value);
- if (RTEST(rb_yield(assoc)))
- rb_ary_push(result, assoc);
- return ST_CONTINUE;
-}
-
-VALUE
-rb_hash_select(argc, argv, hash)
- int argc;
- VALUE *argv;
- VALUE hash;
-{
- VALUE result = rb_ary_new();
- long i;
-
- if (rb_block_given_p()) {
- if (argc > 0) {
- rb_raise(rb_eArgError, "wrong number arguments(%d for 0)", argc);
- }
- rb_hash_foreach(hash, select_i, result);
- }
- else {
- for (i=0; i<argc; i++) {
- rb_ary_push(result, rb_hash_aref(hash, argv[i]));
- }
- }
- return result;
-}
-
-static int
-clear_i(key, value, dummy)
- VALUE key, value, dummy;
-{
- return ST_DELETE;
-}
-
-static VALUE
-rb_hash_clear(hash)
- VALUE hash;
-{
- rb_hash_modify(hash);
- st_foreach(RHASH(hash)->tbl, clear_i, 0);
-
- return hash;
-}
-
-VALUE
-rb_hash_aset(hash, key, val)
- VALUE hash, key, val;
-{
- rb_hash_modify(hash);
- if (TYPE(key) != T_STRING || st_lookup(RHASH(hash)->tbl, key, 0)) {
- st_insert(RHASH(hash)->tbl, key, val);
- }
- else {
- st_add_direct(RHASH(hash)->tbl, rb_str_new4(key), val);
- }
- return val;
-}
-
-static int
-replace_i(key, val, hash)
- VALUE key, val, hash;
-{
- if (key != Qundef) {
- rb_hash_aset(hash, key, val);
- }
-
- return ST_CONTINUE;
-}
-
-static VALUE
-rb_hash_replace(hash, hash2)
- VALUE hash, hash2;
-{
- hash2 = to_hash(hash2);
- rb_hash_clear(hash);
- st_foreach(RHASH(hash2)->tbl, replace_i, hash);
-
- return hash;
-}
-
-static VALUE
-rb_hash_size(hash)
- VALUE hash;
-{
- return INT2FIX(RHASH(hash)->tbl->num_entries);
-}
-
-static VALUE
-rb_hash_empty_p(hash)
- VALUE hash;
-{
- if (RHASH(hash)->tbl->num_entries == 0)
- return Qtrue;
- return Qfalse;
-}
-
-static int
-each_value_i(key, value)
- VALUE key, value;
-{
- if (key == Qundef) return ST_CONTINUE;
- rb_yield(value);
- return ST_CONTINUE;
-}
-
-static VALUE
-rb_hash_each_value(hash)
- VALUE hash;
-{
- rb_hash_foreach(hash, each_value_i, 0);
- return hash;
-}
-
-static int
-each_key_i(key, value)
- VALUE key, value;
-{
- if (key == Qundef) return ST_CONTINUE;
- rb_yield(key);
- return ST_CONTINUE;
-}
-
-static VALUE
-rb_hash_each_key(hash)
- VALUE hash;
-{
- rb_hash_foreach(hash, each_key_i, 0);
- return hash;
-}
-
-static int
-each_pair_i(key, value)
- VALUE key, value;
-{
- if (key == Qundef) return ST_CONTINUE;
- rb_yield(rb_assoc_new(key, value));
- return ST_CONTINUE;
-}
-
-static VALUE
-rb_hash_each_pair(hash)
- VALUE hash;
-{
- rb_hash_foreach(hash, each_pair_i, 0);
- return hash;
-}
-
-static int
-to_a_i(key, value, ary)
- VALUE key, value, ary;
-{
- if (key == Qundef) return ST_CONTINUE;
- rb_ary_push(ary, rb_assoc_new(key, value));
- return ST_CONTINUE;
-}
-
-static VALUE
-rb_hash_to_a(hash)
- VALUE hash;
-{
- VALUE ary;
-
- ary = rb_ary_new();
- st_foreach(RHASH(hash)->tbl, to_a_i, ary);
- if (OBJ_TAINTED(hash)) OBJ_TAINT(ary);
-
- return ary;
-}
-
-static VALUE
-rb_hash_sort(hash)
- VALUE hash;
-{
- VALUE entries = rb_hash_to_a(hash);
- rb_ary_sort_bang(entries);
- return entries;
-}
-
-static int
-inspect_i(key, value, str)
- VALUE key, value, str;
-{
- VALUE str2;
-
- if (key == Qundef) return ST_CONTINUE;
- if (RSTRING(str)->len > 1) {
- rb_str_cat2(str, ", ");
- }
- str2 = rb_inspect(key);
- rb_str_buf_append(str, str2);
- OBJ_INFECT(str, str2);
- rb_str_buf_cat2(str, "=>");
- str2 = rb_inspect(value);
- rb_str_buf_append(str, str2);
- OBJ_INFECT(str, str2);
-
- return ST_CONTINUE;
-}
-
-static VALUE
-inspect_hash(hash)
- VALUE hash;
-{
- VALUE str;
-
- str = rb_str_buf_new2("{");
- st_foreach(RHASH(hash)->tbl, inspect_i, str);
- rb_str_buf_cat2(str, "}");
- OBJ_INFECT(str, hash);
-
- return str;
-}
-
-static VALUE
-rb_hash_inspect(hash)
- VALUE hash;
-{
- if (RHASH(hash)->tbl == 0 || RHASH(hash)->tbl->num_entries == 0)
- return rb_str_new2("{}");
- if (rb_inspecting_p(hash)) return rb_str_new2("{...}");
- return rb_protect_inspect(inspect_hash, hash, 0);
-}
-
-static VALUE
-to_s_hash(hash)
- VALUE hash;
-{
- return rb_ary_to_s(rb_hash_to_a(hash));
-}
-
-static VALUE
-rb_hash_to_s(hash)
- VALUE hash;
-{
- if (rb_inspecting_p(hash)) return rb_str_new2("{...}");
- return rb_protect_inspect(to_s_hash, hash, 0);
-}
-
-static VALUE
-rb_hash_to_hash(hash)
- VALUE hash;
-{
- return hash;
-}
-
-static int
-keys_i(key, value, ary)
- VALUE key, value, ary;
-{
- if (key == Qundef) return ST_CONTINUE;
- rb_ary_push(ary, key);
- return ST_CONTINUE;
-}
-
-static VALUE
-rb_hash_keys(hash)
- VALUE hash;
-{
- VALUE ary;
-
- ary = rb_ary_new();
- st_foreach(RHASH(hash)->tbl, keys_i, ary);
-
- return ary;
-}
-
-static int
-values_i(key, value, ary)
- VALUE key, value, ary;
-{
- if (key == Qundef) return ST_CONTINUE;
- rb_ary_push(ary, value);
- return ST_CONTINUE;
-}
-
-static VALUE
-rb_hash_values(hash)
- VALUE hash;
-{
- VALUE ary;
-
- ary = rb_ary_new();
- st_foreach(RHASH(hash)->tbl, values_i, ary);
-
- return ary;
-}
-
-static VALUE
-rb_hash_has_key(hash, key)
- VALUE hash;
- VALUE key;
-{
- if (st_lookup(RHASH(hash)->tbl, key, 0)) {
- return Qtrue;
- }
- return Qfalse;
-}
-
-static int
-rb_hash_search_value(key, value, data)
- VALUE key, value, *data;
-{
- if (key == Qundef) return ST_CONTINUE;
- if (rb_equal(value, data[1])) {
- data[0] = Qtrue;
- return ST_STOP;
- }
- return ST_CONTINUE;
-}
-
-static VALUE
-rb_hash_has_value(hash, val)
- VALUE hash;
- VALUE val;
-{
- VALUE data[2];
-
- data[0] = Qfalse;
- data[1] = val;
- st_foreach(RHASH(hash)->tbl, rb_hash_search_value, data);
- return data[0];
-}
-
-struct equal_data {
- int result;
- st_table *tbl;
-};
-
-static int
-equal_i(key, val1, data)
- VALUE key, val1;
- struct equal_data *data;
-{
- VALUE val2;
-
- if (key == Qundef) return ST_CONTINUE;
- if (!st_lookup(data->tbl, key, &val2)) {
- data->result = Qfalse;
- return ST_STOP;
- }
- if (!rb_equal(val1, val2)) {
- data->result = Qfalse;
- return ST_STOP;
- }
- return ST_CONTINUE;
-}
-
-static VALUE
-rb_hash_equal(hash1, hash2)
- VALUE hash1, hash2;
-{
- struct equal_data data;
-
- if (hash1 == hash2) return Qtrue;
- if (TYPE(hash2) != T_HASH) return Qfalse;
- if (RHASH(hash1)->tbl->num_entries != RHASH(hash2)->tbl->num_entries)
- return Qfalse;
-
- data.tbl = RHASH(hash2)->tbl;
- data.result = Qtrue;
- st_foreach(RHASH(hash1)->tbl, equal_i, &data);
-
- return data.result;
-}
-
-static int
-rb_hash_invert_i(key, value, hash)
- VALUE key, value;
- VALUE hash;
-{
- if (key == Qundef) return ST_CONTINUE;
- rb_hash_aset(hash, value, key);
- return ST_CONTINUE;
-}
-
-static VALUE
-rb_hash_invert(hash)
- VALUE hash;
-{
- VALUE h = rb_hash_new();
-
- st_foreach(RHASH(hash)->tbl, rb_hash_invert_i, h);
- return h;
-}
-
-static int
-rb_hash_update_i(key, value, hash)
- VALUE key, value;
- VALUE hash;
-{
- if (key == Qundef) return ST_CONTINUE;
- rb_hash_aset(hash, key, value);
- return ST_CONTINUE;
-}
-
-static int
-rb_hash_update_block_i(key, value, hash)
- VALUE key, value;
- VALUE hash;
-{
- if (key == Qundef) return ST_CONTINUE;
- if (rb_hash_has_key(hash, key)) {
- value = rb_yield(rb_ary_new3(3, key, rb_hash_aref(hash, key), value));
- }
- rb_hash_aset(hash, key, value);
- return ST_CONTINUE;
-}
-
-static VALUE
-rb_hash_update(hash1, hash2)
- VALUE hash1, hash2;
-{
- hash2 = to_hash(hash2);
- if (rb_block_given_p()) {
- st_foreach(RHASH(hash2)->tbl, rb_hash_update_block_i, hash1);
- }
- else {
- st_foreach(RHASH(hash2)->tbl, rb_hash_update_i, hash1);
- }
- return hash1;
-}
-
-static int path_tainted = -1;
-
-static char **origenviron;
-#ifdef NT
-#define GET_ENVIRON(e) (e = win32_get_environ())
-#define FREE_ENVIRON(e) win32_free_environ(e)
-static char **my_environ;
-#undef environ
-#define environ my_environ
-#else
-extern char **environ;
-#define GET_ENVIRON(e) (e)
-#define FREE_ENVIRON(e)
-#endif
-
-static VALUE
-env_delete(obj, name)
- VALUE obj, name;
-{
- char *nam, *val;
-
- rb_secure(4);
- StringValue(name);
- nam = RSTRING(name)->ptr;
- if (strlen(nam) != RSTRING(name)->len) {
- rb_raise(rb_eArgError, "bad environment variable name");
- }
- val = getenv(nam);
- if (val) {
- VALUE value = rb_tainted_str_new2(val);
-
- ruby_setenv(nam, 0);
- if (strcmp(nam, "PATH") == 0 && !OBJ_TAINTED(name)) {
- path_tainted = 0;
- }
- return value;
- }
- return Qnil;
-}
-
-static VALUE
-env_delete_m(obj, name)
- VALUE obj, name;
-{
- VALUE val = env_delete(obj, name);
- if (rb_block_given_p()) rb_yield(name);
- return val;
-}
-
-static VALUE
-rb_f_getenv(obj, name)
- VALUE obj, name;
-{
- char *nam, *env;
-
- StringValue(name);
- nam = RSTRING(name)->ptr;
- if (strlen(nam) != RSTRING(name)->len) {
- rb_raise(rb_eArgError, "bad environment variable name");
- }
- env = getenv(nam);
- if (env) {
- if (strcmp(nam, "PATH") == 0 && !rb_env_path_tainted())
- return rb_str_new2(env);
- return rb_tainted_str_new2(env);
- }
- return Qnil;
-}
-
-static VALUE
-env_fetch(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE key, if_none;
- char *nam, *env;
-
- rb_scan_args(argc, argv, "11", &key, &if_none);
- StringValue(key);
- nam = RSTRING(key)->ptr;
- if (strlen(nam) != RSTRING(key)->len) {
- rb_raise(rb_eArgError, "bad environment variable name");
- }
- env = getenv(nam);
- if (!env) {
- if (rb_block_given_p()) {
- if (argc > 1) {
- rb_raise(rb_eArgError, "wrong number of arguments");
- }
- return rb_yield(key);
- }
- if (argc == 1) {
- rb_raise(rb_eIndexError, "key not found");
- }
- return if_none;
- }
- if (strcmp(nam, "PATH") == 0 && !rb_env_path_tainted())
- return rb_str_new2(env);
- return rb_tainted_str_new2(env);
-}
-
-static void
-path_tainted_p(path)
- char *path;
-{
- path_tainted = rb_path_check(path)?0:1;
-}
-
-int
-rb_env_path_tainted()
-{
- if (path_tainted < 0) {
- path_tainted_p(getenv("PATH"));
- }
- return path_tainted;
-}
-
-static int
-envix(nam)
-char *nam;
-{
- register int i, len = strlen(nam);
- char **env;
-
- env = GET_ENVIRON(environ);
- for (i = 0; env[i]; i++) {
- if (
-#ifdef WIN32
- strnicmp(env[i],nam,len) == 0
-#else
- memcmp(env[i],nam,len) == 0
-#endif
- && env[i][len] == '=')
- break; /* memcmp must come first to avoid */
- } /* potential SEGV's */
- FREE_ENVIRON(environ);
- return i;
-}
-
-void
-ruby_setenv(name, value)
- const char *name;
- const char *value;
-{
-#if defined(WIN32) && !defined(__CYGWIN32__)
- /* The sane way to deal with the environment.
- * Has these advantages over putenv() & co.:
- * * enables us to store a truly empty value in the
- * environment (like in UNIX).
- * * we don't have to deal with RTL globals, bugs and leaks.
- * * Much faster.
- * Why you may want to enable USE_WIN32_RTL_ENV:
- * * environ[] and RTL functions will not reflect changes,
- * which might be an issue if extensions want to access
- * the env. via RTL. This cuts both ways, since RTL will
- * not see changes made by extensions that call the Win32
- * functions directly, either.
- * GSAR 97-06-07
- *
- * REMARK: USE_WIN32_RTL_ENV is already obsoleted since we don't use
- * RTL's environ global variable directly yet.
- */
- SetEnvironmentVariable(name,value);
-#elif defined __CYGWIN__
-#undef setenv
-#undef unsetenv
- if (value)
- setenv(name,value,1);
- else
- unsetenv(name);
-#else /* WIN32 */
-
- int i=envix(name); /* where does it go? */
-
- if (environ == origenviron) { /* need we copy environment? */
- int j;
- int max;
- char **tmpenv;
-
- for (max = i; environ[max]; max++) ;
- tmpenv = ALLOC_N(char*, max+2);
- for (j=0; j<max; j++) /* copy environment */
- tmpenv[j] = strdup(environ[j]);
- tmpenv[max] = 0;
- environ = tmpenv; /* tell exec where it is now */
- }
- if (!value) {
- if (environ != origenviron) {
- char **envp = origenviron;
- while (*envp && *envp != environ[i]) envp++;
- if (!*envp)
- free(environ[i]);
- }
- while (environ[i]) {
- environ[i] = environ[i+1];
- i++;
- }
- return;
- }
- if (!environ[i]) { /* does not exist yet */
- REALLOC_N(environ, char*, i+2); /* just expand it a bit */
- environ[i+1] = 0; /* make sure it's null terminated */
- }
- else {
- if (environ[i] != origenviron[i])
- free(environ[i]);
- }
- environ[i] = ALLOC_N(char, strlen(name) + strlen(value) + 2);
-#ifndef MSDOS
- sprintf(environ[i],"%s=%s",name,value); /* all that work just for this */
-#else
- /* MS-DOS requires environment variable names to be in uppercase */
- /* [Tom Dinger, 27 August 1990: Well, it doesn't _require_ it, but
- * some utilities and applications may break because they only look
- * for upper case strings. (Fixed strupr() bug here.)]
- */
- strcpy(environ[i],name); strupr(environ[i]);
- sprintf(environ[i] + strlen(name),"=%s", value);
-#endif /* MSDOS */
-
-#endif /* WIN32 */
-}
-
-void
-ruby_unsetenv(name)
- const char *name;
-{
- ruby_setenv(name, 0);
-}
-
-static VALUE
-env_aset(obj, nm, val)
- VALUE obj, nm, val;
-{
- char *name, *value;
-
- if (rb_safe_level() >= 4) {
- rb_raise(rb_eSecurityError, "cannot change environment variable");
- }
-
- if (NIL_P(val)) {
- env_delete(obj, nm);
- return Qnil;
- }
-
- StringValue(nm);
- StringValue(val);
- name = RSTRING(nm)->ptr;
- value = RSTRING(val)->ptr;
- if (strlen(name) != RSTRING(nm)->len)
- rb_raise(rb_eArgError, "bad environment variable name");
- if (strlen(value) != RSTRING(val)->len)
- rb_raise(rb_eArgError, "bad environment variable value");
-
- ruby_setenv(name, value);
- if (strcmp(name, "PATH") == 0) {
- if (OBJ_TAINTED(val)) {
- /* already tainted, no check */
- path_tainted = 1;
- return val;
- }
- else {
- path_tainted_p(value);
- }
- }
- return val;
-}
-
-static VALUE
-env_keys()
-{
- char **env;
- VALUE ary = rb_ary_new();
-
- env = GET_ENVIRON(environ);
- while (*env) {
- char *s = strchr(*env, '=');
- if (s) {
- rb_ary_push(ary, rb_tainted_str_new(*env, s-*env));
- }
- env++;
- }
- FREE_ENVIRON(environ);
- return ary;
-}
-
-static VALUE
-env_each_key(hash)
- VALUE hash;
-{
- char **env;
-
- env = GET_ENVIRON(environ);
- while (*env) {
- char *s = strchr(*env, '=');
- if (s) {
- rb_yield(rb_tainted_str_new(*env, s-*env));
- }
- env++;
- }
- FREE_ENVIRON(environ);
- return Qnil;
-}
-
-static VALUE
-env_values()
-{
- char **env;
- VALUE ary = rb_ary_new();
-
- env = GET_ENVIRON(environ);
- while (*env) {
- char *s = strchr(*env, '=');
- if (s) {
- rb_ary_push(ary, rb_tainted_str_new2(s+1));
- }
- env++;
- }
- FREE_ENVIRON(environ);
- return ary;
-}
-
-static VALUE
-env_each_value(hash)
- VALUE hash;
-{
- char **env;
-
- env = GET_ENVIRON(environ);
- while (*env) {
- char *s = strchr(*env, '=');
- if (s) {
- rb_yield(rb_tainted_str_new2(s+1));
- }
- env++;
- }
- FREE_ENVIRON(environ);
- return Qnil;
-}
-
-static VALUE
-env_each(hash)
- VALUE hash;
-{
- char **env;
-
- env = GET_ENVIRON(environ);
- while (*env) {
- char *s = strchr(*env, '=');
- if (s) {
- rb_yield(rb_assoc_new(rb_tainted_str_new(*env, s-*env),
- rb_tainted_str_new2(s+1)));
- }
- env++;
- }
- FREE_ENVIRON(environ);
- return Qnil;
-}
-
-static VALUE
-env_reject_bang()
-{
- volatile VALUE keys;
- VALUE *ptr;
- int len, del = 0;
-
- rb_secure(4);
- keys = env_keys();
- ptr = RARRAY(keys)->ptr;
- len = RARRAY(keys)->len;
-
- while (len--) {
- VALUE val = rb_f_getenv(Qnil, *ptr);
- if (!NIL_P(val)) {
- if (RTEST(rb_yield(rb_assoc_new(*ptr, val)))) {
- env_delete(Qnil, *ptr);
- del++;
- }
- }
- ptr++;
- }
- if (del == 0) return Qnil;
- return envtbl;
-}
-
-static VALUE
-env_delete_if()
-{
- env_reject_bang();
- return envtbl;
-}
-
-static VALUE
-env_select(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE result = rb_ary_new();
- long i;
-
- if (rb_block_given_p()) {
- char **env;
-
- if (argc > 0) {
- rb_raise(rb_eArgError, "wrong number arguments(%d for 0)", argc);
- }
- env = GET_ENVIRON(environ);
- while (*env) {
- char *s = strchr(*env, '=');
- if (s) {
- VALUE assoc = rb_assoc_new(rb_tainted_str_new(*env, s-*env),
- rb_tainted_str_new2(s+1));
- if (RTEST(rb_yield(assoc))) {
- rb_ary_push(result, assoc);
- }
- }
- env++;
- }
- FREE_ENVIRON(environ);
- }
- else {
- for (i=0; i<argc; i++) {
- rb_ary_push(result, rb_f_getenv(Qnil, argv[i]));
- }
- }
- return result;
-}
-
-static VALUE
-env_to_s()
-{
- return rb_str_new2("ENV");
-}
-
-static VALUE
-env_inspect()
-{
- char **env;
- VALUE str = rb_str_buf_new2("{");
- VALUE i;
-
- env = GET_ENVIRON(environ);
- while (*env) {
- char *s = strchr(*env, '=');
-
- if (env != environ) {
- rb_str_buf_cat2(str, ", ");
- }
- if (s) {
- rb_str_buf_cat2(str, "\"");
- rb_str_buf_cat(str, *env, s-*env);
- rb_str_buf_cat2(str, "\"=>");
- i = rb_inspect(rb_str_new2(s+1));
- rb_str_buf_append(str, i);
- }
- env++;
- }
- FREE_ENVIRON(environ);
- rb_str_buf_cat2(str, "}");
- OBJ_TAINT(str);
-
- return str;
-}
-
-static VALUE
-env_to_a()
-{
- char **env;
- VALUE ary = rb_ary_new();
-
- env = GET_ENVIRON(environ);
- while (*env) {
- char *s = strchr(*env, '=');
- if (s) {
- rb_ary_push(ary, rb_assoc_new(rb_tainted_str_new(*env, s-*env),
- rb_tainted_str_new2(s+1)));
- }
- env++;
- }
- FREE_ENVIRON(environ);
- return ary;
-}
-
-static VALUE
-env_none()
-{
- return Qnil;
-}
-
-static VALUE
-env_size()
-{
- int i;
- char **env;
-
- env = GET_ENVIRON(environ);
- for(i=0; env[i]; i++)
- ;
- FREE_ENVIRON(environ);
- return INT2FIX(i);
-}
-
-static VALUE
-env_empty_p()
-{
- char **env;
-
- env = GET_ENVIRON(environ);
- if (env[0] == 0) {
- FREE_ENVIRON(environ);
- return Qtrue;
- }
- FREE_ENVIRON(environ);
- return Qfalse;
-}
-
-static VALUE
-env_has_key(env, key)
- VALUE env, key;
-{
- char *s;
-
- s = StringValuePtr(key);
- if (strlen(s) != RSTRING(key)->len)
- rb_raise(rb_eArgError, "bad environment variable name");
- if (getenv(s)) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-env_has_value(dmy, value)
- VALUE dmy, value;
-{
- char **env;
-
- if (TYPE(value) != T_STRING) return Qfalse;
- env = GET_ENVIRON(environ);
- while (*env) {
- char *s = strchr(*env, '=')+1;
- if (s) {
- if (strncmp(s, RSTRING(value)->ptr, strlen(s)) == 0) {
- FREE_ENVIRON(environ);
- return Qtrue;
- }
- }
- env++;
- }
- FREE_ENVIRON(environ);
- return Qfalse;
-}
-
-static VALUE
-env_index(dmy, value)
- VALUE dmy, value;
-{
- char **env;
- VALUE str;
-
- if (TYPE(value) != T_STRING) return Qnil;
- env = GET_ENVIRON(environ);
- while (*env) {
- char *s = strchr(*env, '=')+1;
- if (s) {
- if (strncmp(s, RSTRING(value)->ptr, strlen(s)) == 0) {
- str = rb_tainted_str_new(*env, s-*env-1);
- FREE_ENVIRON(environ);
- return str;
- }
- }
- env++;
- }
- FREE_ENVIRON(environ);
- return Qnil;
-}
-
-static VALUE
-env_indexes(argc, argv)
- int argc;
- VALUE *argv;
-{
- int i;
- VALUE indexes = rb_ary_new2(argc);
-
- rb_warn("ENV.%s is deprecated; use ENV.select",
- rb_id2name(rb_frame_last_func()));
- for (i=0;i<argc;i++) {
- char *v = 0;
- if (TYPE(argv[i]) == T_STRING) {
- v = getenv(RSTRING(argv[i])->ptr);
- }
- if (v) {
- RARRAY(indexes)->ptr[i] = rb_tainted_str_new2(v);
- }
- else {
- RARRAY(indexes)->ptr[i] = Qnil;
- }
- RARRAY(indexes)->len = i+1;
- }
-
- return indexes;
-}
-
-static VALUE
-env_to_hash()
-{
- char **env;
- VALUE hash = rb_hash_new();
-
- env = GET_ENVIRON(environ);
- while (*env) {
- char *s = strchr(*env, '=');
- if (s) {
- rb_hash_aset(hash, rb_tainted_str_new(*env, s-*env),
- rb_tainted_str_new2(s+1));
- }
- env++;
- }
- FREE_ENVIRON(environ);
- return hash;
-}
-
-static VALUE
-env_reject()
-{
- return rb_hash_delete_if(env_to_hash());
-}
-
-void
-Init_Hash()
-{
- id_hash = rb_intern("hash");
- id_yield = rb_intern("yield");
- id_default = rb_intern("default");
-
- rb_cHash = rb_define_class("Hash", rb_cObject);
-
- rb_include_module(rb_cHash, rb_mEnumerable);
-
- rb_define_singleton_method(rb_cHash, "allocate", rb_hash_s_alloc, 0);
- rb_define_singleton_method(rb_cHash, "[]", rb_hash_s_create, -1);
- rb_define_method(rb_cHash,"initialize", rb_hash_initialize, -1);
-
- rb_define_method(rb_cHash,"clone", rb_hash_clone, 0);
- rb_define_method(rb_cHash,"rehash", rb_hash_rehash, 0);
-
- rb_define_method(rb_cHash,"to_hash", rb_hash_to_hash, 0);
- rb_define_method(rb_cHash,"to_a", rb_hash_to_a, 0);
- rb_define_method(rb_cHash,"to_s", rb_hash_to_s, 0);
- rb_define_method(rb_cHash,"inspect", rb_hash_inspect, 0);
-
- rb_define_method(rb_cHash,"==", rb_hash_equal, 1);
- rb_define_method(rb_cHash,"[]", rb_hash_aref, 1);
- rb_define_method(rb_cHash,"fetch", rb_hash_fetch, -1);
- rb_define_method(rb_cHash,"[]=", rb_hash_aset, 2);
- rb_define_method(rb_cHash,"store", rb_hash_aset, 2);
- rb_define_method(rb_cHash,"default", rb_hash_default, -1);
- rb_define_method(rb_cHash,"default=", rb_hash_set_default, 1);
- rb_define_method(rb_cHash,"index", rb_hash_index, 1);
- rb_define_method(rb_cHash,"indexes", rb_hash_indexes, -1);
- rb_define_method(rb_cHash,"indices", rb_hash_indexes, -1);
- rb_define_method(rb_cHash,"size", rb_hash_size, 0);
- rb_define_method(rb_cHash,"length", rb_hash_size, 0);
- rb_define_method(rb_cHash,"empty?", rb_hash_empty_p, 0);
-
- rb_define_method(rb_cHash,"each", rb_hash_each_pair, 0);
- rb_define_method(rb_cHash,"each_value", rb_hash_each_value, 0);
- rb_define_method(rb_cHash,"each_key", rb_hash_each_key, 0);
- rb_define_method(rb_cHash,"each_pair", rb_hash_each_pair, 0);
- rb_define_method(rb_cHash,"sort", rb_hash_sort, 0);
-
- rb_define_method(rb_cHash,"keys", rb_hash_keys, 0);
- rb_define_method(rb_cHash,"values", rb_hash_values, 0);
-
- rb_define_method(rb_cHash,"shift", rb_hash_shift, 0);
- rb_define_method(rb_cHash,"delete", rb_hash_delete, 1);
- rb_define_method(rb_cHash,"delete_if", rb_hash_delete_if, 0);
- rb_define_method(rb_cHash,"select", rb_hash_select, -1);
- rb_define_method(rb_cHash,"reject", rb_hash_reject, 0);
- rb_define_method(rb_cHash,"reject!", rb_hash_reject_bang, 0);
- rb_define_method(rb_cHash,"clear", rb_hash_clear, 0);
- rb_define_method(rb_cHash,"invert", rb_hash_invert, 0);
- rb_define_method(rb_cHash,"update", rb_hash_update, 1);
- rb_define_method(rb_cHash,"replace", rb_hash_replace, 1);
-
- rb_define_method(rb_cHash,"include?", rb_hash_has_key, 1);
- rb_define_method(rb_cHash,"member?", rb_hash_has_key, 1);
- rb_define_method(rb_cHash,"has_key?", rb_hash_has_key, 1);
- rb_define_method(rb_cHash,"has_value?", rb_hash_has_value, 1);
- rb_define_method(rb_cHash,"key?", rb_hash_has_key, 1);
- rb_define_method(rb_cHash,"value?", rb_hash_has_value, 1);
-
-#ifndef __MACOS__ /* environment variables nothing on MacOS. */
- origenviron = environ;
- envtbl = rb_obj_alloc(rb_cObject);
- rb_extend_object(envtbl, rb_mEnumerable);
-
- rb_define_singleton_method(envtbl,"[]", rb_f_getenv, 1);
- rb_define_singleton_method(envtbl,"fetch", env_fetch, -1);
- rb_define_singleton_method(envtbl,"[]=", env_aset, 2);
- rb_define_singleton_method(envtbl,"store", env_aset, 2);
- rb_define_singleton_method(envtbl,"each", env_each, 0);
- rb_define_singleton_method(envtbl,"each_pair", env_each, 0);
- rb_define_singleton_method(envtbl,"each_key", env_each_key, 0);
- rb_define_singleton_method(envtbl,"each_value", env_each_value, 0);
- rb_define_singleton_method(envtbl,"delete", env_delete_m, 1);
- rb_define_singleton_method(envtbl,"delete_if", env_delete_if, 0);
- rb_define_singleton_method(envtbl,"reject", env_reject, 0);
- rb_define_singleton_method(envtbl,"reject!", env_reject_bang, 0);
- rb_define_singleton_method(envtbl,"select", env_select, -1);
- rb_define_singleton_method(envtbl,"to_s", env_to_s, 0);
- rb_define_singleton_method(envtbl,"inspect", env_inspect, 0);
- rb_define_singleton_method(envtbl,"rehash", env_none, 0);
- rb_define_singleton_method(envtbl,"to_a", env_to_a, 0);
- rb_define_singleton_method(envtbl,"index", env_index, 1);
- rb_define_singleton_method(envtbl,"indexes", env_indexes, -1);
- rb_define_singleton_method(envtbl,"indices", env_indexes, -1);
- rb_define_singleton_method(envtbl,"size", env_size, 0);
- rb_define_singleton_method(envtbl,"length", env_size, 0);
- rb_define_singleton_method(envtbl,"empty?", env_empty_p, 0);
- rb_define_singleton_method(envtbl,"keys", env_keys, 0);
- rb_define_singleton_method(envtbl,"values", env_values, 0);
- rb_define_singleton_method(envtbl,"include?", env_has_key, 1);
- rb_define_singleton_method(envtbl,"member?", env_has_key, 1);
- rb_define_singleton_method(envtbl,"has_key?", env_has_key, 1);
- rb_define_singleton_method(envtbl,"has_value?", env_has_value, 1);
- rb_define_singleton_method(envtbl,"key?", env_has_key, 1);
- rb_define_singleton_method(envtbl,"value?", env_has_value, 1);
- rb_define_singleton_method(envtbl,"to_hash", env_to_hash, 0);
-
- rb_define_global_const("ENV", envtbl);
-#else /* __MACOS__ */
- envtbl = rb_hash_s_new(0, NULL, rb_cHash);
- rb_define_global_const("ENV", envtbl);
-#endif /* ifndef __MACOS__ environment variables nothing on MacOS. */
-}
diff --git a/inits.c b/inits.c
deleted file mode 100644
index d3fffb654e..0000000000
--- a/inits.c
+++ /dev/null
@@ -1,80 +0,0 @@
-/**********************************************************************
-
- inits.c -
-
- $Author$
- $Date$
- created at: Tue Dec 28 16:01:58 JST 1993
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
-
-**********************************************************************/
-
-#include "ruby.h"
-
-void Init_Array _((void));
-void Init_Bignum _((void));
-void Init_Comparable _((void));
-void Init_Dir _((void));
-void Init_Enumerable _((void));
-void Init_Exception _((void));
-void Init_eval _((void));
-void Init_load _((void));
-void Init_Proc _((void));
-void Init_Thread _((void));
-void Init_File _((void));
-void Init_GC _((void));
-void Init_Hash _((void));
-void Init_IO _((void));
-void Init_Math _((void));
-void Init_marshal _((void));
-void Init_Numeric _((void));
-void Init_Object _((void));
-void Init_pack _((void));
-void Init_Precision _((void));
-void Init_sym _((void));
-void Init_process _((void));
-void Init_Random _((void));
-void Init_Range _((void));
-void Init_Regexp _((void));
-void Init_signal _((void));
-void Init_String _((void));
-void Init_Struct _((void));
-void Init_Time _((void));
-void Init_var_tables _((void));
-void Init_version _((void));
-
-void
-rb_call_inits()
-{
- Init_sym();
- Init_var_tables();
- Init_Object();
- Init_Comparable();
- Init_Enumerable();
- Init_Precision();
- Init_eval();
- Init_String();
- Init_Exception();
- Init_Thread();
- Init_Numeric();
- Init_Bignum();
- Init_Array();
- Init_Hash();
- Init_Struct();
- Init_Regexp();
- Init_pack();
- Init_Range();
- Init_IO();
- Init_Dir();
- Init_Time();
- Init_Random();
- Init_signal();
- Init_process();
- Init_load();
- Init_Proc();
- Init_Math();
- Init_GC();
- Init_marshal();
- Init_version();
-}
diff --git a/install-sh b/install-sh
deleted file mode 100644
index e69de29bb2..0000000000
--- a/install-sh
+++ /dev/null
diff --git a/instruby.rb b/instruby.rb
deleted file mode 100644
index 7818455dec..0000000000
--- a/instruby.rb
+++ /dev/null
@@ -1,102 +0,0 @@
-#!./miniruby
-
-load "./rbconfig.rb"
-include Config
-
-File.umask(0)
-destdir = ARGV[0] || ''
-
-$:.unshift CONFIG["srcdir"]+"/lib"
-require "ftools"
-require "find"
-
-exeext = CONFIG["EXEEXT"]
-if ENV["prefix"]
- prefix = ENV["prefix"]
-else
- prefix = CONFIG["prefix"]
-end
-
-ruby_install_name = CONFIG["ruby_install_name"]
-version = "/"+CONFIG["MAJOR"]+"."+CONFIG["MINOR"]
-arch = "/"+CONFIG["arch"]
-
-bindir = destdir+CONFIG["bindir"]
-libdir = destdir+CONFIG["libdir"]
-rubylibdir = destdir+CONFIG["prefix"]+"/lib/ruby"+version
-archlibdir = rubylibdir+arch
-sitelibdir = destdir+CONFIG["sitedir"]+version
-sitearchlibdir = sitelibdir+arch
-mandir = destdir+CONFIG["mandir"] + "/man1"
-wdir = Dir.getwd
-
-File.makedirs bindir, true
-File.install ruby_install_name+exeext,
- "#{bindir}/#{ruby_install_name}#{exeext}", 0755, true
-rubyw = ruby_install_name.sub(/ruby/, '\&w')+exeext
-if File.exist? rubyw
- File.install rubyw, "#{bindir}/#{rubyw}", 0755, true
-end
-for dll in Dir['*.dll']
- File.install dll, "#{bindir}/#{dll}", 0755, true
-end
-File.makedirs libdir, true
-if CONFIG["LIBRUBY"] != CONFIG["LIBRUBY_A"]
- for lib in [CONFIG["LIBRUBY"]]
- if File.exist? lib
- File.install lib, libdir, 0555, true
- end
- end
-end
-Dir.chdir libdir
-if File.exist? CONFIG["LIBRUBY_SO"]
- for link in CONFIG["LIBRUBY_ALIASES"].split
- if File.exist? link
- File.delete link
- end
- File.symlink CONFIG["LIBRUBY_SO"], link
- print "link #{CONFIG['LIBRUBY_SO']} -> #{link}\n"
- end
-end
-Dir.chdir wdir
-File.makedirs rubylibdir, true
-File.makedirs archlibdir, true
-File.makedirs sitelibdir, true
-File.makedirs sitearchlibdir, true
-
-if RUBY_PLATFORM =~ /-aix/
- File.install "ruby.imp", archlibdir, 0644, true
-end
-
-Dir.chdir "ext"
-if defined? CROSS_COMPILING
- system "#{CONFIG['MINIRUBY']} extmk.rb install #{destdir}"
-else
- system "../miniruby#{exeext} extmk.rb install #{destdir}"
-end
-Dir.chdir CONFIG["srcdir"]
-
-File.install "sample/irb.rb", "#{bindir}/irb", 0755, true
-
-Find.find("lib") do |f|
- next unless /\.rb$/ =~ f || /help-message$/ =~ f
- dir = rubylibdir+"/"+File.dirname(f[4..-1])
- File.makedirs dir, true unless File.directory? dir
- File.install f, dir, 0644, true
-end
-
-for f in Dir["*.h"]
- File.install f, archlibdir, 0644, true
-end
-if RUBY_PLATFORM =~ /mswin32|mingw/
- File.makedirs archlibdir + "/win32", true
- File.install "win32/win32.h", archlibdir + "/win32", 0644, true
-end
-File.install wdir+'/'+CONFIG['LIBRUBY_A'], archlibdir, 0644, true
-
-File.makedirs mandir, true
-File.install "ruby.1", mandir+"/"+ruby_install_name+".1", 0644, true
-Dir.chdir wdir
-File.install "config.h", archlibdir, 0644, true
-File.install "rbconfig.rb", archlibdir, 0644, true
-# vi:set sw=2:
diff --git a/intern.h b/intern.h
deleted file mode 100644
index 0eed0ddda6..0000000000
--- a/intern.h
+++ /dev/null
@@ -1,446 +0,0 @@
-/**********************************************************************
-
- intern.h -
-
- $Author$
- $Date$
- created at: Thu Jun 10 14:22:17 JST 1993
-
- Copyright (C) 1993-2002 Yukihiro Matsumoto
- Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
- Copyright (C) 2000 Information-technology Promotion Agency, Japan
-
-**********************************************************************/
-
-/*
- * Functions and variables that are used by more than one source file of
- * the kernel.
- */
-
-/* array.c */
-void rb_mem_clear _((register VALUE*, register long));
-VALUE rb_assoc_new _((VALUE, VALUE));
-VALUE rb_ary_new _((void));
-VALUE rb_ary_new2 _((long));
-VALUE rb_ary_new3 __((long,...));
-VALUE rb_ary_new4 _((long, VALUE *));
-VALUE rb_ary_freeze _((VALUE));
-VALUE rb_ary_aref _((int, VALUE*, VALUE));
-void rb_ary_store _((VALUE, long, VALUE));
-VALUE rb_ary_dup _((VALUE));
-VALUE rb_ary_to_ary _((VALUE));
-VALUE rb_ary_to_s _((VALUE));
-VALUE rb_ary_push _((VALUE, VALUE));
-VALUE rb_ary_pop _((VALUE));
-VALUE rb_ary_shift _((VALUE));
-VALUE rb_ary_unshift _((VALUE, VALUE));
-VALUE rb_ary_entry _((VALUE, long));
-VALUE rb_ary_each _((VALUE));
-VALUE rb_ary_join _((VALUE, VALUE));
-VALUE rb_ary_print_on _((VALUE, VALUE));
-VALUE rb_ary_reverse _((VALUE));
-VALUE rb_ary_sort _((VALUE));
-int rb_cmpint _((VALUE));
-VALUE rb_ary_sort_bang _((VALUE));
-VALUE rb_ary_delete _((VALUE, VALUE));
-VALUE rb_ary_delete_at _((VALUE, long));
-VALUE rb_ary_clear _((VALUE));
-VALUE rb_ary_plus _((VALUE, VALUE));
-VALUE rb_ary_concat _((VALUE, VALUE));
-VALUE rb_ary_assoc _((VALUE, VALUE));
-VALUE rb_ary_rassoc _((VALUE, VALUE));
-VALUE rb_ary_includes _((VALUE, VALUE));
-VALUE rb_ary_cmp _((VALUE, VALUE));
-VALUE rb_protect_inspect _((VALUE(*)(ANYARGS),VALUE,VALUE));
-VALUE rb_inspecting_p _((VALUE));
-/* bignum.c */
-VALUE rb_big_clone _((VALUE));
-void rb_big_2comp _((VALUE));
-VALUE rb_big_norm _((VALUE));
-VALUE rb_uint2big _((unsigned long));
-VALUE rb_int2big _((long));
-VALUE rb_uint2inum _((unsigned long));
-VALUE rb_int2inum _((long));
-VALUE rb_cstr_to_inum _((const char*, int, int));
-VALUE rb_str_to_inum _((VALUE, int, int));
-VALUE rb_cstr2inum _((const char*, int));
-VALUE rb_str2inum _((VALUE, int));
-VALUE rb_big2str _((VALUE, int));
-long rb_big2long _((VALUE));
-#define rb_big2int(x) rb_big2long(x)
-unsigned long rb_big2ulong _((VALUE));
-#define rb_big2uint(x) rb_big2ulong(x)
-#if HAVE_LONG_LONG
-VALUE rb_ll2inum _((LONG_LONG));
-VALUE rb_ull2inum _((unsigned LONG_LONG));
-LONG_LONG rb_big2ll _((VALUE));
-unsigned LONG_LONG rb_big2ull _((VALUE));
-#endif /* HAVE_LONG_LONG */
-void rb_quad_pack _((char*,VALUE));
-VALUE rb_quad_unpack _((const char*,int));
-VALUE rb_dbl2big _((double));
-double rb_big2dbl _((VALUE));
-VALUE rb_big_plus _((VALUE, VALUE));
-VALUE rb_big_minus _((VALUE, VALUE));
-VALUE rb_big_mul _((VALUE, VALUE));
-VALUE rb_big_divmod _((VALUE, VALUE));
-VALUE rb_big_pow _((VALUE, VALUE));
-VALUE rb_big_and _((VALUE, VALUE));
-VALUE rb_big_or _((VALUE, VALUE));
-VALUE rb_big_xor _((VALUE, VALUE));
-VALUE rb_big_lshift _((VALUE, VALUE));
-VALUE rb_big_rand _((VALUE, double));
-/* class.c */
-VALUE rb_class_boot _((VALUE));
-VALUE rb_class_new _((VALUE));
-VALUE rb_mod_clone _((VALUE));
-VALUE rb_mod_dup _((VALUE));
-VALUE rb_singleton_class_new _((VALUE));
-VALUE rb_singleton_class_clone _((VALUE));
-void rb_singleton_class_attached _((VALUE,VALUE));
-VALUE rb_make_metaclass _((VALUE, VALUE));
-VALUE rb_class_inherited _((VALUE, VALUE));
-VALUE rb_define_class_id _((ID, VALUE));
-VALUE rb_module_new _((void));
-VALUE rb_define_module_id _((ID));
-VALUE rb_mod_included_modules _((VALUE));
-VALUE rb_mod_include_p _((VALUE, VALUE));
-VALUE rb_mod_ancestors _((VALUE));
-VALUE rb_class_instance_methods _((int, VALUE*, VALUE));
-VALUE rb_class_protected_instance_methods _((int, VALUE*, VALUE));
-VALUE rb_class_private_instance_methods _((int, VALUE*, VALUE));
-VALUE rb_obj_singleton_methods _((int, VALUE*, VALUE));
-void rb_define_method_id _((VALUE, ID, VALUE (*)(ANYARGS), int));
-void rb_frozen_class_p _((VALUE));
-void rb_undef _((VALUE, ID));
-void rb_define_protected_method _((VALUE, const char*, VALUE (*)(ANYARGS), int));
-void rb_define_private_method _((VALUE, const char*, VALUE (*)(ANYARGS), int));
-void rb_define_singleton_method _((VALUE, const char*, VALUE(*)(ANYARGS), int));
-void rb_define_private_method _((VALUE, const char*, VALUE(*)(ANYARGS), int));
-VALUE rb_singleton_class _((VALUE));
-/* enum.c */
-/* error.c */
-EXTERN int ruby_nerrs;
-VALUE rb_exc_new _((VALUE, const char*, long));
-VALUE rb_exc_new2 _((VALUE, const char*));
-VALUE rb_exc_new3 _((VALUE, VALUE));
-NORETURN(void rb_loaderror __((const char*, ...)));
-NORETURN(void rb_name_error __((VALUE id, const char*, ...)));
-NORETURN(void rb_invalid_str _((const char*, const char*)));
-void rb_compile_error __((const char*, ...));
-void rb_compile_error_append __((const char*, ...));
-NORETURN(void rb_load_fail _((char*)));
-NORETURN(void rb_error_frozen _((char*)));
-/* eval.c */
-NORETURN(void rb_exc_raise _((VALUE)));
-NORETURN(void rb_exc_fatal _((VALUE)));
-void rb_remove_method _((VALUE, const char*));
-void rb_disable_super _((VALUE, const char*));
-void rb_enable_super _((VALUE, const char*));
-void rb_clear_cache _((void));
-void rb_alias _((VALUE, ID, ID));
-void rb_attr _((VALUE,ID,int,int,int));
-int rb_method_boundp _((VALUE, ID, int));
-VALUE rb_dvar_defined _((ID));
-VALUE rb_dvar_curr _((ID));
-VALUE rb_dvar_ref _((ID));
-void rb_dvar_asgn _((ID, VALUE));
-void rb_dvar_push _((ID, VALUE));
-VALUE *rb_svar _((int));
-VALUE rb_eval_cmd _((VALUE, VALUE, int));
-int rb_respond_to _((VALUE, ID));
-void rb_interrupt _((void));
-VALUE rb_apply _((VALUE, ID, VALUE));
-void rb_backtrace _((void));
-ID rb_frame_last_func _((void));
-VALUE rb_obj_instance_eval _((int, VALUE*, VALUE));
-VALUE rb_mod_module_eval _((int, VALUE*, VALUE));
-void rb_load _((VALUE, int));
-void rb_load_protect _((VALUE, int, int*));
-NORETURN(void rb_jump_tag _((int)));
-int rb_provided _((const char*));
-void rb_provide _((const char*));
-VALUE rb_f_require _((VALUE, VALUE));
-void rb_obj_call_init _((VALUE, int, VALUE*));
-VALUE rb_class_new_instance _((int, VALUE*, VALUE));
-VALUE rb_f_lambda _((void));
-VALUE rb_protect _((VALUE (*)(VALUE), VALUE, int*));
-void rb_set_end_proc _((void (*)(VALUE), VALUE));
-void rb_mark_end_proc _((void));
-void rb_exec_end_proc _((void));
-void ruby_finalize _((void));
-void ruby_stop _((int));
-void rb_gc_mark_threads _((void));
-void rb_thread_start_timer _((void));
-void rb_thread_stop_timer _((void));
-void rb_thread_schedule _((void));
-void rb_thread_wait_fd _((int));
-int rb_thread_fd_writable _((int));
-void rb_thread_fd_close _((int));
-int rb_thread_alone _((void));
-void rb_thread_polling _((void));
-void rb_thread_sleep _((int));
-void rb_thread_sleep_forever _((void));
-VALUE rb_thread_stop _((void));
-VALUE rb_thread_wakeup _((VALUE));
-VALUE rb_thread_run _((VALUE));
-VALUE rb_thread_create _((VALUE (*)(ANYARGS), void*));
-void rb_thread_interrupt _((void));
-void rb_thread_trap_eval _((VALUE, int));
-void rb_thread_signal_raise _((char*));
-int rb_thread_select(ANYARGS);
-void rb_thread_wait_for(ANYARGS);
-VALUE rb_thread_current _((void));
-VALUE rb_thread_main _((void));
-VALUE rb_thread_local_aref _((VALUE, ID));
-VALUE rb_thread_local_aset _((VALUE, ID, VALUE));
-void rb_thread_atfork _((void));
-/* file.c */
-int eaccess _((const char*, int));
-VALUE rb_file_s_expand_path _((int, VALUE *));
-void rb_file_const _((const char*, VALUE));
-int rb_find_file_ext _((VALUE*, const char* const*));
-VALUE rb_find_file _((VALUE));
-/* gc.c */
-int ruby_stack_check _((void));
-int ruby_stack_length _((VALUE**));
-char *rb_source_filename _((const char *));
-void rb_gc_mark_locations _((VALUE*, VALUE*));
-void rb_mark_tbl _((struct st_table*));
-void rb_mark_hash _((struct st_table*));
-void rb_gc_mark_maybe _((VALUE));
-void rb_gc_mark _((VALUE));
-void rb_gc_force_recycle _((VALUE));
-void rb_gc _((void));
-void rb_gc_call_finalizer_at_exit _((void));
-VALUE rb_gc_enable _((void));
-VALUE rb_gc_disable _((void));
-VALUE rb_gc_start _((void));
-/* hash.c */
-VALUE rb_hash _((VALUE));
-VALUE rb_hash_new _((void));
-VALUE rb_hash_freeze _((VALUE));
-VALUE rb_hash_aref _((VALUE, VALUE));
-VALUE rb_hash_aset _((VALUE, VALUE, VALUE));
-VALUE rb_hash_delete_if _((VALUE));
-VALUE rb_hash_delete _((VALUE,VALUE));
-int rb_path_check _((char *));
-int rb_env_path_tainted _((void));
-/* io.c */
-EXTERN VALUE rb_fs;
-EXTERN VALUE rb_output_fs;
-EXTERN VALUE rb_rs;
-EXTERN VALUE rb_default_rs;
-EXTERN VALUE rb_output_rs;
-VALUE rb_io_write _((VALUE, VALUE));
-VALUE rb_io_gets _((VALUE));
-VALUE rb_io_getc _((VALUE));
-VALUE rb_io_ungetc _((VALUE, VALUE));
-VALUE rb_io_close _((VALUE));
-VALUE rb_io_eof _((VALUE));
-VALUE rb_io_binmode _((VALUE));
-VALUE rb_io_addstr _((VALUE, VALUE));
-VALUE rb_io_printf _((int, VALUE*, VALUE));
-VALUE rb_io_print _((int, VALUE*, VALUE));
-VALUE rb_io_puts _((int, VALUE*, VALUE));
-VALUE rb_file_open _((const char*, const char*));
-VALUE rb_gets _((void));
-/* marshal.c */
-VALUE rb_marshal_dump _((VALUE, VALUE));
-VALUE rb_marshal_load _((VALUE));
-/* numeric.c */
-void rb_num_zerodiv _((void));
-VALUE rb_num_coerce_bin _((VALUE, VALUE));
-VALUE rb_float_new _((double));
-VALUE rb_num2fix _((VALUE));
-VALUE rb_fix2str _((VALUE, int));
-VALUE rb_fix_upto _((VALUE, VALUE));
-/* object.c */
-int rb_eql _((VALUE, VALUE));
-VALUE rb_any_to_s _((VALUE));
-VALUE rb_inspect _((VALUE));
-VALUE rb_obj_is_instance_of _((VALUE, VALUE));
-VALUE rb_obj_is_kind_of _((VALUE, VALUE));
-VALUE rb_obj_alloc _((VALUE));
-VALUE rb_obj_clone _((VALUE));
-VALUE rb_obj_dup _((VALUE));
-VALUE rb_obj_taint _((VALUE));
-VALUE rb_obj_tainted _((VALUE));
-VALUE rb_obj_untaint _((VALUE));
-VALUE rb_obj_freeze _((VALUE));
-VALUE rb_obj_id _((VALUE));
-VALUE rb_obj_class _((VALUE));
-VALUE rb_class_real _((VALUE));
-VALUE rb_convert_type _((VALUE,int,const char*,const char*));
-VALUE rb_check_convert_type _((VALUE,int,const char*,const char*));
-VALUE rb_to_int _((VALUE));
-VALUE rb_Integer _((VALUE));
-VALUE rb_Float _((VALUE));
-VALUE rb_String _((VALUE));
-VALUE rb_Array _((VALUE));
-double rb_cstr_to_dbl _((const char *, int));
-double rb_str_to_dbl _((VALUE, int));
-/* parse.y */
-EXTERN int ruby_sourceline;
-EXTERN char *ruby_sourcefile;
-#define yyparse ruby_yyparse
-#define yylex ruby_yylex
-#define yyerror ruby_yyerror
-#define yylval ruby_yylval
-#define yychar ruby_yychar
-#define yydebug ruby_yydebug
-int yyparse _((void));
-ID rb_id_attrset _((ID));
-void rb_parser_append_print _((void));
-void rb_parser_while_loop _((int, int));
-int rb_is_const_id _((ID));
-int rb_is_instance_id _((ID));
-int rb_is_class_id _((ID));
-int rb_is_local_id _((ID));
-VALUE rb_backref_get _((void));
-void rb_backref_set _((VALUE));
-VALUE rb_lastline_get _((void));
-void rb_lastline_set _((VALUE));
-VALUE rb_sym_all_symbols _((void));
-/* process.c */
-int rb_proc_exec _((const char*));
-VALUE rb_f_exec _((int,VALUE*));
-int rb_waitpid _((int,int*,int));
-void rb_syswait _((int));
-VALUE rb_proc_times _((VALUE));
-/* range.c */
-VALUE rb_range_new _((VALUE, VALUE, int));
-VALUE rb_range_beg_len _((VALUE, long*, long*, long, int));
-VALUE rb_length_by_each _((VALUE));
-/* re.c */
-int rb_memcmp _((char*,char*,long));
-int rb_memcicmp _((char*,char*,long));
-VALUE rb_reg_nth_defined _((int, VALUE));
-VALUE rb_reg_nth_match _((int, VALUE));
-VALUE rb_reg_last_match _((VALUE));
-VALUE rb_reg_match_pre _((VALUE));
-VALUE rb_reg_match_post _((VALUE));
-VALUE rb_reg_match_last _((VALUE));
-VALUE rb_reg_new _((const char*, long, int));
-VALUE rb_reg_match _((VALUE, VALUE));
-VALUE rb_reg_match2 _((VALUE));
-int rb_reg_options _((VALUE));
-void rb_set_kcode _((const char*));
-const char* rb_get_kcode _((void));
-/* ruby.c */
-EXTERN VALUE rb_argv;
-EXTERN VALUE rb_argv0;
-void rb_load_file _((char*));
-void ruby_script _((char*));
-void ruby_prog_init _((void));
-void ruby_set_argv _((int, char**));
-void ruby_process_options _((int, char**));
-void ruby_load_script _((void));
-void ruby_init_loadpath _((void));
-void ruby_incpush _((const char*));
-/* signal.c */
-VALUE rb_f_kill _((int, VALUE*));
-void rb_gc_mark_trap_list _((void));
-#ifdef POSIX_SIGNAL
-#define posix_signal ruby_posix_signal
-void posix_signal _((int, RETSIGTYPE (*)(int)));
-#endif
-void rb_trap_exit _((void));
-void rb_trap_exec _((void));
-/* sprintf.c */
-VALUE rb_f_sprintf _((int, VALUE*));
-/* string.c */
-VALUE rb_str_new _((const char*, long));
-VALUE rb_str_new2 _((const char*));
-VALUE rb_str_new3 _((VALUE));
-VALUE rb_str_new4 _((VALUE));
-VALUE rb_str_new5 _((VALUE, const char *, long));
-VALUE rb_tainted_str_new _((const char*, long));
-VALUE rb_tainted_str_new2 _((const char*));
-VALUE rb_str_buf_new _((long));
-VALUE rb_str_buf_new2 _((const char*));
-VALUE rb_str_buf_append _((VALUE, VALUE));
-VALUE rb_str_buf_cat _((VALUE, const char *, long));
-VALUE rb_str_buf_cat2 _((VALUE, const char *));
-VALUE rb_obj_as_string _((VALUE));
-VALUE rb_str_dup _((VALUE));
-VALUE rb_str_dup_frozen _((VALUE));
-VALUE rb_str_plus _((VALUE, VALUE));
-VALUE rb_str_times _((VALUE, VALUE));
-VALUE rb_str_substr _((VALUE, long, long));
-void rb_str_modify _((VALUE));
-VALUE rb_str_freeze _((VALUE));
-VALUE rb_str_resize _((VALUE, long));
-VALUE rb_str_cat _((VALUE, const char*, long));
-VALUE rb_str_cat2 _((VALUE, const char*));
-VALUE rb_str_append _((VALUE, VALUE));
-VALUE rb_str_concat _((VALUE, VALUE));
-int rb_str_hash _((VALUE));
-int rb_str_cmp _((VALUE, VALUE));
-VALUE rb_str_upto _((VALUE, VALUE, int));
-void rb_str_update _((VALUE, long, long, VALUE));
-VALUE rb_str_inspect _((VALUE));
-VALUE rb_str_split _((VALUE, const char*));
-void rb_str_associate _((VALUE, VALUE));
-VALUE rb_str_associated _((VALUE));
-void rb_str_setter _((VALUE, ID, VALUE*));
-/* struct.c */
-VALUE rb_struct_new __((VALUE, ...));
-VALUE rb_struct_define __((const char*, ...));
-VALUE rb_struct_alloc _((VALUE, VALUE));
-VALUE rb_struct_aref _((VALUE, VALUE));
-VALUE rb_struct_aset _((VALUE, VALUE, VALUE));
-VALUE rb_struct_getmember _((VALUE, ID));
-VALUE rb_struct_iv_get _((VALUE, char*));
-/* time.c */
-VALUE rb_time_new(ANYARGS);
-/* variable.c */
-VALUE rb_mod_name _((VALUE));
-VALUE rb_class_path _((VALUE));
-void rb_set_class_path _((VALUE, VALUE, const char*));
-VALUE rb_path2class _((const char*));
-void rb_name_class _((VALUE, ID));
-void rb_autoload _((const char*, const char*));
-VALUE rb_f_autoload _((VALUE, VALUE, VALUE));
-void rb_gc_mark_global_tbl _((void));
-VALUE rb_f_trace_var _((int, VALUE*));
-VALUE rb_f_untrace_var _((int, VALUE*));
-VALUE rb_f_global_variables _((void));
-void rb_alias_variable _((ID, ID));
-struct st_table* rb_generic_ivar_table _((VALUE));
-void rb_copy_generic_ivar _((VALUE,VALUE));
-void rb_mark_generic_ivar _((VALUE));
-void rb_mark_generic_ivar_tbl _((void));
-void rb_free_generic_ivar _((VALUE));
-VALUE rb_ivar_get _((VALUE, ID));
-VALUE rb_ivar_set _((VALUE, ID, VALUE));
-VALUE rb_ivar_defined _((VALUE, ID));
-VALUE rb_iv_set _((VALUE, const char *, VALUE));
-VALUE rb_iv_get _((VALUE, const char *));
-VALUE rb_obj_instance_variables _((VALUE));
-VALUE rb_obj_remove_instance_variable _((VALUE, VALUE));
-void *rb_mod_const_at _((VALUE, void*));
-void *rb_mod_const_of _((VALUE, void*));
-VALUE rb_const_list _((void*));
-VALUE rb_mod_constants _((VALUE));
-VALUE rb_mod_remove_const _((VALUE, VALUE));
-int rb_const_defined_at _((VALUE, ID));
-int rb_autoload_defined _((ID));
-int rb_const_defined _((VALUE, ID));
-VALUE rb_const_get _((VALUE, ID));
-VALUE rb_const_get_at _((VALUE, ID));
-void rb_const_set _((VALUE, ID, VALUE));
-void rb_const_assign _((VALUE, ID, VALUE));
-VALUE rb_mod_constants _((VALUE));
-void rb_autoload_load _((ID));
-VALUE rb_cvar_defined _((VALUE, ID));
-void rb_cvar_set _((VALUE, ID, VALUE, int));
-VALUE rb_cvar_get _((VALUE, ID));
-void rb_cv_set _((VALUE, const char *, VALUE));
-VALUE rb_cv_get _((VALUE, const char *));
-void rb_define_class_variable _((VALUE, const char *, VALUE));
-VALUE rb_mod_class_variables _((VALUE));
-VALUE rb_mod_remove_cvar _((VALUE, VALUE));
-/* version.c */
-void ruby_show_version _((void));
-void ruby_show_copyright _((void));
diff --git a/io.c b/io.c
deleted file mode 100644
index 9d3881110d..0000000000
--- a/io.c
+++ /dev/null
@@ -1,3824 +0,0 @@
-/**********************************************************************
-
- io.c -
-
- $Author$
- $Date$
- created at: Fri Oct 15 18:08:59 JST 1993
-
- Copyright (C) 1993-2002 Yukihiro Matsumoto
- Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
- Copyright (C) 2000 Information-technology Promotion Agency, Japan
-
-**********************************************************************/
-
-#include "ruby.h"
-#include "rubyio.h"
-#include "rubysig.h"
-#include "env.h"
-#include <ctype.h>
-#include <errno.h>
-
-#if defined(MSDOS) || defined(__BOW__) || defined(__CYGWIN__) || defined(NT) || defined(__human68k__) || defined(__EMX__) || defined(__BEOS__)
-# define NO_SAFE_RENAME
-#endif
-
-#if defined(MSDOS) || defined(__CYGWIN__) || defined(NT)
-# define NO_LONG_FNAME
-#endif
-
-#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(sun) || defined(_nec_ews)
-# define USE_SETVBUF
-#endif
-
-#ifdef __QNXNTO__
-#include "unix.h"
-#endif
-
-#include <sys/types.h>
-#if !defined(DJGPP) && !defined(NT) && !defined(__human68k__)
-#include <sys/ioctl.h>
-#endif
-#if defined(HAVE_FCNTL_H) || defined(NT)
-#include <fcntl.h>
-#elif defined(HAVE_SYS_FCNTL_H)
-#include <sys/fcntl.h>
-#endif
-
-#if !HAVE_OFF_T && !defined(off_t)
-# define off_t long
-#endif
-#if !HAVE_FSEEKO && !defined(fseeko)
-# define fseeko fseek
-#endif
-#if !HAVE_FTELLO && !defined(ftello)
-# define ftello ftell
-#endif
-
-#ifdef HAVE_SYS_TIME_H
-# include <sys/time.h>
-#else
-#ifndef NT
-struct timeval {
- long tv_sec; /* seconds */
- long tv_usec; /* and microseconds */
-};
-#endif
-#endif
-
-#include <sys/stat.h>
-
-/* EMX has sys/parm.h, but.. */
-#if defined(HAVE_SYS_PARAM_H) && !defined(__EMX__)
-# include <sys/param.h>
-#else
-# define NOFILE 64
-#endif
-
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-
-extern void Init_File _((void));
-
-#ifdef __BEOS__
-# ifndef NOFILE
-# define NOFILE (OPEN_MAX)
-# endif
-#include <net/socket.h>
-#endif
-
-#include "util.h"
-
-VALUE rb_cIO;
-VALUE rb_eEOFError;
-VALUE rb_eIOError;
-
-VALUE rb_stdin, rb_stdout, rb_stderr, rb_defout;
-static VALUE orig_stdin, orig_stdout, orig_stderr;
-static int saved_fd[3] = {0, 1, 2};
-
-VALUE rb_output_fs;
-VALUE rb_rs;
-VALUE rb_output_rs;
-VALUE rb_default_rs;
-
-static VALUE argf;
-
-static ID id_write;
-
-extern char *ruby_inplace_mode;
-
-struct timeval rb_time_interval _((VALUE));
-
-static VALUE filename, current_file;
-static int gets_lineno;
-static int init_p = 0, next_p = 0, first_p = 1;
-static VALUE lineno;
-
-#ifdef _STDIO_USES_IOSTREAM /* GNU libc */
-# ifdef _IO_fpos_t
-# define READ_DATA_PENDING(fp) ((fp)->_IO_read_ptr != (fp)->_IO_read_end)
-# define READ_DATA_PENDING_COUNT(fp) ((fp)->_IO_read_end - (fp)->_IO_read_ptr)
-# else
-# define READ_DATA_PENDING(fp) ((fp)->_gptr < (fp)->_egptr)
-# define READ_DATA_PENDING_COUNT(fp) ((fp)->_egptr - (fp)->_gptr)
-# endif
-#elif defined(FILE_COUNT)
-# define READ_DATA_PENDING(fp) ((fp)->FILE_COUNT > 0)
-# define READ_DATA_PENDING_COUNT(fp) ((fp)->FILE_COUNT)
-#elif defined(__BEOS__)
-# define READ_DATA_PENDING(fp) (fp->_state._eof == 0)
-#elif defined(__UCLIBC__)
-# define READ_DATA_PENDING(fp) ((fp)->bufpos < (fp)->bufend)
-#else
-/* requires systems own version of the ReadDataPending() */
-extern int ReadDataPending();
-# define READ_DATA_PENDING(fp) ReadDataPending(fp)
-#endif
-
-#define READ_CHECK(fp) do {\
- if (!READ_DATA_PENDING(fp)) {\
- rb_thread_wait_fd(fileno(fp));\
- rb_io_check_closed(fptr);\
- }\
-} while(0)
-
-void
-rb_eof_error()
-{
- rb_raise(rb_eEOFError, "End of file reached");
-}
-
-VALUE
-rb_io_taint_check(io)
- VALUE io;
-{
- if (!OBJ_TAINTED(io) && rb_safe_level() >= 4)
- rb_raise(rb_eSecurityError, "Insecure: operation on untainted IO");
- return io;
-}
-
-void
-rb_io_check_closed(fptr)
- OpenFile *fptr;
-{
- if (!fptr) {
- rb_raise(rb_eIOError, "uninitialized stream");
- }
- if (!fptr->f && !fptr->f2) {
- rb_raise(rb_eIOError, "closed stream");
- }
-}
-
-void
-rb_io_check_readable(fptr)
- OpenFile *fptr;
-{
- if (!(fptr->mode & FMODE_READABLE)) {
- rb_raise(rb_eIOError, "not opened for reading");
- }
-}
-
-void
-rb_io_check_writable(fptr)
- OpenFile *fptr;
-{
- if (!(fptr->mode & FMODE_WRITABLE)) {
- rb_raise(rb_eIOError, "not opened for writing");
- }
-}
-
-int
-rb_read_pending(fp)
- FILE *fp;
-{
- return READ_DATA_PENDING(fp);
-}
-
-void
-rb_read_check(fp)
- FILE *fp;
-{
- if (!READ_DATA_PENDING(fp)) {
- rb_thread_wait_fd(fileno(fp));
- }
-}
-
-static int
-ruby_dup(orig)
- int orig;
-{
- int fd;
-
- fd = dup(orig);
- if (fd < 0) {
- if (errno == EMFILE || errno == ENFILE) {
- rb_gc();
- fd = dup(orig);
- }
- if (fd < 0) {
- rb_sys_fail(0);
- }
- }
- return fd;
-}
-
-static void
-io_fflush(f, path)
- FILE *f;
- const char *path;
-{
- int n;
-
- rb_thread_fd_writable(fileno(f));
- TRAP_BEG;
- n = fflush(f);
- TRAP_END;
- if (n == EOF) rb_sys_fail(path);
-}
-
-/* writing functions */
-static VALUE
-io_write(io, str)
- VALUE io, str;
-{
- OpenFile *fptr;
- FILE *f;
- int n;
-
- rb_secure(4);
- if (TYPE(str) != T_STRING)
- str = rb_obj_as_string(str);
- if (RSTRING(str)->len == 0) return INT2FIX(0);
-
- if (TYPE(io) != T_FILE) {
- /* port is not IO, call write method for it. */
- return rb_funcall(io, id_write, 1, str);
- }
-
- GetOpenFile(io, fptr);
- rb_io_check_writable(fptr);
- f = GetWriteFile(fptr);
-
-#ifdef __human68k__
- {
- register char *ptr = RSTRING(str)->ptr;
- n = (int)RSTRING(str)->len;
- while (--n >= 0)
- if (fputc(*ptr++, f) == EOF)
- break;
- n = ptr - RSTRING(str)->ptr;
- }
- if (n == 0 && ferror(f))
- rb_sys_fail(fptr->path);
-#else
- n = fwrite(RSTRING(str)->ptr, 1, RSTRING(str)->len, f);
- if (n == 0 && ferror(f)) {
- rb_sys_fail(fptr->path);
- }
-#endif
- if (fptr->mode & FMODE_SYNC) {
- io_fflush(f, fptr->path);
- fptr->mode &= ~FMODE_WBUF;
- }
- else {
- fptr->mode |= FMODE_WBUF;
- }
-
- return INT2FIX(n);
-}
-
-VALUE
-rb_io_write(io, str)
- VALUE io, str;
-{
- return rb_funcall(io, id_write, 1, str);
-}
-
-VALUE
-rb_io_addstr(io, str)
- VALUE io, str;
-{
- rb_io_write(io, str);
- return io;
-}
-
-static VALUE
-rb_io_flush(io)
- VALUE io;
-{
- OpenFile *fptr;
- FILE *f;
-
- GetOpenFile(io, fptr);
- rb_io_check_writable(fptr);
- f = GetWriteFile(fptr);
-
- io_fflush(f, fptr->path);
- fptr->mode &= ~FMODE_WBUF;
-
- return io;
-}
-
-static VALUE
-rb_io_tell(io)
- VALUE io;
-{
- OpenFile *fptr;
- off_t pos;
-
- GetOpenFile(io, fptr);
- pos = ftello(fptr->f);
- if (ferror(fptr->f)) rb_sys_fail(fptr->path);
-
-#if SIZEOF_OFF_T > SIZEOF_LONG
-# if !HAVE_LONG_LONG
-# error off_t is bigger than long, but you have no long long...
-# endif
- return rb_ll2inum(pos);
-#else
- return rb_int2inum(pos);
-#endif
-}
-
-#ifndef SEEK_CUR
-# define SEEK_SET 0
-# define SEEK_CUR 1
-# define SEEK_END 2
-#endif
-
-static VALUE
-rb_io_seek(io, offset, whence)
- VALUE io, offset;
- int whence;
-{
- OpenFile *fptr;
- long pos;
-
- GetOpenFile(io, fptr);
- pos = fseeko(fptr->f, NUM2OFFT(offset), whence);
- if (pos != 0) rb_sys_fail(fptr->path);
- clearerr(fptr->f);
-
- return INT2FIX(0);
-}
-
-static VALUE
-rb_io_seek_m(argc, argv, io)
- int argc;
- VALUE *argv;
- VALUE io;
-{
- VALUE offset, ptrname;
- int whence;
-
- rb_scan_args(argc, argv, "11", &offset, &ptrname);
- if (argc == 1) whence = SEEK_SET;
- else whence = NUM2INT(ptrname);
-
- return rb_io_seek(io, offset, whence);
-}
-
-static VALUE
-rb_io_set_pos(io, offset)
- VALUE io, offset;
-{
- OpenFile *fptr;
- long pos;
-
- GetOpenFile(io, fptr);
- pos = fseeko(fptr->f, NUM2OFFT(offset), SEEK_SET);
- if (pos != 0) rb_sys_fail(fptr->path);
- clearerr(fptr->f);
-
- return INT2NUM(pos);
-}
-
-static VALUE
-rb_io_rewind(io)
- VALUE io;
-{
- OpenFile *fptr;
-
- GetOpenFile(io, fptr);
- if (fseeko(fptr->f, 0L, 0) != 0) rb_sys_fail(fptr->path);
- clearerr(fptr->f);
- if (io == current_file) {
- gets_lineno -= fptr->lineno;
- }
- fptr->lineno = 0;
-
- return INT2FIX(0);
-}
-
-VALUE
-rb_io_eof(io)
- VALUE io;
-{
- OpenFile *fptr;
- int ch;
-
- GetOpenFile(io, fptr);
- rb_io_check_readable(fptr);
-
- if (feof(fptr->f)) return Qtrue;
- if (READ_DATA_PENDING(fptr->f)) return Qfalse;
- READ_CHECK(fptr->f);
- TRAP_BEG;
- ch = getc(fptr->f);
- TRAP_END;
-
- if (ch != EOF) {
- ungetc(ch, fptr->f);
- return Qfalse;
- }
- return Qtrue;
-}
-
-static VALUE
-rb_io_sync(io)
- VALUE io;
-{
- OpenFile *fptr;
-
- GetOpenFile(io, fptr);
- return (fptr->mode & FMODE_SYNC) ? Qtrue : Qfalse;
-}
-
-static VALUE
-rb_io_set_sync(io, mode)
- VALUE io, mode;
-{
- OpenFile *fptr;
-
- GetOpenFile(io, fptr);
- if (RTEST(mode)) {
- fptr->mode |= FMODE_SYNC;
- }
- else {
- fptr->mode &= ~FMODE_SYNC;
- }
- return mode;
-}
-
-static VALUE
-rb_io_fsync(io)
- VALUE io;
-{
-#ifdef HAVE_FSYNC
- OpenFile *fptr;
- FILE *f;
-
- GetOpenFile(io, fptr);
- rb_io_check_writable(fptr);
- f = GetWriteFile(fptr);
-
- io_fflush(f, fptr->path);
- fptr->mode &= ~FMODE_WBUF;
- if (fsync(fileno(f)) < 0)
- rb_sys_fail(fptr->path);
- return INT2FIX(0);
-#else
- rb_notimplement();
- return Qnil; /* not reached */
-#endif
-}
-
-static VALUE
-rb_io_fileno(io)
- VALUE io;
-{
- OpenFile *fptr;
- int fd;
-
- GetOpenFile(io, fptr);
- fd = fileno(fptr->f);
- return INT2FIX(fd);
-}
-
-static VALUE
-rb_io_pid(io)
- VALUE io;
-{
- OpenFile *fptr;
-
- GetOpenFile(io, fptr);
- if (!fptr->pid)
- return Qnil;
- return INT2FIX(fptr->pid);
-}
-
-static VALUE
-rb_io_inspect(obj)
- VALUE obj;
-{
- OpenFile *fptr;
- char *buf, *cname;
-
- GetOpenFile(obj, fptr);
- if (!fptr->path) return rb_any_to_s(obj);
- cname = rb_class2name(CLASS_OF(obj));
- buf = ALLOCA_N(char, strlen(cname) + strlen(fptr->path) + 5);
- sprintf(buf, "#<%s:%s>", cname, fptr->path);
- return rb_str_new2(buf);
-}
-
-static VALUE
-rb_io_to_io(io)
- VALUE io;
-{
- return io;
-}
-
-/* reading functions */
-
-static long
-io_fread(ptr, len, f)
- char *ptr;
- long len;
- FILE *f;
-{
- long n = len;
- int c;
-
- while (n > 0) {
-#ifdef READ_DATA_PENDING_COUNT
- int i = READ_DATA_PENDING_COUNT(f);
- if (i <= 0) {
- rb_thread_wait_fd(fileno(f));
- i = READ_DATA_PENDING_COUNT(f);
- }
- if (i > 0) {
- if (i > n) i = n;
- TRAP_BEG;
- c = fread(ptr, 1, i, f);
- TRAP_END;
- if (c < 0) goto eof;
- ptr += c;
- n -= c;
- if (c < i) goto eof;
- continue;
- }
-#else
- if (!READ_DATA_PENDING(f)) {
- rb_thread_wait_fd(fileno(f));
- }
-#endif
- TRAP_BEG;
- c = getc(f);
- TRAP_END;
- if (c == EOF) {
- eof:
- if (ferror(f)) {
- switch (errno) {
- case EINTR:
- continue;
- case EAGAIN:
-#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
- case EWOULDBLOCK:
-#endif
- return len - n;
- }
- return 0;
- }
- *ptr = '\0';
- break;
- }
- *ptr++ = c;
- n--;
- }
-
- return len - n;
-}
-
-#ifndef S_ISREG
-# define S_ISREG(m) ((m & S_IFMT) == S_IFREG)
-#endif
-
-#define SMALLBUF 100
-
-static VALUE
-read_all(port)
- VALUE port;
-{
- OpenFile *fptr;
- VALUE str = Qnil;
- struct stat st;
- off_t siz = BUFSIZ;
- long bytes = 0;
- int n;
-
- GetOpenFile(port, fptr);
- rb_io_check_readable(fptr);
-
- if (feof(fptr->f)) return Qnil;
- if (fstat(fileno(fptr->f), &st) == 0 && S_ISREG(st.st_mode)
-#ifdef __BEOS__
- && (st.st_dev > 3)
-#endif
- )
- {
- if (st.st_size == 0) {
- getc(fptr->f); /* force EOF */
- return rb_str_new(0, 0);
- }
- else {
- off_t pos = ftello(fptr->f);
- if (st.st_size > pos && pos >= 0) {
- siz = st.st_size - pos + 1;
- if (siz > LONG_MAX) {
- rb_raise(rb_eIOError, "file too big for single read");
- }
- }
- }
- }
- str = rb_tainted_str_new(0, (long)siz);
- READ_CHECK(fptr->f);
- for (;;) {
- n = io_fread(RSTRING(str)->ptr+bytes, (long)siz-bytes, fptr->f);
- if (n == 0 && bytes == 0) {
- if (feof(fptr->f)) return Qnil;
- rb_sys_fail(fptr->path);
- }
- bytes += n;
- if (bytes < siz) break;
- siz += BUFSIZ;
- rb_str_resize(str, siz);
- }
- if (bytes == 0) return rb_str_new(0,0);
- if (bytes != siz) rb_str_resize(str, bytes);
-
- return str;
-}
-
-static VALUE
-io_read(argc, argv, io)
- int argc;
- VALUE *argv;
- VALUE io;
-{
- OpenFile *fptr;
- int n, len;
- VALUE length, str;
-
- rb_scan_args(argc, argv, "01", &length);
- if (NIL_P(length)) {
- return read_all(io);
- }
-
- len = NUM2INT(length);
- if (len < 0) {
- rb_raise(rb_eArgError, "negative length %d given", len);
- }
- GetOpenFile(io, fptr);
- rb_io_check_readable(fptr);
-
- if (feof(fptr->f)) return Qnil;
- str = rb_str_new(0, len);
- if (len == 0) return str;
-
- READ_CHECK(fptr->f);
- n = io_fread(RSTRING(str)->ptr, len, fptr->f);
- if (n == 0) {
- if (feof(fptr->f)) return Qnil;
- rb_sys_fail(fptr->path);
- }
- RSTRING(str)->len = n;
- RSTRING(str)->ptr[n] = '\0';
- OBJ_TAINT(str);
-
- return str;
-}
-
-static VALUE
-rb_io_getline_fast(fptr)
- OpenFile *fptr;
-{
- FILE *f = fptr->f;
- VALUE str = Qnil;
- int c;
- char buf[8192];
- char *bp, *bpe = buf + sizeof buf - 3;
- int cnt;
- int append = 0;
-
- again:
- bp = buf;
- for (;;) {
- READ_CHECK(f);
- TRAP_BEG;
- c = getc(f);
- TRAP_END;
- if (c == EOF) {
- if (ferror(f)) {
- if (errno == EINTR) continue;
- rb_sys_fail(fptr->path);
- }
- break;
- }
- if ((*bp++ = c) == '\n') break;
- if (bp == bpe) break;
- }
- cnt = bp - buf;
-
- if (c == EOF && !append && cnt == 0) {
- str = Qnil;
- goto return_gets;
- }
-
- if (append)
- rb_str_cat(str, buf, cnt);
- else
- str = rb_str_new(buf, cnt);
-
- if (c != EOF && RSTRING(str)->ptr[RSTRING(str)->len-1] != '\n') {
- append = 1;
- goto again;
- }
-
- return_gets:
- if (!NIL_P(str)) {
- fptr->lineno++;
- lineno = INT2FIX(fptr->lineno);
- OBJ_TAINT(str);
- }
-
- return str;
-}
-
-static VALUE
-rb_io_getline(rs, fptr)
- VALUE rs;
- OpenFile *fptr;
-{
- FILE *f;
- VALUE str = Qnil;
- int c, newline;
- char *rsptr;
- int rslen, rspara = 0;
-
- if (NIL_P(rs)) {
- rsptr = 0;
- rslen = 0;
- }
- else if (rs == rb_default_rs) {
- return rb_io_getline_fast(fptr);
- }
- else {
- StringValue(rs);
- rslen = RSTRING(rs)->len;
- if (rslen == 0) {
- rsptr = "\n\n";
- rslen = 2;
- rspara = 1;
- }
- else if (rslen == 1 && RSTRING(rs)->ptr[0] == '\n') {
- return rb_io_getline_fast(fptr);
- }
- else {
- rsptr = RSTRING(rs)->ptr;
- }
- }
-
- f = fptr->f;
- if (rspara) {
- do {
- READ_CHECK(f);
- TRAP_BEG;
- c = getc(f);
- TRAP_END;
- if (c != '\n') {
- ungetc(c,f);
- break;
- }
- } while (c != EOF);
- }
-
- newline = rslen ? rsptr[rslen - 1] : 0777;
- {
- char buf[8192];
- char *bp, *bpe = buf + sizeof buf - 3;
- int cnt;
- int append = 0;
-
- again:
- bp = buf;
-
- if (rslen) {
- for (;;) {
- READ_CHECK(f);
- TRAP_BEG;
- c = getc(f);
- TRAP_END;
- if (c == EOF) {
- if (ferror(f)) {
- if (errno == EINTR) continue;
- rb_sys_fail(fptr->path);
- }
- break;
- }
- if ((*bp++ = c) == newline) break;
- if (bp == bpe) break;
- }
- cnt = bp - buf;
- }
- else {
- READ_CHECK(f);
- cnt = io_fread(buf, sizeof(buf), f);
- if (cnt == 0) {
- if (ferror(f)) rb_sys_fail(fptr->path);
- c = EOF;
- }
- else {
- c = 0;
- }
- }
-
- if (c == EOF && !append && cnt == 0) {
- str = Qnil;
- goto return_gets;
- }
-
- if (append)
- rb_str_cat(str, buf, cnt);
- else
- str = rb_str_new(buf, cnt);
-
- if (c != EOF &&
- (!rslen ||
- RSTRING(str)->len < rslen ||
- memcmp(RSTRING(str)->ptr+RSTRING(str)->len-rslen,rsptr,rslen))) {
- append = 1;
- goto again;
- }
- }
-
- return_gets:
- if (rspara) {
- while (c != EOF) {
- READ_CHECK(f);
- TRAP_BEG;
- c = getc(f);
- TRAP_END;
- if (c != '\n') {
- ungetc(c, f);
- break;
- }
- }
- }
-
- if (!NIL_P(str)) {
- fptr->lineno++;
- lineno = INT2FIX(fptr->lineno);
- OBJ_TAINT(str);
- }
-
- return str;
-}
-
-VALUE
-rb_io_gets(io)
- VALUE io;
-{
- OpenFile *fptr;
-
- GetOpenFile(io, fptr);
- rb_io_check_readable(fptr);
- return rb_io_getline_fast(fptr);
-}
-
-static VALUE
-rb_io_gets_m(argc, argv, io)
- int argc;
- VALUE *argv;
- VALUE io;
-{
- VALUE rs, str;
- OpenFile *fptr;
-
- if (argc == 0) {
- rs = rb_rs;
- }
- else {
- rb_scan_args(argc, argv, "1", &rs);
- }
- GetOpenFile(io, fptr);
- rb_io_check_readable(fptr);
- str = rb_io_getline(rs, fptr);
-
- if (!NIL_P(str)) {
- rb_lastline_set(str);
- }
- return str;
-}
-
-static VALUE
-rb_io_lineno(io)
- VALUE io;
-{
- OpenFile *fptr;
-
- GetOpenFile(io, fptr);
- rb_io_check_readable(fptr);
- return INT2NUM(fptr->lineno);
-}
-
-static VALUE
-rb_io_set_lineno(io, lineno)
- VALUE io, lineno;
-{
- OpenFile *fptr;
-
- GetOpenFile(io, fptr);
- rb_io_check_readable(fptr);
- fptr->lineno = NUM2INT(lineno);
- return lineno;
-}
-
-static void
-lineno_setter(val, id, var)
- VALUE val;
- ID id;
- VALUE *var;
-{
- gets_lineno = NUM2INT(val);
- *var = INT2FIX(gets_lineno);
-}
-
-static VALUE
-argf_set_lineno(argf, val)
- VALUE argf, val;
-{
- gets_lineno = NUM2INT(val);
- lineno = INT2FIX(gets_lineno);
- return Qnil;
-}
-
-static VALUE
-argf_lineno()
-{
- return lineno;
-}
-
-static VALUE
-rb_io_readline(argc, argv, io)
- int argc;
- VALUE *argv;
- VALUE io;
-{
- VALUE line = rb_io_gets_m(argc, argv, io);
-
- if (NIL_P(line)) {
- rb_eof_error();
- }
- return line;
-}
-
-static VALUE
-rb_io_readlines(argc, argv, io)
- int argc;
- VALUE *argv;
- VALUE io;
-{
- VALUE line, ary;
- VALUE rs, str;
- OpenFile *fptr;
-
- if (argc == 0) {
- rs = rb_rs;
- }
- else {
- rb_scan_args(argc, argv, "1", &rs);
- }
- GetOpenFile(io, fptr);
- rb_io_check_readable(fptr);
- ary = rb_ary_new();
- while (!NIL_P(line = rb_io_getline(rs, fptr))) {
- rb_ary_push(ary, line);
- }
- return ary;
-}
-
-static VALUE
-rb_io_each_line(argc, argv, io)
- int argc;
- VALUE *argv;
- VALUE io;
-{
- VALUE str;
- OpenFile *fptr;
- VALUE rs;
-
- if (argc == 0) {
- rs = rb_rs;
- }
- else {
- rb_scan_args(argc, argv, "1", &rs);
- }
- GetOpenFile(io, fptr);
- rb_io_check_readable(fptr);
- while (!NIL_P(str = rb_io_getline(rs, fptr))) {
- rb_yield(str);
- }
- return io;
-}
-
-static VALUE
-rb_io_each_byte(io)
- VALUE io;
-{
- OpenFile *fptr;
- FILE *f;
- int c;
-
- GetOpenFile(io, fptr);
- rb_io_check_readable(fptr);
- f = fptr->f;
-
- for (;;) {
- READ_CHECK(f);
- TRAP_BEG;
- c = getc(f);
- TRAP_END;
- if (c == EOF) {
- if (ferror(f)) {
- if (errno == EINTR) continue;
- rb_sys_fail(fptr->path);
- }
- break;
- }
- rb_yield(INT2FIX(c & 0xff));
- }
- if (ferror(f)) rb_sys_fail(fptr->path);
- return io;
-}
-
-VALUE
-rb_io_getc(io)
- VALUE io;
-{
- OpenFile *fptr;
- FILE *f;
- int c;
-
- GetOpenFile(io, fptr);
- rb_io_check_readable(fptr);
- f = fptr->f;
-
- retry:
- READ_CHECK(f);
- TRAP_BEG;
- c = getc(f);
- TRAP_END;
-
- if (c == EOF) {
- if (ferror(f)) {
- if (errno == EINTR) goto retry;
- rb_sys_fail(fptr->path);
- }
- return Qnil;
- }
- return INT2FIX(c & 0xff);
-}
-
-int
-rb_getc(f)
- FILE *f;
-{
- int c;
-
- if (!READ_DATA_PENDING(f)) {
- rb_thread_wait_fd(fileno(f));
- }
- TRAP_BEG;
- c = getc(f);
- TRAP_END;
-
- return c;
-}
-
-static VALUE
-rb_io_readchar(io)
- VALUE io;
-{
- VALUE c = rb_io_getc(io);
-
- if (NIL_P(c)) {
- rb_eof_error();
- }
- return c;
-}
-
-VALUE
-rb_io_ungetc(io, c)
- VALUE io, c;
-{
- OpenFile *fptr;
- int cc = NUM2INT(c);
-
- GetOpenFile(io, fptr);
- rb_io_check_readable(fptr);
-
- if (ungetc(cc, fptr->f) == EOF && cc != EOF)
- rb_sys_fail(fptr->path);
- return Qnil;
-}
-
-static VALUE
-rb_io_isatty(io)
- VALUE io;
-{
- OpenFile *fptr;
-
- GetOpenFile(io, fptr);
- if (isatty(fileno(fptr->f)) == 0)
- return Qfalse;
- return Qtrue;
-}
-
-static void
-fptr_finalize(fptr, fin)
- OpenFile *fptr;
-{
- int n1 = 0, n2 = 0, e = 0, f1, f2 = -1;
-
- if (fptr->f2) {
- f2 = fileno(fptr->f2);
- n2 = fclose(fptr->f2);
- fptr->f2 = 0;
- if (n2 < 0) e = errno;
- }
- if (fptr->f) {
- f1 = fileno(fptr->f);
- n1 = fclose(fptr->f);
- fptr->f = 0;
- if (n1 < 0 && errno == EBADF) {
- if (f1 == f2 || !(fptr->mode & FMODE_WBUF)) {
- n1 = 0;
- }
- }
- }
- if (!fin && (n1 < 0 || n2 < 0)) {
- if (n1 == 0) errno = e;
- rb_sys_fail(fptr->path);
- }
-}
-
-static void
-rb_io_fptr_cleanup(fptr, fin)
- OpenFile *fptr;
- int fin;
-{
- if (fptr->finalize) {
- (*fptr->finalize)(fptr);
- }
- else {
- fptr_finalize(fptr, fin);
- }
-
- if (fptr->path) {
- free(fptr->path);
- fptr->path = 0;
- }
-}
-
-void
-rb_io_fptr_finalize(fptr)
- OpenFile *fptr;
-{
- if (!fptr) return;
- if (!fptr->f && !fptr->f2) return;
- if (fileno(fptr->f) < 3) return;
-
- rb_io_fptr_cleanup(fptr, Qtrue);
-}
-
-VALUE
-rb_io_close(io)
- VALUE io;
-{
- OpenFile *fptr;
- int fd;
-
- fptr = RFILE(io)->fptr;
- if (!fptr) return Qnil;
- if (!fptr->f && !fptr->f2) return Qnil;
-
- fd = fileno(fptr->f);
- rb_io_fptr_cleanup(fptr, Qfalse);
- rb_thread_fd_close(fd);
-
- if (fptr->pid) {
- rb_syswait(fptr->pid);
- fptr->pid = 0;
- }
-
- return Qnil;
-}
-
-static VALUE
-rb_io_close_m(io)
- VALUE io;
-{
- if (rb_safe_level() >= 4 && !OBJ_TAINTED(io)) {
- rb_raise(rb_eSecurityError, "Insecure: can't close");
- }
- rb_io_check_closed(RFILE(io)->fptr);
- rb_io_close(io);
- return Qnil;
-}
-
-static VALUE
-rb_io_closed(io)
- VALUE io;
-{
- OpenFile *fptr;
-
- fptr = RFILE(io)->fptr;
- return (fptr->f || fptr->f2)?Qfalse:Qtrue;
-}
-
-static VALUE
-rb_io_close_read(io)
- VALUE io;
-{
- OpenFile *fptr;
- int n;
-
- if (rb_safe_level() >= 4 && !OBJ_TAINTED(io)) {
- rb_raise(rb_eSecurityError, "Insecure: can't close");
- }
- GetOpenFile(io, fptr);
- if (fptr->f2 == 0 && (fptr->mode & FMODE_WRITABLE)) {
- rb_raise(rb_eIOError, "closing non-duplex IO for reading");
- }
- if (fptr->f2 == 0) {
- return rb_io_close(io);
- }
- n = fclose(fptr->f);
- fptr->mode &= ~FMODE_READABLE;
- fptr->f = fptr->f2;
- fptr->f2 = 0;
- if (n != 0) rb_sys_fail(fptr->path);
-
- return Qnil;
-}
-
-static VALUE
-rb_io_close_write(io)
- VALUE io;
-{
- OpenFile *fptr;
- int n;
-
- if (rb_safe_level() >= 4 && !OBJ_TAINTED(io)) {
- rb_raise(rb_eSecurityError, "Insecure: can't close");
- }
- GetOpenFile(io, fptr);
- if (fptr->f2 == 0 && (fptr->mode & FMODE_READABLE)) {
- rb_raise(rb_eIOError, "closing non-duplex IO for writing");
- }
- if (fptr->f2 == 0) {
- return rb_io_close(io);
- }
- n = fclose(fptr->f2);
- fptr->f2 = 0;
- fptr->mode &= ~FMODE_WRITABLE;
- if (n != 0) rb_sys_fail(fptr->path);
-
- return Qnil;
-}
-
-static VALUE
-rb_io_syswrite(io, str)
- VALUE io, str;
-{
- OpenFile *fptr;
- FILE *f;
- int n;
-
- rb_secure(4);
- if (TYPE(str) != T_STRING)
- str = rb_obj_as_string(str);
-
- GetOpenFile(io, fptr);
- rb_io_check_writable(fptr);
- f = GetWriteFile(fptr);
-
- if (fptr->mode & FMODE_WBUF) {
- rb_warn("syswrite for buffered IO");
- }
- if (!rb_thread_fd_writable(fileno(f))) {
- rb_io_check_closed(fptr);
- }
- n = write(fileno(f), RSTRING(str)->ptr, RSTRING(str)->len);
-
- if (n == -1) rb_sys_fail(fptr->path);
-
- return INT2FIX(n);
-}
-
-static VALUE
-rb_io_sysread(io, len)
- VALUE io, len;
-{
- OpenFile *fptr;
- int n, ilen;
- VALUE str;
-
- ilen = NUM2INT(len);
- GetOpenFile(io, fptr);
- rb_io_check_readable(fptr);
-
- if (READ_DATA_PENDING(fptr->f)) {
- rb_raise(rb_eIOError, "sysread for buffered IO");
- }
- str = rb_str_new(0, ilen);
-
- n = fileno(fptr->f);
- rb_thread_wait_fd(fileno(fptr->f));
- TRAP_BEG;
- n = read(fileno(fptr->f), RSTRING(str)->ptr, RSTRING(str)->len);
- TRAP_END;
-
- if (n == -1) rb_sys_fail(fptr->path);
- if (n == 0 && ilen > 0) {
- rb_eof_error();
- }
-
- RSTRING(str)->len = n;
- RSTRING(str)->ptr[n] = '\0';
- OBJ_TAINT(str);
-
- return str;
-}
-
-VALUE
-rb_io_binmode(io)
- VALUE io;
-{
-#if defined(NT) || defined(DJGPP) || defined(__CYGWIN__) || defined(__human68k__) || defined(__EMX__)
- OpenFile *fptr;
-
- GetOpenFile(io, fptr);
-#ifdef __human68k__
- if (fptr->f)
- fmode(fptr->f, _IOBIN);
- if (fptr->f2)
- fmode(fptr->f2, _IOBIN);
-#else
- if (fptr->f && setmode(fileno(fptr->f), O_BINARY) == -1)
- rb_sys_fail(fptr->path);
- if (fptr->f2 && setmode(fileno(fptr->f2), O_BINARY) == -1)
- rb_sys_fail(fptr->path);
-#endif
-
- fptr->mode |= FMODE_BINMODE;
-#endif
- return io;
-}
-
-int
-rb_io_mode_flags(mode)
- const char *mode;
-{
- int flags = 0;
- const char *m = mode;
-
- switch (*m++) {
- case 'r':
- flags |= FMODE_READABLE;
- break;
- case 'w':
- flags |= FMODE_WRITABLE;
- break;
- case 'a':
- flags |= FMODE_WRITABLE;
- break;
- default:
- error:
- rb_raise(rb_eArgError, "illegal access mode %s", mode);
- }
-
- if (*m == 'b') {
- flags |= FMODE_BINMODE;
- m++;
- }
-
- if (*m == '+') {
- flags |= FMODE_READWRITE;
- if (m[1] != 0) goto error;
- }
- else if (*m != 0) goto error;
-
- return flags;
-}
-
-static int
-rb_io_binmode_flags(mode)
- int mode;
-{
- int flags;
-
- switch (mode & (O_RDONLY|O_WRONLY|O_RDWR)) {
- case O_RDONLY:
- flags = FMODE_READABLE;
- break;
- case O_WRONLY:
- flags = FMODE_WRITABLE;
- break;
- case O_RDWR:
- flags = FMODE_WRITABLE|FMODE_READABLE;
- break;
- }
-
-#ifdef O_BINARY
- if (mode & O_BINARY) {
- flags |= FMODE_BINMODE;
- }
-#endif
-
- return flags;
-}
-
-static int
-rb_io_mode_binmode(mode)
- const char *mode;
-{
- int flags = 0;
- const char *m = mode;
-
- switch (*m++) {
- case 'r':
- flags |= O_RDONLY;
- break;
- case 'w':
- flags |= O_WRONLY | O_CREAT | O_TRUNC;
- break;
- case 'a':
- flags |= O_WRONLY | O_CREAT | O_APPEND;
- break;
- default:
- error:
- rb_raise(rb_eArgError, "illegal access mode %s", mode);
- }
-
- if (*m == 'b') {
-#ifdef O_BINARY
- flags |= O_BINARY;
-#endif
- m++;
- }
-
- if (*m == '+') {
- flags |= O_RDWR;
- if (m[1] != 0) goto error;
- }
- else if (*m != 0) goto error;
-
- return flags;
-}
-
-static char*
-rb_io_binmode_mode(flags, mode)
- int flags;
- char *mode;
-{
- char *p = mode;
-
- switch (flags & (O_RDONLY|O_WRONLY|O_RDWR)) {
- case O_RDONLY:
- *p++ = 'r';
- break;
- case O_WRONLY:
- *p++ = 'w';
- break;
- case O_RDWR:
- *p++ = 'w';
- *p++ = '+';
- break;
- }
- *p++ = '\0';
-#ifdef O_BINARY
- if (flags & O_BINARY) {
- if (mode[1] == '+') {
- mode[1] = 'b'; mode[2] = '+'; mode[3] = '\0';
- }
- else {
- mode[1] = 'b'; mode[2] = '\0';
- }
- }
-#endif
- return mode;
-}
-
-static int
-rb_sysopen(fname, flags, mode)
- char *fname;
- int flags;
- unsigned int mode;
-{
- int fd;
-
- fd = open(fname, flags, mode);
- if (fd < 0) {
- if (errno == EMFILE || errno == ENFILE) {
- rb_gc();
- fd = open(fname, flags, mode);
- }
- if (fd < 0) {
- rb_sys_fail(fname);
- }
- }
- return fd;
-}
-
-FILE *
-rb_fopen(fname, mode)
- const char *fname;
- const char *mode;
-{
- FILE *file;
-
- file = fopen(fname, mode);
- if (!file) {
- if (errno == EMFILE || errno == ENFILE) {
- rb_gc();
- file = fopen(fname, mode);
- }
- if (!file) {
- rb_sys_fail(fname);
- }
- }
-#ifdef USE_SETVBUF
- if (setvbuf(file, NULL, _IOFBF, 0) != 0)
- rb_warn("setvbuf() can't be honered for %s", fname);
-#endif
-#ifdef __human68k__
- fmode(file, _IOTEXT);
-#endif
- return file;
-}
-
-FILE *
-rb_fdopen(fd, mode)
- int fd;
- const char *mode;
-{
- FILE *file;
-
- file = fdopen(fd, mode);
- if (!file) {
- if (errno == EMFILE || errno == ENFILE) {
- rb_gc();
- file = fdopen(fd, mode);
- }
- if (!file) {
- rb_sys_fail(0);
- }
- }
-
-#ifdef USE_SETVBUF
- if (setvbuf(file, NULL, _IOFBF, 0) != 0)
- rb_warn("setvbuf() can't be honered (fd=%d)", fd);
-#endif
- return file;
-}
-
-static VALUE
-rb_file_open_internal(io, fname, mode)
- VALUE io;
- const char *fname, *mode;
-{
- OpenFile *fptr;
-
- MakeOpenFile(io, fptr);
-
- fptr->mode = rb_io_mode_flags(mode);
- fptr->f = rb_fopen(fname, mode);
- fptr->path = strdup(fname);
-
- return io;
-}
-
-VALUE
-rb_file_open(fname, mode)
- const char *fname, *mode;
-{
- VALUE io = rb_obj_alloc(rb_cFile);
-
- return rb_file_open_internal(io, fname, mode);
-}
-
-static VALUE
-rb_file_sysopen_internal(io, fname, flags, mode)
- VALUE io;
- char *fname;
- int flags, mode;
-{
- OpenFile *fptr;
- int fd;
- char *m;
- char mbuf[4];
-
- MakeOpenFile(io, fptr);
-
- fd = rb_sysopen(fname, flags, mode);
- m = rb_io_binmode_mode(flags, mbuf);
- fptr->mode = rb_io_binmode_flags(flags);
- fptr->f = rb_fdopen(fd, m);
- fptr->path = strdup(fname);
-
- return io;
-}
-
-VALUE
-rb_file_sysopen(fname, flags, mode)
- const char *fname;
- int flags, mode;
-{
- VALUE io = rb_obj_alloc(rb_cFile);
-
- return rb_file_sysopen_internal(io, fname, flags, mode);
-}
-
-#if defined (NT) || defined(DJGPP) || defined(__CYGWIN__) || defined(__human68k__)
-static struct pipe_list {
- OpenFile *fptr;
- struct pipe_list *next;
-} *pipe_list;
-
-static void
-pipe_add_fptr(fptr)
- OpenFile *fptr;
-{
- struct pipe_list *list;
-
- list = ALLOC(struct pipe_list);
- list->fptr = fptr;
- list->next = pipe_list;
- pipe_list = list;
-}
-
-static void
-pipe_del_fptr(fptr)
- OpenFile *fptr;
-{
- struct pipe_list *list = pipe_list;
- struct pipe_list *tmp;
-
- if (list->fptr == fptr) {
- pipe_list = list->next;
- free(list);
- return;
- }
-
- while (list->next) {
- if (list->next->fptr == fptr) {
- tmp = list->next;
- list->next = list->next->next;
- free(tmp);
- return;
- }
- list = list->next;
- }
-}
-
-#if defined (NT) || defined(DJGPP) || defined(__CYGWIN__) || defined(__human68k__)
-static void
-pipe_atexit _((void))
-{
- struct pipe_list *list = pipe_list;
- struct pipe_list *tmp;
-
- while (list) {
- tmp = list->next;
- rb_io_fptr_finalize(list->fptr);
- list = tmp;
- }
-}
-#endif
-
-static void pipe_finalize _((OpenFile *fptr));
-
-static void
-pipe_finalize(fptr)
- OpenFile *fptr;
-{
-#if !defined (__CYGWIN__)
- extern VALUE rb_last_status;
- int status;
- if (fptr->f) {
- status = pclose(fptr->f);
- }
- if (fptr->f2) {
- status = pclose(fptr->f2);
- }
- fptr->f = fptr->f2 = 0;
-#if defined DJGPP
- status <<= 8;
-#endif
- rb_last_status = INT2FIX(status);
-#else
- fptr_finalize(fptr, Qtrue);
-#endif
- pipe_del_fptr(fptr);
-}
-#endif
-
-void
-rb_io_synchronized(fptr)
- OpenFile *fptr;
-{
- fptr->mode |= FMODE_SYNC;
-}
-
-void
-rb_io_unbuffered(fptr)
- OpenFile *fptr;
-{
- rb_io_synchronized(fptr);
-}
-
-static VALUE
-pipe_open(pname, mode)
- char *pname, *mode;
-{
- int modef = rb_io_mode_flags(mode);
- OpenFile *fptr;
-
-#if defined(NT) || defined(DJGPP) || defined(__human68k__)
- FILE *f = popen(pname, mode);
-
- if (!f) rb_sys_fail(pname);
- else {
- VALUE port = rb_obj_alloc(rb_cIO);
-
- MakeOpenFile(port, fptr);
- fptr->finalize = pipe_finalize;
- fptr->mode = modef;
-
- pipe_add_fptr(fptr);
- if (modef & FMODE_READABLE) fptr->f = f;
- if (modef & FMODE_WRITABLE) {
- if (fptr->f) fptr->f2 = f;
- else fptr->f = f;
- rb_io_synchronized(fptr);
- }
- return port;
- }
-#else
- int pid, pr[2], pw[2];
- volatile int doexec;
-
- if (((modef & FMODE_READABLE) && pipe(pr) == -1) ||
- ((modef & FMODE_WRITABLE) && pipe(pw) == -1))
- rb_sys_fail(pname);
-
- doexec = (strcmp("-", pname) != 0);
- if (!doexec) {
- fflush(stdin); /* is it really needed? */
- fflush(stdout);
- fflush(stderr);
- }
-
- retry:
- switch ((pid = fork())) {
- case 0: /* child */
- if (modef & FMODE_READABLE) {
- close(pr[0]);
- if (pr[1] != 1) {
- dup2(pr[1], 1);
- close(pr[1]);
- }
- }
- if (modef & FMODE_WRITABLE) {
- close(pw[1]);
- if (pw[0] != 0) {
- dup2(pw[0], 0);
- close(pw[0]);
- }
- }
-
- if (doexec) {
- int fd;
-
- for (fd = 3; fd < NOFILE; fd++)
- close(fd);
- rb_proc_exec(pname);
- fprintf(stderr, "%s:%d: command not found: %s\n",
- ruby_sourcefile, ruby_sourceline, pname);
- _exit(127);
- }
- rb_io_synchronized(RFILE(orig_stdout)->fptr);
- rb_io_synchronized(RFILE(orig_stderr)->fptr);
- return Qnil;
-
- case -1: /* fork failed */
- if (errno == EAGAIN) {
- rb_thread_sleep(1);
- goto retry;
- }
- close(pr[0]); close(pw[1]);
- rb_sys_fail(pname);
- break;
-
- default: /* parent */
- if (pid < 0) rb_sys_fail(pname);
- else {
- VALUE port = rb_obj_alloc(rb_cIO);
-
- MakeOpenFile(port, fptr);
- fptr->mode = modef;
- fptr->mode |= FMODE_SYNC;
- fptr->pid = pid;
-
- if (modef & FMODE_READABLE) {
- close(pr[1]);
- fptr->f = rb_fdopen(pr[0], "r");
- }
- if (modef & FMODE_WRITABLE) {
- FILE *f = rb_fdopen(pw[1], "w");
-
- close(pw[0]);
- if (fptr->f) fptr->f2 = f;
- else fptr->f = f;
- }
-#if defined (__CYGWIN__)
- fptr->finalize = pipe_finalize;
- pipe_add_fptr(fptr);
-#endif
- return port;
- }
- }
-#endif
-}
-
-static VALUE
-rb_io_popen(str, argc, argv, klass)
- char *str;
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- char *mode;
- VALUE pname, pmode, port;
- char mbuf[4];
-
- if (rb_scan_args(argc, argv, "11", &pname, &pmode) == 1) {
- mode = "r";
- }
- else if (FIXNUM_P(pmode)) {
- mode = rb_io_binmode_mode(FIX2INT(pmode), mbuf);
- }
- else {
- mode = StringValuePtr(pmode);
- }
- SafeStringValue(pname);
- port = pipe_open(str, mode);
- if (NIL_P(port)) {
- /* child */
- if (rb_block_given_p()) {
- rb_yield(Qnil);
- fflush(stdout);
- fflush(stderr);
- _exit(0);
- }
- return Qnil;
- }
- RBASIC(port)->klass = klass;
- if (rb_block_given_p()) {
- return rb_ensure(rb_yield, port, rb_io_close, port);
- }
- return port;
-}
-
-static VALUE
-rb_io_s_popen(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- char *str = 0;
-
- if (argc >= 1) {
- str = StringValuePtr(argv[0]);
- }
- return rb_io_popen(str, argc, argv, klass);
-}
-
-static VALUE
-rb_open_file(argc, argv, io)
- int argc;
- VALUE *argv;
- VALUE io;
-{
- VALUE fname, vmode, file, perm;
- char *path, *mode;
- int flags, fmode;
-
- rb_scan_args(argc, argv, "12", &fname, &vmode, &perm);
- SafeStringValue(fname);
- path = RSTRING(fname)->ptr;
-
- if (FIXNUM_P(vmode) || !NIL_P(perm)) {
- flags = FIXNUM_P(vmode) ? NUM2INT(vmode) : rb_io_mode_binmode(StringValuePtr(vmode));
- fmode = NIL_P(perm) ? 0666 : NUM2INT(perm);
-
- file = rb_file_sysopen_internal(io, path, flags, fmode);
- }
- else {
- mode = NIL_P(vmode) ? "r" : StringValuePtr(vmode);
- file = rb_file_open_internal(io, RSTRING(fname)->ptr, mode);
- }
- return io;
-}
-
-static VALUE
-rb_io_s_open(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- VALUE io = rb_class_new_instance(argc, argv, klass);
-
- if (rb_block_given_p()) {
- return rb_ensure(rb_yield, io, rb_io_close, io);
- }
-
- return io;
-}
-
-static VALUE
-rb_f_open(argc, argv)
- int argc;
- VALUE *argv;
-{
- if (argc >= 1) {
- char *str = StringValuePtr(argv[0]);
-
- if (str[0] == '|') {
- return rb_io_popen(str+1, argc, argv, rb_cIO);
- }
- }
- return rb_io_s_open(argc, argv, rb_cFile);
-}
-
-static VALUE
-rb_io_open(fname, mode)
- char *fname, *mode;
-{
- if (fname[0] == '|') {
- return pipe_open(fname+1, mode);
- }
- else {
- return rb_file_open(fname, mode);
- }
-}
-
-static VALUE
-rb_io_get_io(io)
- VALUE io;
-{
- return rb_convert_type(io, T_FILE, "IO", "to_io");
-}
-
-static char*
-rb_io_mode_string(fptr)
- OpenFile *fptr;
-{
- switch (fptr->mode & FMODE_READWRITE) {
- case FMODE_READABLE:
- default:
- return "r";
- case FMODE_WRITABLE:
- return "w";
- case FMODE_READWRITE:
- return "r+";
- }
-}
-
-static VALUE
-io_reopen(io, nfile)
- VALUE io, nfile;
-{
- OpenFile *fptr, *orig;
- char *mode;
- int fd;
- off_t pos;
-
- nfile = rb_io_get_io(nfile);
- if (rb_safe_level() >= 4 && (!OBJ_TAINTED(io) || !OBJ_TAINTED(nfile))) {
- rb_raise(rb_eSecurityError, "Insecure: can't reopen");
- }
- GetOpenFile(io, fptr);
- GetOpenFile(nfile, orig);
-
- if (fptr == orig) return io;
- if (orig->mode & FMODE_READABLE) {
- pos = ftello(orig->f);
- }
- if (orig->f2) {
- io_fflush(orig->f2, orig->path);
- }
- else if (orig->mode & FMODE_WRITABLE) {
- io_fflush(orig->f, orig->path);
- }
- orig->mode &= ~FMODE_WBUF;
- rb_thread_fd_close(fileno(fptr->f));
-
- /* copy OpenFile structure */
- fptr->mode = orig->mode;
- fptr->pid = orig->pid;
- fptr->lineno = orig->lineno;
- if (fptr->path) free(fptr->path);
- if (orig->path) fptr->path = strdup(orig->path);
- else fptr->path = 0;
- fptr->finalize = orig->finalize;
-
- mode = rb_io_mode_string(fptr);
- fd = fileno(fptr->f);
- if (fd < 3) {
- clearerr(fptr->f);
- /* need to keep stdio objects */
- if (dup2(fileno(orig->f), fd) < 0)
- rb_sys_fail(orig->path);
- }
- else {
- fclose(fptr->f);
- if (dup2(fileno(orig->f), fd) < 0)
- rb_sys_fail(orig->path);
- fptr->f = rb_fdopen(fd, mode);
- }
- if ((orig->mode & FMODE_READABLE) && pos >= 0) {
- fseeko(fptr->f, pos, SEEK_SET);
- fseeko(orig->f, pos, SEEK_SET);
- }
-
- if (fptr->f2) {
- fd = fileno(fptr->f2);
- fclose(fptr->f2);
- if (orig->f2) {
- if (dup2(fileno(orig->f2), fd) < 0)
- rb_sys_fail(orig->path);
- fptr->f2 = rb_fdopen(fd, "w");
- }
- else {
- fptr->f2 = 0;
- }
- }
-
- if (fptr->mode & FMODE_BINMODE) {
- rb_io_binmode(io);
- }
-
- RBASIC(io)->klass = RBASIC(nfile)->klass;
- return io;
-}
-
-static VALUE
-rb_io_reopen(argc, argv, file)
- int argc;
- VALUE *argv;
- VALUE file;
-{
- VALUE fname, nmode;
- char *mode;
- OpenFile *fptr;
-
- rb_secure(4);
- if (rb_scan_args(argc, argv, "11", &fname, &nmode) == 1) {
- if (TYPE(fname) != T_STRING) { /* fname must be IO */
- return io_reopen(file, fname);
- }
- }
-
- SafeStringValue(fname);
- if (!NIL_P(nmode)) {
- mode = StringValuePtr(nmode);
- }
- else {
- mode = "r";
- }
-
- GetOpenFile(file, fptr);
- if (fptr->path) {
- free(fptr->path);
- fptr->path = 0;
- }
-
- fptr->path = strdup(RSTRING(fname)->ptr);
- fptr->mode = rb_io_mode_flags(mode);
- if (!fptr->f) {
- fptr->f = rb_fopen(RSTRING(fname)->ptr, mode);
- if (fptr->f2) {
- fclose(fptr->f2);
- fptr->f2 = 0;
- }
-
- return file;
- }
-
- if (freopen(RSTRING(fname)->ptr, mode, fptr->f) == 0) {
- rb_sys_fail(fptr->path);
- }
-#ifdef USE_SETVBUF
- if (setvbuf(fptr->f, NULL, _IOFBF, 0) != 0)
- rb_warn("setvbuf() can't be honered for %s", RSTRING(fname)->ptr);
-#endif
-
- if (fptr->f2) {
- if (freopen(RSTRING(fname)->ptr, "w", fptr->f2) == 0) {
- rb_sys_fail(fptr->path);
- }
- }
-
- return file;
-}
-
-static VALUE
-rb_io_clone(io)
- VALUE io;
-{
- OpenFile *fptr, *orig;
- int fd;
- char *mode;
- VALUE clone = rb_obj_clone(io);
-
- GetOpenFile(io, orig);
- MakeOpenFile(clone, fptr);
-
- if (orig->f2) {
- io_fflush(orig->f2, orig->path);
- }
- else if (orig->mode & FMODE_WRITABLE) {
- io_fflush(orig->f, orig->path);
- }
- orig->mode &= ~FMODE_WBUF;
-
- /* copy OpenFile structure */
- fptr->mode = orig->mode;
- fptr->pid = orig->pid;
- fptr->lineno = orig->lineno;
- if (orig->path) fptr->path = strdup(orig->path);
- fptr->finalize = orig->finalize;
-
- switch (fptr->mode & FMODE_READWRITE) {
- case FMODE_READABLE:
- default:
- mode = "r"; break;
- case FMODE_WRITABLE:
- mode = "w"; break;
- case FMODE_READWRITE:
- if (orig->f2) mode = "r";
- else mode = "r+";
- break;
- }
- fd = ruby_dup(fileno(orig->f));
- fptr->f = rb_fdopen(fd, mode);
- if (fptr->f2) {
- if (fileno(orig->f) != fileno(orig->f2)) {
- fd = ruby_dup(fileno(orig->f2));
- }
- fptr->f = rb_fdopen(fd, "w");
- }
- if (fptr->mode & FMODE_BINMODE) {
- rb_io_binmode(clone);
- }
-
- return clone;
-}
-
-VALUE
-rb_io_printf(argc, argv, out)
- int argc;
- VALUE argv[];
- VALUE out;
-{
- rb_io_write(out, rb_f_sprintf(argc, argv));
- return Qnil;
-}
-
-static VALUE
-rb_f_printf(argc, argv)
- int argc;
- VALUE argv[];
-{
- VALUE out;
-
- if (argc == 0) return Qnil;
- if (TYPE(argv[0]) == T_STRING) {
- out = rb_defout;
- }
- else {
- out = argv[0];
- argv++;
- argc--;
- }
- rb_io_write(out, rb_f_sprintf(argc, argv));
-
- return Qnil;
-}
-
-VALUE
-rb_io_print(argc, argv, out)
- int argc;
- VALUE *argv;
- VALUE out;
-{
- int i;
- VALUE line;
-
- /* if no argument given, print `$_' */
- if (argc == 0) {
- argc = 1;
- line = rb_lastline_get();
- argv = &line;
- }
- for (i=0; i<argc; i++) {
- if (!NIL_P(rb_output_fs) && i>0) {
- rb_io_write(out, rb_output_fs);
- }
- switch (TYPE(argv[i])) {
- case T_NIL:
- rb_io_write(out, rb_str_new2("nil"));
- break;
- default:
- rb_io_write(out, argv[i]);
- break;
- }
- }
- if (!NIL_P(rb_output_rs)) {
- rb_io_write(out, rb_output_rs);
- }
-
- return Qnil;
-}
-
-static VALUE
-rb_f_print(argc, argv)
- int argc;
- VALUE *argv;
-{
- rb_io_print(argc, argv, rb_defout);
- return Qnil;
-}
-
-static VALUE
-rb_io_putc(io, ch)
- VALUE io, ch;
-{
- OpenFile *fptr;
- FILE *f;
- int c = NUM2CHR(ch);
-
- rb_secure(4);
- GetOpenFile(io, fptr);
- rb_io_check_writable(fptr);
- f = GetWriteFile(fptr);
-
- if (fputc(c, f) == EOF)
- rb_sys_fail(fptr->path);
- fptr->mode |= FMODE_WBUF;
- if (fptr->mode & FMODE_SYNC) {
- io_fflush(f, fptr->path);
- fptr->mode &= ~FMODE_WBUF;
- }
- else {
- fptr->mode |= FMODE_WBUF;
- }
-
- return ch;
-}
-
-static VALUE
-rb_f_putc(recv, ch)
- VALUE recv, ch;
-{
- return rb_io_putc(rb_defout, ch);
-}
-
-static VALUE
-io_puts_ary(ary, out)
- VALUE ary, out;
-{
- VALUE tmp;
- int i;
-
- for (i=0; i<RARRAY(ary)->len; i++) {
- tmp = RARRAY(ary)->ptr[i];
- if (rb_inspecting_p(tmp)) {
- tmp = rb_str_new2("[...]");
- }
- rb_io_puts(1, &tmp, out);
- }
- return Qnil;
-}
-
-VALUE
-rb_io_puts(argc, argv, out)
- int argc;
- VALUE *argv;
- VALUE out;
-{
- int i;
- VALUE line;
-
- /* if no argument given, print newline. */
- if (argc == 0) {
- rb_io_write(out, rb_default_rs);
- return Qnil;
- }
- for (i=0; i<argc; i++) {
- if (NIL_P(argv[i])) {
- line = rb_str_new2("nil");
- }
- else {
- line = rb_check_convert_type(argv[i], T_ARRAY, "Array", "to_ary");
- if (!NIL_P(line)) {
- rb_protect_inspect(io_puts_ary, line, out);
- continue;
- }
- line = rb_obj_as_string(argv[i]);
- }
- rb_io_write(out, line);
- if (RSTRING(line)->ptr[RSTRING(line)->len-1] != '\n') {
- rb_io_write(out, rb_default_rs);
- }
- }
-
- return Qnil;
-}
-
-static VALUE
-rb_f_puts(argc, argv)
- int argc;
- VALUE *argv;
-{
- rb_io_puts(argc, argv, rb_defout);
- return Qnil;
-}
-
-void
-rb_p(obj) /* for debug print within C code */
- VALUE obj;
-{
- rb_io_write(rb_defout, rb_obj_as_string(rb_inspect(obj)));
- rb_io_write(rb_defout, rb_default_rs);
-}
-
-static VALUE
-rb_f_p(argc, argv)
- int argc;
- VALUE *argv;
-{
- int i;
-
- for (i=0; i<argc; i++) {
- rb_p(argv[i]);
- }
- if (TYPE(rb_defout) == T_FILE) {
- rb_io_flush(rb_defout);
- }
- return Qnil;
-}
-
-static VALUE
-rb_obj_display(argc, argv, self)
- int argc;
- VALUE *argv;
- VALUE self;
-{
- VALUE out;
-
- if (rb_scan_args(argc, argv, "01", &out) == 0) {
- out = rb_defout;
- }
-
- rb_io_write(out, self);
-
- return Qnil;
-}
-
-static void
-rb_io_defset(val, id)
- VALUE val;
- ID id;
-{
- if (!rb_respond_to(val, id_write)) {
- rb_raise(rb_eTypeError, "$> must have write method, %s given",
- rb_class2name(CLASS_OF(val)));
- }
- rb_defout = val;
-}
-
-static void
-set_stdin(val, id, var)
- VALUE val;
- ID id;
- VALUE *var;
-{
- OpenFile *fptr;
-
- if (val == *var) return;
- if (TYPE(val) != T_FILE) {
- *var = val;
- return;
- }
- if (TYPE(*var) != T_FILE) {
- *var = orig_stdin;
- }
-
- GetOpenFile(val, fptr);
- rb_io_check_readable(fptr);
- if (fileno(fptr->f) == 0 && saved_fd[0] != 0) {
- dup2(saved_fd[0], 0);
- close(saved_fd[0]);
- saved_fd[0] = 0;
- }
- else {
- saved_fd[0] = dup(0);
- dup2(fileno(fptr->f), 0);
- }
-
- *var = val;
-}
-
-static void
-set_outfile(val, var, orig, stdf)
- VALUE val;
- VALUE *var;
- VALUE orig;
- FILE *stdf;
-{
- OpenFile *fptr;
- FILE *f;
- int fd;
-
- if (val == *var) return;
-
- if (TYPE(*var) == T_FILE && !rb_io_closed(*var)) {
- rb_io_flush(*var);
- }
- if (TYPE(val) != T_FILE) {
- *var = val;
- return;
- }
- if (TYPE(*var) != T_FILE) {
- *var = orig;
- }
-
- GetOpenFile(val, fptr);
- rb_io_check_writable(fptr);
- f = GetWriteFile(fptr);
- fd = fileno(stdf);
- if (fileno(fptr->f) == fd && saved_fd[fd] != fd) {
- dup2(saved_fd[fd], fd);
- close(saved_fd[fd]);
- saved_fd[fd] = fd;
- }
- else {
- saved_fd[fd] = dup(fd);
- dup2(fileno(fptr->f), fd);
- }
-
- *var = val;
-}
-
-static void
-set_stdout(val, id, var)
- VALUE val;
- ID id;
- VALUE *var;
-{
- set_outfile(val, var, orig_stdout, stdout);
-}
-
-static void
-set_stderr(val, id, var)
- VALUE val;
- ID id;
- VALUE *var;
-{
- set_outfile(val, var, orig_stderr, stderr);
-}
-
-static VALUE
-prep_stdio(f, mode, klass)
- FILE *f;
- int mode;
- VALUE klass;
-{
- OpenFile *fp;
- VALUE io = rb_obj_alloc(klass);
-
- MakeOpenFile(io, fp);
- fp->f = f;
- fp->mode = mode;
-
- return io;
-}
-
-static void
-prep_path(io, path)
- VALUE io;
- char *path;
-{
- OpenFile *fptr;
-
- GetOpenFile(io, fptr);
- if (fptr->path) rb_bug("illegal prep_path() call");
- fptr->path = strdup(path);
-}
-
-static VALUE
-rb_io_s_alloc(klass)
- VALUE klass;
-{
- NEWOBJ(io, struct RFile);
- OBJSETUP(io, klass, T_FILE);
-
- io->fptr = 0;
-
- return (VALUE)io;
-}
-
-static VALUE
-rb_io_initialize(argc, argv, io)
- int argc;
- VALUE *argv;
- VALUE io;
-{
- VALUE fnum, mode;
- OpenFile *fp;
- char *m = "r";
-
- if (rb_scan_args(argc, argv, "11", &fnum, &mode) == 2) {
- SafeStringValue(mode);
- m = RSTRING(mode)->ptr;
- }
- MakeOpenFile(io, fp);
- fp->f = rb_fdopen(NUM2INT(fnum), m);
- fp->mode = rb_io_mode_flags(m);
-
- return io;
-}
-
-static VALUE
-rb_file_initialize(argc, argv, io)
- int argc;
- VALUE *argv;
- VALUE io;
-{
- if (RFILE(io)->fptr) {
- rb_io_close_m(io);
- free(RFILE(io)->fptr);
- RFILE(io)->fptr = 0;
- }
- if (0 < argc && argc < 3) {
- VALUE fd = rb_check_convert_type(argv[0], T_FIXNUM, "Fixnum", "to_int");
-
- if (!NIL_P(fd)) {
- argv[0] = fd;
- return rb_io_initialize(argc, argv, io);
- }
- }
- rb_open_file(argc, argv, io);
-
- return io;
-}
-
-static VALUE
-rb_io_s_new(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- if (rb_block_given_p()) {
- char *cname = rb_class2name(klass);
-
- rb_warn("%s::new() does not take block; use %::open() instead",
- cname, cname);
- }
- return rb_class_new_instance(argc, argv, klass);
-}
-
-static int binmode = 0;
-
-static VALUE
-argf_forward()
-{
- return rb_funcall3(current_file, ruby_frame->last_func,
- ruby_frame->argc, ruby_frame->argv);
-}
-
-static VALUE
-argf_binmode()
-{
- if (TYPE(current_file) != T_FILE) {
- argf_forward();
- }
- else {
- rb_io_binmode(current_file);
- }
- binmode = 1;
- return argf;
-}
-
-static int
-next_argv()
-{
- extern VALUE rb_argv;
- char *fn;
-
- if (init_p == 0) {
- if (RARRAY(rb_argv)->len > 0) {
- next_p = 1;
- }
- else {
- next_p = -1;
- current_file = rb_stdin;
- filename = rb_str_new2("-");
- }
- init_p = 1;
- first_p = 0;
- gets_lineno = 0;
- }
-
- retry:
- if (next_p == 1) {
- next_p = 0;
- if (RARRAY(rb_argv)->len > 0) {
- filename = rb_ary_shift(rb_argv);
- fn = StringValuePtr(filename);
- if (strlen(fn) == 1 && fn[0] == '-') {
- current_file = rb_stdin;
- if (ruby_inplace_mode) {
- rb_warn("Can't do inplace edit for stdio");
- rb_defout = rb_stdout;
- }
- }
- else {
- FILE *fr = rb_fopen(fn, "r");
-
- if (ruby_inplace_mode) {
- struct stat st, st2;
- VALUE str;
- FILE *fw;
-
- if (TYPE(rb_defout) == T_FILE && rb_defout != rb_stdout) {
- rb_io_close(rb_defout);
- }
- fstat(fileno(fr), &st);
- if (*ruby_inplace_mode) {
- str = rb_str_new2(fn);
-#ifdef NO_LONG_FNAME
- ruby_add_suffix(str, ruby_inplace_mode);
-#else
- rb_str_cat2(str, ruby_inplace_mode);
-#endif
-#ifdef NO_SAFE_RENAME
- (void)fclose(fr);
- (void)unlink(RSTRING(str)->ptr);
- (void)rename(fn, RSTRING(str)->ptr);
- fr = rb_fopen(RSTRING(str)->ptr, "r");
-#else
- if (rename(fn, RSTRING(str)->ptr) < 0) {
- rb_warn("Can't rename %s to %s: %s, skipping file",
- fn, RSTRING(str)->ptr, strerror(errno));
- fclose(fr);
- goto retry;
- }
-#endif
- }
- else {
-#ifdef NO_SAFE_RENAME
- rb_fatal("Can't do inplace edit without backup");
-#else
- if (unlink(fn) < 0) {
- rb_warn("Can't remove %s: %s, skipping file",
- fn, strerror(errno));
- fclose(fr);
- goto retry;
- }
-#endif
- }
- fw = rb_fopen(fn, "w");
-#ifndef NO_SAFE_RENAME
- fstat(fileno(fw), &st2);
-#ifdef HAVE_FCHMOD
- fchmod(fileno(fw), st.st_mode);
-#else
- chmod(fn, st.st_mode);
-#endif
- if (st.st_uid!=st2.st_uid || st.st_gid!=st2.st_gid) {
- fchown(fileno(fw), st.st_uid, st.st_gid);
- }
-#endif
- rb_defout = prep_stdio(fw, FMODE_WRITABLE, rb_cFile);
- prep_path(rb_defout, fn);
- }
- current_file = prep_stdio(fr, FMODE_READABLE, rb_cFile);
- prep_path(current_file, fn);
- }
- if (binmode) rb_io_binmode(current_file);
- }
- else {
- init_p = 0;
- return Qfalse;
- }
- }
- return Qtrue;
-}
-
-static void
-any_close(file)
- VALUE file;
-{
- if (TYPE(file) == T_FILE)
- rb_io_close(file);
- else
- rb_funcall3(file, rb_intern("close"), 0, 0);
-}
-
-static VALUE
-argf_getline(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE line;
-
- retry:
- if (!next_argv()) return Qnil;
- if (TYPE(current_file) != T_FILE) {
- line = rb_funcall3(current_file, rb_intern("gets"), argc, argv);
- }
- else if (argc == 0 && rb_rs == rb_default_rs) {
- line = rb_io_gets(current_file);
- }
- else {
- VALUE rs;
- OpenFile *fptr;
-
- if (argc == 0) {
- rs = rb_rs;
- }
- else {
- rb_scan_args(argc, argv, "1", &rs);
- }
- GetOpenFile(current_file, fptr);
- rb_io_check_readable(fptr);
- line = rb_io_getline(rs, fptr);
- }
- if (NIL_P(line) && next_p != -1) {
- any_close(current_file);
- next_p = 1;
- goto retry;
- }
- gets_lineno++;
- lineno = INT2FIX(gets_lineno);
-
- return line;
-}
-
-static VALUE
-rb_f_gets(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE line = argf_getline(argc, argv);
-
- rb_lastline_set(line);
- return line;
-}
-
-VALUE
-rb_gets()
-{
- VALUE line;
-
- if (rb_rs != rb_default_rs) {
- return rb_f_gets(0, 0);
- }
-
- retry:
- if (!next_argv()) return Qnil;
- line = rb_io_gets(current_file);
- if (NIL_P(line) && next_p != -1) {
- any_close(current_file);
- next_p = 1;
- goto retry;
- }
- rb_lastline_set(line);
- if (!NIL_P(line)) {
- gets_lineno++;
- lineno = INT2FIX(gets_lineno);
- }
-
- return line;
-}
-
-static VALUE
-rb_f_readline(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE line = rb_f_gets(argc, argv);
-
- if (NIL_P(line)) {
- rb_eof_error();
- }
-
- return line;
-}
-
-static VALUE
-rb_f_getc()
-{
- rb_warn("getc is obsolete; use STDIN.getc instead");
- return rb_io_getc(rb_stdin);
-}
-
-static VALUE
-rb_f_readlines(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE line, ary;
-
- ary = rb_ary_new();
- while (!NIL_P(line = argf_getline(argc, argv))) {
- rb_ary_push(ary, line);
- }
-
- return ary;
-}
-
-static VALUE
-rb_f_backquote(obj, str)
- VALUE obj, str;
-{
- VALUE port, result;
-
- SafeStringValue(str);
- port = pipe_open(RSTRING(str)->ptr, "r");
- if (NIL_P(port)) return rb_str_new(0,0);
- result = read_all(port);
-
- rb_io_close(port);
-
- if (NIL_P(result)) return rb_str_new(0,0);
- return result;
-}
-
-#ifdef HAVE_SYS_SELECT_H
-#include <sys/select.h>
-#endif
-
-static VALUE
-rb_f_select(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- VALUE read, write, except, timeout, res, list;
- fd_set rset, wset, eset, pset;
- fd_set *rp, *wp, *ep;
- struct timeval *tp, timerec;
- OpenFile *fptr;
- int i, max = 0, n;
- int interrupt_flag = 0;
- int pending = 0;
-
- rb_scan_args(argc, argv, "13", &read, &write, &except, &timeout);
- if (NIL_P(timeout)) {
- tp = 0;
- }
- else {
- timerec = rb_time_interval(timeout);
- tp = &timerec;
- }
-
- FD_ZERO(&pset);
- if (!NIL_P(read)) {
- Check_Type(read, T_ARRAY);
- rp = &rset;
- FD_ZERO(rp);
- for (i=0; i<RARRAY(read)->len; i++) {
- GetOpenFile(rb_io_get_io(RARRAY(read)->ptr[i]), fptr);
- FD_SET(fileno(fptr->f), rp);
- if (READ_DATA_PENDING(fptr->f)) { /* check for buffered data */
- pending++;
- FD_SET(fileno(fptr->f), &pset);
- }
- if (max < fileno(fptr->f)) max = fileno(fptr->f);
- }
- if (pending) { /* no blocking if there's buffered data */
- timerec.tv_sec = timerec.tv_usec = 0;
- tp = &timerec;
- }
- }
- else
- rp = 0;
-
- if (!NIL_P(write)) {
- Check_Type(write, T_ARRAY);
- wp = &wset;
- FD_ZERO(wp);
- for (i=0; i<RARRAY(write)->len; i++) {
- GetOpenFile(rb_io_get_io(RARRAY(write)->ptr[i]), fptr);
- FD_SET(fileno(fptr->f), wp);
- if (max < fileno(fptr->f)) max = fileno(fptr->f);
- if (fptr->f2) {
- FD_SET(fileno(fptr->f2), wp);
- if (max < fileno(fptr->f2)) max = fileno(fptr->f2);
- }
- }
- }
- else
- wp = 0;
-
- if (!NIL_P(except)) {
- Check_Type(except, T_ARRAY);
- ep = &eset;
- FD_ZERO(ep);
- for (i=0; i<RARRAY(except)->len; i++) {
- GetOpenFile(rb_io_get_io(RARRAY(except)->ptr[i]), fptr);
- FD_SET(fileno(fptr->f), ep);
- if (max < fileno(fptr->f)) max = fileno(fptr->f);
- if (fptr->f2) {
- FD_SET(fileno(fptr->f2), ep);
- if (max < fileno(fptr->f2)) max = fileno(fptr->f2);
- }
- }
- }
- else {
- ep = 0;
- }
-
- max++;
-
- n = rb_thread_select(max, rp, wp, ep, tp);
- if (n < 0) {
- rb_sys_fail(0);
- }
- if (!pending && n == 0) return Qnil; /* returns nil on timeout */
-
- res = rb_ary_new2(3);
- rb_ary_push(res, rp?rb_ary_new():rb_ary_new2(0));
- rb_ary_push(res, wp?rb_ary_new():rb_ary_new2(0));
- rb_ary_push(res, ep?rb_ary_new():rb_ary_new2(0));
-
- if (interrupt_flag == 0) {
- if (rp) {
- list = RARRAY(res)->ptr[0];
- for (i=0; i< RARRAY(read)->len; i++) {
- GetOpenFile(rb_io_get_io(RARRAY(read)->ptr[i]), fptr);
- if (FD_ISSET(fileno(fptr->f), rp)
- || FD_ISSET(fileno(fptr->f), &pset)) {
- rb_ary_push(list, RARRAY(read)->ptr[i]);
- }
- }
- }
-
- if (wp) {
- list = RARRAY(res)->ptr[1];
- for (i=0; i< RARRAY(write)->len; i++) {
- GetOpenFile(rb_io_get_io(RARRAY(write)->ptr[i]), fptr);
- if (FD_ISSET(fileno(fptr->f), wp)) {
- rb_ary_push(list, RARRAY(write)->ptr[i]);
- }
- else if (fptr->f2 && FD_ISSET(fileno(fptr->f2), wp)) {
- rb_ary_push(list, RARRAY(write)->ptr[i]);
- }
- }
- }
-
- if (ep) {
- list = RARRAY(res)->ptr[2];
- for (i=0; i< RARRAY(except)->len; i++) {
- GetOpenFile(rb_io_get_io(RARRAY(except)->ptr[i]), fptr);
- if (FD_ISSET(fileno(fptr->f), ep)) {
- rb_ary_push(list, RARRAY(except)->ptr[i]);
- }
- else if (fptr->f2 && FD_ISSET(fileno(fptr->f2), ep)) {
- rb_ary_push(list, RARRAY(except)->ptr[i]);
- }
- }
- }
- }
-
- return res; /* returns an empty array on interrupt */
-}
-
-#if !defined(MSDOS) && !defined(__human68k__)
-static int
-io_cntl(fd, cmd, narg, io_p)
- int fd, cmd, io_p;
- long narg;
-{
- int retval;
-
-#ifdef HAVE_FCNTL
- TRAP_BEG;
-# if defined(__CYGWIN__)
- retval = io_p?ioctl(fd, cmd, (void*)narg):fcntl(fd, cmd, narg);
-# else
- retval = io_p?ioctl(fd, cmd, narg):fcntl(fd, cmd, narg);
-# endif
- TRAP_END;
-#else
- if (!io_p) {
- rb_notimplement();
- }
- TRAP_BEG;
- retval = ioctl(fd, cmd, narg);
- TRAP_END;
-#endif
- return retval;
-}
-#endif
-
-static VALUE
-rb_io_ctl(io, req, arg, io_p)
- VALUE io, req, arg;
- int io_p;
-{
-#if !defined(MSDOS) && !defined(__human68k__)
- int cmd = NUM2ULONG(req);
- OpenFile *fptr;
- int len = 0;
- long narg = 0;
- int retval;
-
- rb_secure(2);
- GetOpenFile(io, fptr);
-
- if (NIL_P(arg) || arg == Qfalse) {
- narg = 0;
- }
- else if (FIXNUM_P(arg)) {
- narg = FIX2INT(arg);
- }
- else if (arg == Qtrue) {
- narg = 1;
- }
- else if (rb_obj_is_kind_of(arg, rb_cInteger)) {
- narg = NUM2LONG(arg);
- }
- else {
- StringValue(arg);
-
-#ifdef IOCPARM_MASK
-#ifndef IOCPARM_LEN
-#define IOCPARM_LEN(x) (((x) >> 16) & IOCPARM_MASK)
-#endif
-#endif
-#ifdef IOCPARM_LEN
- len = IOCPARM_LEN(cmd); /* on BSDish systems we're safe */
-#else
- len = 256; /* otherwise guess at what's safe */
-#endif
- rb_str_modify(arg);
-
- if (len <= RSTRING(arg)->len) {
- len = RSTRING(arg)->len;
- }
- if (RSTRING(arg)->len < len) {
- rb_str_resize(arg, len+1);
- }
- RSTRING(arg)->ptr[len] = 17; /* a little sanity check here */
- narg = (long)RSTRING(arg)->ptr;
- }
- retval = io_cntl(fileno(fptr->f), cmd, narg, io_p);
- if (retval < 0) rb_sys_fail(fptr->path);
- if (TYPE(arg) == T_STRING && RSTRING(arg)->ptr[len] != 17) {
- rb_raise(rb_eArgError, "return value overflowed string");
- }
-
- if (fptr->f2 && fileno(fptr->f) != fileno(fptr->f2)) {
- /* call on f2 too; ignore result */
- io_cntl(fileno(fptr->f2), cmd, narg, io_p);
- }
-
- return INT2NUM(retval);
-#else
- rb_notimplement();
- return Qnil; /* not reached */
-#endif
-}
-
-static VALUE
-rb_io_ioctl(argc, argv, io)
- int argc;
- VALUE *argv;
- VALUE io;
-{
- VALUE req, arg;
-
- rb_scan_args(argc, argv, "11", &req, &arg);
- return rb_io_ctl(io, req, arg, 1);
-}
-
-static VALUE
-rb_io_fcntl(argc, argv, io)
- int argc;
- VALUE *argv;
- VALUE io;
-{
-#ifdef HAVE_FCNTL
- VALUE req, arg;
-
- rb_scan_args(argc, argv, "11", &req, &arg);
- return rb_io_ctl(io, req, arg, 0);
-#else
- rb_notimplement();
- return Qnil; /* not reached */
-#endif
-}
-
-static VALUE
-rb_f_syscall(argc, argv)
- int argc;
- VALUE *argv;
-{
-#if defined(HAVE_SYSCALL) && !defined(__CHECKER__)
-#ifdef atarist
- unsigned long arg[14]; /* yes, we really need that many ! */
-#else
- unsigned long arg[8];
-#endif
- int retval = -1;
- int i = 1;
- int items = argc - 1;
-
- /* This probably won't work on machines where sizeof(long) != sizeof(int)
- * or where sizeof(long) != sizeof(char*). But such machines will
- * not likely have syscall implemented either, so who cares?
- */
-
- rb_secure(2);
- if (argc == 0)
- rb_raise(rb_eArgError, "too few arguments for syscall");
- arg[0] = NUM2INT(argv[0]); argv++;
- while (items--) {
- if (FIXNUM_P(*argv)) {
- arg[i] = (unsigned long)NUM2INT(*argv);
- }
- else {
- VALUE v = *argv;
-
- StringValue(v);
- rb_str_modify(v);
- arg[i] = (unsigned long)RSTRING(v)->ptr;
- }
- argv++;
- i++;
- }
- TRAP_BEG;
- switch (argc) {
- case 1:
- retval = syscall(arg[0]);
- break;
- case 2:
- retval = syscall(arg[0],arg[1]);
- break;
- case 3:
- retval = syscall(arg[0],arg[1],arg[2]);
- break;
- case 4:
- retval = syscall(arg[0],arg[1],arg[2],arg[3]);
- break;
- case 5:
- retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4]);
- break;
- case 6:
- retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5]);
- break;
- case 7:
- retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6]);
- break;
- case 8:
- retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
- arg[7]);
- break;
-#ifdef atarist
- case 9:
- retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
- arg[7], arg[8]);
- break;
- case 10:
- retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
- arg[7], arg[8], arg[9]);
- break;
- case 11:
- retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
- arg[7], arg[8], arg[9], arg[10]);
- break;
- case 12:
- retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
- arg[7], arg[8], arg[9], arg[10], arg[11]);
- break;
- case 13:
- retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
- arg[7], arg[8], arg[9], arg[10], arg[11], arg[12]);
- break;
- case 14:
- retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
- arg[7], arg[8], arg[9], arg[10], arg[11], arg[12], arg[13]);
- break;
-#endif /* atarist */
- }
- TRAP_END;
- if (retval < 0) rb_sys_fail(0);
- return INT2NUM(retval);
-#else
- rb_notimplement();
- return Qnil; /* not reached */
-#endif
-}
-
-static VALUE
-rb_io_s_pipe()
-{
-#ifndef __human68k__
- int pipes[2];
- VALUE r, w;
-
-#ifdef NT
- if (_pipe(pipes, 1024, O_BINARY) == -1)
-#else
- if (pipe(pipes) == -1)
-#endif
- rb_sys_fail(0);
-
- r = prep_stdio(rb_fdopen(pipes[0], "r"), FMODE_READABLE, rb_cIO);
- w = prep_stdio(rb_fdopen(pipes[1], "w"), FMODE_WRITABLE|FMODE_SYNC, rb_cIO);
-
- return rb_assoc_new(r, w);
-#else
- rb_notimplement();
- return Qnil; /* not reached */
-#endif
-}
-
-struct foreach_arg {
- int argc;
- VALUE sep;
- VALUE io;
- OpenFile *fptr;
-};
-
-static VALUE
-io_s_foreach(arg)
- struct foreach_arg *arg;
-{
- VALUE str;
-
- while (!NIL_P(str = rb_io_getline(arg->sep, arg->fptr))) {
- rb_yield(str);
- }
- return Qnil;
-}
-
-static VALUE
-rb_io_s_foreach(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE fname, io;
- OpenFile *fptr;
- struct foreach_arg arg;
-
- rb_scan_args(argc, argv, "11", &fname, &arg.sep);
- SafeStringValue(fname);
-
- if (argc == 1) {
- arg.sep = rb_default_rs;
- }
- io = rb_io_open(RSTRING(fname)->ptr, "r");
- if (NIL_P(io)) return Qnil;
- GetOpenFile(io, fptr);
- arg.fptr = fptr;
-
- return rb_ensure(io_s_foreach, (VALUE)&arg, rb_io_close, io);
-}
-
-static VALUE
-io_s_readlines(arg)
- struct foreach_arg *arg;
-{
- return rb_io_readlines(arg->argc, &arg->sep, arg->io);
-}
-
-static VALUE
-rb_io_s_readlines(argc, argv, io)
- int argc;
- VALUE *argv;
- VALUE io;
-{
- VALUE fname;
- struct foreach_arg arg;
-
- rb_scan_args(argc, argv, "11", &fname, &arg.sep);
- SafeStringValue(fname);
-
- arg.argc = argc - 1;
- arg.io = rb_io_open(RSTRING(fname)->ptr, "r");
- if (NIL_P(arg.io)) return Qnil;
- return rb_ensure(io_s_readlines, (VALUE)&arg, rb_io_close, arg.io);
-}
-
-static VALUE
-io_s_read(arg)
- struct foreach_arg *arg;
-{
- return io_read(arg->argc, &arg->sep, arg->io);
-}
-
-static VALUE
-rb_io_s_read(argc, argv, io)
- int argc;
- VALUE *argv;
- VALUE io;
-{
- VALUE fname, offset;
- struct foreach_arg arg;
-
- rb_scan_args(argc, argv, "12", &fname, &arg.sep, &offset);
- SafeStringValue(fname);
-
- arg.argc = argc ? 1 : 0;
- arg.io = rb_io_open(RSTRING(fname)->ptr, "r");
- if (NIL_P(arg.io)) return Qnil;
- if (!NIL_P(offset)) {
- rb_io_seek(arg.io, offset, SEEK_SET);
- }
- return rb_ensure(io_s_read, (VALUE)&arg, rb_io_close, arg.io);
-}
-
-static VALUE
-argf_tell()
-{
- if (!next_argv()) {
- rb_raise(rb_eArgError, "no stream to tell");
- }
-
- if (TYPE(current_file) != T_FILE) {
- return argf_forward();
- }
- return rb_io_tell(current_file);
-}
-
-static VALUE
-argf_seek_m(argc, argv, self)
- int argc;
- VALUE *argv;
- VALUE self;
-{
- if (!next_argv()) {
- rb_raise(rb_eArgError, "no stream to seek");
- }
-
- if (TYPE(current_file) != T_FILE) {
- return argf_forward();
- }
- return rb_io_seek_m(argc, argv, current_file);
-}
-
-static VALUE
-argf_set_pos(self, offset)
- VALUE self, offset;
-{
- if (!next_argv()) {
- rb_raise(rb_eArgError, "no stream to set position");
- }
-
- if (TYPE(current_file) != T_FILE) {
- return argf_forward();
- }
- return rb_io_set_pos(current_file, offset);
-}
-
-static VALUE
-argf_rewind()
-{
- if (!next_argv()) {
- rb_raise(rb_eArgError, "no stream to rewind");
- }
- if (TYPE(current_file) != T_FILE) {
- return argf_forward();
- }
- return rb_io_rewind(current_file);
-}
-
-static VALUE
-argf_fileno()
-{
- if (!next_argv()) {
- rb_raise(rb_eArgError, "no stream");
- }
- if (TYPE(current_file) != T_FILE) {
- return argf_forward();
- }
- return rb_io_fileno(current_file);
-}
-
-static VALUE
-argf_to_io()
-{
- return current_file;
-}
-
-static VALUE
-argf_read(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE tmp, str;
- int len;
-
- if (argc == 1) len = NUM2INT(argv[0]);
- str = Qnil;
-
- retry:
- if (!next_argv()) return str;
- if (TYPE(current_file) != T_FILE) {
- tmp = argf_forward();
- StringValue(tmp);
- }
- else {
- tmp = io_read(argc, argv, current_file);
- }
- if (NIL_P(tmp) && next_p != -1) {
- any_close(current_file);
- next_p = 1;
- goto retry;
- }
- if (NIL_P(tmp) || RSTRING(tmp)->len == 0) return str;
- else if (NIL_P(str)) str = tmp;
- else rb_str_append(str, tmp);
- if (argc == 0) {
- goto retry;
- }
- if (RSTRING(tmp)->len < len) {
- len -= RSTRING(tmp)->len;
- argv[0] = INT2FIX(len);
- goto retry;
- }
-
- return str;
-}
-
-static VALUE
-argf_getc()
-{
- VALUE byte;
-
- retry:
- if (!next_argv()) return Qnil;
- if (TYPE(current_file) != T_FILE) {
- byte = rb_funcall3(current_file, rb_intern("getc"), 0, 0);
- }
- else {
- byte = rb_io_getc(current_file);
- }
- if (NIL_P(byte) && next_p != -1) {
- any_close(current_file);
- next_p = 1;
- goto retry;
- }
-
- return byte;
-}
-
-static VALUE
-argf_readchar()
-{
- VALUE c = argf_getc();
-
- if (NIL_P(c)) {
- rb_eof_error();
- }
- return c;
-}
-
-static VALUE
-argf_eof()
-{
- int first = first_p;
-
- if (!next_argv()) return Qtrue;
- if (next_p == 1) {
- return Qtrue;
- }
- if (TYPE(current_file) != T_FILE) {
- return argf_forward();
- }
- if (rb_io_eof(current_file)) {
- next_p = 1;
- return Qtrue;
- }
- return Qfalse;
-}
-
-static VALUE
-argf_each_line(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE str;
-
- while (RTEST(str = argf_getline(argc, argv))) {
- rb_yield(str);
- }
- return argf;
-}
-
-static VALUE
-argf_each_byte()
-{
- VALUE byte;
-
- while (!NIL_P(byte = argf_getc())) {
- rb_yield(byte);
- }
- return Qnil;
-}
-
-static VALUE
-argf_filename()
-{
- return filename;
-}
-
-static VALUE
-argf_file()
-{
- return current_file;
-}
-
-static VALUE
-argf_skip()
-{
- if (next_p != -1) {
- any_close(current_file);
- next_p = 1;
- }
- return argf;
-}
-
-static VALUE
-argf_close()
-{
- any_close(current_file);
- if (next_p != -1) {
- next_p = 1;
- }
- gets_lineno = 0;
- return argf;
-}
-
-static VALUE
-argf_closed()
-{
- if (TYPE(current_file) != T_FILE) {
- return argf_forward();
- }
- return rb_io_closed(current_file);
-}
-
-static VALUE
-opt_i_get()
-{
- if (!ruby_inplace_mode) return Qnil;
- return rb_str_new2(ruby_inplace_mode);
-}
-
-static void
-opt_i_set(val)
- VALUE val;
-{
- if (!RTEST(val)) {
- if (ruby_inplace_mode) free(ruby_inplace_mode);
- ruby_inplace_mode = 0;
- return;
- }
- StringValue(val);
- if (ruby_inplace_mode) free(ruby_inplace_mode);
- ruby_inplace_mode = 0;
- ruby_inplace_mode = strdup(RSTRING(val)->ptr);
-}
-
-void
-Init_IO()
-{
- rb_eIOError = rb_define_class("IOError", rb_eStandardError);
- rb_eEOFError = rb_define_class("EOFError", rb_eIOError);
-
- id_write = rb_intern("write");
-
- rb_define_global_function("syscall", rb_f_syscall, -1);
-
- rb_define_global_function("open", rb_f_open, -1);
- rb_define_global_function("printf", rb_f_printf, -1);
- rb_define_global_function("print", rb_f_print, -1);
- rb_define_global_function("putc", rb_f_putc, 1);
- rb_define_global_function("puts", rb_f_puts, -1);
- rb_define_global_function("gets", rb_f_gets, -1);
- rb_define_global_function("readline", rb_f_readline, -1);
- rb_define_global_function("getc", rb_f_getc, 0);
- rb_define_global_function("select", rb_f_select, -1);
-
- rb_define_global_function("readlines", rb_f_readlines, -1);
-
- rb_define_global_function("`", rb_f_backquote, 1);
-
- rb_define_global_function("p", rb_f_p, -1);
- rb_define_method(rb_mKernel, "display", rb_obj_display, -1);
-
- rb_cIO = rb_define_class("IO", rb_cObject);
- rb_include_module(rb_cIO, rb_mEnumerable);
-
- rb_define_singleton_method(rb_cIO, "allocate", rb_io_s_alloc, 0);
- rb_define_singleton_method(rb_cIO, "new", rb_io_s_new, -1);
- rb_define_singleton_method(rb_cIO, "open", rb_io_s_open, -1);
- rb_define_singleton_method(rb_cIO, "for_fd", rb_class_new_instance, -1);
- rb_define_singleton_method(rb_cIO, "popen", rb_io_s_popen, -1);
- rb_define_singleton_method(rb_cIO, "foreach", rb_io_s_foreach, -1);
- rb_define_singleton_method(rb_cIO, "readlines", rb_io_s_readlines, -1);
- rb_define_singleton_method(rb_cIO, "read", rb_io_s_read, -1);
- rb_define_singleton_method(rb_cIO, "select", rb_f_select, -1);
- rb_define_singleton_method(rb_cIO, "pipe", rb_io_s_pipe, 0);
-
- rb_define_method(rb_cIO, "initialize", rb_io_initialize, -1);
-
- rb_output_fs = Qnil;
- rb_define_hooked_variable("$,", &rb_output_fs, 0, rb_str_setter);
-
- rb_rs = rb_default_rs = rb_str_new2("\n");
- rb_output_rs = Qnil;
- rb_global_variable(&rb_default_rs);
- OBJ_FREEZE(rb_default_rs); /* avoid modifying RS_default */
- rb_define_variable("$/", &rb_rs);
- rb_define_variable("$-0", &rb_rs);
- rb_define_variable("$\\", &rb_output_rs);
-
- rb_define_hooked_variable("$.", &lineno, 0, lineno_setter);
- rb_define_virtual_variable("$_", rb_lastline_get, rb_lastline_set);
-
- rb_define_method(rb_cIO, "clone", rb_io_clone, 0);
- rb_define_method(rb_cIO, "reopen", rb_io_reopen, -1);
-
- rb_define_method(rb_cIO, "print", rb_io_print, -1);
- rb_define_method(rb_cIO, "putc", rb_io_putc, 1);
- rb_define_method(rb_cIO, "puts", rb_io_puts, -1);
- rb_define_method(rb_cIO, "printf", rb_io_printf, -1);
-
- rb_define_method(rb_cIO, "each", rb_io_each_line, -1);
- rb_define_method(rb_cIO, "each_line", rb_io_each_line, -1);
- rb_define_method(rb_cIO, "each_byte", rb_io_each_byte, 0);
-
- rb_define_method(rb_cIO, "syswrite", rb_io_syswrite, 1);
- rb_define_method(rb_cIO, "sysread", rb_io_sysread, 1);
-
- rb_define_method(rb_cIO, "fileno", rb_io_fileno, 0);
- rb_define_alias(rb_cIO, "to_i", "fileno");
- rb_define_method(rb_cIO, "to_io", rb_io_to_io, 0);
-
- rb_define_method(rb_cIO, "fsync", rb_io_fsync, 0);
- rb_define_method(rb_cIO, "sync", rb_io_sync, 0);
- rb_define_method(rb_cIO, "sync=", rb_io_set_sync, 1);
-
- rb_define_method(rb_cIO, "lineno", rb_io_lineno, 0);
- rb_define_method(rb_cIO, "lineno=", rb_io_set_lineno, 1);
-
- rb_define_method(rb_cIO, "readlines", rb_io_readlines, -1);
-
- rb_define_method(rb_cIO, "read", io_read, -1);
- rb_define_method(rb_cIO, "write", io_write, 1);
- rb_define_method(rb_cIO, "gets", rb_io_gets_m, -1);
- rb_define_method(rb_cIO, "readline", rb_io_readline, -1);
- rb_define_method(rb_cIO, "getc", rb_io_getc, 0);
- rb_define_method(rb_cIO, "readchar", rb_io_readchar, 0);
- rb_define_method(rb_cIO, "ungetc",rb_io_ungetc, 1);
- rb_define_method(rb_cIO, "<<", rb_io_addstr, 1);
- rb_define_method(rb_cIO, "flush", rb_io_flush, 0);
- rb_define_method(rb_cIO, "tell", rb_io_tell, 0);
- rb_define_method(rb_cIO, "seek", rb_io_seek_m, -1);
- rb_define_const(rb_cIO, "SEEK_SET", INT2FIX(SEEK_SET));
- rb_define_const(rb_cIO, "SEEK_CUR", INT2FIX(SEEK_CUR));
- rb_define_const(rb_cIO, "SEEK_END", INT2FIX(SEEK_END));
- rb_define_method(rb_cIO, "rewind", rb_io_rewind, 0);
- rb_define_method(rb_cIO, "pos", rb_io_tell, 0);
- rb_define_method(rb_cIO, "pos=", rb_io_set_pos, 1);
- rb_define_method(rb_cIO, "eof", rb_io_eof, 0);
- rb_define_method(rb_cIO, "eof?", rb_io_eof, 0);
-
- rb_define_method(rb_cIO, "close", rb_io_close_m, 0);
- rb_define_method(rb_cIO, "closed?", rb_io_closed, 0);
- rb_define_method(rb_cIO, "close_read", rb_io_close_read, 0);
- rb_define_method(rb_cIO, "close_write", rb_io_close_write, 0);
-
- rb_define_method(rb_cIO, "isatty", rb_io_isatty, 0);
- rb_define_method(rb_cIO, "tty?", rb_io_isatty, 0);
- rb_define_method(rb_cIO, "binmode", rb_io_binmode, 0);
-
- rb_define_method(rb_cIO, "ioctl", rb_io_ioctl, -1);
- rb_define_method(rb_cIO, "fcntl", rb_io_fcntl, -1);
- rb_define_method(rb_cIO, "pid", rb_io_pid, 0);
- rb_define_method(rb_cIO, "inspect", rb_io_inspect, 0);
-
- rb_stdin = orig_stdin = prep_stdio(stdin, FMODE_READABLE, rb_cIO);
- rb_define_hooked_variable("$stdin", &rb_stdin, 0, set_stdin);
- rb_stdout = orig_stdout = prep_stdio(stdout, FMODE_WRITABLE, rb_cIO);
- rb_define_hooked_variable("$stdout", &rb_stdout, 0, set_stdout);
- rb_stderr = orig_stderr = prep_stdio(stderr, FMODE_WRITABLE, rb_cIO);
- rb_define_hooked_variable("$stderr", &rb_stderr, 0, set_stderr);
- rb_defout = rb_stdout;
- rb_define_hooked_variable("$>", &rb_defout, 0, rb_io_defset);
- rb_define_hooked_variable("$defout", &rb_defout, 0, rb_io_defset);
-
- rb_define_global_const("STDIN", rb_stdin);
- rb_define_global_const("STDOUT", rb_stdout);
- rb_define_global_const("STDERR", rb_stderr);
-
- argf = rb_obj_alloc(rb_cObject);
- rb_extend_object(argf, rb_mEnumerable);
-
- rb_define_readonly_variable("$<", &argf);
- rb_define_global_const("ARGF", argf);
-
- rb_define_singleton_method(argf, "fileno", argf_fileno, 0);
- rb_define_singleton_method(argf, "to_i", argf_fileno, 0);
- rb_define_singleton_method(argf, "to_io", argf_to_io, 0);
- rb_define_singleton_method(argf, "each", argf_each_line, -1);
- rb_define_singleton_method(argf, "each_line", argf_each_line, -1);
- rb_define_singleton_method(argf, "each_byte", argf_each_byte, 0);
-
- rb_define_singleton_method(argf, "read", argf_read, -1);
- rb_define_singleton_method(argf, "readlines", rb_f_readlines, -1);
- rb_define_singleton_method(argf, "to_a", rb_f_readlines, -1);
- rb_define_singleton_method(argf, "gets", rb_f_gets, -1);
- rb_define_singleton_method(argf, "readline", rb_f_readline, -1);
- rb_define_singleton_method(argf, "getc", argf_getc, 0);
- rb_define_singleton_method(argf, "readchar", argf_readchar, 0);
- rb_define_singleton_method(argf, "tell", argf_tell, 0);
- rb_define_singleton_method(argf, "seek", argf_seek_m, -1);
- rb_define_singleton_method(argf, "rewind", argf_rewind, 0);
- rb_define_singleton_method(argf, "pos", argf_tell, 0);
- rb_define_singleton_method(argf, "pos=", argf_set_pos, 1);
- rb_define_singleton_method(argf, "eof", argf_eof, 0);
- rb_define_singleton_method(argf, "eof?", argf_eof, 0);
- rb_define_singleton_method(argf, "binmode", argf_binmode, 0);
-
- rb_define_singleton_method(argf, "to_s", argf_filename, 0);
- rb_define_singleton_method(argf, "filename", argf_filename, 0);
- rb_define_singleton_method(argf, "file", argf_file, 0);
- rb_define_singleton_method(argf, "skip", argf_skip, 0);
- rb_define_singleton_method(argf, "close", argf_close, 0);
- rb_define_singleton_method(argf, "closed?", argf_closed, 0);
-
- rb_define_singleton_method(argf, "lineno", argf_lineno, 0);
- rb_define_singleton_method(argf, "lineno=", argf_set_lineno, 1);
-
- current_file = rb_stdin;
- rb_global_variable(&current_file);
- filename = rb_str_new2("-");
- rb_define_readonly_variable("$FILENAME", &filename);
-
- rb_define_virtual_variable("$-i", opt_i_get, opt_i_set);
-
-#if defined (NT) || defined(DJGPP) || defined(__CYGWIN__) || defined(__human68k__)
- atexit(pipe_atexit);
-#endif
-
- Init_File();
-
- rb_define_method(rb_cFile, "initialize", rb_file_initialize, -1);
-
- rb_file_const("RDONLY", INT2FIX(O_RDONLY));
- rb_file_const("WRONLY", INT2FIX(O_WRONLY));
- rb_file_const("RDWR", INT2FIX(O_RDWR));
- rb_file_const("APPEND", INT2FIX(O_APPEND));
- rb_file_const("CREAT", INT2FIX(O_CREAT));
- rb_file_const("EXCL", INT2FIX(O_EXCL));
-#if defined(O_NDELAY) || defined(O_NONBLOCK)
-# ifdef O_NONBLOCK
- rb_file_const("NONBLOCK", INT2FIX(O_NONBLOCK));
-# else
- rb_file_const("NONBLOCK", INT2FIX(O_NDELAY));
-# endif
-#endif
- rb_file_const("TRUNC", INT2FIX(O_TRUNC));
-#ifdef O_NOCTTY
- rb_file_const("NOCTTY", INT2FIX(O_NOCTTY));
-#endif
-#ifdef O_BINARY
- rb_file_const("BINARY", INT2FIX(O_BINARY));
-#endif
-#ifdef O_SYNC
- rb_file_const("SYNC", INT2FIX(O_SYNC));
-#endif
-}
diff --git a/keywords b/keywords
deleted file mode 100644
index 6ba1be49fd..0000000000
--- a/keywords
+++ /dev/null
@@ -1,42 +0,0 @@
-struct kwtable {char *name; int id[2]; enum lex_state state;};
-%%
-__LINE__, k__LINE__, k__LINE__, EXPR_END
-__FILE__, k__FILE__, k__FILE__, EXPR_END
-BEGIN, klBEGIN, klBEGIN, EXPR_END
-END, klEND, klEND, EXPR_END
-alias, kALIAS, kALIAS, EXPR_FNAME
-and, kAND, kAND, EXPR_BEG
-begin, kBEGIN, kBEGIN, EXPR_BEG
-break, kBREAK, kBREAK, EXPR_MID
-case, kCASE, kCASE, EXPR_BEG
-class, kCLASS, kCLASS, EXPR_CLASS
-def, kDEF, kDEF, EXPR_FNAME
-defined?, kDEFINED, kDEFINED, EXPR_ARG
-do, kDO, kDO, EXPR_BEG
-else, kELSE, kELSE, EXPR_BEG
-elsif, kELSIF, kELSIF, EXPR_BEG
-end, kEND, kEND, EXPR_END
-ensure, kENSURE, kENSURE, EXPR_BEG
-false, kFALSE, kFALSE, EXPR_END
-for, kFOR, kFOR, EXPR_BEG
-if, kIF, kIF_MOD, EXPR_BEG
-in, kIN, kIN, EXPR_BEG
-module, kMODULE, kMODULE, EXPR_BEG
-next, kNEXT, kNEXT, EXPR_MID
-nil, kNIL, kNIL, EXPR_END
-not, kNOT, kNOT, EXPR_BEG
-or, kOR, kOR, EXPR_BEG
-redo, kREDO, kREDO, EXPR_END
-rescue, kRESCUE, kRESCUE_MOD, EXPR_MID
-retry, kRETRY, kRETRY, EXPR_END
-return, kRETURN, kRETURN, EXPR_MID
-self, kSELF, kSELF, EXPR_END
-super, kSUPER, kSUPER, EXPR_ARG
-then, kTHEN, kTHEN, EXPR_BEG
-true, kTRUE, kTRUE, EXPR_END
-undef, kUNDEF, kUNDEF, EXPR_FNAME
-unless, kUNLESS, kUNLESS_MOD, EXPR_BEG
-until, kUNTIL, kUNTIL_MOD, EXPR_BEG
-when, kWHEN, kWHEN, EXPR_BEG
-while, kWHILE, kWHILE_MOD, EXPR_BEG
-yield, kYIELD, kYIELD, EXPR_ARG
diff --git a/lex.c b/lex.c
deleted file mode 100644
index 979246f047..0000000000
--- a/lex.c
+++ /dev/null
@@ -1,137 +0,0 @@
-/* C code produced by gperf version 2.7.2 */
-/* Command-line: gperf -p -j1 -i 1 -g -o -t -N rb_reserved_word -k'1,3,$' ./keywords */
-struct kwtable {char *name; int id[2]; enum lex_state state;};
-
-#define TOTAL_KEYWORDS 40
-#define MIN_WORD_LENGTH 2
-#define MAX_WORD_LENGTH 8
-#define MIN_HASH_VALUE 6
-#define MAX_HASH_VALUE 55
-/* maximum key range = 50, duplicates = 0 */
-
-#ifdef __GNUC__
-__inline
-#else
-#ifdef __cplusplus
-inline
-#endif
-#endif
-static unsigned int
-hash (str, len)
- register const char *str;
- register unsigned int len;
-{
- static unsigned char asso_values[] =
- {
- 56, 56, 56, 56, 56, 56, 56, 56, 56, 56,
- 56, 56, 56, 56, 56, 56, 56, 56, 56, 56,
- 56, 56, 56, 56, 56, 56, 56, 56, 56, 56,
- 56, 56, 56, 56, 56, 56, 56, 56, 56, 56,
- 56, 56, 56, 56, 56, 56, 56, 56, 56, 56,
- 56, 56, 56, 56, 56, 56, 56, 56, 56, 56,
- 56, 56, 56, 11, 56, 56, 36, 56, 1, 37,
- 31, 1, 56, 56, 56, 56, 29, 56, 1, 56,
- 56, 56, 56, 56, 56, 56, 56, 56, 56, 56,
- 56, 56, 56, 56, 56, 1, 56, 32, 1, 2,
- 1, 1, 4, 23, 56, 17, 56, 20, 9, 2,
- 9, 26, 14, 56, 5, 1, 1, 16, 56, 21,
- 20, 9, 56, 56, 56, 56, 56, 56, 56, 56,
- 56, 56, 56, 56, 56, 56, 56, 56, 56, 56,
- 56, 56, 56, 56, 56, 56, 56, 56, 56, 56,
- 56, 56, 56, 56, 56, 56, 56, 56, 56, 56,
- 56, 56, 56, 56, 56, 56, 56, 56, 56, 56,
- 56, 56, 56, 56, 56, 56, 56, 56, 56, 56,
- 56, 56, 56, 56, 56, 56, 56, 56, 56, 56,
- 56, 56, 56, 56, 56, 56, 56, 56, 56, 56,
- 56, 56, 56, 56, 56, 56, 56, 56, 56, 56,
- 56, 56, 56, 56, 56, 56, 56, 56, 56, 56,
- 56, 56, 56, 56, 56, 56, 56, 56, 56, 56,
- 56, 56, 56, 56, 56, 56, 56, 56, 56, 56,
- 56, 56, 56, 56, 56, 56, 56, 56, 56, 56,
- 56, 56, 56, 56, 56, 56
- };
- register int hval = len;
-
- switch (hval)
- {
- default:
- case 3:
- hval += asso_values[(unsigned char)str[2]];
- case 2:
- case 1:
- hval += asso_values[(unsigned char)str[0]];
- break;
- }
- return hval + asso_values[(unsigned char)str[len - 1]];
-}
-
-static
-#ifdef __GNUC__
-__inline
-#endif
-struct kwtable *
-rb_reserved_word (str, len)
- register const char *str;
- register unsigned int len;
-{
- static struct kwtable wordlist[] =
- {
- {""}, {""}, {""}, {""}, {""}, {""},
- {"end", kEND, kEND, EXPR_END},
- {"else", kELSE, kELSE, EXPR_BEG},
- {"case", kCASE, kCASE, EXPR_BEG},
- {"ensure", kENSURE, kENSURE, EXPR_BEG},
- {"module", kMODULE, kMODULE, EXPR_BEG},
- {"elsif", kELSIF, kELSIF, EXPR_BEG},
- {"def", kDEF, kDEF, EXPR_FNAME},
- {"rescue", kRESCUE, kRESCUE_MOD, EXPR_MID},
- {"not", kNOT, kNOT, EXPR_BEG},
- {"then", kTHEN, kTHEN, EXPR_BEG},
- {"yield", kYIELD, kYIELD, EXPR_ARG},
- {"for", kFOR, kFOR, EXPR_BEG},
- {"self", kSELF, kSELF, EXPR_END},
- {"false", kFALSE, kFALSE, EXPR_END},
- {"retry", kRETRY, kRETRY, EXPR_END},
- {"return", kRETURN, kRETURN, EXPR_MID},
- {"true", kTRUE, kTRUE, EXPR_END},
- {"if", kIF, kIF_MOD, EXPR_BEG},
- {"defined?", kDEFINED, kDEFINED, EXPR_ARG},
- {"super", kSUPER, kSUPER, EXPR_ARG},
- {"undef", kUNDEF, kUNDEF, EXPR_FNAME},
- {"break", kBREAK, kBREAK, EXPR_MID},
- {"in", kIN, kIN, EXPR_BEG},
- {"do", kDO, kDO, EXPR_BEG},
- {"nil", kNIL, kNIL, EXPR_END},
- {"until", kUNTIL, kUNTIL_MOD, EXPR_BEG},
- {"unless", kUNLESS, kUNLESS_MOD, EXPR_BEG},
- {"or", kOR, kOR, EXPR_BEG},
- {"next", kNEXT, kNEXT, EXPR_MID},
- {"when", kWHEN, kWHEN, EXPR_BEG},
- {"redo", kREDO, kREDO, EXPR_END},
- {"and", kAND, kAND, EXPR_BEG},
- {"begin", kBEGIN, kBEGIN, EXPR_BEG},
- {"__LINE__", k__LINE__, k__LINE__, EXPR_END},
- {"class", kCLASS, kCLASS, EXPR_CLASS},
- {"__FILE__", k__FILE__, k__FILE__, EXPR_END},
- {"END", klEND, klEND, EXPR_END},
- {"BEGIN", klBEGIN, klBEGIN, EXPR_END},
- {"while", kWHILE, kWHILE_MOD, EXPR_BEG},
- {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""},
- {""},
- {"alias", kALIAS, kALIAS, EXPR_FNAME}
- };
-
- if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)
- {
- register int key = hash (str, len);
-
- if (key <= MAX_HASH_VALUE && key >= 0)
- {
- register const char *s = wordlist[key].name;
-
- if (*str == *s && !strcmp (str + 1, s + 1))
- return &wordlist[key];
- }
- }
- return 0;
-}
diff --git a/lib/English.rb b/lib/English.rb
deleted file mode 100644
index 625b035270..0000000000
--- a/lib/English.rb
+++ /dev/null
@@ -1,27 +0,0 @@
-alias $ERROR_INFO $!
-alias $ERROR_POSITION $@
-alias $LOADED_FEATURES $"
-alias $FS $;
-alias $FIELD_SEPARATOR $;
-alias $OFS $,
-alias $OUTPUT_FIELD_SEPARATOR $,
-alias $RS $/
-alias $INPUT_RECORD_SEPARATOR $/
-alias $ORS $\
-alias $OUTPUT_RECORD_SEPARATOR $\
-alias $INPUT_LINE_NUMBER $.
-alias $NR $.
-alias $LAST_READ_LINE $_
-alias $DEFAULT_OUTPUT $>
-alias $DEFAULT_INPUT $<
-alias $PID $$
-alias $PROCESS_ID $$
-alias $CHILD_STATUS $?
-alias $LAST_MATCH_INFO $~
-alias $IGNORECASE $=
-alias $PROGRAM_NAME $0
-alias $ARGV $*
-alias $MATCH $&
-alias $PREMATCH $`
-alias $POSTMATCH $'
-alias $LAST_PAREN_MATCH $+
diff --git a/lib/Env.rb b/lib/Env.rb
deleted file mode 100644
index 452a28659e..0000000000
--- a/lib/Env.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-# Env.rb -- imports environment variables as global variables, Perlish ;(
-# Usage:
-#
-# require 'Env'
-# p $USER
-# $USER = "matz"
-# p ENV["USER"]
-
-require 'importenv'
-
-if __FILE__ == $0
- p $TERM
- $TERM = nil
- p $TERM
- p ENV["TERM"]
- $TERM = "foo"
- p ENV["TERM"]
-end
diff --git a/lib/README b/lib/README
deleted file mode 100644
index d05964fa67..0000000000
--- a/lib/README
+++ /dev/null
@@ -1,72 +0,0 @@
-English.rb lets Perl'ish global variables have English names
-Env.rb loads importenv.rb
-README this file
-base64.rb encodes/decodes base64 (obsolete)
-benchmark.rb a benchmark utility
-cgi-lib.rb simple CGI support library (old style)
-cgi.rb CGI support library
-cgi/session CGI session class
-complex.rb complex number suppor
-date.rb date object
-date2.rb date object (obsolete; use date)
-debug.rb ruby debugger
-delegate.rb delegates messages to other object
-e2mmap.rb exception utilities
-eregex.rb extended regular expression (just a proof of concept)
-final.rb adds finalizer to the object (simple)
-finalize.rb adds finalizer to the object
-find.rb traverses directory tree
-forwardable.rb explicit delegation library
-ftools.rb file tools
-ftplib.rb obsolete - use net/ftp
-getoptlong.rb GNU getoptlong compatible
-getopts.rb parses command line options (use getoptlong)
-importenv.rb imports environment variables as global variables
-irb.rb interactive ruby
-jcode.rb Japanese text handling (replace String methods)
-mailread.rb reads mail headers
-mathn.rb extended math operation
-matrix.rb matrix calculation library
-mkmf.rb Makefile maker
-monitor.rb exclusive region monitor for thread
-mutex_m.rb mutex mixin
-net/ftp.rb ftp access
-net/http.rb HTTP access
-net/imap.rb IMAP4 access
-net/pop.rb POP3 access
-net/protocol.rb abstract class for net library
-net/smtp.rb SMTP access
-net/telnet.rb telnet library
-observer.rb observer desing pattern library (provides Observable)
-open3.rb opens subprocess connection stdin/stdout/stderr
-ostruct.rb python style object
-parsearg.rb argument parser using getopts
-parsedate.rb parses date string
-ping.rb checks whether host is up, using TCP echo.
-pp.rb pretty print objects
-prettyprint.rb pretty printing algorithm
-profile.rb ruby profiler
-pstore.rb persistent object strage using marshal
-rational.rb rational number support
-readbytes.rb define IO#readbytes
-resolv.rb DNS resolver in Ruby
-resolv-replace.rb replace Socket DNS by resolve.rb
-shell.rb runs commands and does pipeline operations like shell
-shellwords.rb split into words like shell
-singleton.rb singleton design pattern library
-sync.rb 2 phase lock
-telnet.rb obsolete - use net/telnet
-tempfile.rb temporary file with automatic removal
-time.rb RFC2822, RFC2616, ISO8601 style time formatting/parsing
-thread.rb thread support
-thwait.rb thread syncronization class
-timeout.rb provides timeout
-tracer.rb execution tracer
-tsort.rb topological sorting
-uri.rb URI support
-uri/ftp.rb ftp scheme support
-uri/http.rb http scheme support
-uri/https.rb https scheme support
-uri/ldap.rb ldap scheme support
-uri/mailto.rb mailto scheme support
-weakref.rb weak reference class
diff --git a/lib/base64.rb b/lib/base64.rb
deleted file mode 100644
index d7461d82e7..0000000000
--- a/lib/base64.rb
+++ /dev/null
@@ -1,29 +0,0 @@
-require "kconv"
-
-def decode64(str)
- str.unpack("m")[0]
-end
-
-def decode_b(str)
- str.gsub!(/=\?ISO-2022-JP\?B\?([!->@-~]+)\?=/i) {
- decode64($1)
- }
- str = Kconv::toeuc(str)
- str.gsub!(/=\?SHIFT_JIS\?B\?([!->@-~]+)\?=/i) {
- decode64($1)
- }
- str = Kconv::toeuc(str)
- str.gsub!(/\n/, ' ')
- str.gsub!(/\0/, '')
- str
-end
-
-def encode64(bin)
- [bin].pack("m")
-end
-
-def b64encode(bin, len = 60)
- encode64(bin).scan(/.{1,#{len}}/o) do
- print $&, "\n"
- end
-end
diff --git a/lib/benchmark.rb b/lib/benchmark.rb
deleted file mode 100644
index e6c63a7c14..0000000000
--- a/lib/benchmark.rb
+++ /dev/null
@@ -1,651 +0,0 @@
-#
-# benchmark.rb
-#
-=begin
- 2001-11-26: Time.times renamed Process.times for ruby17 (gotoken#notwork.org)
- 2001-01-12: made bmbm module func. bmbm return Tms array.
- 2001-01-10: added bmbm, Job and INSTALL.rb (gotoken#notwork.org)
- 2000-04-00: report() prints tag before eval block (gotoken#notwork.org)
- 2000-02-22: report(): measure -> Benchmark::measure (nakahiro#sarion.co.jp)
- 2000-01-02: bug fix, documentation (gotoken#notwork.org)
- 2000-01-01: measure can take a tag as opt. (nobu.nakada#nifty.ne.jp)
- 2000-01-01: first release (gotoken#notwork.org)
-=end
-
-=begin
-= benchmark.rb
-
-== NAME
-((*benchmark.rb*)) - a benchmark utility
-
-== SYNOPSIS
- ----------
- require "benchmark"
- include Benchmark
- ----------
-
-== DESCRIPTION
-
-benchmark.rb provides some utilities to measure and report the
-times used and passed to execute.
-
-== SIMPLE EXAMPLE
-
-=== EXAMPLE 0
-To ((<measure>)) the times to make (({"a"*1_000_000})):
-
- ----------
- puts measure{ "a"*1_000_000 }
- ----------
-
-On my machine (FreeBSD 3.2 on P5100MHz) this reported as follows:
-
- ----------
- 1.166667 0.050000 1.216667 ( 0.571355)
- ----------
-
-The above shows user time, system time, user+system, and really passed
-time. The unit of time is second.
-
-=== EXAMPLE 1
-To do some experiments sequentially, ((<bm>)) is useful:
-
- ----------
- n = 50000
- bm do |x|
- x.report{for i in 1..n; a = "1"; end}
- x.report{n.times do ; a = "1"; end}
- x.report{1.upto(n) do ; a = "1"; end}
- end
- ----------
-
-The result:
- ----------
- user system total real
- 1.033333 0.016667 1.016667 ( 0.492106)
- 1.483333 0.000000 1.483333 ( 0.694605)
- 1.516667 0.000000 1.516667 ( 0.711077)
- ----------
-
-=== EXAMPLE 2
-To put a label in each ((<report>)):
-
- ----------
- n = 50000
- bm(7) do |x|
- x.report("for:") {for i in 1..n; a = "1"; end}
- x.report("times:") {n.times do ; a = "1"; end}
- x.report("upto:") {1.upto(n) do ; a = "1"; end}
- end
- ----------
-
-The option (({7})) specifies the offset of each report accoding to the
-longest label.
-
-This reports as follows:
-
- ----------
- user system total real
- for: 1.050000 0.000000 1.050000 ( 0.503462)
- times: 1.533333 0.016667 1.550000 ( 0.735473)
- upto: 1.500000 0.016667 1.516667 ( 0.711239)
- ----------
-
-=== EXAMPLE 3
-
-By the way, benchmarks might seem to depend on the order of items. It
-is caused by the cost of memory allocation and the garbage collection.
-To prevent this boresome, Benchmark::((<bmbm>)) is provided, e.g., to
-compare ways for sort array of strings:
-
- ----------
- require "rbconfig"
- include Config
- def file
- open("%s/lib/ruby/%s.%s/tk.rb" %
- [CONFIG['prefix'],CONFIG['MAJOR'],CONFIG['MINOR']]).read
- end
-
- n = 10
- bmbm do |x|
- x.report("destructive!"){
- t = (file*n).to_a; t.each{|line| line.upcase!}; t.sort!
- }
- x.report("method chain"){
- t = (file*n).to_a.collect{|line| line.upcase}.sort
- }
- end
- ----------
-
-This reports:
-
- ----------
- Rehearsal ------------------------------------------------
- destructive! 2.664062 0.070312 2.734375 ( 2.783401)
- method chain 5.257812 0.156250 5.414062 ( 5.736088)
- --------------------------------------- total: 8.148438sec
-
- user system total real
- destructive! 2.359375 0.007812 2.367188 ( 2.381015)
- method chain 3.046875 0.023438 3.070312 ( 3.085816)
- ----------
-
-=== EXAMPLE 4
-To report statistics of sequential experiments with unique label,
-((<benchmark>)) is available:
-
- ----------
- n = 50000
- benchmark(" "*7 + CAPTION, 7, FMTSTR, ">total:", ">avg:") do |x|
- tf = x.report("for:") {for i in 1..n; a = "1"; end}
- tt = x.report("times:"){n.times do ; a = "1"; end}
- tu = x.report("upto:") {1.upto(n) do ; a = "1"; end}
- [tf+tt+tu, (tf+tt+tu)/3]
- end
- ----------
-
-The result:
-
- ----------
- user system total real
- for: 1.016667 0.016667 1.033333 ( 0.485749)
- times: 1.450000 0.016667 1.466667 ( 0.681367)
- upto: 1.533333 0.000000 1.533333 ( 0.722166)
- >total: 4.000000 0.033333 4.033333 ( 1.889282)
- >avg: 1.333333 0.011111 1.344444 ( 0.629761)
- ----------
-
-== Benchmark module
-
-=== CONSTANT
-:CAPTION
- CAPTION is a caption string which is used in Benchmark::((<benchmark>)) and
- Benchmark::Report#((<report>)).
-:FMTSTR
- FMTSTR is a format string which is used in Benchmark::((<benchmark>)) and
- Benchmark::Report#((<report>)). See also Benchmark::Tms#((<format>)).
-:BENCHMARK_VERSION
- BENCHMARK_VERSION is version string which statnds for the last modification
- date (YYYY-MM-DD).
-
-=== INNER CLASS
-* ((<Benchmark::Job>))
-* ((<Benchmark::Report>))
-* ((<Benchmark::Tms>))
-
-=== MODULE FUNCTION
-==== benchmark
- ----------
- benchmark([caption [, label_width [, fmtstr]]]) do |x| ... end
- benchmark([caption [, label_width [, fmtstr]]]) do array_of_Tms end
- benchmark([caption [, label_width [, fmtstr [, labels...]]]]) do
- ...
- array_of_Tms
- end
- ----------
-
-(({benchmark})) reports the times. In the first form the block variable x is
-treated as a ((<Benchmark::Report>)) object, which has ((<report>)) method.
-In the second form, each member of array_of_Tms is reported in the
-specified form if the member is a ((<Benchmark::Tms>)) object. The
-last form provides combined above two forms (See ((<EXAMPLE 3>))).
-
-The following lists the meaning of each option.
-
-:caption
- A string ((|caption|)) is printed once before execution of the given block.
-
-:label_width
- An integer ((|label_width|)) is used as an offset in each report.
-
-:fmtstr
- An string ((|fmtstr|)) is used to format each measurement.
- See ((<format>))
-
-:labels
- The rest parameters labels is used as prefix of the format to the
- value of block, that is array_of_Tms.
-
-==== bm
- ----------
- bm([label_width [, labels ...]) do ... end
- ----------
-
-(({bm})) is a simpler interface of ((<benchmark>)).
-(({bm})) acts as same as follows:
-
- benchmark(" "*label_width + CAPTION, label_width, FMTSTR, *labels) do
- ...
- end
-
-==== bmbm
- ----------
- bmbm([label_width]) do |x|
- x.item("label1") { .... }
- ....
- end
- ----------
-
-(({bmbm})) is yet another ((<benchmark>)). This utility function is
-provited to prevent a kind of job order dependency, which is caused
-by memory allocation and object creation. The usage is similar to
-((<bm>)) but has less options and does extra three things:
-
- (1) ((*Rehearsal*)): runs all items in the job ((<list>)) to allocate
- enough memory.
- (2) ((*GC*)): before each ((<measure>))ment, invokes (({GC.start})) to
- prevent the influence of previous job.
- (3) If given ((|label_width|)) is less than the maximal width of labels
- given as ((|item|))'s argument, the latter is used.
- Because (({bmbm})) is a 2-pass procedure, this is possible.
-
-(({bmbm})) returns an array which consists of Tms correspoding to each
-(({item})).
-==== measure
- ----------
- measure([label]) do ... end
- ----------
-
-measure returns the times used and passed to execute the given block as a
-Benchmark::Tms object.
-
-==== realtime
- ----------
- realtime do ... end
- ----------
-
-realtime returns the times passed to execute the given block.
-
-== Benchmark::Report
-
-=== CLASS METHOD
-
-==== Benchmark::Report::new(width)
- ----------
- Benchmark::Report::new([width [, fmtstr]])
- ----------
-
-Usually, one doesn't have to use this method directly,
-(({Benchmark::Report::new})) is called by ((<benchmark>)) or ((<bm>)).
-((|width|)) and ((|fmtstr|)) are the offset of ((|label|)) and
-format string responsively; Both of them are used in ((<format>)).
-
-=== METHOD
-
-==== report
-
- ----------
- report(fmt, *args)
- ----------
-
-This method reports label and time formated by ((|fmt|)). See
-((<format>)) of Benchmark::Tms for formatting rule.
-
-== Benchmark::Tms
-
-=== CLASS METHOD
-
-== Benchmark::Job
-
-=== CLASS METHOD
-
-==== Benchmark::Job::new
- ----------
- Benchmark::Job::new(width)
- ----------
-
-Usually, one doesn't have to use this method directly,
-(({Benchmark::Job::new})) is called by ((<bmbm>)).
-((|width|)) is a initial value for the offset ((|label|)) for formatting.
-((<bmbm>)) passes its argument ((|width|)) to this constructor.
-
-=== METHOD
-
-==== item
- ----------
- item(((|lable|))){ .... }
- ----------
-
-(({item})) registers a pair of (((|label|))) and given block as job ((<list>)).
-==== width
-
-Maximum length of labels in ((<list>)) plus one.
-
-==== list
-
-array of array which consists of label and jop proc.
-
-==== report
-
-alias to ((<item>)).
-
-==== Benchmark::Tms::new
- ----------
- Benchmark::Tms::new([u [, s [, cu [, cs [, re [, l]]]]]])
- ----------
-
-returns new Benchmark::Tms object which has
-((|u|)) as ((<utime>)),
-((|s|)) as ((<stime>)),
-((|cu|)) as ((<cutime>))
-((|cs|)) as ((<cstime>)),
-((|re|)) as ((<real>)) and
-((|l|)) as ((<label>)).
-
-The default value is assumed as 0.0 for ((|u|)), ((|s|)), ((|cu|)),
-((|cs|)) and ((|re|)). The default of ((|l|)) is null string ((({""}))).
-
-==== operator +
- ----------
- tms1 + tms2
- ----------
-
-returns a new Benchmark::Tms object as memberwise summation.
-This method and ((<(('operator /'))>)) is useful to take statistics.
-
-==== operator /
- ----------
- tms / num
- ----------
-
-returns a new Benchmark::Tms object as memberwise division by ((|num|)).
-This method and ((<operator +>)) is useful to take statistics.
-
-==== add
- ----------
- add do ... end
- ----------
-
-returns a new Benchmark::Tms object which is the result of additional
-execution which is given by block.
-
-==== add!
- ----------
- add! do ... end
- ----------
-
-do additional execution which is given by block.
-
-==== format
- ----------
- format([fmtstr [, *args]])
- ----------
-
-(({format})) returns formatted string of (({self})) according to a
-((|fmtstr|)) like (({Kernel::format})). In addition, (({format})) accepts
-some extentions as follows:
- :%u
- ((<utime>)).
- :%y
- ((<stime>)). (Mnemonic: y of ``s((*y*))stem'')
- :%U
- ((<cutime>)).
- :%Y
- ((<cstime>)).
- :%t
- ((<total>)).
- :%r
- ((<real>)).
- :%n
- ((<label>)). (Mnemonic: n of ``((*n*))ame'')
-
-If fmtstr is not given ((<FMTSTR>)) is used as default value.
-
-==== utime
-
-returns user time.
-
-==== stime
-
-returns system time.
-
-==== cutime
-
-returns user time of children.
-
-==== cstime
-
-returns system time of children.
-
-==== total
-
-returns total time, that is
-((<utime>)) + ((<stime>)) + ((<cutime>)) + ((<cstime>)).
-
-==== real
-
-returns really passed time.
-
-==== label
-
-returns label.
-
-==== to_a
-
-returns a new array as follows
-
- [label, utime, stime, cutime, cstime, real]
-
-==== to_s
-
-same as (({format()})). See also ((<format>)).
-
-== HISTORY
-<<< benchmark.rb
-
-== AUTHOR
-
-Gotoken (gotoken@notwork.org).
-=end
-
-module Benchmark
- BENCHMARK_VERSION = "2001-11-26"
-
- def Benchmark::times()
- Process::times()
- end
-
- def benchmark(caption = "", label_width = nil, fmtstr = nil, *labels)
- sync = STDOUT.sync
- STDOUT.sync = true
- label_width ||= 0
- fmtstr ||= FMTSTR
- raise ArgumentError, "no block" unless iterator?
- print caption
- results = yield(Report.new(label_width, fmtstr))
- Array === results and results.grep(Tms).each {|t|
- print((labels.shift || t.label || "").ljust(label_width),
- t.format(fmtstr))
- }
- STDOUT.sync = sync
- end
-
- def bm(label_width = 0, *labels, &blk)
- benchmark(" "*label_width + CAPTION, label_width, FMTSTR, *labels, &blk)
- end
-
- def bmbm(width = 0, &blk)
- job = Job.new(width)
- yield(job)
- width = job.width
- sync = STDOUT.sync
- STDOUT.sync = true
-
- # rehearsal
- print "Rehearsal "
- puts '-'*(width+CAPTION.length - "Rehearsal ".length)
- list = []
- job.list.each{|label,item|
- print(label.ljust(width))
- res = Benchmark::measure(&item)
- print res.format(@fmtstr)
- list.push res
- }
- sum = Tms.new; list.each{|i| sum += i}
- ets = sum.format("total: %tsec")
- printf("%s %s\n\n",
- "-"*(width+CAPTION.length-ets.length-1), ets)
-
- # take
- print ' '*width, CAPTION
- list = []
- ary = []
- job.list.each{|label,item|
- GC::start
- print label.ljust(width)
- res = Benchmark::measure(&item)
- print res.format(@fmtstr)
- ary.push res
- list.push [label, res]
- }
-
- STDOUT.sync = sync
- ary
- end
-
- def measure(label = "")
- t0, r0 = Benchmark.times, Time.now
- yield
- t1, r1 = Benchmark.times, Time.now
- Benchmark::Tms.new(t1.utime - t0.utime,
- t1.stime - t0.stime,
- t1.cutime - t0.cutime,
- t1.cstime - t0.cstime,
- r1.to_f - r0.to_f,
- label)
- end
-
- def realtime(&blk)
- Benchmark::measure(&blk).real
- end
-
- class Job
- def initialize(width)
- @width = width
- @list = []
- end
-
- def item(label = "", &blk)
- raise ArgmentError, "no block" unless block_given?
- label.concat ' '
- w = label.length
- @width = w if @width < w
- @list.push [label, blk]
- self
- end
-
- alias report item
- attr_reader :list, :width
- end
-
- module_function :benchmark, :measure, :realtime, :bm, :bmbm
-
- class Report
- def initialize(width = 0, fmtstr = nil)
- @width, @fmtstr = width, fmtstr
- end
-
- def item(label = "", *fmt, &blk)
- print label.ljust(@width)
- res = Benchmark::measure(&blk)
- print res.format(@fmtstr, *fmt)
- res
- end
-
- alias report item
- end
-
- class Tms
- CAPTION = " user system total real\n"
- FMTSTR = "%10.6u %10.6y %10.6t %10.6r\n"
-
- attr_reader :utime, :stime, :cutime, :cstime, :real, :total, :label
-
- def initialize(u = 0.0, s = 0.0, cu = 0.0, cs = 0.0, real = 0.0, l = nil)
- @utime, @stime, @cutime, @cstime, @real, @label = u, s, cu, cs, real, l
- @total = @utime + @stime + @cutime + @cstime
- end
-
- def add(&blk)
- self + Benchmark::measure(&blk)
- end
-
- def add!
- t = Benchmark::measure(&blk)
- @utime = utime + t.utime
- @stime = stime + t.stime
- @cutime = cutime + t.cutime
- @cstime = cstime + t.cstime
- @real = real + t.real
- self
- end
-
- def +(x); memberwise(:+, x) end
- def -(x); memberwise(:-, x) end
- def *(x); memberwise(:*, x) end
- def /(x); memberwise(:/, x) end
-
- def format(arg0 = nil, *args)
- fmtstr = (arg0 || FMTSTR).dup
- fmtstr.gsub!(/(%[-+\.\d]*)n/){"#{$1}s" % label}
- fmtstr.gsub!(/(%[-+\.\d]*)u/){"#{$1}f" % utime}
- fmtstr.gsub!(/(%[-+\.\d]*)y/){"#{$1}f" % stime}
- fmtstr.gsub!(/(%[-+\.\d]*)U/){"#{$1}f" % cutime}
- fmtstr.gsub!(/(%[-+\.\d]*)Y/){"#{$1}f" % cstime}
- fmtstr.gsub!(/(%[-+\.\d]*)t/){"#{$1}f" % total}
- fmtstr.gsub!(/(%[-+\.\d]*)r/){"(#{$1}f)" % real}
- arg0 ? Kernel::format(fmtstr, *args) : fmtstr
- end
-
- def to_s
- format
- end
-
- def to_a
- [@label, @utime, @stime, @cutime, @cstime, @real]
- end
-
- protected
- def memberwise(op, x)
- case x
- when Benchmark::Tms
- Benchmark::Tms.new(utime.__send__(op, x.utime),
- stime.__send__(op, x.stime),
- cutime.__send__(op, x.cutime),
- cstime.__send__(op, x.cstime),
- real.__send__(op, x.real)
- )
- else
- Benchmark::Tms.new(utime.__send__(op, x),
- stime.__send__(op, x),
- cutime.__send__(op, x),
- cstime.__send__(op, x),
- real.__send__(op, x)
- )
- end
- end
- end
-
- CAPTION = Benchmark::Tms::CAPTION
- FMTSTR = Benchmark::Tms::FMTSTR
-end
-
-if __FILE__ == $0
- include Benchmark
-
- n = ARGV[0].to_i.nonzero? || 50000
- puts %Q([#{n} times iterations of `a = "1"'])
- benchmark(" " + CAPTION, 7, FMTSTR) do |x|
- x.report("for:") {for i in 1..n; a = "1"; end} # Benchmark::measure
- x.report("times:") {n.times do ; a = "1"; end}
- x.report("upto:") {1.upto(n) do ; a = "1"; end}
- end
-
- benchmark do
- [
- measure{for i in 1..n; a = "1"; end}, # Benchmark::measure
- measure{n.times do ; a = "1"; end},
- measure{1.upto(n) do ; a = "1"; end}
- ]
- end
-end
diff --git a/lib/cgi-lib.rb b/lib/cgi-lib.rb
deleted file mode 100644
index ffe3fcf367..0000000000
--- a/lib/cgi-lib.rb
+++ /dev/null
@@ -1,270 +0,0 @@
-=begin
-
-= simple CGI support library
-
-= example
-
-== get form values
-
- require "cgi-lib.rb"
- query = CGI.new
- query['field'] # <== value of 'field'
- query.keys # <== array of fields
-
-and query has Hash class methods
-
-
-== get cookie values
-
- require "cgi-lib.rb"
- query = CGI.new
- query.cookie['name'] # <== cookie value of 'name'
- query.cookie.keys # <== all cookie names
-
-and query.cookie has Hash class methods
-
-
-== print HTTP header and HTML string to $>
-
- require "cgi-lib.rb"
- CGI::print{
- CGI::tag("HTML"){
- CGI::tag("HEAD"){ CGI::tag("TITLE"){"TITLE"} } +
- CGI::tag("BODY"){
- CGI::tag("FORM", {"ACTION"=>"test.rb", "METHOD"=>"POST"}){
- CGI::tag("INPUT", {"TYPE"=>"submit", "VALUE"=>"submit"})
- } +
- CGI::tag("HR")
- }
- }
- }
-
-
-== make raw cookie string
-
- require "cgi-lib.rb"
- cookie1 = CGI::cookie({'name' => 'name',
- 'value' => 'value',
- 'path' => 'path', # optional
- 'domain' => 'domain', # optional
- 'expires' => Time.now, # optional
- 'secure' => true # optional
- })
-
- CGI::print("Content-Type: text/html", cookie1, cookie2){ "string" }
-
-
-== print HTTP header and string to $>
-
- require "cgi-lib.rb"
- CGI::print{ "string" }
- # == CGI::print("Content-Type: text/html"){ "string" }
- CGI::print("Content-Type: text/html", cookie1, cookie2){ "string" }
-
-
-=== NPH (no-parse-header) mode
-
- require "cgi-lib.rb"
- CGI::print("nph"){ "string" }
- # == CGI::print("nph", "Content-Type: text/html"){ "string" }
- CGI::print("nph", "Content-Type: text/html", cookie1, cookie2){ "string" }
-
-
-== make HTML tag string
-
- require "cgi-lib.rb"
- CGI::tag("element", {"attribute_name"=>"attribute_value"}){"content"}
-
-
-== make HTTP header string
-
- require "cgi-lib.rb"
- CGI::header # == CGI::header("Content-Type: text/html")
- CGI::header("Content-Type: text/html", cookie1, cookie2)
-
-
-=== NPH (no-parse-header) mode
-
- CGI::header("nph") # == CGI::header("nph", "Content-Type: text/html")
- CGI::header("nph", "Content-Type: text/html", cookie1, cookie2)
-
-
-== escape url encode
-
- require "cgi-lib.rb"
- url_encoded_string = CGI::escape("string")
-
-
-== unescape url encoded
-
- require "cgi-lib.rb"
- string = CGI::unescape("url encoded string")
-
-
-== escape HTML &"<>
-
- require "cgi-lib.rb"
- CGI::escapeHTML("string")
-
-
-=end
-
-require "delegate"
-
-class CGI < SimpleDelegator
-
- CR = "\015"
- LF = "\012"
- EOL = CR + LF
-
- RFC822_DAYS = %w[ Sun Mon Tue Wed Thu Fri Sat ]
- RFC822_MONTHS = %w[ Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ]
-
- # make rfc1123 date string
- def CGI::rfc1123_date(time)
- t = time.clone.gmtime
- return format("%s, %.2d %s %d %.2d:%.2d:%.2d GMT",
- RFC822_DAYS[t.wday], t.day, RFC822_MONTHS[t.month-1], t.year,
- t.hour, t.min, t.sec)
- end
-
- # escape url encode
- def CGI::escape(str)
- str.gsub(/[^a-zA-Z0-9_\-.]/n){ sprintf("%%%02X", $&.unpack("C")[0]) }
- end
-
- # unescape url encoded
- def CGI::unescape(str)
- str.gsub(/\+/, ' ').gsub(/%([0-9a-fA-F]{2})/){ [$1.hex].pack("c") }
- end
-
- # escape HTML
- def CGI::escapeHTML(str)
- str.gsub(/&/, "&amp;").gsub(/\"/, "&quot;").gsub(/>/, "&gt;").gsub(/</, "&lt;")
- end
-
- # offline mode. read name=value pairs on standard input.
- def read_from_cmdline
- require "shellwords.rb"
- words = Shellwords.shellwords(
- if not ARGV.empty?
- ARGV.join(' ')
- else
- STDERR.print "(offline mode: enter name=value pairs on standard input)\n" if STDIN.tty?
- readlines.join(' ').gsub(/\n/, '')
- end.gsub(/\\=/, '%3D').gsub(/\\&/, '%26'))
-
- if words.find{|x| x =~ /=/} then words.join('&') else words.join('+') end
- end
-
- def initialize(input = $stdin)
-
- @inputs = {}
- @cookie = {}
-
- case ENV['REQUEST_METHOD']
- when "GET"
- ENV['QUERY_STRING'] or ""
- when "POST"
- input.read(Integer(ENV['CONTENT_LENGTH'])) or ""
- else
- read_from_cmdline
- end.split(/[&;]/).each do |x|
- key, val = x.split(/=/,2).collect{|x|CGI::unescape(x)}
- if @inputs.include?(key)
- @inputs[key] += "\0" + (val or "")
- else
- @inputs[key] = (val or "")
- end
- end
-
- super(@inputs)
-
- if ENV.has_key?('HTTP_COOKIE') or ENV.has_key?('COOKIE')
- (ENV['HTTP_COOKIE'] or ENV['COOKIE']).split("; ").each do |x|
- key, val = x.split(/=/,2)
- key = CGI::unescape(key)
- val = val.split(/&/).collect{|x|CGI::unescape(x)}.join("\0")
- if @cookie.include?(key)
- @cookie[key] += "\0" + val
- else
- @cookie[key] = val
- end
- end
- end
- end
-
- attr("inputs")
- attr("cookie")
-
- # make HTML tag string
- def CGI::tag(element, attributes = {})
- "<" + escapeHTML(element) + attributes.collect{|name, value|
- " " + escapeHTML(name) + '="' + escapeHTML(value) + '"'
- }.to_s + ">" +
- (iterator? ? yield.to_s + "</" + escapeHTML(element) + ">" : "")
- end
-
- # make raw cookie string
- def CGI::cookie(options)
- "Set-Cookie: " + options['name'] + '=' + escape(options['value']) +
- (options['domain'] ? '; domain=' + options['domain'] : '') +
- (options['path'] ? '; path=' + options['path'] : '') +
- (options['expires'] ? '; expires=' + rfc1123_date(options['expires']) : '') +
- (options['secure'] ? '; secure' : '')
- end
-
- # make HTTP header string
- def CGI::header(*options)
- if ENV['MOD_RUBY']
- options.each{|option|
- option.sub(/(.*?): (.*)/){
- Apache::request[$1] = $2
- }
- }
- Apache::request.send_http_header
- ''
- else
- if options.delete("nph") or (ENV['SERVER_SOFTWARE'] =~ /IIS/)
- [(ENV['SERVER_PROTOCOL'] or "HTTP/1.0") + " 200 OK",
- "Date: " + rfc1123_date(Time.now),
- "Server: " + (ENV['SERVER_SOFTWARE'] or ""),
- "Connection: close"] +
- (options.empty? ? ["Content-Type: text/html"] : options)
- else
- options.empty? ? ["Content-Type: text/html"] : options
- end.join(EOL) + EOL + EOL
- end
- end
-
- # print HTTP header and string to $>
- def CGI::print(*options)
- $>.print CGI::header(*options) + yield.to_s
- end
-
- # print message to $>
- def CGI::message(message, title = "", header = ["Content-Type: text/html"])
- if message.kind_of?(Hash)
- title = message['title']
- header = message['header']
- message = message['body']
- end
- CGI::print(*header){
- CGI::tag("HTML"){
- CGI::tag("HEAD"){ CGI.tag("TITLE"){ title } } +
- CGI::tag("BODY"){ message }
- }
- }
- true
- end
-
- # print error message to $> and exit
- def CGI::error
- CGI::message({'title'=>'ERROR', 'body'=>
- CGI::tag("PRE"){
- "ERROR: " + CGI::tag("STRONG"){ escapeHTML($!.to_s) } + "\n" + escapeHTML($@.join("\n"))
- }
- })
- exit
- end
-end
diff --git a/lib/cgi.rb b/lib/cgi.rb
deleted file mode 100644
index 84d545f464..0000000000
--- a/lib/cgi.rb
+++ /dev/null
@@ -1,1949 +0,0 @@
-=begin
-
-== NAME
-
-cgi.rb - cgi support library
-
-Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
-
-Copyright (C) 2000 Information-technology Promotion Agency, Japan
-
-Wakou Aoyama <wakou@fsinet.or.jp>
-
-
-
-== EXAMPLE
-
-=== GET FORM VALUES
-
- require "cgi"
- cgi = CGI.new
- values = cgi['field_name'] # <== array of 'field_name'
- # if not 'field_name' included, then return [].
- fields = cgi.keys # <== array of field names
-
- # returns true if form has 'field_name'
- cgi.has_key?('field_name')
- cgi.has_key?('field_name')
- cgi.include?('field_name')
-
-
-=== GET FORM VALUES AS HASH
-
- require "cgi"
- cgi = CGI.new
- params = cgi.params
-
-cgi.params is a hash.
-
- cgi.params['new_field_name'] = ["value"] # add new param
- cgi.params['field_name'] = ["new_value"] # change value
- cgi.params.delete('field_name') # delete param
- cgi.params.clear # delete all params
-
-
-=== SAVE FORM VALUES TO FILE
-
- require "pstore"
- db = PStore.new("query.db")
- db.transaction do
- db["params"] = cgi.params
- end
-
-
-=== RESTORE FORM VALUES FROM FILE
-
- require "pstore"
- db = PStore.new("query.db")
- db.transaction do
- cgi.params = db["params"]
- end
-
-
-=== GET MULTIPART FORM VALUES
-
- require "cgi"
- cgi = CGI.new
- values = cgi['field_name'] # <== array of 'field_name'
- values[0].read # <== body of values[0]
- values[0].local_path # <== path to local file of values[0]
- values[0].original_filename # <== original filename of values[0]
- values[0].content_type # <== content_type of values[0]
-
-and values[0] has Tempfile class methods.
-(Tempfile class object has File class methods)
-
-
-=== GET COOKIE VALUES
-
- require "cgi"
- cgi = CGI.new
- values = cgi.cookies['name'] # <== array of 'name'
- # if not 'name' included, then return [].
- names = cgi.cookies.keys # <== array of cookie names
-
-and cgi.cookies is a hash.
-
-
-=== GET COOKIE OBJECTS
-
- require "cgi"
- cgi = CGI.new
- for name, cookie in cgi.cookies
- cookie.expires = Time.now + 30
- end
- cgi.out("cookie" => cgi.cookies){"string"}
-
- cgi.cookies # { "name1" => cookie1, "name2" => cookie2, ... }
-
- require "cgi"
- cgi = CGI.new
- cgi.cookies['name'].expires = Time.now + 30
- cgi.out("cookie" => cgi.cookies['name']){"string"}
-
-and see MAKE COOKIE OBJECT.
-
-
-=== GET ENVIRONMENT VALUE
-
- require "cgi"
- cgi = CGI.new
- value = cgi.auth_type
- # ENV["AUTH_TYPE"]
-
-see http://www.w3.org/CGI/
-
-AUTH_TYPE CONTENT_LENGTH CONTENT_TYPE GATEWAY_INTERFACE PATH_INFO
-PATH_TRANSLATED QUERY_STRING REMOTE_ADDR REMOTE_HOST REMOTE_IDENT
-REMOTE_USER REQUEST_METHOD SCRIPT_NAME SERVER_NAME SERVER_PORT
-SERVER_PROTOCOL SERVER_SOFTWARE
-
-content_length and server_port return Integer. and the others return String.
-
-and HTTP_COOKIE, HTTP_COOKIE2
-
- value = cgi.raw_cookie
- # ENV["HTTP_COOKIE"]
- value = cgi.raw_cookie2
- # ENV["HTTP_COOKIE2"]
-
-and other HTTP_*
-
- value = cgi.accept
- # ENV["HTTP_ACCEPT"]
- value = cgi.accept_charset
- # ENV["HTTP_ACCEPT_CHARSET"]
-
-HTTP_ACCEPT HTTP_ACCEPT_CHARSET HTTP_ACCEPT_ENCODING HTTP_ACCEPT_LANGUAGE
-HTTP_CACHE_CONTROL HTTP_FROM HTTP_HOST HTTP_NEGOTIATE HTTP_PRAGMA
-HTTP_REFERER HTTP_USER_AGENT
-
-
-=== PRINT HTTP HEADER AND HTML STRING TO $DEFAULT_OUTPUT ($>)
-
- require "cgi"
- cgi = CGI.new("html3") # add HTML generation methods
- cgi.out() do
- cgi.html() do
- cgi.head{ cgi.title{"TITLE"} } +
- cgi.body() do
- cgi.form() do
- cgi.textarea("get_text") +
- cgi.br +
- cgi.submit
- end +
- cgi.pre() do
- CGI::escapeHTML(
- "params: " + cgi.params.inspect + "\n" +
- "cookies: " + cgi.cookies.inspect + "\n" +
- ENV.collect() do |key, value|
- key + " --> " + value + "\n"
- end.join("")
- )
- end
- end
- end
- end
-
- # add HTML generation methods
- CGI.new("html3") # html3.2
- CGI.new("html4") # html4.01 (Strict)
- CGI.new("html4Tr") # html4.01 Transitional
- CGI.new("html4Fr") # html4.01 Frameset
-
-
-=end
-
-raise "Please, use ruby1.5.4 or later." if RUBY_VERSION < "1.5.4"
-
-require 'English'
-
-class CGI
-
- CR = "\015"
- LF = "\012"
- EOL = CR + LF
- REVISION = '$Id$'
-
- NEEDS_BINMODE = true if /WIN/ni.match(RUBY_PLATFORM)
- PATH_SEPARATOR = {'UNIX'=>'/', 'WINDOWS'=>'\\', 'MACINTOSH'=>':'}
-
- HTTP_STATUS = {
- "OK" => "200 OK",
- "PARTIAL_CONTENT" => "206 Partial Content",
- "MULTIPLE_CHOICES" => "300 Multiple Choices",
- "MOVED" => "301 Moved Permanently",
- "REDIRECT" => "302 Found",
- "NOT_MODIFIED" => "304 Not Modified",
- "BAD_REQUEST" => "400 Bad Request",
- "AUTH_REQUIRED" => "401 Authorization Required",
- "FORBIDDEN" => "403 Forbidden",
- "NOT_FOUND" => "404 Not Found",
- "METHOD_NOT_ALLOWED" => "405 Method Not Allowed",
- "NOT_ACCEPTABLE" => "406 Not Acceptable",
- "LENGTH_REQUIRED" => "411 Length Required",
- "PRECONDITION_FAILED" => "412 Rrecondition Failed",
- "SERVER_ERROR" => "500 Internal Server Error",
- "NOT_IMPLEMENTED" => "501 Method Not Implemented",
- "BAD_GATEWAY" => "502 Bad Gateway",
- "VARIANT_ALSO_VARIES" => "506 Variant Also Negotiates"
- }
-
- RFC822_DAYS = %w[ Sun Mon Tue Wed Thu Fri Sat ]
- RFC822_MONTHS = %w[ Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ]
-
- def env_table
- ENV
- end
-
- def stdinput
- $stdin
- end
-
- def stdoutput
- $DEFAULT_OUTPUT
- end
-
- private :env_table, :stdinput, :stdoutput
-
-=begin
-== METHODS
-=end
-
-=begin
-=== ESCAPE URL ENCODE
- url_encoded_string = CGI::escape("string")
-=end
- def CGI::escape(string)
- string.gsub(/([^ a-zA-Z0-9_.-]+)/n) do
- '%' + $1.unpack('H2' * $1.size).join('%').upcase
- end.tr(' ', '+')
- end
-
-
-=begin
-=== UNESCAPE URL ENCODED
- string = CGI::unescape("url encoded string")
-=end
- def CGI::unescape(string)
- string.tr('+', ' ').gsub(/((?:%[0-9a-fA-F]{2})+)/n) do
- [$1.delete('%')].pack('H*')
- end
- end
-
-
-=begin
-=== ESCAPE HTML &\"<>
- CGI::escapeHTML("string")
-=end
- def CGI::escapeHTML(string)
- string.gsub(/&/n, '&amp;').gsub(/\"/n, '&quot;').gsub(/>/n, '&gt;').gsub(/</n, '&lt;')
- end
-
-
-=begin
-=== UNESCAPE HTML
- CGI::unescapeHTML("HTML escaped string")
-=end
- def CGI::unescapeHTML(string)
- string.gsub(/&(.*?);/n) do
- match = $1.dup
- case match
- when /\Aamp\z/ni then '&'
- when /\Aquot\z/ni then '"'
- when /\Agt\z/ni then '>'
- when /\Alt\z/ni then '<'
- when /\A#0*(\d+)\z/n then
- if Integer($1) < 256
- Integer($1).chr
- else
- if Integer($1) < 65536 and ($KCODE[0] == ?u or $KCODE[0] == ?U)
- [Integer($1)].pack("U")
- else
- "&##{$1};"
- end
- end
- when /\A#x([0-9a-f]+)\z/ni then
- if $1.hex < 256
- $1.hex.chr
- else
- if $1.hex < 65536 and ($KCODE[0] == ?u or $KCODE[0] == ?U)
- [$1.hex].pack("U")
- else
- "&#x#{$1};"
- end
- end
- else
- "&#{match};"
- end
- end
- end
-
-
-=begin
-=== ESCAPE ELEMENT
- print CGI::escapeElement('<BR><A HREF="url"></A>', "A", "IMG")
- # "<BR>&lt;A HREF="url"&gt;&lt;/A&gt"
-
- print CGI::escapeElement('<BR><A HREF="url"></A>', ["A", "IMG"])
- # "<BR>&lt;A HREF="url"&gt;&lt;/A&gt"
-=end
- def CGI::escapeElement(string, *elements)
- elements = elements[0] if elements[0].kind_of?(Array)
- unless elements.empty?
- string.gsub(/<\/?(?:#{elements.join("|")})(?!\w)(?:.|\n)*?>/ni) do
- CGI::escapeHTML($&)
- end
- else
- string
- end
- end
-
-
-=begin
-=== UNESCAPE ELEMENT
- print CGI::unescapeElement(
- CGI::escapeHTML('<BR><A HREF="url"></A>'), "A", "IMG")
- # "&lt;BR&gt;<A HREF="url"></A>"
-
- print CGI::unescapeElement(
- CGI::escapeHTML('<BR><A HREF="url"></A>'), ["A", "IMG"])
- # "&lt;BR&gt;<A HREF="url"></A>"
-=end
- def CGI::unescapeElement(string, *elements)
- elements = elements[0] if elements[0].kind_of?(Array)
- unless elements.empty?
- string.gsub(/&lt;\/?(?:#{elements.join("|")})(?!\w)(?:.|\n)*?&gt;/ni) do
- CGI::unescapeHTML($&)
- end
- else
- string
- end
- end
-
-
-=begin
-=== MAKE RFC1123 DATE STRING
- CGI::rfc1123_date(Time.now)
- # Sat, 01 Jan 2000 00:00:00 GMT
-=end
- def CGI::rfc1123_date(time)
- t = time.clone.gmtime
- return format("%s, %.2d %s %.4d %.2d:%.2d:%.2d GMT",
- RFC822_DAYS[t.wday], t.day, RFC822_MONTHS[t.month-1], t.year,
- t.hour, t.min, t.sec)
- end
-
-
-=begin
-=== MAKE HTTP HEADER STRING
- header
- # Content-Type: text/html
-
- header("text/plain")
- # Content-Type: text/plain
-
- header({"nph" => true,
- "status" => "OK", # == "200 OK"
- # "status" => "200 GOOD",
- "server" => ENV['SERVER_SOFTWARE'],
- "connection" => "close",
- "type" => "text/html",
- "charset" => "iso-2022-jp",
- # Content-Type: text/html; charset=iso-2022-jp
- "language" => "ja",
- "expires" => Time.now + 30,
- "cookie" => [cookie1, cookie2],
- "my_header1" => "my_value"
- "my_header2" => "my_value"})
-
-header will not convert charset.
-
-status:
-
- "OK" --> "200 OK"
- "PARTIAL_CONTENT" --> "206 Partial Content"
- "MULTIPLE_CHOICES" --> "300 Multiple Choices"
- "MOVED" --> "301 Moved Permanently"
- "REDIRECT" --> "302 Found"
- "NOT_MODIFIED" --> "304 Not Modified"
- "BAD_REQUEST" --> "400 Bad Request"
- "AUTH_REQUIRED" --> "401 Authorization Required"
- "FORBIDDEN" --> "403 Forbidden"
- "NOT_FOUND" --> "404 Not Found"
- "METHOD_NOT_ALLOWED" --> "405 Method Not Allowed"
- "NOT_ACCEPTABLE" --> "406 Not Acceptable"
- "LENGTH_REQUIRED" --> "411 Length Required"
- "PRECONDITION_FAILED" --> "412 Rrecondition Failed"
- "SERVER_ERROR" --> "500 Internal Server Error"
- "NOT_IMPLEMENTED" --> "501 Method Not Implemented"
- "BAD_GATEWAY" --> "502 Bad Gateway"
- "VARIANT_ALSO_VARIES" --> "506 Variant Also Negotiates"
-
-=end
- def header(options = "text/html")
-
- buf = ""
-
- case options
- when String
- options = { "type" => options }
- when Hash
- options = options.dup
- end
-
- unless options.has_key?("type")
- options["type"] = "text/html"
- end
-
- if options.has_key?("charset")
- options["type"] += "; charset=" + options.delete("charset")
- end
-
- options.delete("nph") if defined?(MOD_RUBY)
- if options.delete("nph") or /IIS/n.match(env_table['SERVER_SOFTWARE'])
- buf += (env_table["SERVER_PROTOCOL"] or "HTTP/1.0") + " " +
- (HTTP_STATUS[options["status"]] or options["status"] or "200 OK") +
- EOL +
- "Date: " + CGI::rfc1123_date(Time.now) + EOL
-
- unless options.has_key?("server")
- options["server"] = (env_table['SERVER_SOFTWARE'] or "")
- end
-
- unless options.has_key?("connection")
- options["connection"] = "close"
- end
-
- options.delete("status")
- end
-
- if options.has_key?("status")
- buf += "Status: " +
- (HTTP_STATUS[options["status"]] or options["status"]) + EOL
- options.delete("status")
- end
-
- if options.has_key?("server")
- buf += "Server: " + options.delete("server") + EOL
- end
-
- if options.has_key?("connection")
- buf += "Connection: " + options.delete("connection") + EOL
- end
-
- buf += "Content-Type: " + options.delete("type") + EOL
-
- if options.has_key?("length")
- buf += "Content-Length: " + options.delete("length").to_s + EOL
- end
-
- if options.has_key?("language")
- buf += "Content-Language: " + options.delete("language") + EOL
- end
-
- if options.has_key?("expires")
- buf += "Expires: " + CGI::rfc1123_date( options.delete("expires") ) + EOL
- end
-
- if options.has_key?("cookie")
- if options["cookie"].kind_of?(String) or
- options["cookie"].kind_of?(Cookie)
- buf += "Set-Cookie: " + options.delete("cookie").to_s + EOL
- elsif options["cookie"].kind_of?(Array)
- options.delete("cookie").each{|cookie|
- buf += "Set-Cookie: " + cookie.to_s + EOL
- }
- elsif options["cookie"].kind_of?(Hash)
- options.delete("cookie").each_value{|cookie|
- buf += "Set-Cookie: " + cookie.to_s + EOL
- }
- end
- end
- if @output_cookies
- for cookie in @output_cookies
- buf += "Set-Cookie: " + cookie.to_s + EOL
- end
- end
-
- options.each{|key, value|
- buf += key + ": " + value + EOL
- }
-
- if defined?(MOD_RUBY)
- table = Apache::request.headers_out
- buf.scan(/([^:]+): (.+)#{EOL}/n){ |name, value|
- $stderr.printf("name:%s value:%s\n", name, value) if $DEBUG
- case name
- when 'Set-Cookie'
- table.add($1, $2)
- when /^status$/ni
- Apache::request.status_line = value
- Apache::request.status = value.to_i
- when /^content-type$/ni
- Apache::request.content_type = value
- when /^content-encoding$/ni
- Apache::request.content_encoding = value
- when /^location$/ni
- if Apache::request.status == 200
- Apache::request.status = 302
- end
- Apache::request.headers_out[name] = value
- else
- Apache::request.headers_out[name] = value
- end
- }
- Apache::request.send_http_header
- ''
- else
- buf + EOL
- end
-
- end # header()
-
-
-=begin
-=== PRINT HTTP HEADER AND STRING TO $DEFAULT_OUTPUT ($>)
- cgi = CGI.new
- cgi.out{ "string" }
- # Content-Type: text/html
- # Content-Length: 6
- #
- # string
-
- cgi.out("text/plain"){ "string" }
- # Content-Type: text/plain
- # Content-Length: 6
- #
- # string
-
- cgi.out({"nph" => true,
- "status" => "OK", # == "200 OK"
- "server" => ENV['SERVER_SOFTWARE'],
- "connection" => "close",
- "type" => "text/html",
- "charset" => "iso-2022-jp",
- # Content-Type: text/html; charset=iso-2022-jp
- "language" => "ja",
- "expires" => Time.now + (3600 * 24 * 30),
- "cookie" => [cookie1, cookie2],
- "my_header1" => "my_value",
- "my_header2" => "my_value"}){ "string" }
-
-if "HEAD" == REQUEST_METHOD then output only HTTP header.
-
-if charset is "iso-2022-jp" or "euc-jp" or "shift_jis" then
-convert string charset, and set language to "ja".
-
-=end
- def out(options = "text/html")
-
- options = { "type" => options } if options.kind_of?(String)
- content = yield
-
- if options.has_key?("charset")
- require "nkf"
- case options["charset"]
- when /iso-2022-jp/ni
- content = NKF::nkf('-j', content)
- options["language"] = "ja" unless options.has_key?("language")
- when /euc-jp/ni
- content = NKF::nkf('-e', content)
- options["language"] = "ja" unless options.has_key?("language")
- when /shift_jis/ni
- content = NKF::nkf('-s', content)
- options["language"] = "ja" unless options.has_key?("language")
- end
- end
-
- options["length"] = content.length.to_s
- output = stdoutput
- output.binmode if defined? output.binmode
- output.print header(options)
- output.print content unless "HEAD" == env_table['REQUEST_METHOD']
- end
-
-
-=begin
-=== PRINT
- cgi = CGI.new
- cgi.print # default: cgi.print == $DEFAULT_OUTPUT.print
-=end
- def print(*options)
- stdoutput.print(*options)
- end
-
-
-=begin
-=== MAKE COOKIE OBJECT
- cookie1 = CGI::Cookie::new("name", "value1", "value2", ...)
- cookie1 = CGI::Cookie::new({"name" => "name", "value" => "value"})
- cookie1 = CGI::Cookie::new({'name' => 'name',
- 'value' => ['value1', 'value2', ...],
- 'path' => 'path', # optional
- 'domain' => 'domain', # optional
- 'expires' => Time.now, # optional
- 'secure' => true # optional
- })
-
- cgi.out({"cookie" => [cookie1, cookie2]}){ "string" }
-
- name = cookie1.name
- values = cookie1.value
- path = cookie1.path
- domain = cookie1.domain
- expires = cookie1.expires
- secure = cookie1.secure
-
- cookie1.name = 'name'
- cookie1.value = ['value1', 'value2', ...]
- cookie1.path = 'path'
- cookie1.domain = 'domain'
- cookie1.expires = Time.now + 30
- cookie1.secure = true
-=end
- require "delegate"
- class Cookie < SimpleDelegator
-
- def initialize(name = "", *value)
- options = if name.kind_of?(String)
- { "name" => name, "value" => value }
- else
- name
- end
- unless options.has_key?("name")
- raise ArgumentError, "`name' required"
- end
-
- @name = options["name"]
- @value = Array(options["value"])
- # simple support for IE
- if options["path"]
- @path = options["path"]
- else
- %r|^(.*/)|.match(ENV["SCRIPT_NAME"])
- @path = ($1 or "")
- end
- @domain = options["domain"]
- @expires = options["expires"]
- @secure = options["secure"] == true ? true : false
-
- super(@value)
- end
-
- attr_accessor("name", "value", "path", "domain", "expires")
- attr_reader("secure")
- def secure=(val)
- @secure = val if val == true or val == false
- @secure
- end
-
- def to_s
- buf = ""
- buf += @name + '='
-
- if @value.kind_of?(String)
- buf += CGI::escape(@value)
- else
- buf += @value.collect{|v| CGI::escape(v) }.join("&")
- end
-
- if @domain
- buf += '; domain=' + @domain
- end
-
- if @path
- buf += '; path=' + @path
- end
-
- if @expires
- buf += '; expires=' + CGI::rfc1123_date(@expires)
- end
-
- if @secure == true
- buf += '; secure'
- end
-
- buf
- end
-
- end # class Cookie
-
-
-=begin
-=== PARSE RAW COOKIE STRING
- cookies = CGI::Cookie::parse("raw_cookie_string")
- # { "name1" => cookie1, "name2" => cookie2, ... }
-=end
- def Cookie::parse(raw_cookie)
- cookies = Hash.new([])
- return cookies unless raw_cookie
-
- raw_cookie.split('; ').each do |pairs|
- name, values = pairs.split('=',2)
- name = CGI::unescape(name)
- values ||= ""
- values = values.split('&').collect{|v| CGI::unescape(v) }
- unless cookies.has_key?(name)
- cookies[name] = Cookie::new({ "name" => name, "value" => values })
- end
- end
-
- cookies
- end
-
-
-=begin
-=== PARSE QUERY STRING
- params = CGI::parse("query_string")
- # {"name1" => ["value1", "value2", ...],
- # "name2" => ["value1", "value2", ...], ... }
-=end
- def CGI::parse(query)
- params = Hash.new([])
-
- query.split(/[&;]/n).each do |pairs|
- key, value = pairs.split('=',2).collect{|v| CGI::unescape(v) }
- if params.has_key?(key)
- params[key].push(value)
- else
- params[key] = [value]
- end
- end
-
- params
- end
-
-
- module QueryExtension
-
- for env in %w[ CONTENT_LENGTH SERVER_PORT ]
- eval( <<-END )
- def #{env.sub(/^HTTP_/n, '').downcase}
- env_table["#{env}"] && Integer(env_table["#{env}"])
- end
- END
- end
-
- for env in %w[ AUTH_TYPE CONTENT_TYPE GATEWAY_INTERFACE PATH_INFO
- PATH_TRANSLATED QUERY_STRING REMOTE_ADDR REMOTE_HOST
- REMOTE_IDENT REMOTE_USER REQUEST_METHOD SCRIPT_NAME
- SERVER_NAME SERVER_PROTOCOL SERVER_SOFTWARE
-
- HTTP_ACCEPT HTTP_ACCEPT_CHARSET HTTP_ACCEPT_ENCODING
- HTTP_ACCEPT_LANGUAGE HTTP_CACHE_CONTROL HTTP_FROM HTTP_HOST
- HTTP_NEGOTIATE HTTP_PRAGMA HTTP_REFERER HTTP_USER_AGENT ]
- eval( <<-END )
- def #{env.sub(/^HTTP_/n, '').downcase}
- env_table["#{env}"]
- end
- END
- end
-
- def raw_cookie
- env_table["HTTP_COOKIE"]
- end
-
- def raw_cookie2
- env_table["HTTP_COOKIE2"]
- end
-
- attr_accessor("cookies")
- attr("params")
- def params=(hash)
- @params.clear
- @params.update(hash)
- end
-
- def param(name)
- @params[name].join("\0")
- end
-
- def read_multipart(boundary, content_length)
- params = Hash.new([])
- boundary = "--" + boundary
- buf = ""
- bufsize = 10 * 1024
-
- # start multipart/form-data
- stdinput.binmode
- boundary_size = boundary.size + EOL.size
- content_length -= boundary_size
- status = stdinput.read(boundary_size)
- if nil == status
- raise EOFError, "no content body"
- end
-
- require "tempfile"
-
- until -1 == content_length
- head = nil
- body = Tempfile.new("CGI")
- body.binmode
-
- until head and /#{boundary}(?:#{EOL}|--)/n.match(buf)
-
- if (not head) and /#{EOL}#{EOL}/n.match(buf)
- buf = buf.sub(/\A((?:.|\n)*?#{EOL})#{EOL}/n) do
- head = $1.dup
- ""
- end
- next
- end
-
- if head and ( (EOL + boundary + EOL).size < buf.size )
- body.print buf[0 ... (buf.size - (EOL + boundary + EOL).size)]
- buf[0 ... (buf.size - (EOL + boundary + EOL).size)] = ""
- end
-
- c = if bufsize < content_length
- stdinput.read(bufsize) or ''
- else
- stdinput.read(content_length) or ''
- end
- buf += c
- content_length -= c.size
-
- end
-
- buf = buf.sub(/\A((?:.|\n)*?)(?:#{EOL})?#{boundary}(#{EOL}|--)/n) do
- body.print $1
- if "--" == $2
- content_length = -1
- end
- ""
- end
-
- body.rewind
-
- eval <<-END
- def body.local_path
- #{body.path.dump}
- end
- END
-
- /Content-Disposition:.* filename="?([^\";]*)"?/ni.match(head)
- eval <<-END
- def body.original_filename
- #{
- filename = ($1 or "").dup
- if /Mac/ni.match(env_table['HTTP_USER_AGENT']) and
- /Mozilla/ni.match(env_table['HTTP_USER_AGENT']) and
- (not /MSIE/ni.match(env_table['HTTP_USER_AGENT']))
- CGI::unescape(filename)
- else
- filename
- end.dump.untaint
- }.taint
- end
- END
-
- /Content-Type: (.*)/ni.match(head)
- eval <<-END
- def body.content_type
- #{($1 or "").dump.untaint}.taint
- end
- END
-
- /Content-Disposition:.* name="?([^\";]*)"?/ni.match(head)
- name = $1.dup
-
- if params.has_key?(name)
- params[name].push(body)
- else
- params[name] = [body]
- end
-
- end
-
- params
- end # read_multipart
- private :read_multipart
-
- # offline mode. read name=value pairs on standard input.
- def read_from_cmdline
- require "shellwords"
-
- string = unless ARGV.empty?
- ARGV.join(' ')
- else
- if STDIN.tty?
- STDERR.print(
- %|(offline mode: enter name=value pairs on standard input)\n|
- )
- end
- readlines.join(' ').gsub(/\n/n, '')
- end.gsub(/\\=/n, '%3D').gsub(/\\&/n, '%26')
-
- words = Shellwords.shellwords(string)
-
- if words.find{|x| /=/n.match(x) }
- words.join('&')
- else
- words.join('+')
- end
- end
- private :read_from_cmdline
-
- def initialize_query()
- if ("POST" == env_table['REQUEST_METHOD']) and
- %r|\Amultipart/form-data.*boundary=\"?([^\";,]+)\"?|n.match(env_table['CONTENT_TYPE'])
- boundary = $1.dup
- @params = read_multipart(boundary, Integer(env_table['CONTENT_LENGTH']))
- else
- @params = CGI::parse(
- case env_table['REQUEST_METHOD']
- when "GET", "HEAD"
- if defined?(MOD_RUBY)
- Apache::request.args or ""
- else
- env_table['QUERY_STRING'] or ""
- end
- when "POST"
- stdinput.binmode
- stdinput.read(Integer(env_table['CONTENT_LENGTH'])) or ''
- else
- read_from_cmdline
- end
- )
- end
-
- @cookies = CGI::Cookie::parse((env_table['HTTP_COOKIE'] or env_table['COOKIE']))
-
- end
- private :initialize_query
-
- def [](*args)
- @params[*args]
- end
-
- def keys(*args)
- @params.keys(*args)
- end
-
- def has_key?(*args)
- @params.has_key?(*args)
- end
- alias key? has_key?
- alias include? has_key?
-
- end # QueryExtension
-
-
-=begin
-=== HTML PRETTY FORMAT
- print CGI::pretty("<HTML><BODY></BODY></HTML>")
- # <HTML>
- # <BODY>
- # </BODY>
- # </HTML>
-
- print CGI::pretty("<HTML><BODY></BODY></HTML>", "\t")
- # <HTML>
- # <BODY>
- # </BODY>
- # </HTML>
-=end
- def CGI::pretty(string, shift = " ")
- lines = string.gsub(/(?!\A)<(?:.|\n)*?>/n, "\n\\0").gsub(/<(?:.|\n)*?>(?!\n)/n, "\\0\n")
- end_pos = 0
- while end_pos = lines.index(/^<\/(\w+)/n, end_pos)
- element = $1.dup
- start_pos = lines.rindex(/^\s*<#{element}/ni, end_pos)
- lines[start_pos ... end_pos] = "__" + lines[start_pos ... end_pos].gsub(/\n(?!\z)/n, "\n" + shift) + "__"
- end
- lines.gsub(/^((?:#{Regexp::quote(shift)})*)__(?=<\/?\w)/n, '\1')
- end
-
-
-=begin
-== HTML ELEMENTS
-
- cgi = CGI.new("html3") # add HTML generation methods
- cgi.element
- cgi.element{ "string" }
- cgi.element({ "ATTRIBUTE1" => "value1", "ATTRIBUTE2" => "value2" })
- cgi.element({ "ATTRIBUTE1" => "value1", "ATTRIBUTE2" => "value2" }){ "string" }
-
- # add HTML generation methods
- CGI.new("html3") # html3.2
- CGI.new("html4") # html4.0 (Strict)
- CGI.new("html4Tr") # html4.0 Transitional
- CGI.new("html4Fr") # html4.0 Frameset
-
-=end
-
-
- module TagMaker
-
- # - -
- def nn_element_def(element)
- <<-END.gsub(/element\.downcase/n, element.downcase).gsub(/element\.upcase/n, element.upcase)
- "<element.upcase" + attributes.collect{|name, value|
- next unless value
- " " + CGI::escapeHTML(name) +
- if true == value
- ""
- else
- '="' + CGI::escapeHTML(value) + '"'
- end
- }.to_s + ">" +
- if block_given?
- yield.to_s
- else
- ""
- end +
- "</element.upcase>"
- END
- end
-
- # - O EMPTY
- def nOE_element_def(element)
- <<-END.gsub(/element\.downcase/n, element.downcase).gsub(/element\.upcase/n, element.upcase)
- "<element.upcase" + attributes.collect{|name, value|
- next unless value
- " " + CGI::escapeHTML(name) +
- if true == value
- ""
- else
- '="' + CGI::escapeHTML(value) + '"'
- end
- }.to_s + ">"
- END
- end
-
- # O O or - O
- def nO_element_def(element)
- <<-END.gsub(/element\.downcase/n, element.downcase).gsub(/element\.upcase/n, element.upcase)
- "<element.upcase" + attributes.collect{|name, value|
- next unless value
- " " + CGI::escapeHTML(name) +
- if true == value
- ""
- else
- '="' + CGI::escapeHTML(value) + '"'
- end
- }.to_s + ">" +
- if block_given?
- yield.to_s + "</element.upcase>"
- else
- ""
- end
- END
- end
-
- end # TagMaker
-
-
- module HtmlExtension
-
-
-=begin
-=== A ELEMENT
- a("url")
- # = a({ "HREF" => "url" })
-=end
- def a(href = "")
- attributes = if href.kind_of?(String)
- { "HREF" => href }
- else
- href
- end
- if block_given?
- super(attributes){ yield }
- else
- super(attributes)
- end
- end
-
-
-=begin
-=== BASE ELEMENT
- base("url")
- # = base({ "HREF" => "url" })
-=end
- def base(href = "")
- attributes = if href.kind_of?(String)
- { "HREF" => href }
- else
- href
- end
- if block_given?
- super(attributes){ yield }
- else
- super(attributes)
- end
- end
-
-
-=begin
-=== BLOCKQUOTE ELEMENT
- blockquote("url"){ "string" }
- # = blockquote({ "CITE" => "url" }){ "string" }
-=end
- def blockquote(cite = nil)
- attributes = if cite.kind_of?(String)
- { "CITE" => cite }
- else
- cite or ""
- end
- if block_given?
- super(attributes){ yield }
- else
- super(attributes)
- end
- end
-
-
-=begin
-=== CAPTION ELEMENT
- caption("align"){ "string" }
- # = caption({ "ALIGN" => "align" }){ "string" }
-=end
- def caption(align = nil)
- attributes = if align.kind_of?(String)
- { "ALIGN" => align }
- else
- align or ""
- end
- if block_given?
- super(attributes){ yield }
- else
- super(attributes)
- end
- end
-
-
-=begin
-=== CHECKBOX
- checkbox("name")
- # = checkbox({ "NAME" => "name" })
-
- checkbox("name", "value")
- # = checkbox({ "NAME" => "name", "VALUE" => "value" })
-
- checkbox("name", "value", true)
- # = checkbox({ "NAME" => "name", "VALUE" => "value", "CHECKED" => true })
-=end
- def checkbox(name = "", value = nil, checked = nil)
- attributes = if name.kind_of?(String)
- { "TYPE" => "checkbox", "NAME" => name,
- "VALUE" => value, "CHECKED" => checked }
- else
- name["TYPE"] = "checkbox"
- name
- end
- input(attributes)
- end
-
-
-=begin
-=== CHECKBOX_GROUP
- checkbox_group("name", "foo", "bar", "baz")
- # <INPUT TYPE="checkbox" NAME="name" VALUE="foo">foo
- # <INPUT TYPE="checkbox" NAME="name" VALUE="bar">bar
- # <INPUT TYPE="checkbox" NAME="name" VALUE="baz">baz
-
- checkbox_group("name", ["foo"], ["bar", true], "baz")
- # <INPUT TYPE="checkbox" NAME="name" VALUE="foo">foo
- # <INPUT TYPE="checkbox" SELECTED NAME="name" VALUE="bar">bar
- # <INPUT TYPE="checkbox" NAME="name" VALUE="baz">baz
-
- checkbox_group("name", ["1", "Foo"], ["2", "Bar", true], "Baz")
- # <INPUT TYPE="checkbox" NAME="name" VALUE="1">Foo
- # <INPUT TYPE="checkbox" SELECTED NAME="name" VALUE="2">Bar
- # <INPUT TYPE="checkbox" NAME="name" VALUE="Baz">Baz
-
- checkbox_group({ "NAME" => "name",
- "VALUES" => ["foo", "bar", "baz"] })
-
- checkbox_group({ "NAME" => "name",
- "VALUES" => [["foo"], ["bar", true], "baz"] })
-
- checkbox_group({ "NAME" => "name",
- "VALUES" => [["1", "Foo"], ["2", "Bar", true], "Baz"] })
-=end
- def checkbox_group(name = "", *values)
- if name.kind_of?(Hash)
- values = name["VALUES"]
- name = name["NAME"]
- end
- values.collect{|value|
- if value.kind_of?(String)
- checkbox(name, value) + value
- else
- if value[value.size - 1] == true
- checkbox(name, value[0], true) +
- value[value.size - 2]
- else
- checkbox(name, value[0]) +
- value[value.size - 1]
- end
- end
- }.to_s
- end
-
-
-=begin
-=== FILE_FIELD
- file_field("name")
- # <INPUT TYPE="file" NAME="name" SIZE="20">
-
- file_field("name", 40)
- # <INPUT TYPE="file" NAME="name" SIZE="40">
-
- file_field("name", 40, 100)
- # <INPUT TYPE="file" NAME="name" SIZE="40", MAXLENGTH="100">
-
- file_field({ "NAME" => "name", "SIZE" => 40 })
- # <INPUT TYPE="file" NAME="name" SIZE="40">
-=end
- def file_field(name = "", size = 20, maxlength = nil)
- attributes = if name.kind_of?(String)
- { "TYPE" => "file", "NAME" => name,
- "SIZE" => size.to_s }
- else
- name["TYPE"] = "file"
- name
- end
- attributes["MAXLENGTH"] = maxlength.to_s if maxlength
- input(attributes)
- end
-
-
-=begin
-=== FORM ELEMENT
- form{ "string" }
- # <FORM METHOD="post" ENCTYPE="application/x-www-form-urlencoded">string</FORM>
-
- form("get"){ "string" }
- # <FORM METHOD="get" ENCTYPE="application/x-www-form-urlencoded">string</FORM>
-
- form("get", "url"){ "string" }
- # <FORM METHOD="get" ACTION="url" ENCTYPE="application/x-www-form-urlencoded">string</FORM>
-
- form({"METHOD" => "post", "ENCTYPE" => "enctype"}){ "string" }
- # <FORM METHOD="post" ENCTYPE="enctype">string</FORM>
-
-The hash keys are case sensitive. Ask the samples.
-=end
- def form(method = "post", action = nil, enctype = "application/x-www-form-urlencoded")
- attributes = if method.kind_of?(String)
- { "METHOD" => method, "ACTION" => action,
- "ENCTYPE" => enctype }
- else
- unless method.has_key?("METHOD")
- method["METHOD"] = "post"
- end
- unless method.has_key?("ENCTYPE")
- method["ENCTYPE"] = enctype
- end
- method
- end
- if block_given?
- body = yield
- else
- body = ""
- end
- if @output_hidden
- hidden = @output_hidden.collect{|k,v|
- "<INPUT TYPE=HIDDEN NAME=\"#{k}\" VALUE=\"#{v}\">"
- }.to_s
- body += hidden
- end
- super(attributes){body}
- end
-
-=begin
-=== HIDDEN FIELD
- hidden("name")
- # <INPUT TYPE="hidden" NAME="name">
-
- hidden("name", "value")
- # <INPUT TYPE="hidden" NAME="name" VALUE="value">
-
- hidden({ "NAME" => "name", "VALUE" => "reset", "ID" => "foo" })
- # <INPUT TYPE="hidden" NAME="name" VALUE="value" ID="foo">
-=end
- def hidden(name = "", value = nil)
- attributes = if name.kind_of?(String)
- { "TYPE" => "hidden", "NAME" => name, "VALUE" => value }
- else
- name["TYPE"] = "hidden"
- name
- end
- input(attributes)
- end
-
-
-=begin
-=== HTML ELEMENT
-
- html{ "string" }
- # <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><HTML>string</HTML>
-
- html({ "LANG" => "ja" }){ "string" }
- # <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><HTML LANG="ja">string</HTML>
-
- html({ "DOCTYPE" => false }){ "string" }
- # <HTML>string</HTML>
-
- html({ "DOCTYPE" => '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">' }){ "string" }
- # <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"><HTML>string</HTML>
-
- html({ "PRETTY" => " " }){ "<BODY></BODY>" }
- # <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
- # <HTML>
- # <BODY>
- # </BODY>
- # </HTML>
-
- html({ "PRETTY" => "\t" }){ "<BODY></BODY>" }
- # <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
- # <HTML>
- # <BODY>
- # </BODY>
- # </HTML>
-
- html("PRETTY"){ "<BODY></BODY>" }
- # = html({ "PRETTY" => " " }){ "<BODY></BODY>" }
-
- html(if $VERBOSE then "PRETTY" end){ "HTML string" }
-
-=end
- def html(attributes = {})
- if nil == attributes
- attributes = {}
- elsif "PRETTY" == attributes
- attributes = { "PRETTY" => true }
- end
- pretty = attributes.delete("PRETTY")
- pretty = " " if true == pretty
- buf = ""
-
- if attributes.has_key?("DOCTYPE")
- if attributes["DOCTYPE"]
- buf += attributes.delete("DOCTYPE")
- else
- attributes.delete("DOCTYPE")
- end
- else
- buf += doctype
- end
-
- if block_given?
- buf += super(attributes){ yield }
- else
- buf += super(attributes)
- end
-
- if pretty
- CGI::pretty(buf, pretty)
- else
- buf
- end
-
- end
-
-
-=begin
-=== IMAGE_BUTTON
- image_button("url")
- # <INPUT TYPE="image" SRC="url">
-
- image_button("url", "name", "string")
- # <INPUT TYPE="image" SRC="url" NAME="name", ALT="string">
-
- image_button({ "SRC" => "url", "ATL" => "strng" })
- # <INPUT TYPE="image" SRC="url" ALT="string">
-=end
- def image_button(src = "", name = nil, alt = nil)
- attributes = if src.kind_of?(String)
- { "TYPE" => "image", "SRC" => src, "NAME" => name,
- "ALT" => alt }
- else
- src["TYPE"] = "image"
- src["SRC"] ||= ""
- src
- end
- input(attributes)
- end
-
-
-=begin
-=== IMG ELEMENT
- img("src", "alt", 100, 50)
- # <IMG SRC="src" ALT="alt" WIDTH="100", HEIGHT="50">
-
- img({ "SRC" => "src", "ALT" => "alt", "WIDTH" => 100, "HEIGHT" => 50 })
- # <IMG SRC="src" ALT="alt" WIDTH="100", HEIGHT="50">
-=end
- def img(src = "", alt = "", width = nil, height = nil)
- attributes = if src.kind_of?(String)
- { "SRC" => src, "ALT" => alt }
- else
- src
- end
- attributes["WIDTH"] = width.to_s if width
- attributes["HEIGHT"] = height.to_s if height
- super(attributes)
- end
-
-
-=begin
-=== MULTIPART FORM
- multipart_form{ "string" }
- # <FORM METHOD="post" ENCTYPE="multipart/form-data">string</FORM>
-
- multipart_form("url"){ "string" }
- # <FORM METHOD="post" ACTION="url" ENCTYPE="multipart/form-data">string</FORM>
-=end
- def multipart_form(action = nil, enctype = "multipart/form-data")
- attributes = if action == nil
- { "METHOD" => "post", "ENCTYPE" => enctype }
- elsif action.kind_of?(String)
- { "METHOD" => "post", "ACTION" => action,
- "ENCTYPE" => enctype }
- else
- unless action.has_key?("METHOD")
- action["METHOD"] = "post"
- end
- unless action.has_key?("ENCTYPE")
- action["ENCTYPE"] = enctype
- end
- action
- end
- if block_given?
- form(attributes){ yield }
- else
- form(attributes)
- end
- end
-
-
-=begin
-=== PASSWORD_FIELD
- password_field("name")
- # <INPUT TYPE="password" NAME="name" SIZE="40">
-
- password_field("name", "value")
- # <INPUT TYPE="password" NAME="name" VALUE="value" SIZE="40">
-
- password_field("password", "value", 80, 200)
- # <INPUT TYPE="password" NAME="name" VALUE="value", SIZE="80", MAXLENGTH="200">
-
- password_field({ "NAME" => "name", "VALUE" => "value" })
- # <INPUT TYPE="password" NAME="name" VALUE="value">
-=end
- def password_field(name = "", value = nil, size = 40, maxlength = nil)
- attributes = if name.kind_of?(String)
- { "TYPE" => "password", "NAME" => name,
- "VALUE" => value, "SIZE" => size.to_s }
- else
- name["TYPE"] = "password"
- name
- end
- attributes["MAXLENGTH"] = maxlength.to_s if maxlength
- input(attributes)
- end
-
-
-=begin
-=== POPUP_MENU
- popup_menu("name", "foo", "bar", "baz")
- # <SELECT NAME="name">
- # <OPTION VALUE="foo">foo</OPTION>
- # <OPTION VALUE="bar">bar</OPTION>
- # <OPTION VALUE="baz">baz</OPTION>
- # </SELECT>
-
- popup_menu("name", ["foo"], ["bar", true], "baz")
- # <SELECT NAME="name">
- # <OPTION VALUE="foo">foo</OPTION>
- # <OPTION VALUE="bar" SELECTED>bar</OPTION>
- # <OPTION VALUE="baz">baz</OPTION>
- # </SELECT>
-
- popup_menu("name", ["1", "Foo"], ["2", "Bar", true], "Baz")
- # <SELECT NAME="name">
- # <OPTION VALUE="1">Foo</OPTION>
- # <OPTION SELECTED VALUE="2">Bar</OPTION>
- # <OPTION VALUE="Baz">Baz</OPTION>
- # </SELECT>
-
- popup_menu({"NAME" => "name", "SIZE" => 2, "MULTIPLE" => true,
- "VALUES" => [["1", "Foo"], ["2", "Bar", true], "Baz"] })
- # <SELECT NAME="name" MULTIPLE SIZE="2">
- # <OPTION VALUE="1">Foo</OPTION>
- # <OPTION SELECTED VALUE="2">Bar</OPTION>
- # <OPTION VALUE="Baz">Baz</OPTION>
- # </SELECT>
-=end
- def popup_menu(name = "", *values)
-
- if name.kind_of?(Hash)
- values = name["VALUES"]
- size = name["SIZE"].to_s if name["SIZE"]
- multiple = name["MULTIPLE"]
- name = name["NAME"]
- else
- size = nil
- multiple = nil
- end
-
- select({ "NAME" => name, "SIZE" => size,
- "MULTIPLE" => multiple }){
- values.collect{|value|
- if value.kind_of?(String)
- option({ "VALUE" => value }){ value }
- else
- if value[value.size - 1] == true
- option({ "VALUE" => value[0], "SELECTED" => true }){
- value[value.size - 2]
- }
- else
- option({ "VALUE" => value[0] }){
- value[value.size - 1]
- }
- end
- end
- }.to_s
- }
-
- end
-
-
-=begin
-=== RADIO_BUTTON
- radio_button("name", "value")
- # <INPUT TYPE="radio" NAME="name", VALUE="value">
-
- radio_button("name", "value", true)
- # <INPUT TYPE="radio" NAME="name", VALUE="value", CHECKED>
-
- radio_button({ "NAME" => "name", "VALUE" => "value", "ID" => "foo" })
- # <INPUT TYPE="radio" NAME="name" VALUE="value" ID="foo">
-=end
- def radio_button(name = "", value = nil, checked = nil)
- attributes = if name.kind_of?(String)
- { "TYPE" => "radio", "NAME" => name,
- "VALUE" => value, "CHECKED" => checked }
- else
- name["TYPE"] = "radio"
- name
- end
- input(attributes)
- end
-
-
-=begin
-=== RADIO_GROUP
- radio_group("name", "foo", "bar", "baz")
- # <INPUT TYPE="radio" NAME="name" VALUE="foo">foo
- # <INPUT TYPE="radio" NAME="name" VALUE="bar">bar
- # <INPUT TYPE="radio" NAME="name" VALUE="baz">baz
-
- radio_group("name", ["foo"], ["bar", true], "baz")
- # <INPUT TYPE="radio" NAME="name" VALUE="foo">foo
- # <INPUT TYPE="radio" SELECTED NAME="name" VALUE="bar">bar
- # <INPUT TYPE="radio" NAME="name" VALUE="baz">baz
-
- radio_group("name", ["1", "Foo"], ["2", "Bar", true], "Baz")
- # <INPUT TYPE="radio" NAME="name" VALUE="1">Foo
- # <INPUT TYPE="radio" SELECTED NAME="name" VALUE="2">Bar
- # <INPUT TYPE="radio" NAME="name" VALUE="Baz">Baz
-
- radio_group({ "NAME" => "name",
- "VALUES" => ["foo", "bar", "baz"] })
-
- radio_group({ "NAME" => "name",
- "VALUES" => [["foo"], ["bar", true], "baz"] })
-
- radio_group({ "NAME" => "name",
- "VALUES" => [["1", "Foo"], ["2", "Bar", true], "Baz"] })
-=end
- def radio_group(name = "", *values)
- if name.kind_of?(Hash)
- values = name["VALUES"]
- name = name["NAME"]
- end
- values.collect{|value|
- if value.kind_of?(String)
- radio_button(name, value) + value
- else
- if value[value.size - 1] == true
- radio_button(name, value[0], true) +
- value[value.size - 2]
- else
- radio_button(name, value[0]) +
- value[value.size - 1]
- end
- end
- }.to_s
- end
-
-
-=begin
-=== RESET BUTTON
- reset
- # <INPUT TYPE="reset">
-
- reset("reset")
- # <INPUT TYPE="reset" VALUE="reset">
-
- reset({ "VALUE" => "reset", "ID" => "foo" })
- # <INPUT TYPE="reset" VALUE="reset" ID="foo">
-=end
- def reset(value = nil, name = nil)
- attributes = if (not value) or value.kind_of?(String)
- { "TYPE" => "reset", "VALUE" => value, "NAME" => name }
- else
- value["TYPE"] = "reset"
- value
- end
- input(attributes)
- end
-
-
-=begin
-=== SCROLLING_LIST
- scrolling_list({"NAME" => "name", "SIZE" => 2, "MULTIPLE" => true,
- "VALUES" => [["1", "Foo"], ["2", "Bar", true], "Baz"] })
- # <SELECT NAME="name" MULTIPLE SIZE="2">
- # <OPTION VALUE="1">Foo</OPTION>
- # <OPTION SELECTED VALUE="2">Bar</OPTION>
- # <OPTION VALUE="Baz">Baz</OPTION>
- # </SELECT>
-=end
- alias scrolling_list popup_menu
-
-
-=begin
-=== SUBMIT BUTTON
- submit
- # <INPUT TYPE="submit">
-
- submit("ok")
- # <INPUT TYPE="submit" VALUE="ok">
-
- submit("ok", "button1")
- # <INPUT TYPE="submit" VALUE="ok" NAME="button1">
-
- submit({ "VALUE" => "ok", "NAME" => "button1", "ID" => "foo" })
- # <INPUT TYPE="submit" VALUE="ok" NAME="button1" ID="foo">
-=end
- def submit(value = nil, name = nil)
- attributes = if (not value) or value.kind_of?(String)
- { "TYPE" => "submit", "VALUE" => value, "NAME" => name }
- else
- value["TYPE"] = "submit"
- value
- end
- input(attributes)
- end
-
-
-=begin
-=== TEXT_FIELD
- text_field("name")
- # <INPUT TYPE="text" NAME="name" SIZE="40">
-
- text_field("name", "value")
- # <INPUT TYPE="text" NAME="name" VALUE="value" SIZE="40">
-
- text_field("name", "value", 80)
- # <INPUT TYPE="text" NAME="name" VALUE="value", SIZE="80">
-
- text_field("name", "value", 80, 200)
- # <INPUT TYPE="text" NAME="name" VALUE="value", SIZE="80", MAXLENGTH="200">
-
- text_field({ "NAME" => "name", "VALUE" => "value" })
- # <INPUT TYPE="text" NAME="name" VALUE="value">
-=end
- def text_field(name = "", value = nil, size = 40, maxlength = nil)
- attributes = if name.kind_of?(String)
- { "TYPE" => "text", "NAME" => name, "VALUE" => value,
- "SIZE" => size.to_s }
- else
- name["TYPE"] = "text"
- name
- end
- attributes["MAXLENGTH"] = maxlength.to_s if maxlength
- input(attributes)
- end
-
-
-=begin
-=== TEXTAREA ELEMENT
- textarea("name")
- # = textarea({ "NAME" => "name", "COLS" => 70, "ROWS" => 10 })
-
- textarea("name", 40, 5)
- # = textarea({ "NAME" => "name", "COLS" => 40, "ROWS" => 5 })
-=end
- def textarea(name = "", cols = 70, rows = 10)
- attributes = if name.kind_of?(String)
- { "NAME" => name, "COLS" => cols.to_s,
- "ROWS" => rows.to_s }
- else
- name
- end
- if block_given?
- super(attributes){ yield }
- else
- super(attributes)
- end
- end
-
- end # HtmlExtension
-
-
- module Html3
-
- def doctype
- %|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">|
- end
-
- def element_init
- extend TagMaker
- methods = ""
- # - -
- for element in %w[ A TT I B U STRIKE BIG SMALL SUB SUP EM STRONG
- DFN CODE SAMP KBD VAR CITE FONT ADDRESS DIV center MAP
- APPLET PRE XMP LISTING DL OL UL DIR MENU SELECT table TITLE
- STYLE SCRIPT H1 H2 H3 H4 H5 H6 TEXTAREA FORM BLOCKQUOTE
- CAPTION ]
- methods += <<-BEGIN + nn_element_def(element) + <<-END
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- end
-
- # - O EMPTY
- for element in %w[ IMG BASE BASEFONT BR AREA LINK PARAM HR INPUT
- ISINDEX META ]
- methods += <<-BEGIN + nOE_element_def(element) + <<-END
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- end
-
- # O O or - O
- for element in %w[ HTML HEAD BODY P PLAINTEXT DT DD LI OPTION tr
- th td ]
- methods += <<-BEGIN + nO_element_def(element) + <<-END
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- end
- eval(methods)
- end
-
- end # Html3
-
-
- module Html4
-
- def doctype
- %|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">|
- end
-
- def element_init
- extend TagMaker
- methods = ""
- # - -
- for element in %w[ TT I B BIG SMALL EM STRONG DFN CODE SAMP KBD
- VAR CITE ABBR ACRONYM SUB SUP SPAN BDO ADDRESS DIV MAP OBJECT
- H1 H2 H3 H4 H5 H6 PRE Q INS DEL DL OL UL LABEL SELECT OPTGROUP
- FIELDSET LEGEND BUTTON TABLE TITLE STYLE SCRIPT NOSCRIPT
- TEXTAREA FORM A BLOCKQUOTE CAPTION ]
- methods += <<-BEGIN + nn_element_def(element) + <<-END
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- end
-
- # - O EMPTY
- for element in %w[ IMG BASE BR AREA LINK PARAM HR INPUT COL META ]
- methods += <<-BEGIN + nOE_element_def(element) + <<-END
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- end
-
- # O O or - O
- for element in %w[ HTML BODY P DT DD LI OPTION THEAD TFOOT TBODY
- COLGROUP TR TH TD HEAD]
- methods += <<-BEGIN + nO_element_def(element) + <<-END
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- end
- eval(methods)
- end
-
- end # Html4
-
-
- module Html4Tr
-
- def doctype
- %|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">|
- end
-
- def element_init
- extend TagMaker
- methods = ""
- # - -
- for element in %w[ TT I B U S STRIKE BIG SMALL EM STRONG DFN
- CODE SAMP KBD VAR CITE ABBR ACRONYM FONT SUB SUP SPAN BDO
- ADDRESS DIV CENTER MAP OBJECT APPLET H1 H2 H3 H4 H5 H6 PRE Q
- INS DEL DL OL UL DIR MENU LABEL SELECT OPTGROUP FIELDSET
- LEGEND BUTTON TABLE IFRAME NOFRAMES TITLE STYLE SCRIPT
- NOSCRIPT TEXTAREA FORM A BLOCKQUOTE CAPTION ]
- methods += <<-BEGIN + nn_element_def(element) + <<-END
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- end
-
- # - O EMPTY
- for element in %w[ IMG BASE BASEFONT BR AREA LINK PARAM HR INPUT
- COL ISINDEX META ]
- methods += <<-BEGIN + nOE_element_def(element) + <<-END
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- end
-
- # O O or - O
- for element in %w[ HTML BODY P DT DD LI OPTION THEAD TFOOT TBODY
- COLGROUP TR TH TD HEAD ]
- methods += <<-BEGIN + nO_element_def(element) + <<-END
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- end
- eval(methods)
- end
-
- end # Html4Tr
-
-
- module Html4Fr
-
- def doctype
- %|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">|
- end
-
- def element_init
- methods = ""
- # - -
- for element in %w[ FRAMESET ]
- methods += <<-BEGIN + nn_element_def(element) + <<-END
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- end
-
- # - O EMPTY
- for element in %w[ FRAME ]
- methods += <<-BEGIN + nOE_element_def(element) + <<-END
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- end
- eval(methods)
- end
-
- end # Html4Fr
-
-
- def initialize(type = "query")
- extend QueryExtension
- if defined?(CGI_PARAMS)
- @params = CGI_PARAMS.nil? ? nil : CGI_PARAMS.dup
- @cookies = CGI_COOKIES.nil? ? nil : CGI_COOKIES.dup
- else
- initialize_query() # set @params, @cookies
- eval "CGI_PARAMS = @params.nil? ? nil : @params.dup"
- eval "CGI_COOKIES = @cookies.nil? ? nil : @cookies.dup"
- end
- @output_cookies = nil
- @output_hidden = nil
-
- case type
- when "html3"
- extend Html3
- element_init()
- extend HtmlExtension
- when "html4"
- extend Html4
- element_init()
- extend HtmlExtension
- when "html4Tr"
- extend Html4Tr
- element_init()
- extend HtmlExtension
- when "html4Fr"
- extend Html4Tr
- element_init()
- extend Html4Fr
- element_init()
- extend HtmlExtension
- end
-
- end
-
- if defined?(MOD_RUBY) and (RUBY_VERSION < "1.4.3")
- raise "Please, use ruby1.4.3 or later."
- else
- at_exit() do
- if defined?(CGI_PARAMS)
- remove_const(:CGI_PARAMS)
- remove_const(:CGI_COOKIES)
- end
- end
- end
-end
-
-
-=begin
-
-== HISTORY
-
-delete. see cvs log.
-
-
-=end
diff --git a/lib/cgi/session.rb b/lib/cgi/session.rb
deleted file mode 100644
index eb8f0cbaf6..0000000000
--- a/lib/cgi/session.rb
+++ /dev/null
@@ -1,185 +0,0 @@
-# Copyright (C) 2001 Yukihiro "Matz" Matsumoto
-# Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
-# Copyright (C) 2000 Information-technology Promotion Agency, Japan
-
-require 'cgi'
-require 'final'
-
-class CGI
- class Session
-
- attr_reader :session_id
-
- def Session::callback(dbman)
- lambda{
- dbman[0].close unless dbman.empty?
- }
- end
-
- def Session::create_new_id
- require 'digest/md5'
- md5 = Digest::MD5::new
- md5.update(String(Time::now))
- md5.update(String(rand(0)))
- md5.update(String($$))
- md5.update('foobar')
- md5.hexdigest[0,16]
- end
-
- def initialize(request, option={})
- session_key = option['session_key'] || '_session_id'
- id, = option['session_id']
- unless id
- if option['new_session']
- id = Session::create_new_id
- end
- end
- unless id
- id, = request[session_key]
- unless id
- id, = request.cookies[session_key]
- end
- unless id
- if option.key?('new_session') and not option['new_session']
- raise ArgumentError, "session_key `%s' should be supplied"%session_key
- end
- id = Session::create_new_id
- end
- end
- @session_id = id
- dbman = option['database_manager'] || FileStore
- @dbman = dbman::new(self, option)
- request.instance_eval do
- @output_hidden = {session_key => id}
- @output_cookies = [
- Cookie::new("name" => session_key,
- "value" => id,
- "path" => if option['session_path'] then
- option['session_path']
- elsif ENV["SCRIPT_NAME"] then
- File::dirname(ENV["SCRIPT_NAME"])
- else
- ""
- end)
- ]
- end
- @dbprot = [@dbman]
- ObjectSpace::define_finalizer(self, Session::callback(@dbprot))
- end
-
- def [](key)
- unless @data
- @data = @dbman.restore
- end
- @data[key]
- end
-
- def []=(key, val)
- unless @write_lock
- @write_lock = true
- end
- unless @data
- @data = @dbman.restore
- end
- @data[key] = val
- end
-
- def update
- @dbman.update
- end
-
- def close
- @dbman.close
- @dbprot.clear
- end
-
- def delete
- @dbman.delete
- @dbprot.clear
- end
-
- class FileStore
- def check_id(id)
- /[^0-9a-zA-Z]/ =~ id.to_s ? false : true
- end
-
- def initialize(session, option={})
- dir = option['tmpdir'] || ENV['TMP'] || '/tmp'
- prefix = option['prefix'] || ''
- id = session.session_id
- unless check_id(id)
- raise ArgumentError, "session_id `%s' is invalid" % id
- end
- path = dir+"/"+prefix+id
- path.untaint
- unless File::exist? path
- @hash = {}
- end
- begin
- @f = open(path, "r+")
- rescue Errno::ENOENT
- @f = open(path, "w+")
- end
- end
-
- def restore
- unless @hash
- @hash = {}
- @f.flock File::LOCK_EX
- @f.rewind
- for line in @f
- line.chomp!
- k, v = line.split('=',2)
- @hash[CGI::unescape(k)] = CGI::unescape(v)
- end
- end
- @hash
- end
-
- def update
- @f.rewind
- for k,v in @hash
- @f.printf "%s=%s\n", CGI::escape(k), CGI::escape(String(v))
- end
- @f.truncate @f.tell
- end
-
- def close
- return if @f.closed?
- update
- @f.close
- end
-
- def delete
- path = @f.path
- @f.close
- File::unlink path
- end
- end
-
- class MemoryStore
- GLOBAL_HASH_TABLE = {}
-
- def initialize(session, option=nil)
- @session_id = session.session_id
- GLOBAL_HASH_TABLE[@session_id] ||= {}
- end
-
- def restore
- GLOBAL_HASH_TABLE[@session_id]
- end
-
- def update
- # don't need to update; hash is shared
- end
-
- def close
- # don't need to close
- end
-
- def delete
- GLOBAL_HASH_TABLE.delete(@session_id)
- end
- end
- end
-end
diff --git a/lib/complex.rb b/lib/complex.rb
deleted file mode 100644
index 77d8859a6a..0000000000
--- a/lib/complex.rb
+++ /dev/null
@@ -1,489 +0,0 @@
-#
-# complex.rb -
-# $Release Version: 0.5 $
-# $Revision: 1.3 $
-# $Date: 1998/07/08 10:05:28 $
-# by Keiju ISHITSUKA(SHL Japan Inc.)
-#
-# --
-# Usage:
-# class Complex < Numeric
-#
-# Complex(x, y) --> x + yi
-# y.im --> 0 + yi
-#
-# Complex::polar
-#
-# Complex::+
-# Complex::-
-# Complex::*
-# Complex::/
-# Complex::**
-# Complex::%
-# Complex::divmod -- obsolete
-# Complex::abs
-# Complex::abs2
-# Complex::arg
-# Complex::polar
-# Complex::conjugate
-# Complex::<=>
-# Complex::==
-# Complex::to_f
-# Complex::to_r
-# Complex::to_s
-#
-# Complex::I
-#
-# Numeric::im
-#
-# Math.sqrt
-# Math.exp
-# Math.cos
-# Math.sin
-# Math.tan
-# Math.log
-# Math.log10
-# Math.atan2
-#
-#
-
-def Complex(a, b = 0)
- if a.kind_of?(Complex) and b == 0
- a
- elsif b.kind_of?(Complex)
- if a.kind_of?(Complex)
- Complex(a.real-b.image, a.image + b.real)
- else
- Complex(a-b.image, b.real)
- end
- elsif b == 0 and defined? Complex::Unify
- a
- else
- Complex.new(a, b)
- end
-end
-
-class Complex < Numeric
- @RCS_ID='-$Id: complex.rb,v 1.3 1998/07/08 10:05:28 keiju Exp keiju $-'
-
- def Complex.generic?(other)
- other.kind_of?(Integer) or
- other.kind_of?(Float) or
- (defined?(Rational) and other.kind_of?(Rational))
- end
-
- def Complex.polar(r, theta)
- Complex(r*Math.cos(theta), r*Math.sin(theta))
- end
-
- def initialize(a, b = 0)
- raise "non numeric 1st arg `#{a.inspect}'" if !a.kind_of? Numeric
- raise "non numeric 2nd arg `#{b.inspect}'" if !b.kind_of? Numeric
- @real = a
- @image = b
- end
-
- def + (other)
- if other.kind_of?(Complex)
- re = @real + other.real
- im = @image + other.image
- Complex(re, im)
- elsif Complex.generic?(other)
- Complex(@real + other, @image)
- else
- x , y = other.coerce(self)
- x + y
- end
- end
-
- def - (other)
- if other.kind_of?(Complex)
- re = @real - other.real
- im = @image - other.image
- Complex(re, im)
- elsif Complex.generic?(other)
- Complex(@real - other, @image)
- else
- x , y = other.coerce(self)
- x - y
- end
- end
-
- def * (other)
- if other.kind_of?(Complex)
- re = @real*other.real - @image*other.image
- im = @real*other.image + @image*other.real
- Complex(re, im)
- elsif Complex.generic?(other)
- Complex(@real * other, @image * other)
- else
- x , y = other.coerce(self)
- x * y
- end
- end
-
- def / (other)
- if other.kind_of?(Complex)
- self*other.conjugate/other.abs2
- elsif Complex.generic?(other)
- Complex(@real/other, @image/other)
- else
- x, y = other.coerce(self)
- x/y
- end
- end
-
- def ** (other)
- if other == 0
- return Complex(1)
- end
- if other.kind_of?(Complex)
- r, theta = polar
- ore = other.real
- oim = other.image
- nr = Math.exp!(ore*Math.log!(r) - oim * theta)
- ntheta = theta*ore + oim*Math.log!(r)
- Complex.polar(nr, ntheta)
- elsif other.kind_of?(Integer)
- if other > 0
- x = self
- z = x
- n = other - 1
- while n != 0
- while (div, mod = n.divmod(2)
- mod == 0)
- x = Complex(x.real*x.real - x.image*x.image, 2*x.real*x.image)
- n = div
- end
- z *= x
- n -= 1
- end
- z
- else
- if defined? Rational
- (Rational(1) / self) ** -other
- else
- self ** Float(other)
- end
- end
- elsif Complex.generic?(other)
- r, theta = polar
- Complex.polar(r.power!(other), theta * other)
- else
- x, y = other.coerce(self)
- x/y
- end
- end
-
- def % (other)
- if other.kind_of?(Complex)
- Complex(@real % other.real, @image % other.image)
- elsif Complex.generic?(other)
- Complex(@real % other, @image % other)
- else
- x , y = other.coerce(self)
- x % y
- end
- end
-
-# def divmod(other)
-# if other.kind_of?(Complex)
-# rdiv, rmod = @real.divmod(other.real)
-# idiv, imod = @image.divmod(other.image)
-# return Complex(rdiv, idiv), Complex(rmod, rmod)
-# elsif Complex.generic?(other)
-# Complex(@real.divmod(other), @image.divmod(other))
-# else
-# x , y = other.coerce(self)
-# x.divmod(y)
-# end
-# end
-
- def abs
- Math.sqrt!((@real*@real + @image*@image).to_f)
- end
-
- def abs2
- @real*@real + @image*@image
- end
-
- def arg
- Math.atan2(@image.to_f, @real.to_f)
- end
-
- def polar
- return abs, arg
- end
-
- def conjugate
- Complex(@real, -@image)
- end
-
- def <=> (other)
- self.abs <=> other.abs
- end
-
- def == (other)
- if other.kind_of?(Complex)
- @real == other.real and @image == other.image
- elsif Complex.generic?(other)
- @real == other and @image == 0
- else
- x , y = other.coerce(self)
- x == y
- end
- end
-
- def coerce(other)
- if Complex.generic?(other)
- return Complex.new(other), self
- else
- super
- end
- end
-
- def denominator
- @real.denominator.lcm(@image.denominator)
- end
-
- def numerator
- cd = denominator
- Complex(@real.numerator*(cd/@real.denominator),
- @image.numerator*(cd/@image.denominator))
- end
-
- def to_s
- if @real != 0
- if defined?(Rational) and @image.kind_of?(Rational) and @image.denominator != 1
- if @image >= 0
- @real.to_s+"+("+@image.to_s+")i"
- else
- @real.to_s+"-("+(-@image).to_s+")i"
- end
- else
- if @image >= 0
- @real.to_s+"+"+@image.to_s+"i"
- else
- @real.to_s+"-"+(-@image).to_s+"i"
- end
- end
- else
- if defined?(Rational) and @image.kind_of?(Rational) and @image.denominator != 1
- "("+@image.to_s+")i"
- else
- @image.to_s+"i"
- end
- end
- end
-
- def hash
- @real.hash ^ @image.hash
- end
-
- def inspect
- sprintf("Complex(%s, %s)", @real.inspect, @image.inspect)
- end
-
-
- I = Complex(0,1)
-
- attr :real
- attr :image
-
-end
-
-class Numeric
- def im
- Complex(0, self)
- end
-
- def real
- self
- end
-
- def image
- 0
- end
-
- def arg
- if self >= 0
- return 0
- else
- return Math.atan2(1,1)*4
- end
- end
-
- def polar
- return abs, arg
- end
-
- def conjugate
- self
- end
-end
-
-class Fixnum
- if not defined? Rational
- alias power! **
- end
-
- def ** (other)
- if self < 0
- Complex.new(self) ** other
- else
- if defined? Rational
- if other >= 0
- self.power!(other)
- else
- Rational.new!(self,1)**other
- end
- else
- self.power!(other)
- end
- end
- end
-end
-
-class Bignum
- if not defined? Rational
- alias power! **
- end
-end
-
-class Float
- alias power! **
-end
-
-module Math
- alias sqrt! sqrt
- alias exp! exp
- alias cos! cos
- alias sin! sin
- alias tan! tan
- alias log! log
- alias log10! log10
- alias atan2! atan2
-
- def sqrt(z)
- if Complex.generic?(z)
- if z >= 0
- sqrt!(z)
- else
- Complex(0,sqrt!(-z))
- end
- else
- z**Rational(1,2)
- end
- end
-
- def exp(z)
- if Complex.generic?(z)
- exp!(z)
- else
- Complex(exp!(z.real) * cos!(z.image), exp!(z.real) * sin!(z.image))
- end
- end
-
- def cosh!(x)
- (exp!(x) + exp!(-x))/2.0
- end
-
- def sinh!(x)
- (exp!(x) - exp!(-x))/2.0
- end
-
- def cos(z)
- if Complex.generic?(z)
- cos!(z)
- else
- Complex(cos!(z.real)*cosh!(z.image),
- -sin!(z.real)*sinh!(z.image))
- end
- end
-
- def sin(z)
- if Complex.generic?(z)
- sin!(z)
- else
- Complex(sin!(z.real)*cosh!(z.image),
- cos!(z.real)*sinh!(z.image))
- end
- end
-
- def tan(z)
- if Complex.generic?(z)
- tan!(z)
- else
- sin(z)/cos(z)
- end
- end
-
- def log(z)
- if Complex.generic?(z) and z >= 0
- log!(z)
- else
- r, theta = z.polar
- Complex(log!(r.abs), theta)
- end
- end
-
- def log10(z)
- if Complex.generic?(z)
- log10!(z)
- else
- log(z)/log!(10)
- end
- end
-
- def atan2(x, y)
- if Complex.generic?(x) and Complex.generic?(y)
- atan2!(x, y)
- else
- fail "Not yet implemented."
- end
- end
-
- def atanh!(x)
- log((1.0 + x.to_f) / ( 1.0 - x.to_f)) / 2.0
- end
-
- def atan(z)
- if Complex.generic?(z)
- atan2!(z, 1)
- elsif z.image == 0
- atan2(z.real,1)
- else
- a = z.real
- b = z.image
-
- c = (a*a + b*b - 1.0)
- d = (a*a + b*b + 1.0)
-
- Complex(atan2!((c + sqrt(c*c + 4.0*a*a)), 2.0*a),
- atanh!((-d + sqrt(d*d - 4.0*b*b))/(2.0*b)))
- end
- end
-
- module_function :sqrt
- module_function :sqrt!
- module_function :exp!
- module_function :exp
- module_function :cosh!
- module_function :cos!
- module_function :cos
- module_function :sinh!
- module_function :sin!
- module_function :sin
- module_function :tan!
- module_function :tan
- module_function :log!
- module_function :log
- module_function :log10!
- module_function :log
- module_function :atan2!
- module_function :atan2
-# module_function :atan!
- module_function :atan
- module_function :atanh!
-
-end
diff --git a/lib/date.rb b/lib/date.rb
deleted file mode 100644
index 3422121298..0000000000
--- a/lib/date.rb
+++ /dev/null
@@ -1,345 +0,0 @@
-# date2.rb: Written by Tadayoshi Funaba 1998-2001
-# $Id: date2.rb,v 1.23 2001-01-18 12:09:47+09 tadf Exp $
-
-class Date
-
- include Comparable
-
- IDENT = 2
-
- MONTHNAMES = [nil] + %w(January February March April May June July
- August September October November December)
-
- DAYNAMES = %w(Sunday Monday Tuesday Wednesday Thursday Friday Saturday)
-
- ITALY = 2299161 # 1582-10-15
- ENGLAND = 2361222 # 1752-09-14
- JULIAN = false
- GREGORIAN = true
-
- class << self
-
- def os? (jd, sg)
- case sg
- when Numeric; jd < sg
- else; not sg
- end
- end
-
- def ns? (jd, sg) not os?(jd, sg) end
-
- def civil_to_jd(y, m, d, sg=GREGORIAN)
- if m <= 2
- y -= 1
- m += 12
- end
- a = (y / 100.0).floor
- b = 2 - a + (a / 4.0).floor
- jd = (365.25 * (y + 4716)).floor +
- (30.6001 * (m + 1)).floor +
- d + b - 1524
- if os?(jd, sg)
- jd -= b
- end
- jd
- end
-
- def jd_to_civil(jd, sg=GREGORIAN)
- if os?(jd, sg)
- a = jd
- else
- x = ((jd - 1867216.25) / 36524.25).floor
- a = jd + 1 + x - (x / 4.0).floor
- end
- b = a + 1524
- c = ((b - 122.1) / 365.25).floor
- d = (365.25 * c).floor
- e = ((b - d) / 30.6001).floor
- dom = b - d - (30.6001 * e).floor
- if e <= 13
- m = e - 1
- y = c - 4716
- else
- m = e - 13
- y = c - 4715
- end
- return y, m, dom
- end
-
- def ordinal_to_jd(y, d, sg=GREGORIAN)
- civil_to_jd(y, 1, d, sg)
- end
-
- def jd_to_ordinal(jd, sg=GREGORIAN)
- y = jd_to_civil(jd, sg)[0]
- doy = jd - civil_to_jd(y - 1, 12, 31, ns?(jd, sg))
- return y, doy
- end
-
- def jd_to_commercial(jd, sg=GREGORIAN)
- ns = ns?(jd, sg)
- a = jd_to_civil(jd - 3, ns)[0]
- y = if jd >= commercial_to_jd(a + 1, 1, 1, ns) then a + 1 else a end
- w = 1 + (jd - commercial_to_jd(y, 1, 1, ns)) / 7
- d = (jd + 1) % 7
- if d.zero? then d = 7 end
- return y, w, d
- end
-
- def commercial_to_jd(y, w, d, ns=GREGORIAN)
- jd = civil_to_jd(y, 1, 4, ns)
- (jd - (((jd - 1) + 1) % 7)) +
- 7 * (w - 1) +
- (d - 1)
- end
-
- def clfloor(x, y=1)
- q, r = x.divmod(y)
- q = q.to_i
- return q, r
- end
-
- def rjd_to_jd(rjd) clfloor(rjd + 0.5) end
- def jd_to_rjd(jd, fr) jd + fr - 0.5 end
-
- def mjd_to_jd(mjd) mjd + 2400000.5 end
- def jd_to_mjd(jd) jd - 2400000.5 end
- def tjd_to_jd(tjd) tjd + 2440000.5 end
- def jd_to_tjd(jd) jd - 2440000.5 end
- def tjd2_to_jd(cycle, tjd) tjd_to_jd(cycle * 10000 + tjd) end
- def jd_to_tjd2(jd) clfloor(jd_to_tjd(jd), 10000) end
- def ld_to_jd(ld) ld + 2299160 end
- def jd_to_ld(jd) jd - 2299160 end
-
- def jd_to_wday(jd) (jd + 1) % 7 end
-
- def julian_leap? (y) y % 4 == 0 end
- def gregorian_leap? (y) y % 4 == 0 and y % 100 != 0 or y % 400 == 0 end
-
- alias_method :leap?, :gregorian_leap?
-
- alias_method :new0, :new
-
- def new1(jd=0, sg=ITALY) new0(jd, sg) end
-
- def exist3? (y, m, d, sg=ITALY)
- if m < 0
- m += 13
- end
- if d < 0
- ny, nm = clfloor(y * 12 + m, 12)
- nm, = clfloor(nm + 1, 1)
- jd = civil_to_jd(ny, nm, d + 1, sg)
- ns = ns?(jd, sg)
- return unless [y, m] == jd_to_civil(jd, sg)[0..1]
- return unless [ny, nm, 1] == jd_to_civil(jd - d, ns)
- else
- jd = civil_to_jd(y, m, d, sg)
- return unless [y, m, d] == jd_to_civil(jd, sg)
- end
- jd
- end
-
- alias_method :exist?, :exist3?
-
- def new3(y=-4712, m=1, d=1, sg=ITALY)
- unless jd = exist3?(y, m, d, sg)
- raise ArgumentError, 'invalid date'
- end
- new0(jd, sg)
- end
-
- alias_method :new, :new3
-
- def exist2? (y, d, sg=ITALY)
- if d < 0
- ny, = clfloor(y + 1, 1)
- jd = ordinal_to_jd(ny, d + 1, sg)
- ns = ns?(jd, sg)
- return unless [y] == jd_to_ordinal(jd, sg)[0..0]
- return unless [ny, 1] == jd_to_ordinal(jd - d, ns)
- else
- jd = ordinal_to_jd(y, d, sg)
- return unless [y, d] == jd_to_ordinal(jd, sg)
- end
- jd
- end
-
- def new2(y=-4712, d=1, sg=ITALY)
- unless jd = exist2?(y, d, sg)
- raise ArgumentError, 'invalid date'
- end
- new0(jd, sg)
- end
-
- def existw? (y, w, d, sg=ITALY)
- if d < 0
- d += 8
- end
- if w < 0
- w = jd_to_commercial(commercial_to_jd(y + 1, 1, 1) + w * 7)[1]
- end
- jd = commercial_to_jd(y, w, d)
- return unless ns?(jd, sg)
- return unless [y, w, d] == jd_to_commercial(jd)
- jd
- end
-
- def neww(y=1582, w=41, d=5, sg=ITALY)
- unless jd = existw?(y, w, d, sg)
- raise ArgumentError, 'invalid date'
- end
- new0(jd, sg)
- end
-
- def today(sg=ITALY)
- new0(civil_to_jd(*(Time.now.to_a[3..5].reverse << sg)), sg)
- end
-
- def once(*ids)
- for id in ids
- module_eval <<-"end;"
- alias_method :__#{id.to_i}__, :#{id.id2name}
- private :__#{id.to_i}__
- def #{id.id2name}(*args, &block)
- (@__#{id.to_i}__ ||= [__#{id.to_i}__(*args, &block)])[0]
- end
- end;
- end
- end
-
- private :once
-
- end
-
- def initialize(rjd=0, sg=ITALY) @rjd, @sg = rjd, sg end
-
- def rjd() @rjd end
- def rmjd() type.jd_to_mjd(@rjd) end
- def rtjd() type.jd_to_tjd(@rjd) end
- def rtjd2() type.jd_to_tjd2(@rjd) end
-
- once :rmjd, :rtjd, :rtjd2
-
- def jd() type.rjd_to_jd(@rjd)[0] end
- def fr1() type.rjd_to_jd(@rjd)[1] end
- def mjd() type.jd_to_mjd(jd) end
- def tjd() type.jd_to_tjd(jd) end
- def tjd2() type.jd_to_tjd2(jd) end
- def ld() type.jd_to_ld(jd) end
-
- once :jd, :fr1, :mjd, :tjd, :tjd2, :ld
-
- def civil() type.jd_to_civil(jd, @sg) end
- def ordinal() type.jd_to_ordinal(jd, @sg) end
- def commercial() type.jd_to_commercial(jd, @sg) end
-
- once :civil, :ordinal, :commercial
- private :civil, :ordinal, :commercial
-
- def year() civil[0] end
- def yday() ordinal[1] end
- def mon() civil[1] end
-
- alias_method :month, :mon
-
- def mday() civil[2] end
-
- alias_method :day, :mday
-
- def cwyear() commercial[0] end
- def cweek() commercial[1] end
- def cwday() commercial[2] end
-
- def wday() type.jd_to_wday(jd) end
-
- once :wday
-
- def os? () type.os?(jd, @sg) end
- def ns? () type.ns?(jd, @sg) end
-
- once :os?, :ns?
-
- def leap?
- type.jd_to_civil(type.civil_to_jd(year, 3, 1, ns?) - 1,
- ns?)[-1] == 29
- end
-
- once :leap?
-
- def sg() @sg end
- def newsg(sg=type::ITALY) type.new0(@rjd, sg) end
-
- def italy() newsg(type::ITALY) end
- def england() newsg(type::ENGLAND) end
- def julian() newsg(type::JULIAN) end
- def gregorian() newsg(type::GREGORIAN) end
-
- def + (n)
- case n
- when Numeric; return type.new0(@rjd + n, @sg)
- end
- raise TypeError, 'expected numeric'
- end
-
- def - (x)
- case x
- when Numeric; return type.new0(@rjd - x, @sg)
- when Date; return @rjd - x.rjd
- end
- raise TypeError, 'expected numeric or date'
- end
-
- def <=> (other)
- case other
- when Numeric; return @rjd <=> other
- when Date; return @rjd <=> other.rjd
- end
- raise TypeError, 'expected numeric or date'
- end
-
- def === (other)
- case other
- when Numeric; return jd == other
- when Date; return jd == other.jd
- end
- raise TypeError, 'expected numeric or date'
- end
-
- def >> (n)
- y, m = type.clfloor(year * 12 + (mon - 1) + n, 12)
- m, = type.clfloor(m + 1, 1)
- d = mday
- d -= 1 until jd2 = type.exist3?(y, m, d, ns?)
- self + (jd2 - jd)
- end
-
- def << (n) self >> -n end
-
- def step(limit, step)
- da = self
- op = [:-,:<=,:>=][step<=>0]
- while da.__send__(op, limit)
- yield da
- da += step
- end
- self
- end
-
- def upto(max, &block) step(max, +1, &block) end
- def downto(min, &block) step(min, -1, &block) end
-
- def succ() self + 1 end
-
- alias_method :next, :succ
-
- def eql? (other) Date === other and self == other end
- def hash() type.clfloor(@rjd)[0] end
-
- def inspect() format('#<%s: %s,%s>', type, @rjd, @sg) end
- def to_s() format('%.4d-%02d-%02d', year, mon, mday) end
-
- def _dump(limit) Marshal.dump([@rjd, @sg], -1) end
- def self._load(str) new0(*Marshal.load(str)) end
-
-end
diff --git a/lib/date2.rb b/lib/date2.rb
deleted file mode 100644
index f7da78f650..0000000000
--- a/lib/date2.rb
+++ /dev/null
@@ -1,5 +0,0 @@
-# date2 was overridden by date.
-# To be precise, date was overridden by date2,
-# and date2 was renamed to date.
-
-require 'date'
diff --git a/lib/debug.rb b/lib/debug.rb
deleted file mode 100644
index 481658ccbf..0000000000
--- a/lib/debug.rb
+++ /dev/null
@@ -1,928 +0,0 @@
-# Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
-# Copyright (C) 2000 Information-technology Promotion Agency, Japan
-
-if $SAFE > 0
- STDERR.print "-r debug.rb is not available in safe mode\n"
- exit 1
-end
-
-require 'tracer'
-require 'pp'
-
-class Tracer
- def Tracer.trace_func(*vars)
- Single.trace_func(*vars)
- end
-end
-
-SCRIPT_LINES__ = {} unless defined? SCRIPT_LINES__
-
-class DEBUGGER__
-class Mutex
- def initialize
- @locker = nil
- @waiting = []
- @locked = false;
- end
-
- def locked?
- @locked
- end
-
- def lock
- return if @locker == Thread.current
- while (Thread.critical = true; @locked)
- @waiting.push Thread.current
- Thread.stop
- end
- @locked = true
- @locker = Thread.current
- Thread.critical = false
- self
- end
-
- def unlock
- return unless @locked
- unless @locker == Thread.current
- raise RuntimeError, "unlocked by other"
- end
- Thread.critical = true
- t = @waiting.shift
- @locked = false
- @locker = nil
- Thread.critical = false
- t.run if t
- self
- end
-end
-MUTEX = Mutex.new
-
-class Context
- DEBUG_LAST_CMD = []
-
- begin
- require 'readline'
- def readline(prompt, hist)
- Readline::readline(prompt, hist)
- end
- rescue LoadError
- def readline(prompt, hist)
- STDOUT.print prompt
- STDOUT.flush
- line = STDIN.gets
- exit unless line
- line.chomp!
- line
- end
- USE_READLINE = false
- end
-
- def initialize
- if Thread.current == Thread.main
- @stop_next = 1
- else
- @stop_next = 0
- end
- @last_file = nil
- @file = nil
- @line = nil
- @no_step = nil
- @frames = []
- @finish_pos = 0
- @trace = false
- @catch = "StandardError"
- @suspend_next = false
- end
-
- def stop_next(n=1)
- @stop_next = n
- end
-
- def set_suspend
- @suspend_next = true
- end
-
- def clear_suspend
- @suspend_next = false
- end
-
- def suspend_all
- DEBUGGER__.suspend
- end
-
- def resume_all
- DEBUGGER__.resume
- end
-
- def check_suspend
- while (Thread.critical = true; @suspend_next)
- DEBUGGER__.waiting.push Thread.current
- @suspend_next = false
- Thread.stop
- end
- Thread.critical = false
- end
-
- def trace?
- @trace
- end
-
- def set_trace(arg)
- @trace = arg
- end
-
- def stdout
- DEBUGGER__.stdout
- end
-
- def break_points
- DEBUGGER__.break_points
- end
-
- def display
- DEBUGGER__.display
- end
-
- def context(th)
- DEBUGGER__.context(th)
- end
-
- def set_trace_all(arg)
- DEBUGGER__.set_trace(arg)
- end
-
- def set_last_thread(th)
- DEBUGGER__.set_last_thread(th)
- end
-
- def debug_eval(str, binding)
- begin
- val = eval(str, binding)
- val
- rescue StandardError, ScriptError
- at = eval("caller(0)", binding)
- stdout.printf "%s:%s\n", at.shift, $!.to_s.sub(/\(eval\):1:(in `.*?':)?/, '') #`
- for i in at
- stdout.printf "\tfrom %s\n", i
- end
- throw :debug_error
- end
- end
-
- def debug_silent_eval(str, binding)
- begin
- val = eval(str, binding)
- val
- rescue StandardError, ScriptError
- nil
- end
- end
-
- def var_list(ary, binding)
- ary.sort!
- for v in ary
- stdout.printf " %s => %s\n", v, eval(v, binding).inspect
- end
- end
-
- def debug_variable_info(input, binding)
- case input
- when /^\s*g(?:lobal)?$/
- var_list(global_variables, binding)
-
- when /^\s*l(?:ocal)?$/
- var_list(eval("local_variables", binding), binding)
-
- when /^\s*i(?:nstance)?\s+/
- obj = debug_eval($', binding)
- var_list(obj.instance_variables, obj.instance_eval{binding()})
-
- when /^\s*c(?:onst(?:ant)?)?\s+/
- obj = debug_eval($', binding)
- unless obj.kind_of? Module
- stdout.print "Should be Class/Module: ", $', "\n"
- else
- var_list(obj.constants, obj.module_eval{binding()})
- end
- end
- end
-
- def debug_method_info(input, binding)
- case input
- when /^i(:?nstance)?\s+/
- obj = debug_eval($', binding)
-
- len = 0
- for v in obj.methods.sort
- len += v.size + 1
- if len > 70
- len = v.size + 1
- stdout.print "\n"
- end
- stdout.print v, " "
- end
- stdout.print "\n"
-
- else
- obj = debug_eval(input, binding)
- unless obj.kind_of? Module
- stdout.print "Should be Class/Module: ", input, "\n"
- else
- len = 0
- for v in obj.instance_methods.sort
- len += v.size + 1
- if len > 70
- len = v.size + 1
- stdout.print "\n"
- end
- stdout.print v, " "
- end
- stdout.print "\n"
- end
- end
- end
-
- def thnum
- num = DEBUGGER__.instance_eval{@thread_list[Thread.current]}
- unless num
- DEBUGGER__.make_thread_list
- num = DEBUGGER__.instance_eval{@thread_list[Thread.current]}
- end
- num
- end
-
- def debug_command(file, line, id, binding)
- MUTEX.lock
- set_last_thread(Thread.current)
- frame_pos = 0
- binding_file = file
- binding_line = line
- previous_line = nil
- if (ENV['EMACS'] == 't')
- stdout.printf "\032\032%s:%d:\n", binding_file, binding_line
- else
- stdout.printf "%s:%d:%s", binding_file, binding_line,
- line_at(binding_file, binding_line)
- end
- @frames[0] = [binding, file, line, id]
- display_expressions(binding)
- prompt = true
- while prompt and input = readline("(rdb:%d) "%thnum(), true)
- catch(:debug_error) do
- if input == ""
- input = DEBUG_LAST_CMD[0]
- stdout.print input, "\n"
- else
- DEBUG_LAST_CMD[0] = input
- end
-
- case input
- when /^\s*tr(?:ace)?(?:\s+(on|off))?(?:\s+(all))?$/
- if defined?( $2 )
- if $1 == 'on'
- set_trace_all true
- else
- set_trace_all false
- end
- elsif defined?( $1 )
- if $1 == 'on'
- set_trace true
- else
- set_trace false
- end
- end
- if trace?
- stdout.print "Trace on.\n"
- else
- stdout.print "Trace off.\n"
- end
-
- when /^\s*b(?:reak)?\s+((?:.*?+:)?.+)$/
- pos = $1
- if pos.index(":")
- pos = pos.split(":")
- file = pos[0...-1].join(":")
- pos = pos[-1]
- end
- file = File.basename(file)
- if pos =~ /^\d+$/
- pname = pos
- pos = pos.to_i
- else
- pname = pos = pos.intern.id2name
- end
- break_points.push [true, 0, file, pos]
- stdout.printf "Set breakpoint %d at %s:%s\n", break_points.size, file, pname
-
- when /^\s*wat(?:ch)?\s+(.+)$/
- exp = $1
- break_points.push [true, 1, exp]
- stdout.printf "Set watchpoint %d\n", break_points.size, exp
-
- when /^\s*b(?:reak)?$/
- if break_points.find{|b| b[1] == 0}
- n = 1
- stdout.print "Breakpoints:\n"
- for b in break_points
- if b[0] and b[1] == 0
- stdout.printf " %d %s:%s\n", n, b[2], b[3]
- end
- n += 1
- end
- end
- if break_points.find{|b| b[1] == 1}
- n = 1
- stdout.print "\n"
- stdout.print "Watchpoints:\n"
- for b in break_points
- if b[0] and b[1] == 1
- stdout.printf " %d %s\n", n, b[2]
- end
- n += 1
- end
- end
- if break_points.size == 0
- stdout.print "No breakpoints\n"
- else
- stdout.print "\n"
- end
-
- when /^\s*del(?:ete)?(?:\s+(\d+))?$/
- pos = $1
- unless pos
- input = readline("Clear all breakpoints? (y/n) ", false)
- if input == "y"
- for b in break_points
- b[0] = false
- end
- end
- else
- pos = pos.to_i
- if break_points[pos-1]
- break_points[pos-1][0] = false
- else
- stdout.printf "Breakpoint %d is not defined\n", pos
- end
- end
-
- when /^\s*disp(?:lay)?\s+(.+)$/
- exp = $1
- display.push [true, exp]
- stdout.printf "%d: ", display.size
- display_expression(exp, binding)
-
- when /^\s*disp(?:lay)?$/
- display_expressions(binding)
-
- when /^\s*undisp(?:lay)?(?:\s+(\d+))?$/
- pos = $1
- unless pos
- input = readline("Clear all expressions? (y/n) ", false)
- if input == "y"
- for d in display
- d[0] = false
- end
- end
- else
- pos = pos.to_i
- if display[pos-1]
- display[pos-1][0] = false
- else
- stdout.printf "Display expression %d is not defined\n", pos
- end
- end
-
- when /^\s*c(?:ont)?$/
- prompt = false
-
- when /^\s*s(?:tep)?(?:\s+(\d+))?$/
- if $1
- lev = $1.to_i
- else
- lev = 1
- end
- @stop_next = lev
- prompt = false
-
- when /^\s*n(?:ext)?(?:\s+(\d+))?$/
- if $1
- lev = $1.to_i
- else
- lev = 1
- end
- @stop_next = lev
- @no_step = @frames.size - frame_pos
- prompt = false
-
- when /^\s*w(?:here)?$/, /^\s*f(?:rame)?$/
- display_frames(frame_pos)
-
- when /^\s*l(?:ist)?(?:\s+(.+))?$/
- if not $1
- b = previous_line ? previous_line + 10 : binding_line - 5
- e = b + 9
- elsif $1 == '-'
- b = previous_line ? previous_line - 10 : binding_line - 5
- e = b + 9
- else
- b, e = $1.split(/[-,]/)
- if e
- b = b.to_i
- e = e.to_i
- else
- b = b.to_i - 5
- e = b + 9
- end
- end
- previous_line = b
- display_list(b, e, binding_file, binding_line)
-
- when /^\s*up(?:\s+(\d+))?$/
- previous_line = nil
- if $1
- lev = $1.to_i
- else
- lev = 1
- end
- frame_pos += lev
- if frame_pos >= @frames.size
- frame_pos = @frames.size - 1
- stdout.print "At toplevel\n"
- end
- binding, binding_file, binding_line = @frames[frame_pos]
- stdout.print format_frame(frame_pos)
-
- when /^\s*down(?:\s+(\d+))?$/
- previous_line = nil
- if $1
- lev = $1.to_i
- else
- lev = 1
- end
- frame_pos -= lev
- if frame_pos < 0
- frame_pos = 0
- stdout.print "At stack bottom\n"
- end
- binding, binding_file, binding_line = @frames[frame_pos]
- stdout.print format_frame(frame_pos)
-
- when /^\s*fin(?:ish)?$/
- if frame_pos == @frames.size
- stdout.print "\"finish\" not meaningful in the outermost frame.\n"
- else
- @finish_pos = @frames.size - frame_pos
- frame_pos = 0
- prompt = false
- end
-
- when /^\s*cat(?:ch)?(?:\s+(.+))?$/
- if $1
- excn = $1
- if excn == 'off'
- @catch = nil
- stdout.print "Clear catchpoint.\n"
- else
- @catch = excn
- stdout.printf "Set catchpoint %s.\n", @catch
- end
- else
- if @catch
- stdout.printf "Catchpoint %s.\n", @catch
- else
- stdout.print "No catchpoint.\n"
- end
- end
-
- when /^\s*q(?:uit)?$/
- input = readline("Really quit? (y/n) ", false)
- if input == "y"
- exit! # exit -> exit!: No graceful way to stop threads...
- end
-
- when /^\s*v(?:ar)?\s+/
- debug_variable_info($', binding)
-
- when /^\s*m(?:ethod)?\s+/
- debug_method_info($', binding)
-
- when /^\s*th(?:read)?\s+/
- if DEBUGGER__.debug_thread_info($', binding) == :cont
- prompt = false
- end
-
- when /^\s*pp\s+/
- PP.pp(debug_eval($', binding), 79, stdout)
-
- when /^\s*p\s+/
- stdout.printf "%s\n", debug_eval($', binding).inspect
-
- when /^\s*h(?:elp)?$/
- debug_print_help()
-
- else
- v = debug_eval(input, binding)
- stdout.printf "%s\n", v.inspect unless (v == nil)
- end
- end
- end
- MUTEX.unlock
- resume_all
- end
-
- def debug_print_help
- stdout.print <<EOHELP
-Debugger help v.-0.002b
-Commands
- b[reak] [file|method:]<line|method>
- set breakpoint to some position
- wat[ch] <expression> set watchpoint to some expression
- cat[ch] <an Exception> set catchpoint to an exception
- b[reak] list breakpoints
- cat[ch] show catchpoint
- del[ete][ nnn] delete some or all breakpoints
- disp[lay] <expression> add expression into display expression list
- undisp[lay][ nnn] delete one particular or all display expressions
- c[ont] run until program ends or hit breakpoint
- s[tep][ nnn] step (into methods) one line or till line nnn
- n[ext][ nnn] go over one line or till line nnn
- w[here] display frames
- f[rame] alias for where
- l[ist][ (-|nn-mm)] list program, - lists backwards
- nn-mm lists given lines
- up[ nn] move to higher frame
- down[ nn] move to lower frame
- fin[ish] return to outer frame
- tr[ace] (on|off) set trace mode of current thread
- tr[ace] (on|off) all set trace mode of all threads
- q[uit] exit from debugger
- v[ar] g[lobal] show global variables
- v[ar] l[ocal] show local variables
- v[ar] i[nstance] <object> show instance variables of object
- v[ar] c[onst] <object> show constants of object
- m[ethod] i[nstance] <obj> show methods of object
- m[ethod] <class|module> show instance methods of class or module
- th[read] l[ist] list all threads
- th[read] c[ur[rent]] show current thread
- th[read] [sw[itch]] <nnn> switch thread context to nnn
- th[read] stop <nnn> stop thread nnn
- th[read] resume <nnn> resume thread nnn
- p expression evaluate expression and print its value
- h[elp] print this help
- <everything else> evaluate
-EOHELP
- end
-
- def display_expressions(binding)
- n = 1
- for d in display
- if d[0]
- stdout.printf "%d: ", n
- display_expression(d[1], binding)
- end
- n += 1
- end
- end
-
- def display_expression(exp, binding)
- stdout.printf "%s = %s\n", exp, debug_silent_eval(exp, binding).to_s
- end
-
- def frame_set_pos(file, line)
- if @frames[0]
- @frames[0][1] = file
- @frames[0][2] = line
- end
- end
-
- def display_frames(pos)
- 0.upto(@frames.size - 1) do |n|
- if n == pos
- stdout.print "--> "
- else
- stdout.print " "
- end
- stdout.print format_frame(n)
- end
- end
-
- def format_frame(pos)
- bind, file, line, id = @frames[pos]
- sprintf "#%d %s:%s%s\n", pos + 1, file, line,
- (id ? ":in `#{id.id2name}'" : "")
- end
-
- def display_list(b, e, file, line)
- stdout.printf "[%d, %d] in %s\n", b, e, file
- if lines = SCRIPT_LINES__[file] and lines != true
- n = 0
- b.upto(e) do |n|
- if n > 0 && lines[n-1]
- if n == line
- stdout.printf "=> %d %s\n", n, lines[n-1].chomp
- else
- stdout.printf " %d %s\n", n, lines[n-1].chomp
- end
- end
- end
- else
- stdout.printf "No sourcefile available for %s\n", file
- end
- end
-
- def line_at(file, line)
- lines = SCRIPT_LINES__[file]
- if lines
- return "\n" if lines == true
- line = lines[line-1]
- return "\n" unless line
- return line
- end
- return "\n"
- end
-
- def debug_funcname(id)
- if id.nil?
- "toplevel"
- else
- id.id2name
- end
- end
-
- def check_break_points(file, pos, binding, id)
- return false if break_points.empty?
- file = File.basename(file)
- n = 1
- for b in break_points
- if b[0]
- if b[1] == 0 and b[2] == file and b[3] == pos
- stdout.printf "Breakpoint %d, %s at %s:%s\n", n, debug_funcname(id), file, pos
- return true
- elsif b[1] == 1
- if debug_silent_eval(b[2], binding)
- stdout.printf "Watchpoint %d, %s at %s:%s\n", n, debug_funcname(id), file, pos
- return true
- end
- end
- end
- n += 1
- end
- return false
- end
-
- def excn_handle(file, line, id, binding)
- stdout.printf "%s:%d: `%s' (%s)\n", file, line, $!, $!.type
- if $!.type <= SystemExit
- set_trace_func nil
- exit
- end
-
- if @catch and ($!.type.ancestors.find { |e| e.to_s == @catch })
- fs = @frames.size
- tb = caller(0)[-fs..-1]
- if tb
- for i in tb
- stdout.printf "\tfrom %s\n", i
- end
- end
- suspend_all
- debug_command(file, line, id, binding)
- end
- end
-
- def trace_func(event, file, line, id, binding, klass)
- Tracer.trace_func(event, file, line, id, binding, klass) if trace?
- context(Thread.current).check_suspend
- @file = file
- @line = line
- case event
- when 'line'
- frame_set_pos(file, line)
- if !@no_step or @frames.size == @no_step
- @stop_next -= 1
- elsif @frames.size < @no_step
- @stop_next = 0 # break here before leaving...
- else
- # nothing to do. skipped.
- end
- if @stop_next == 0 or check_break_points(file, line, binding, id)
- @no_step = nil
- suspend_all
- debug_command(file, line, id, binding)
- end
-
- when 'call'
- @frames.unshift [binding, file, line, id]
- if check_break_points(file, id.id2name, binding, id) or
- check_break_points(klass.to_s, id.id2name, binding, id)
- suspend_all
- debug_command(file, line, id, binding)
- end
-
- when 'c-call'
- frame_set_pos(file, line)
-
- when 'class'
- @frames.unshift [binding, file, line, id]
-
- when 'return', 'end'
- if @frames.size == @finish_pos
- @stop_next = 1
- @finish_pos = 0
- end
- @frames.shift
-
- when 'end'
- @frames.shift
-
- when 'raise'
- excn_handle(file, line, id, binding)
-
- end
- @last_file = file
- end
-end
-
-trap("INT") { DEBUGGER__.interrupt }
-@last_thread = Thread::main
-@max_thread = 1
-@thread_list = {Thread::main => 1}
-@break_points = []
-@display = []
-@waiting = []
-@stdout = STDOUT
-
-class << DEBUGGER__
- def stdout
- @stdout
- end
-
- def stdout=(s)
- @stdout = s
- end
-
- def display
- @display
- end
-
- def break_points
- @break_points
- end
-
- def waiting
- @waiting
- end
-
- def set_trace( arg )
- Thread.critical = true
- make_thread_list
- for th in @thread_list
- context(th[0]).set_trace arg
- end
- Thread.critical = false
- arg
- end
-
- def set_last_thread(th)
- @last_thread = th
- end
-
- def suspend
- Thread.critical = true
- make_thread_list
- for th in @thread_list
- next if th[0] == Thread.current
- context(th[0]).set_suspend
- end
- Thread.critical = false
- # Schedule other threads to suspend as soon as possible.
- Thread.pass
- end
-
- def resume
- Thread.critical = true
- make_thread_list
- for th in @thread_list
- next if th[0] == Thread.current
- context(th[0]).clear_suspend
- end
- waiting.each do |th|
- th.run
- end
- waiting.clear
- Thread.critical = false
- # Schedule other threads to restart as soon as possible.
- Thread.pass
- end
-
- def context(thread=Thread.current)
- c = thread[:__debugger_data__]
- unless c
- thread[:__debugger_data__] = c = Context.new
- end
- c
- end
-
- def interrupt
- context(@last_thread).stop_next
- end
-
- def get_thread(num)
- th = @thread_list.index(num)
- unless th
- @stdout.print "No thread ##{num}\n"
- throw :debug_error
- end
- th
- end
-
- def thread_list(num)
- th = get_thread(num)
- if th == Thread.current
- @stdout.print "+"
- else
- @stdout.print " "
- end
- @stdout.printf "%d ", num
- @stdout.print th.inspect, "\t"
- file = context(th).instance_eval{@file}
- if file
- @stdout.print file,":",context(th).instance_eval{@line}
- end
- @stdout.print "\n"
- end
-
- def thread_list_all
- for th in @thread_list.values.sort
- thread_list(th)
- end
- end
-
- def make_thread_list
- hash = {}
- for th in Thread::list
- if @thread_list.key? th
- hash[th] = @thread_list[th]
- else
- @max_thread += 1
- hash[th] = @max_thread
- end
- end
- @thread_list = hash
- end
-
- def debug_thread_info(input, binding)
- case input
- when /^l(?:ist)?/
- make_thread_list
- thread_list_all
-
- when /^c(?:ur(?:rent)?)?$/
- make_thread_list
- thread_list(@thread_list[Thread.current])
-
- when /^(?:sw(?:itch)?\s+)?(\d+)/
- make_thread_list
- th = get_thread($1.to_i)
- if th == Thread.current
- @stdout.print "It's the current thread.\n"
- else
- thread_list(@thread_list[th])
- context(th).stop_next
- th.run
- return :cont
- end
-
- when /^stop\s+(\d+)/
- make_thread_list
- th = get_thread($1.to_i)
- if th == Thread.current
- @stdout.print "It's the current thread.\n"
- elsif th.stop?
- @stdout.print "Already stopped.\n"
- else
- thread_list(@thread_list[th])
- context(th).suspend
- end
-
- when /^resume\s+(\d+)/
- make_thread_list
- th = get_thread($1.to_i)
- if th == Thread.current
- @stdout.print "It's the current thread.\n"
- elsif !th.stop?
- @stdout.print "Already running."
- else
- thread_list(@thread_list[th])
- th.run
- end
- end
- end
-end
-
-stdout.printf "Debug.rb\n"
-stdout.printf "Emacs support available.\n\n"
-set_trace_func proc { |event, file, line, id, binding, klass, *rest|
- DEBUGGER__.context.trace_func event, file, line, id, binding, klass
-}
-end
diff --git a/lib/delegate.rb b/lib/delegate.rb
deleted file mode 100644
index 8dd3395931..0000000000
--- a/lib/delegate.rb
+++ /dev/null
@@ -1,128 +0,0 @@
-# Delegation class that delegates even methods defined in super class,
-# which can not be covered with normal method_missing hack.
-#
-# Delegator is the abstract delegation class. Need to redefine
-# `__getobj__' method in the subclass. SimpleDelegator is the
-# concrete subclass for simple delegation.
-#
-# Usage:
-# foo = Object.new
-# foo2 = SimpleDelegator.new(foo)
-# foo.hash == foo2.hash # => false
-#
-# Foo = DelegateClass(Array)
-#
-# class ExtArray<DelegateClass(Array)
-# ...
-# end
-
-class Delegator
-
- def initialize(obj)
- preserved = ::Kernel.instance_methods
- preserved -= ["to_s","to_a","inspect","==","=~","==="]
- for t in self.type.ancestors
- preserved |= t.instance_methods
- preserved |= t.private_instance_methods
- preserved |= t.protected_instance_methods
- break if t == Delegator
- end
- for method in obj.methods
- next if preserved.include? method
- begin
- eval <<-EOS
- def self.#{method}(*args, &block)
- begin
- __getobj__.__send__(:#{method}, *args, &block)
- rescue Exception
- $@.delete_if{|s| /:in `__getobj__'$/ =~ s} #`
- $@.delete_if{|s| /^\\(eval\\):/ =~ s}
- raise
- end
- end
- EOS
- rescue SyntaxError
- raise NameError, "invalid identifier %s" % method, caller(4)
- end
- end
- end
-
- def __getobj__
- raise NotImplementError, "need to define `__getobj__'"
- end
-
-end
-
-class SimpleDelegator<Delegator
-
- def initialize(obj)
- super
- @obj = obj
- end
-
- def __getobj__
- @obj
- end
-
- def __setobj__(obj)
- @obj = obj
- end
-end
-
-# backward compatibility ^_^;;;
-Delegater = Delegator
-SimpleDelegater = SimpleDelegator
-
-#
-def DelegateClass(superclass)
- klass = Class.new
- methods = superclass.instance_methods(true)
- methods -= ::Kernel.instance_methods
- methods |= ["to_s","to_a","inspect","==","=~","==="]
- klass.module_eval <<-EOS
- def initialize(obj)
- @obj = obj
- end
- EOS
- for method in methods
- begin
- klass.module_eval <<-EOS
- def #{method}(*args, &block)
- begin
- @obj.__send__(:#{method}, *args, &block)
- rescue
- $@[0,2] = nil
- raise
- end
- end
- EOS
- rescue SyntaxError
- raise NameError, "invalid identifier %s" % method, caller(3)
- end
- end
- return klass;
-end
-
-if __FILE__ == $0
- class ExtArray<DelegateClass(Array)
- def initialize()
- super([])
- end
- end
-
- ary = ExtArray.new
- p ary.type
- ary.push 25
- p ary
-
- foo = Object.new
- def foo.test
- 25
- end
- def foo.error
- raise 'this is OK'
- end
- foo2 = SimpleDelegator.new(foo)
- p foo.test == foo2.test # => true
- foo2.error # raise error!
-end
diff --git a/lib/e2mmap.rb b/lib/e2mmap.rb
deleted file mode 100644
index 6739c42518..0000000000
--- a/lib/e2mmap.rb
+++ /dev/null
@@ -1,195 +0,0 @@
-#
-# e2mmap.rb - for ruby 1.1
-# $Release Version: 2.0$
-# $Revision: 1.10 $
-# $Date: 1999/02/17 12:33:17 $
-# by Keiju ISHITSUKA
-#
-# --
-# Usage:
-#
-# U1)
-# class Foo
-# extend Exception2MessageMapper
-# def_e2message ExistingExceptionClass, "message..."
-# def_exception :NewExceptionClass, "message..."[, superclass]
-# ...
-# end
-#
-# U2)
-# module Error
-# extend Exception2MessageMapper
-# def_e2meggage ExistingExceptionClass, "message..."
-# def_exception :NewExceptionClass, "message..."[, superclass]
-# ...
-# end
-# class Foo
-# include Error
-# ...
-# end
-#
-# foo = Foo.new
-# foo.Fail ....
-#
-# U3)
-# module Error
-# extend Exception2MessageMapper
-# def_e2message ExistingExceptionClass, "message..."
-# def_exception :NewExceptionClass, "message..."[, superclass]
-# ...
-# end
-# class Foo
-# extend Exception2MessageMapper
-# include Error
-# ...
-# end
-#
-# Foo.Fail NewExceptionClass, arg...
-# Foo.Fail ExistingExceptionClass, arg...
-#
-#
-fail "Use Ruby 1.1" if VERSION < "1.1"
-
-module Exception2MessageMapper
- @RCS_ID='-$Id: e2mmap.rb,v 1.10 1999/02/17 12:33:17 keiju Exp keiju $-'
-
- E2MM = Exception2MessageMapper
-
- def E2MM.extend_object(cl)
- super
- cl.bind(self) unless cl == E2MM
- end
-
- # backward compatibility
- def E2MM.extend_to(b)
- c = eval("self", b)
- c.extend(self)
- end
-
- def bind(cl)
- self.module_eval %[
- def Raise(err = nil, *rest)
- Exception2MessageMapper.Raise(self.type, err, *rest)
- end
- alias Fail Raise
-
- def self.included(mod)
- mod.extend Exception2MessageMapper
- end
- ]
- end
-
- # Fail(err, *rest)
- # err: exception
- # rest: message arguments
- #
- def Raise(err = nil, *rest)
- E2MM.Raise(self, err, *rest)
- end
- alias Fail Raise
-
- # backward compatibility
- alias fail! fail
- def fail(err = nil, *rest)
- begin
- E2MM.Fail(self, err, *rest)
- rescue E2MM::ErrNotRegisteredException
- super
- end
- end
- class << self
- public :fail
- end
-
-
- # def_e2message(c, m)
- # c: exception
- # m: message_form
- # define exception c with message m.
- #
- def def_e2message(c, m)
- E2MM.def_e2message(self, c, m)
- end
-
- # def_exception(n, m, s)
- # n: exception_name
- # m: message_form
- # s: superclass(default: StandardError)
- # define exception named ``c'' with message m.
- #
- def def_exception(n, m, s = StandardError)
- E2MM.def_exception(self, n, m, s)
- end
-
- #
- # Private definitions.
- #
- # {[class, exp] => message, ...}
- @MessageMap = {}
-
- # E2MM.def_exception(k, e, m)
- # k: class to define exception under.
- # e: exception
- # m: message_form
- # define exception c with message m.
- #
- def E2MM.def_e2message(k, c, m)
- E2MM.instance_eval{@MessageMap[[k, c]] = m}
- c
- end
-
- # E2MM.def_exception(k, n, m, s)
- # k: class to define exception under.
- # n: exception_name
- # m: message_form
- # s: superclass(default: StandardError)
- # define exception named ``c'' with message m.
- #
- def E2MM.def_exception(k, n, m, s = StandardError)
- n = n.id2name if n.kind_of?(Fixnum)
- e = Class.new(s)
- E2MM.instance_eval{@MessageMap[[k, e]] = m}
- k.const_set(n, e)
- end
-
- # Fail(klass, err, *rest)
- # klass: class to define exception under.
- # err: exception
- # rest: message arguments
- #
- def E2MM.Raise(klass = E2MM, err = nil, *rest)
- if form = e2mm_message(klass, err)
- $! = err.new(sprintf(form, *rest))
- $@ = caller(1) if $@.nil?
- #p $@
- #p __FILE__
- $@.shift if $@[0] =~ /^#{Regexp.quote(__FILE__)}:/
- raise
- else
- E2MM.Fail E2MM, ErrNotRegisteredException, err.inspect
- end
- end
- class <<E2MM
- alias Fail Raise
- end
-
- def E2MM.e2mm_message(klass, exp)
- for c in klass.ancestors
- if mes = @MessageMap[[c,exp]]
- #p mes
- m = klass.instance_eval('"' + mes + '"')
- return m
- end
- end
- nil
- end
- class <<self
- alias message e2mm_message
- end
-
- E2MM.def_exception(E2MM,
- :ErrNotRegisteredException,
- "not registerd exception(%s)")
-end
-
-
diff --git a/lib/eregex.rb b/lib/eregex.rb
deleted file mode 100644
index cc7a7f6f46..0000000000
--- a/lib/eregex.rb
+++ /dev/null
@@ -1,37 +0,0 @@
-# this is just a proof of concept toy.
-
-class RegOr
- def initialize(re1, re2)
- @re1 = re1
- @re2 = re2
- end
-
- def =~ (str)
- @re1 =~ str or @re2 =~ str
- end
-end
-
-class RegAnd
- def initialize(re1, re2)
- @re1 = re1
- @re2 = re2
- end
-
- def =~ (str)
- @re1 =~ str and @re2 =~ str
- end
-end
-
-class Regexp
- def |(other)
- RegOr.new(self, other)
- end
- def &(other)
- RegAnd.new(self, other)
- end
-end
-
-if __FILE__ == $0
- p "abc" =~ /b/|/c/
- p "abc" =~ /b/&/c/
-end
diff --git a/lib/final.rb b/lib/final.rb
deleted file mode 100644
index 9d81238823..0000000000
--- a/lib/final.rb
+++ /dev/null
@@ -1,4 +0,0 @@
-# $Id$
-# Copyright (C) 1998 Yukihiro Matsumoto. All rights reserved.
-
-# final.rb is integrated into ObjectSpace; no longer needed.
diff --git a/lib/finalize.rb b/lib/finalize.rb
deleted file mode 100644
index 598569f52e..0000000000
--- a/lib/finalize.rb
+++ /dev/null
@@ -1,201 +0,0 @@
-#
-# finalizer.rb -
-# $Release Version: 0.3$
-# $Revision: 1.4 $
-# $Date: 1998/02/27 05:34:33 $
-# by Keiju ISHITSUKA
-#
-# --
-#
-# Usage:
-#
-# add(obj, dependant, method = :finalize, *opt)
-# add_dependency(obj, dependant, method = :finalize, *opt)
-# add dependency R_method(obj, dependant)
-#
-# delete(obj_or_id, dependant, method = :finalize)
-# delete_dependency(obj_or_id, dependant, method = :finalize)
-# delete dependency R_method(obj, dependant)
-# delete_all_dependency(obj_or_id, dependant)
-# delete dependency R_*(obj, dependant)
-# delete_by_dependant(dependant, method = :finalize)
-# delete dependency R_method(*, dependant)
-# delete_all_by_dependant(dependant)
-# delete dependency R_*(*, dependant)
-# delete_all
-# delete all dependency R_*(*, *)
-#
-# finalize(obj_or_id, dependant, method = :finalize)
-# finalize_dependency(obj_or_id, dependant, method = :finalize)
-# finalize the dependant connected by dependency R_method(obj, dependtant).
-# finalize_all_dependency(obj_or_id, dependant)
-# finalize all dependants connected by dependency R_*(obj, dependtant).
-# finalize_by_dependant(dependant, method = :finalize)
-# finalize the dependant connected by dependency R_method(*, dependtant).
-# finalize_all_by_dependant(dependant)
-# finalize all dependants connected by dependency R_*(*, dependant).
-# finalize_all
-# finalize all dependency registered to the Finalizer.
-#
-# safe{..}
-# stop invoking Finalizer on GC.
-#
-
-module Finalizer
- RCS_ID='-$Id: finalize.rb,v 1.4 1998/02/27 05:34:33 keiju Exp keiju $-'
-
- # @dependency: {id => [[dependant, method, *opt], ...], ...}
-
- # add dependency R_method(obj, dependant)
- def add_dependency(obj, dependant, method = :finalize, *opt)
- ObjectSpace.call_finalizer(obj)
- method = method.intern unless method.kind_of?(Integer)
- assoc = [dependant, method].concat(opt)
- if dep = @dependency[obj.id]
- dep.push assoc
- else
- @dependency[obj.id] = [assoc]
- end
- end
- alias add add_dependency
-
- # delete dependency R_method(obj, dependant)
- def delete_dependency(id, dependant, method = :finalize)
- id = id.id unless id.kind_of?(Integer)
- method = method.intern unless method.kind_of?(Integer)
- for assoc in @dependency[id]
- assoc.delete_if do
- |d, m, *o|
- d == dependant && m == method
- end
- @dependency.delete(id) if assoc.empty?
- end
- end
- alias delete delete_dependency
-
- # delete dependency R_*(obj, dependant)
- def delete_all_dependency(id, dependant)
- id = id.id unless id.kind_of?(Integer)
- method = method.intern unless method.kind_of?(Integer)
- for assoc in @dependency[id]
- assoc.delete_if do
- |d, m, *o|
- d == dependant
- end
- @dependency.delete(id) if assoc.empty?
- end
- end
-
- # delete dependency R_method(*, dependant)
- def delete_by_dependant(dependant, method = :finalize)
- method = method.intern unless method.kind_of?(Integer)
- for id in @dependency.keys
- delete(id, dependant, method)
- end
- end
-
- # delete dependency R_*(*, dependant)
- def delete_all_by_dependant(dependant)
- for id in @dependency.keys
- delete_all_dependency(id, dependant)
- end
- end
-
- # finalize the depandant connected by dependency R_method(obj, dependtant)
- def finalize_dependency(id, dependant, method = :finalize)
- id = id.id unless id.kind_of?(Integer)
- method = method.intern unless method.kind_of?(Integer)
- for assocs in @dependency[id]
- assocs.delete_if do
- |d, m, *o|
- d.send(m, id, *o) if ret = d == dependant && m == method
- ret
- end
- @dependency.delete(id) if assoc.empty?
- end
- end
- alias finalize finalize_dependency
-
- # finalize all dependants connected by dependency R_*(obj, dependtant)
- def finalize_all_dependency(id, dependant)
- id = id.id unless id.kind_of?(Integer)
- method = method.intern unless method.kind_of?(Integer)
- for assoc in @dependency[id]
- assoc.delete_if do
- |d, m, *o|
- d.send(m, id, *o) if ret = d == dependant
- end
- @dependency.delete(id) if assoc.empty?
- end
- end
-
- # finalize the dependant connected by dependency R_method(*, dependtant)
- def finalize_by_dependant(dependant, method = :finalize)
- method = method.intern unless method.kind_of?(Integer)
- for id in @dependency.keys
- finalize(id, dependant, method)
- end
- end
-
- # finalize all dependants connected by dependency R_*(*, dependtant)
- def finalize_all_by_dependant(dependant)
- for id in @dependency.keys
- finalize_all_dependency(id, dependant)
- end
- end
-
- # finalize all dependants registered to the Finalizer.
- def finalize_all
- for id, assocs in @dependency
- for dependant, method, *opt in assocs
- dependant.send(method, id, *opt)
- end
- assocs.clear
- end
- end
-
- # method to call finalize_* safely.
- def safe
- old_status = Thread.critical
- Thread.critical = true
- ObjectSpace.remove_finalizer(@proc)
- yield
- ObjectSpace.add_finalizer(@proc)
- Thread.critical = old_status
- end
-
- # registering function to ObjectSpace#add_finalizer
- def final_of(id)
- if assocs = @dependency.delete(id)
- for dependant, method, *opt in assocs
- dependant.send(method, id, *opt)
- end
- end
- end
-
- @dependency = Hash.new
- @proc = proc{|id| final_of(id)}
- ObjectSpace.add_finalizer(@proc)
-
- module_function :add
- module_function :add_dependency
-
- module_function :delete
- module_function :delete_dependency
- module_function :delete_all_dependency
- module_function :delete_by_dependant
- module_function :delete_all_by_dependant
-
- module_function :finalize
- module_function :finalize_dependency
- module_function :finalize_all_dependency
- module_function :finalize_by_dependant
- module_function :finalize_all_by_dependant
- module_function :finalize_all
-
- module_function :safe
-
- module_function :final_of
- private_class_method :final_of
-
-end
diff --git a/lib/find.rb b/lib/find.rb
deleted file mode 100644
index 3c16533794..0000000000
--- a/lib/find.rb
+++ /dev/null
@@ -1,45 +0,0 @@
-# Usage:
-# require "find"
-#
-# Find.find('/foo','/bar') {|f| ...}
-# or
-# include Find
-# find('/foo','/bar') {|f| ...}
-#
-
-module Find
- def find(*path)
- path.collect!{|d| d.dup}
- while file = path.shift
- catch(:prune) do
- yield file
- begin
- if File.lstat(file).directory? then
- d = Dir.open(file)
- begin
- for f in d
- next if f == "." or f == ".."
- if File::ALT_SEPARATOR and file =~ /^(?:[\/\\]|[A-Za-z]:[\/\\]?)$/ then
- f = file + f
- elsif file == "/" then
- f = "/" + f
- else
- f = File.join(file, f)
- end
- path.unshift f
- end
- ensure
- d.close
- end
- end
- rescue Errno::ENOENT, Errno::EACCES
- end
- end
- end
- end
-
- def prune
- throw :prune
- end
- module_function :find, :prune
-end
diff --git a/lib/forwardable.rb b/lib/forwardable.rb
deleted file mode 100644
index b845f76ec4..0000000000
--- a/lib/forwardable.rb
+++ /dev/null
@@ -1,94 +0,0 @@
-#
-# forwardable.rb -
-# $Release Version: 1.1$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-# original definition by delegator.rb
-# --
-# Usage:
-#
-# class Foo
-# extend Forwardable
-#
-# def_delegators("@out", "printf", "print")
-# def_delegators(:@in, :gets)
-# def_delegator(:@contents, :[], "content_at")
-# end
-# f = Foo.new
-# f.printf ...
-# f.gets
-# f.content_at(1)
-#
-# g = Goo.new
-# g.extend SingleForwardable
-# g.def_delegator("@out", :puts)
-# g.puts ...
-#
-#
-
-module Forwardable
-
- @debug = nil
- class<<self
- attr_accessor :debug
- end
-
- def def_instance_delegators(accessor, *methods)
- for method in methods
- def_instance_delegator(accessor, method)
- end
- end
-
- def def_instance_delegator(accessor, method, ali = method)
- accessor = accessor.id2name if accessor.kind_of?(Integer)
- method = method.id2name if method.kind_of?(Integer)
- ali = ali.id2name if ali.kind_of?(Integer)
-
- module_eval(<<-EOS, "(__FORWARDABLE__)", 1)
- def #{ali}(*args, &block)
- begin
- #{accessor}.__send__(:#{method}, *args, &block)
- rescue Exception
- $@.delete_if{|s| /^\\(__FORWARDABLE__\\):/ =~ s} unless Forwardable::debug
- Kernel::raise
- end
- end
- EOS
- end
-
- alias def_delegators def_instance_delegators
- alias def_delegator def_instance_delegator
-end
-
-module SingleForwardable
- def def_singleton_delegators(accessor, *methods)
- for method in methods
- def_singleton_delegator(accessor, method)
- end
- end
-
- def def_singleton_delegator(accessor, method, ali = method)
- accessor = accessor.id2name if accessor.kind_of?(Integer)
- method = method.id2name if method.kind_of?(Integer)
- ali = ali.id2name if ali.kind_of?(Integer)
-
- instance_eval(<<-EOS, "(__FORWARDABLE__)", 1)
- def #{ali}(*args, &block)
- begin
- #{accessor}.__send__(:#{method}, *args,&block)
- rescue Exception
- $@.delete_if{|s| /^\\(__FORWARDABLE__\\):/ =~ s} unless Forwardable::debug
- Kernel::raise
- end
- end
- EOS
- end
-
- alias def_delegators def_singleton_delegators
- alias def_delegator def_singleton_delegator
-end
-
-
-
-
diff --git a/lib/ftools.rb b/lib/ftools.rb
deleted file mode 100644
index 4047a595eb..0000000000
--- a/lib/ftools.rb
+++ /dev/null
@@ -1,181 +0,0 @@
-class << File
-
- TOO_BIG = 1024 * 1024 * 2 # 2MB
-
- def catname from, to
- if FileTest.directory? to
- File.join to.sub(%r([/\\]$), ''), basename(from)
- else
- to
- end
- end
-
-# copy file
-
- def syscopy from, to
- to = catname(from, to)
-
- fsize = size(from)
- fsize = 1024 if fsize < 512
- fsize = TOO_BIG if fsize > TOO_BIG
-
- fmode = stat(from).mode
- tpath = to
- not_exist = !exist?(tpath)
-
- from = open(from, "r")
- from.binmode
- to = open(to, "w")
- to.binmode
-
- begin
- while true
- r = from.sysread(fsize)
- rsize = r.size
- w = 0
- while w < rsize
- t = to.syswrite(r[w, rsize - w])
- w += t
- end
- end
- rescue EOFError
- ret = true
- rescue
- ret = false
- ensure
- to.close
- from.close
- end
- chmod(fmode, tpath) if not_exist
- ret
- end
-
- def copy from, to, verbose = false
- $stderr.print from, " -> ", catname(from, to), "\n" if verbose
- syscopy from, to
- end
-
- alias cp copy
-
-# move file
-
- def move from, to, verbose = false
- to = catname(from, to)
- $stderr.print from, " -> ", to, "\n" if verbose
-
- if RUBY_PLATFORM =~ /djgpp|cygwin|mswin32/ and FileTest.file? to
- unlink to
- end
- fstat = stat(from)
- begin
- rename from, to
- rescue
- begin
- symlink File.readlink(from), to and unlink from
- rescue
- from_stat = stat(from)
- syscopy from, to and unlink from
- utime(from_stat.atime, from_stat.mtime, to)
- begin
- chown(fstat.uid, fstat.gid, to)
- rescue
- end
- end
- end
- end
-
- alias mv move
-
-# compare two files
-# true: identical
-# false: not identical
-
- def compare from, to, verbose = false
- $stderr.print from, " <=> ", to, "\n" if verbose
- fsize = size(from)
- fsize = 1024 if fsize < 512
- fsize = TOO_BIG if fsize > TOO_BIG
-
- from = open(from, "r")
- from.binmode
- to = open(to, "r")
- to.binmode
-
- ret = false
- fr = tr = ''
-
- begin
- while fr == tr
- fr = from.read(fsize)
- if fr
- tr = to.read(fr.size)
- else
- ret = to.read(fsize)
- ret = !ret || ret.length == 0
- break
- end
- end
- rescue
- ret = false
- ensure
- to.close
- from.close
- end
- ret
- end
-
- alias cmp compare
-
-# unlink files safely
-
- def safe_unlink(*files)
- verbose = if files[-1].is_a? String then false else files.pop end
- begin
- $stderr.print files.join(" "), "\n" if verbose
- chmod 0777, *files
- unlink(*files)
- rescue
-# STDERR.print "warning: Couldn't unlink #{files.join ' '}\n"
- end
- end
-
- alias rm_f safe_unlink
-
- def makedirs(*dirs)
- verbose = if dirs[-1].is_a? String then false else dirs.pop end
-# mode = if dirs[-1].is_a? Fixnum then dirs.pop else 0755 end
- mode = 0755
- for dir in dirs
- next if FileTest.directory? dir
- parent = dirname(dir)
- makedirs parent unless FileTest.directory? parent
- $stderr.print "mkdir ", dir, "\n" if verbose
- if basename(dir) != ""
- Dir.mkdir dir, mode
- end
- end
- end
-
- alias mkpath makedirs
-
- alias o_chmod chmod
-
- vsave, $VERBOSE = $VERBOSE, false
- def chmod(mode, *files)
- verbose = if files[-1].is_a? String then false else files.pop end
- $stderr.printf "chmod %04o %s\n", mode, files.join(" ") if verbose
- o_chmod mode, *files
- end
- $VERBOSE = vsave
-
- def install(from, to, mode = nil, verbose = false)
- to = catname(from, to)
- unless FileTest.exist? to and cmp from, to
- safe_unlink to if FileTest.exist? to
- cp from, to, verbose
- chmod mode, to, verbose if mode
- end
- end
-
-end
-# vi:set sw=2:
diff --git a/lib/ftplib.rb b/lib/ftplib.rb
deleted file mode 100644
index 4cb1b752d6..0000000000
--- a/lib/ftplib.rb
+++ /dev/null
@@ -1,14 +0,0 @@
-#
-# ftplib.rb
-#
-
-$stderr.puts 'Warning: ftplib.rb is obsolete: use net/ftp'
-
-require 'net/ftp'
-
-FTP = ::Net::FTP
-FTPError = ::Net::FTPError
-FTPReplyError = ::Net::FTPReplyError
-FTPTempError = ::Net::FTPTempError
-FTPPermError = ::Net::FTPPermError
-FTPProtoError = ::Net::FTPProtoError
diff --git a/lib/getoptlong.rb b/lib/getoptlong.rb
deleted file mode 100644
index e90a9d45bc..0000000000
--- a/lib/getoptlong.rb
+++ /dev/null
@@ -1,467 +0,0 @@
-# -*- Ruby -*-
-# Copyright (C) 1998, 1999, 2000 Motoyuki Kasahara
-#
-# You may redistribute it and/or modify it under the same license
-# terms as Ruby.
-#
-
-#
-# Documents and latest version of `getoptlong.rb' are found at:
-# http://www.sra.co.jp/people/m-kasahr/ruby/getoptlong/
-#
-
-#
-# Parse command line options just like GNU getopt_long().
-#
-class GetoptLong
- #
- # Orderings.
- #
- ORDERINGS = [REQUIRE_ORDER = 0, PERMUTE = 1, RETURN_IN_ORDER = 2]
-
- #
- # Argument flags.
- #
- ARGUMENT_FLAGS = [NO_ARGUMENT = 0, REQUIRED_ARGUMENT = 1,
- OPTIONAL_ARGUMENT = 2]
-
- #
- # Status codes.
- #
- STATUS_YET, STATUS_STARTED, STATUS_TERMINATED = 0, 1, 2
-
- #
- # Error types.
- #
- class AmbigousOption < StandardError; end
- class NeedlessArgument < StandardError; end
- class MissingArgument < StandardError; end
- class InvalidOption < StandardError; end
-
- #
- # Initializer.
- #
- def initialize(*arguments)
- #
- # Current ordering.
- #
- if ENV.include?('POSIXLY_CORRECT')
- @ordering = REQUIRE_ORDER
- else
- @ordering = PERMUTE
- end
-
- #
- # Hash table of option names.
- # Keyes of the table are option names, and their values are canonical
- # names of the options.
- #
- @canonical_names = Hash.new
-
- #
- # Hash table of argument flags.
- # Keyes of the table are option names, and their values are argument
- # flags of the options.
- #
- @argument_flags = Hash.new
-
- #
- # Whether error messages are output to stderr.
- #
- @quiet = FALSE
-
- #
- # Status code.
- #
- @status = STATUS_YET
-
- #
- # Error code.
- #
- @error = nil
-
- #
- # Error message.
- #
- @error_message = nil
-
- #
- # Rest of catinated short options.
- #
- @rest_singles = ''
-
- #
- # List of non-option-arguments.
- # Append them to ARGV when option processing is terminated.
- #
- @non_option_arguments = Array.new
-
- if 0 < arguments.length
- set_options(*arguments)
- end
- end
-
- #
- # Set ordering.
- #
- def ordering=(ordering)
- #
- # The method is failed if option processing has already started.
- #
- if @status != STATUS_YET
- set_error(ArgumentError, "argument error")
- raise RuntimeError,
- "invoke ordering=, but option processing has already started"
- end
-
- #
- # Check ordering.
- #
- if !ORDERINGS.include?(ordering)
- raise ArgumentError, "invalid ordering `#{ordering}'"
- end
- if ordering == PERMUTE && ENV.include?('POSIXLY_CORRECT')
- @ordering = REQUIRE_ORDER
- else
- @ordering = ordering
- end
- end
-
- #
- # Return ordering.
- #
- attr_reader :ordering
-
- #
- # Set options
- #
- def set_options(*arguments)
- #
- # The method is failed if option processing has already started.
- #
- if @status != STATUS_YET
- raise RuntimeError,
- "invoke set_options, but option processing has already started"
- end
-
- #
- # Clear tables of option names and argument flags.
- #
- @canonical_names.clear
- @argument_flags.clear
-
- arguments.each do |arg|
- #
- # Each argument must be an Array.
- #
- if !arg.is_a?(Array)
- raise ArgumentError, "the option list contains non-Array argument"
- end
-
- #
- # Find an argument flag and it set to `argument_flag'.
- #
- argument_flag = nil
- arg.each do |i|
- if ARGUMENT_FLAGS.include?(i)
- if argument_flag != nil
- raise ArgumentError, "too many argument-flags"
- end
- argument_flag = i
- end
- end
- raise ArgumentError, "no argument-flag" if argument_flag == nil
-
- canonical_name = nil
- arg.each do |i|
- #
- # Check an option name.
- #
- next if i == argument_flag
- begin
- if !i.is_a?(String) || i !~ /^-([^-]|-.+)$/
- raise ArgumentError, "an invalid option `#{i}'"
- end
- if (@canonical_names.include?(i))
- raise ArgumentError, "option redefined `#{i}'"
- end
- rescue
- @canonical_names.clear
- @argument_flags.clear
- raise
- end
-
- #
- # Register the option (`i') to the `@canonical_names' and
- # `@canonical_names' Hashes.
- #
- if canonical_name == nil
- canonical_name = i
- end
- @canonical_names[i] = canonical_name
- @argument_flags[i] = argument_flag
- end
- raise ArgumentError, "no option name" if canonical_name == nil
- end
- return self
- end
-
- #
- # Set/Unset `quit' mode.
- #
- attr_writer :quiet
-
- #
- # Return the flag of `quiet' mode.
- #
- attr_reader :quiet
-
- #
- # `quiet?' is an alias of `quiet'.
- #
- alias quiet? quiet
-
- #
- # Termintate option processing.
- #
- def terminate
- return nil if @status == STATUS_TERMINATED
- raise RuntimeError, "an error has occured" if @error != nil
-
- @status = STATUS_TERMINATED
- @non_option_arguments.reverse_each do |argument|
- ARGV.unshift(argument)
- end
-
- @canonical_names = nil
- @argument_flags = nil
- @rest_singles = nil
- @non_option_arguments = nil
-
- return self
- end
-
- #
- # Examine whether option processing is termintated or not.
- #
- def terminated?
- return @status == STATUS_TERMINATED
- end
-
- #
- # Set an error (protected).
- #
- def set_error(type, message)
- $stderr.print("#{$0}: #{message}\n") if !@quiet
-
- @error = type
- @error_message = message
- @canonical_names = nil
- @argument_flags = nil
- @rest_singles = nil
- @non_option_arguments = nil
-
- raise type, message
- end
- protected :set_error
-
- #
- # Examine whether an option processing is failed.
- #
- attr_reader :error
-
- #
- # `error?' is an alias of `error'.
- #
- alias error? error
-
- #
- # Return an error message.
- #
- def error_message
- return @error_message
- end
-
- #
- # Get next option name and its argument as an array.
- #
- def get
- option_name, option_argument = nil, ''
-
- #
- # Check status.
- #
- return nil if @error != nil
- case @status
- when STATUS_YET
- @status = STATUS_STARTED
- when STATUS_TERMINATED
- return nil
- end
-
- #
- # Get next option argument.
- #
- if 0 < @rest_singles.length
- argument = '-' + @rest_singles
- elsif (ARGV.length == 0)
- terminate
- return nil
- elsif @ordering == PERMUTE
- while 0 < ARGV.length && ARGV[0] !~ /^-./
- @non_option_arguments.push(ARGV.shift)
- end
- if ARGV.length == 0
- terminate
- return nil
- end
- argument = ARGV.shift
- elsif @ordering == REQUIRE_ORDER
- if (ARGV[0] !~ /^-./)
- terminate
- return nil
- end
- argument = ARGV.shift
- else
- argument = ARGV.shift
- end
-
- #
- # Check the special argument `--'.
- # `--' indicates the end of the option list.
- #
- if argument == '--' && @rest_singles.length == 0
- terminate
- return nil
- end
-
- #
- # Check for long and short options.
- #
- if argument =~ /^(--[^=]+)/ && @rest_singles.length == 0
- #
- # This is a long style option, which start with `--'.
- #
- pattern = $1
- if @canonical_names.include?(pattern)
- option_name = pattern
- else
- #
- # The option `option_name' is not registered in `@canonical_names'.
- # It may be an abbreviated.
- #
- match_count = 0
- @canonical_names.each_key do |key|
- if key.index(pattern) == 0
- option_name = key
- match_count += 1
- end
- end
- if 2 <= match_count
- set_error(AmbigousOption, "option `#{argument}' is ambiguous")
- elsif match_count == 0
- set_error(InvalidOption, "unrecognized option `#{argument}'")
- end
- end
-
- #
- # Check an argument to the option.
- #
- if @argument_flags[option_name] == REQUIRED_ARGUMENT
- if argument =~ /=(.*)$/
- option_argument = $1
- elsif 0 < ARGV.length
- option_argument = ARGV.shift
- else
- set_error(MissingArgument,
- "option `#{argument}' requires an argument")
- end
- elsif @argument_flags[option_name] == OPTIONAL_ARGUMENT
- if argument =~ /=(.*)$/
- option_argument = $1
- elsif 0 < ARGV.length && ARGV[0] !~ /^-./
- option_argument = ARGV.shift
- else
- option_argument = ''
- end
- elsif argument =~ /=(.*)$/
- set_error(NeedlessArgument,
- "option `#{option_name}' doesn't allow an argument")
- end
-
- elsif argument =~ /^(-(.))(.*)/
- #
- # This is a short style option, which start with `-' (not `--').
- # Short options may be catinated (e.g. `-l -g' is equivalent to
- # `-lg').
- #
- option_name, ch, @rest_singles = $1, $2, $3
-
- if @canonical_names.include?(option_name)
- #
- # The option `option_name' is found in `@canonical_names'.
- # Check its argument.
- #
- if @argument_flags[option_name] == REQUIRED_ARGUMENT
- if 0 < @rest_singles.length
- option_argument = @rest_singles
- @rest_singles = ''
- elsif 0 < ARGV.length
- option_argument = ARGV.shift
- else
- # 1003.2 specifies the format of this message.
- set_error(MissingArgument, "option requires an argument -- #{ch}")
- end
- elsif @argument_flags[option_name] == OPTIONAL_ARGUMENT
- if 0 < @rest_singles.length
- option_argument = @rest_singles
- @rest_singles = ''
- elsif 0 < ARGV.length && ARGV[0] !~ /^-./
- option_argument = ARGV.shift
- else
- option_argument = ''
- end
- end
- else
- #
- # This is an invalid option.
- # 1003.2 specifies the format of this message.
- #
- if ENV.include?('POSIXLY_CORRECT')
- set_error(InvalidOption, "illegal option -- #{ch}")
- else
- set_error(InvalidOption, "invalid option -- #{ch}")
- end
- end
- else
- #
- # This is a non-option argument.
- # Only RETURN_IN_ORDER falled into here.
- #
- return '', argument
- end
-
- return @canonical_names[option_name], option_argument
- end
-
- #
- # `get_option' is an alias of `get'.
- #
- alias get_option get
-
- #
- # Iterator version of `get'.
- #
- def each
- loop do
- option_name, option_argument = get_option
- break if option_name == nil
- yield option_name, option_argument
- end
- end
-
- #
- # `each_option' is an alias of `each'.
- #
- alias each_option each
-end
diff --git a/lib/getopts.rb b/lib/getopts.rb
deleted file mode 100644
index b1cffd9ba0..0000000000
--- a/lib/getopts.rb
+++ /dev/null
@@ -1,116 +0,0 @@
-#
-# getopts.rb -
-# $Release Version: $
-# $Revision$
-# $Date$
-# by Yasuo OHBA(SHL Japan Inc. Technology Dept.)
-#
-# --
-# this is obsolete; use getoptlong
-#
-# 2000-03-21
-# modified by Minero Aoki <aamine@dp.u-netsurf.ne.jp>
-#
-# 2002-03-05
-# rewritten by Akinori MUSHA <knu@ruby-lang.org>
-#
-
-$RCS_ID=%q$Header$
-
-
-def getopts(single_options, *options)
- boolopts = {}
- valopts = {}
-
- #
- # set defaults
- #
- single_options.scan(/.:?/) do |opt|
- if opt.size == 1
- boolopts[opt] = false
- else
- valopts[opt[0, 1]] = nil
- end
- end if single_options
-
- options.each do |arg|
- opt, val = arg.split(':', 2)
-
- if val
- valopts[opt] = val.empty? ? nil : val
- else
- boolopts[opt] = false
- end
- end
-
- #
- # scan
- #
- c = 0
- argv = ARGV
-
- while arg = argv.shift
- case arg
- when /\A--(.*)/
- if $1.empty? # xinit -- -bpp 24
- break
- end
-
- opt, val = $1.split('=', 2)
-
- if opt.size == 1
- argv.unshift arg
- return nil
- elsif valopts.key? opt # imclean --src +trash
- valopts[opt] = val || argv.shift or return nil
- elsif boolopts.key? opt # ruby --verbose
- boolopts[opt] = true
- else
- argv.unshift arg
- return nil
- end
-
- c += 1
- when /\A-(.+)/
- opts = $1
-
- until opts.empty?
- opt = opts.slice!(0, 1)
-
- if valopts.key? opt
- val = opts
-
- if val.empty? # ruby -e 'p $:'
- valopts[opt] = argv.shift or return nil
- else # cc -ohello ...
- valopts[opt] = val
- end
-
- c += 1
- break
- elsif boolopts.key? opt
- boolopts[opt] = true # ruby -h
- c += 1
- else
- argv.unshift arg
- return nil
- end
- end
- else
- argv.unshift arg
- break
- end
- end
-
- #
- # set
- #
- boolopts.each do |opt, val|
- eval "$OPT_#{opt} = val"
- end
- valopts.each do |opt, val|
- eval "$OPT_#{opt} = val"
- end
-
- c
-end
diff --git a/lib/importenv.rb b/lib/importenv.rb
deleted file mode 100644
index 435d6f972a..0000000000
--- a/lib/importenv.rb
+++ /dev/null
@@ -1,31 +0,0 @@
-# importenv.rb -- imports environment variables as global variables, Perlish ;(
-#
-# Usage:
-#
-# require 'importenv'
-# p $USER
-# $USER = "matz"
-# p ENV["USER"]
-
-for k,v in ENV
- next unless /^[a-zA-Z][_a-zA-Z0-9]*/ =~ k
- eval <<EOS
- $#{k} = v
- trace_var "$#{k}", proc{|v|
- ENV[%q!#{k}!] = v
- $#{k} = v
- if v == nil
- untrace_var "$#{k}"
- end
- }
-EOS
-end
-
-if __FILE__ == $0
- p $TERM
- $TERM = nil
- p $TERM
- p ENV["TERM"]
- $TERM = "foo"
- p ENV["TERM"]
-end
diff --git a/lib/irb.rb b/lib/irb.rb
deleted file mode 100644
index 1b8444b5b3..0000000000
--- a/lib/irb.rb
+++ /dev/null
@@ -1,314 +0,0 @@
-#
-# irb.rb - irb main module
-# $Release Version: 0.7.4 $
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-#
-# --
-#
-#
-#
-require "e2mmap"
-
-require "irb/init"
-require "irb/context"
-require "irb/extend-command"
-require "irb/workspace"
-
-require "irb/ruby-lex"
-require "irb/input-method"
-require "irb/locale"
-
-STDOUT.sync = true
-
-module IRB
- @RCS_ID='-$Id$-'
-
- class Abort < Exception;end
-
- #
- @CONF = {}
-
- def IRB.conf
- @CONF
- end
-
- # IRB version method
- def IRB.version
- if v = @CONF[:VERSION] then return v end
-
- require "irb/version"
- rv = @RELEASE_VERSION.sub(/\.0/, "")
- @CONF[:VERSION] = format("irb %s(%s)", rv, @LAST_UPDATE_DATE)
- end
-
- # initialize IRB and start TOP_LEVEL irb
- def IRB.start(ap_path = nil)
- $0 = File::basename(ap_path, ".rb") if ap_path
-
- IRB.initialize(ap_path)
- IRB.parse_opts
- IRB.load_modules
-
- if @CONF[:SCRIPT]
- irb = Irb.new(nil, @CONF[:SCRIPT])
- else
- irb = Irb.new
- end
-
- @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC]
- @CONF[:MAIN_CONTEXT] = irb.context
-
- trap("SIGINT") do
- irb.signal_handle
- end
-
- catch(:IRB_EXIT) do
- irb.eval_input
- end
- print "\n"
- end
-
- def IRB.irb_exit(irb, ret)
- throw :IRB_EXIT, ret
- end
-
- def IRB.irb_abort(irb, exception = Abort)
- if defined? Thread
- irb.context.thread.raise exception, "abort then interrupt!!"
- else
- raise exception, "abort then interrupt!!"
- end
- end
-
- #
- # irb interpriter main routine
- #
- class Irb
- def initialize(workspace = nil, input_method = nil)
- @context = Context.new(self, workspace, input_method)
- @context.main.extend ExtendCommand
- @signal_status = :IN_IRB
-
- @scanner = RubyLex.new
- @scanner.exception_on_syntax_error = false
- end
- attr_reader :context
- attr_accessor :scanner
-
- def eval_input
- @scanner.set_input(@context.io) do
- signal_status(:IN_INPUT) do
- unless l = @context.io.gets
- if @context.ignore_eof? and @context.io.readable_atfer_eof?
- l = "\n"
- if @context.verbose?
- printf "Use \"exit\" to leave %s\n", @context.ap_name
- end
- end
- end
- l
- end
- end
-
- @scanner.set_prompt do
- |ltype, indent, continue, line_no|
- if ltype
- f = @context.prompt_s
- elsif continue
- f = @context.prompt_c
- else @context.prompt_i
- f = @context.prompt_i
- end
- f = "" unless f
- @context.io.prompt = p = prompt(f, ltype, indent, line_no)
- if @context.auto_indent_mode
- unless ltype
- ind = prompt(@context.prompt_i, ltype, indent, line_no).size +
- indent * 2 - p.size
- ind += 2 if continue
- @context.io.prompt = p + " " * ind if ind > 0
- end
- end
- end
-
- @scanner.each_top_level_statement do
- |line, line_no|
- signal_status(:IN_EVAL) do
- begin
- trace_in do
- @context._ = @context.workspace.evaluate(line,
- @context.irb_path,
- line_no)
-# @context._ = irb_eval(line, @context.bind, @context.irb_path, line_no)
- end
-
- if @context.inspect?
- printf @context.return_format, @context._.inspect
- else
- printf @context.return_format, @context._
- end
- rescue StandardError, ScriptError, Abort
- $! = RuntimeError.new("unknown exception raised") unless $!
- print $!.type, ": ", $!, "\n"
- if $@[0] =~ /irb(2)?(\/.*|-.*|\.rb)?:/ && $!.type.to_s !~ /^IRB/
- irb_bug = true
- else
- irb_bug = false
- end
-
- messages = []
- lasts = []
- levels = 0
- for m in $@
- m = @context.workspace.filter_backtrace(m) unless irb_bug
- if m
- if messages.size < @context.back_trace_limit
- messages.push "\tfrom "+m
- else
- lasts.push "\tfrom "+m
- if lasts.size > @context.back_trace_limit
- lasts.shift
- levels += 1
- end
- end
- end
- end
- print messages.join("\n"), "\n"
- unless lasts.empty?
- printf "... %d levels...\n", levels if levels > 0
- print lasts.join("\n")
- end
- print "Maybe IRB bug!!\n" if irb_bug
- end
- end
- end
- end
-
-# def irb_eval(line, bind, path, line_no)
-# id, str = catch(:IRB_TOPLEVEL_EVAL){
-# return eval(line, bind, path, line_no)
-# }
-# case id
-# when :EVAL_TOPLEVEL
-# eval(str, bind, "(irb_internal)", 1)
-# when :EVAL_CONTEXT
-# @context.instance_eval(str)
-# else
-# IRB.fail IllegalParameter
-# end
-# end
-
- def signal_handle
- unless @context.ignore_sigint?
- print "\nabort!!\n" if @context.verbose?
- exit
- end
-
- case @signal_status
- when :IN_INPUT
- print "^C\n"
- raise RubyLex::TerminateLineInput
- when :IN_EVAL
- IRB.irb_abort(self)
- when :IN_LOAD
- IRB.irb_abort(self, LoadAbort)
- when :IN_IRB
- # ignore
- else
- # ignore other cases as well
- end
- end
-
- def signal_status(status)
- return yield if @signal_status == :IN_LOAD
-
- signal_status_back = @signal_status
- @signal_status = status
- begin
- yield
- ensure
- @signal_status = signal_status_back
- end
- end
-
- def trace_in
- Tracer.on if @context.use_tracer?
- begin
- yield
- ensure
- Tracer.off if @context.use_tracer?
- end
- end
-
- def prompt(prompt, ltype, indent, line_no)
- p = prompt.dup
- p.gsub!(/%([0-9]+)?([a-zA-Z])/) do
- case $2
- when "N"
- @context.irb_name
- when "m"
- @context.main.to_s
- when "M"
- @context.main.inspect
- when "l"
- ltype
- when "i"
- if $1
- format("%" + $1 + "d", indent)
- else
- indent.to_s
- end
- when "n"
- if $1
- format("%" + $1 + "d", line_no)
- else
- line_no.to_s
- end
- when "%"
- "%"
- end
- end
- p
- end
-
- def inspect
- ary = []
- for iv in instance_variables
- case iv
- when "@signal_status"
- ary.push format("%s=:%s", iv, @signal_status.id2name)
- when "@context"
- ary.push format("%s=%s", iv, eval(iv).__to_s__)
- else
- ary.push format("%s=%s", iv, eval(iv))
- end
- end
- format("#<%s: %s>", type, ary.join(", "))
- end
- end
-
- # Singleton method
- def @CONF.inspect
- IRB.version unless self[:VERSION]
-
- array = []
- for k, v in sort{|a1, a2| a1[0].id2name <=> a2[0].id2name}
- case k
- when :MAIN_CONTEXT
- next
- when :PROMPT
- s = v.collect{
- |kk, vv|
- ss = vv.collect{|kkk, vvv| ":#{kkk.id2name}=>#{vvv.inspect}"}
- format(":%s=>{%s}", kk.id2name, ss.join(", "))
- }
- array.push format("CONF[:%s]={%s}", k.id2name, s.join(", "))
- else
- array.push format("CONF[:%s]=%s", k.id2name, v.inspect)
- end
- end
- array.join("\n")
- end
-end
diff --git a/lib/irb/completion.rb b/lib/irb/completion.rb
deleted file mode 100644
index 01dcbd2219..0000000000
--- a/lib/irb/completion.rb
+++ /dev/null
@@ -1,177 +0,0 @@
-#
-# irb/completor.rb -
-# $Release Version: 0.7.1$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-# From Original Idea of shugo@ruby-lang.org
-#
-
-require "readline"
-
-module IRB
- module InputCompletor
-
- @RCS_ID='-$Id$-'
-
- ReservedWords = [
- "BEGIN", "END",
- "alias", "and",
- "begin", "break",
- "case", "class",
- "def", "defined", "do",
- "else", "elsif", "end", "ensure",
- "false", "for",
- "if", "in",
- "module",
- "next", "nil", "not",
- "or",
- "redo", "rescue", "retry", "return",
- "self", "super",
- "then", "true",
- "undef", "unless", "until",
- "when", "while",
- "yield",
- ]
-
- CompletionProc = proc { |input|
- bind = IRB.conf[:MAIN_CONTEXT].workspace.binding
- case input
- when /^(\/[^\/]*\/)\.([^.]*)$/
- # Regexp
- receiver = $1
- message = Regexp.quote($2)
-
- candidates = Regexp.instance_methods(true)
- select_message(receiver, message, candidates)
-
- when /^([^\]]*\])\.([^.]*)$/
- # Array
- receiver = $1
- message = Regexp.quote($2)
-
- candidates = Array.instance_methods(true)
- select_message(receiver, message, candidates)
-
- when /^([^\}]*\})\.([^.]*)$/
- # Proc or Hash
- receiver = $1
- message = Regexp.quote($2)
-
- candidates = Proc.instance_methods(true) | Hash.instance_methods(true)
- select_message(receiver, message, candidates)
-
- when /^(:[^:]*)$/
- # Symbol
- if Symbol.respond_to?(:all_symbols)
- sym = $1
- candidates = Symbol.all_symbols.collect{|s| s.id2name}
- candidates.grep(/^#{sym}/)
- else
- []
- end
-
- when /^::([A-Z][^:\.\(]*)$/
- # Absolute Constant or class methods
- receiver = $1
- candidates = Object.constants
- candidates.grep(/^#{receiver}/).collect{|e| "::" + e}
-
- when /^(((::)?[A-Z][^:.\(]*)+)::?([^:.]*)$/
- # Constant or class methods
- receiver = $1
- message = Regexp.quote($4)
- begin
- candidates = eval("#{receiver}.constants | #{receiver}.methods", bind)
- rescue Exception
- candidates = []
- end
- candidates.grep(/^#{message}/).collect{|e| receiver + "::" + e}
-
- when /^(:[^.]+)\.([^.]*)$/
- # Symbol
- receiver = $1
- message = Regexp.quote($2)
-
- candidates = Symbol.instance_methods(true)
- select_message(receiver, message, candidates)
-
- when /^([0-9_]+(\.[0-9_]+)?(e[0-9]+)?)\.([^.]*)$/
- # Numeric
- receiver = $1
- message = Regexp.quote($4)
-
- begin
- candidates = eval(receiver, bind).methods
- rescue Exception
- candidates
- end
- select_message(receiver, message, candidates)
-
-# when /^(\$?(\.?[^.]+)+)\.([^.]*)$/
- when /^((\.?[^.]+)+)\.([^.]*)$/
- # variable
- receiver = $1
- message = Regexp.quote($3)
-
- gv = eval "global_variables", bind
- lv = eval "local_variables", bind
- cv = eval "type.constants", bind
-
- if (gv | lv | cv).include?(receiver)
- # foo.func and foo is local var.
- candidates = eval("#{receiver}.methods", bind)
- elsif /^[A-Z]/ =~ receiver and /\./ !~ receiver
- # Foo::Bar.func
- begin
- candidates = eval("#{receiver}.methods", bind)
- rescue Exception
- candidates = []
- end
- else
- # func1.func2
- candidates = []
- ObjectSpace.each_object(Module){|m|
- next if /^(IRB|SLex|RubyLex|RubyToken)/ =~ m.name
- candidates.concat m.instance_methods
- }
- candidates.sort!
- candidates.uniq!
- end
- select_message(receiver, message, candidates)
-
- when /^\.([^.]*)$/
- # unknown(maybe String)
-
- receiver = ""
- message = Regexp.quote($1)
-
- candidates = String.instance_methods(true)
- select_message(receiver, message, candidates)
-
- else
- candidates = eval("methods | private_methods | local_variables | type.constants", bind)
-
- (candidates|ReservedWords).grep(/^#{Regexp.quote(input)}/)
- end
- }
-
- Operators = ["%", "&", "*", "**", "+", "-", "/",
- "<", "<<", "<=", "<=>", "==", "===", "=~", ">", ">=", ">>",
- "[]", "[]=", "^",]
-
- def self.select_message(receiver, message, candidates)
- candidates.grep(/^#{message}/).collect do |e|
- case e
- when /^[a-zA-Z_]/
- receiver + "." + e
- when /^[0-9]/
- when *Operators
- #receiver + " " + e
- end
- end
- end
- end
-end
-
-Readline.completion_proc = IRB::InputCompletor::CompletionProc
diff --git a/lib/irb/context.rb b/lib/irb/context.rb
deleted file mode 100644
index ffc77de875..0000000000
--- a/lib/irb/context.rb
+++ /dev/null
@@ -1,289 +0,0 @@
-#
-# irb/context.rb - irb context
-# $Release Version: 0.7.3$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-#
-# --
-#
-#
-#
-module IRB
- class Context
- #
- # Arguments:
- # input_method: nil -- stdin or readline
- # String -- File
- # other -- using this as InputMethod
- #
- def initialize(irb, workspace = nil, input_method = nil)
- @irb = irb
- if workspace
- @workspace = workspace
- else
- @workspace = WorkSpace.new unless workspace
- end
- @thread = Thread.current if defined? Thread
- @irb_level = 0
-
- # copy of default configuration
- @ap_name = IRB.conf[:AP_NAME]
- @rc = IRB.conf[:RC]
- @load_modules = IRB.conf[:LOAD_MODULES]
-
- self.math_mode = IRB.conf[:MATH_MODE]
- @use_readline = IRB.conf[:USE_READLINE]
- @inspect_mode = IRB.conf[:INSPECT_MODE]
- self.use_tracer = IRB.conf[:USE_TRACER]
-# @use_loader = IRB.conf[:USE_LOADER]
-
- self.prompt_mode = IRB.conf[:PROMPT_MODE]
-
- @ignore_sigint = IRB.conf[:IGNORE_SIGINT]
- @ignore_eof = IRB.conf[:IGNORE_EOF]
-
- @back_trace_limit = IRB.conf[:BACK_TRACE_LIMIT]
-
- debug_level = IRB.conf[:DEBUG_LEVEL]
- @verbose = IRB.conf[:VERBOSE]
-
- @tracer_initialized = false
-
- if IRB.conf[:SINGLE_IRB] or !defined?(JobManager)
- @irb_name = IRB.conf[:IRB_NAME]
- else
- @irb_name = "irb#"+IRB.JobManager.n_jobs.to_s
- end
- @irb_path = "(" + @irb_name + ")"
-
- case input_method
- when nil
- if (use_readline.nil? && IRB.conf[:PROMPT_MODE] != :INF_RUBY ||
- use_readline?)
- @io = ReadlineInputMethod.new
- else
- @io = StdioInputMethod.new
- end
- when String
- @io = FileInputMethod.new(input_method)
- @irb_name = File.basename(input_method)
- @irb_path = input_method
- else
- @io = input_method
- end
- end
-
- def main
- @workspace.main
- end
-
- attr_accessor :workspace
- attr_reader :thread
- attr_accessor :io
-
- attr_reader :_
-
- attr_accessor :irb
- attr_accessor :ap_name
- attr_accessor :rc
- attr_accessor :load_modules
- attr_accessor :irb_name
- attr_accessor :irb_path
-
- attr_accessor :math_mode
- attr_accessor :use_readline
- attr_reader :inspect_mode
- attr_reader :use_tracer
-# attr :use_loader
-
- attr_reader :debug_level
- attr_accessor :verbose
-
- attr_reader :prompt_mode
- attr_accessor :prompt_i
- attr_accessor :prompt_s
- attr_accessor :prompt_c
- attr_accessor :auto_indent_mode
- attr_accessor :return_format
-
- attr_accessor :ignore_sigint
- attr_accessor :ignore_eof
-
- attr_accessor :back_trace_limit
-
-# alias use_loader? use_loader
- alias use_tracer? use_tracer
- alias use_readline? use_readline
- alias rc? rc
- alias math? math_mode
- alias verbose? verbose
- alias ignore_sigint? ignore_sigint
- alias ignore_eof? ignore_eof
-
- def _=(value)
- @_ = value
- @workspace.evaluate "_ = IRB.conf[:MAIN_CONTEXT]._"
- end
-
- def irb_name
- if @irb_level == 0
- @irb_name
- elsif @irb_name =~ /#[0-9]*$/
- @irb_name + "." + @irb_level.to_s
- else
- @irb_name + "#0." + @irb_level.to_s
- end
- end
-
- def prompt_mode=(mode)
- @prompt_mode = mode
- pconf = IRB.conf[:PROMPT][mode]
- @prompt_i = pconf[:PROMPT_I]
- @prompt_s = pconf[:PROMPT_S]
- @prompt_c = pconf[:PROMPT_C]
- @return_format = pconf[:RETURN]
- if ai = pconf.include?(:AUTO_INDENT)
- @auto_indent_mode = ai
- else
- @auto_indent_mode = IRB.conf[:AUTO_INDENT]
- end
- end
-
- def inspect?
- @inspect_mode.nil? && !@math_mode or @inspect_mode
- end
-
- def file_input?
- @io.type == FileInputMethod
- end
-
- def use_tracer=(opt)
- if opt
- IRB.initialize_tracer
- unless @tracer_initialized
- Tracer.set_get_line_procs(@irb_path) {
- |line_no|
- @io.line(line_no)
- }
- @tracer_initialized = true
- end
- elsif !opt && @use_tracer
- Tracer.off
- end
- @use_tracer=opt
- end
-
- def use_loader
- IRB.conf[:USE_LOADER]
- end
-
- def use_loader=(opt)
- IRB.conf[:USE_LOADER] = opt
- if opt
- IRB.initialize_loader
- end
- print "Switch to load/require#{unless use_loader; ' non';end} trace mode.\n" if verbose?
- opt
- end
-
- def inspect_mode=(opt)
- if opt
- @inspect_mode = opt
- else
- @inspect_mode = !@inspect_mode
- end
- print "Switch to#{unless @inspect_mode; ' non';end} inspect mode.\n" if verbose?
- @inspect_mode
- end
-
- def math_mode=(opt)
- if @math_mode == true && opt == false
- IRB.fail CantRetuenNormalMode
- return
- end
-
- @math_mode = opt
- if math_mode
- IRB.initialize_mathn
- main.instance_eval("include Math")
- print "start math mode\n" if verbose?
- end
- end
-
- def use_readline=(opt)
- @use_readline = opt
- print "use readline module\n" if @use_readline
- end
-
- def debug_level=(value)
- @debug_level = value
- RubyLex.debug_level = value
- SLex.debug_level = value
- end
-
- def debug?
- @debug_level > 0
- end
-
- def change_binding(*_main)
- back = @workspace
- @workspace = WorkSpace.new(*_main)
- unless _main.empty?
- begin
- main.extend ExtendCommand
- rescue
- print "can't change binding to: ", main.inspect, "\n"
- @workspace = back
- return nil
- end
- end
- @irb_level += 1
- begin
- catch(:SU_EXIT) do
- @irb.eval_input
- end
- ensure
- @irb_level -= 1
- @workspace = back
- end
- end
- alias change_workspace change_binding
-
-
- alias __exit__ exit
- def exit(ret = 0)
- if @irb_level == 0
- IRB.irb_exit(@irb, ret)
- else
- throw :SU_EXIT, ret
- end
- end
-
- NOPRINTING_IVARS = ["@_"]
- NO_INSPECTING_IVARS = ["@irb", "@io"]
- IDNAME_IVARS = ["@prompt_mode"]
-
- alias __inspect__ inspect
- def inspect
- array = []
- for ivar in instance_variables.sort{|e1, e2| e1 <=> e2}
- name = ivar.sub(/^@(.*)$/){$1}
- val = instance_eval(ivar)
- case ivar
- when *NOPRINTING_IVARS
- next
- when *NO_INSPECTING_IVARS
- array.push format("conf.%s=%s", name, val.to_s)
- when *IDNAME_IVARS
- array.push format("conf.%s=:%s", name, val.id2name)
- else
- array.push format("conf.%s=%s", name, val.inspect)
- end
- end
- array.join("\n")
- end
- alias __to_s__ to_s
- alias to_s inspect
- end
-end
diff --git a/lib/irb/extend-command.rb b/lib/irb/extend-command.rb
deleted file mode 100644
index 3f92707d01..0000000000
--- a/lib/irb/extend-command.rb
+++ /dev/null
@@ -1,126 +0,0 @@
-#
-# irb/extend-command.rb - irb command extend
-# $Release Version: 0.7.3$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-#
-# --
-#
-#
-#
-module IRB
- #
- # IRB extended command
- #
- module ExtendCommand
-# include Loader
-
- def irb_exit(ret = 0)
- irb_context.exit(ret)
- end
- alias irb_quit irb_exit
-
- def irb_fork(&block)
- pid = send ExtendCommand.irb_original_method_name("fork")
- unless pid
- class<<self
- alias_method :exit, ExtendCommand.irb_original_method_name('exit')
- end
- if iterator?
- begin
- yield
- ensure
- exit
- end
- end
- end
- pid
- end
-
- def irb_change_binding(*main)
- irb_context.change_binding(*main)
- end
- alias irb_change_workspace irb_change_binding
-
- def irb_source(file)
- irb_context.source(file)
- end
-
- def irb(*obj)
- require "irb/multi-irb"
- IRB.irb(nil, *obj)
- end
-
- def irb_context
- IRB.conf[:MAIN_CONTEXT]
- end
-
- def irb_jobs
- require "irb/multi-irb"
- IRB.JobManager
- end
-
- def irb_fg(key)
- require "irb/multi-irb"
- IRB.JobManager.switch(key)
- end
-
- def irb_kill(*keys)
- require "irb/multi-irb"
- IRB.JobManager.kill(*keys)
- end
-
- # extend command functions
- def ExtendCommand.extend_object(obj)
- super
- unless (class<<obj;ancestors;end).include?(ExtendCommand)
- obj.install_aliases
- end
- end
-
- OVERRIDE_NOTHING = 0
- OVERRIDE_PRIVATE_ONLY = 0x01
- OVERRIDE_ALL = 0x02
-
- def install_aliases(override = OVERRIDE_NOTHING)
-
- install_alias_method(:exit, :irb_exit, override | OVERRIDE_PRIVATE_ONLY)
- install_alias_method(:quit, :irb_quit, override | OVERRIDE_PRIVATE_ONLY)
- install_alias_method(:fork, :irb_fork, override | OVERRIDE_PRIVATE_ONLY)
- install_alias_method(:kill, :irb_kill, override | OVERRIDE_PRIVATE_ONLY)
-
- install_alias_method(:irb_cb, :irb_change_binding, override)
- install_alias_method(:irb_ws, :irb_change_workspace, override)
- install_alias_method(:source, :irb_source, override)
- install_alias_method(:conf, :irb_context, override)
- install_alias_method(:jobs, :irb_jobs, override)
- install_alias_method(:fg, :irb_fg, override)
- end
-
- # override = {OVERRIDE_NOTHING, OVERRIDE_PRIVATE_ONLY, OVERRIDE_ALL}
- def install_alias_method(to, from, override = OVERRIDE_NOTHING)
- to = to.id2name unless to.kind_of?(String)
- from = from.id2name unless from.kind_of?(String)
-
- if override == OVERRIDE_ALL or
- (override == OVERRIDE_PRIVATE_ONLY) && !respond_to?(to) or
- (override == OVERRIDE_NOTHING) && !respond_to?(to, true)
- target = self
- (class<<self;self;end).instance_eval{
- if target.respond_to?(to, true) &&
- !target.respond_to?(ExtendCommand.irb_original_method_name(to), true)
- alias_method(ExtendCommand.irb_original_method_name(to), to)
- end
- alias_method to, from
- }
- else
- print "irb: warn: can't alias #{to} from #{from}.\n"
- end
- end
-
- def self.irb_original_method_name(method_name)
- "irb_" + method_name + "_org"
- end
- end
-end
diff --git a/lib/irb/frame.rb b/lib/irb/frame.rb
deleted file mode 100644
index 1090cd9684..0000000000
--- a/lib/irb/frame.rb
+++ /dev/null
@@ -1,67 +0,0 @@
-#
-# frame.rb -
-# $Release Version: 0.7.1$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)
-#
-# --
-#
-#
-#
-
-require "e2mmap"
-
-module IRB
- class Frame
- extend Exception2MessageMapper
- def_exception :FrameOverflow, "frame overflow"
- def_exception :FrameUnderflow, "frame underflow"
-
- INIT_STACK_TIMES = 3
- CALL_STACK_OFFSET = 3
-
- def initialize
- @frames = [TOPLEVEL_BINDING] * INIT_STACK_TIMES
- end
-
- def trace_func(event, file, line, id, binding)
- case event
- when 'call', 'class'
- @frames.push binding
- when 'return', 'end'
- @frames.pop
- end
- end
-
- def top(n = 0)
- bind = @frames[-(n + CALL_STACK_OFFSET)]
- Fail FrameUnderflow unless bind
- bind
- end
-
- def bottom(n = 0)
- bind = @frames[n]
- Fail FrameOverflow unless bind
- bind
- end
-
- # singleton functions
- def Frame.bottom(n = 0)
- @backtrace.bottom(n)
- end
-
- def Frame.top(n = 0)
- @backtrace.top(n)
- end
-
- def Frame.sender
- eval "self", @backtrace.top
- end
-
- @backtrace = Frame.new
- set_trace_func proc{|event, file, line, id, binding, klass|
- @backtrace.trace_func(event, file, line, id, binding)
- }
- end
-end
diff --git a/lib/irb/help.rb b/lib/irb/help.rb
deleted file mode 100644
index 0821f68d13..0000000000
--- a/lib/irb/help.rb
+++ /dev/null
@@ -1,33 +0,0 @@
-#
-# irb/help.rb - print usase module
-# $Release Version: 0.7.3$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-#
-# --
-#
-#
-#
-
-module IRB
- def IRB.print_usage
- lc = IRB.conf[:LC_MESSAGES]
- path = lc.find("irb/help-message")
- space_line = false
- File.foreach(path) do
- |l|
- if /^\s*$/ =~ l
- lc.puts l unless space_line
- space_line = true
- next
- end
- space_line = false
-
- l.sub!(/#.*$/, "")
- next if /^\s*$/ =~ l
- lc.puts l
- end
- end
-end
-
diff --git a/lib/irb/init.rb b/lib/irb/init.rb
deleted file mode 100644
index f34a51b345..0000000000
--- a/lib/irb/init.rb
+++ /dev/null
@@ -1,232 +0,0 @@
-#
-# irb/init.rb - irb initialize module
-# $Release Version: 0.7.3$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-#
-# --
-#
-#
-#
-
-module IRB
-
- # initialize config
- def IRB.initialize(ap_path)
- IRB.init_config(ap_path)
- IRB.init_error
- IRB.run_config
- end
-
- # @CONF default setting
- def IRB.init_config(ap_path)
- # class instance variables
- @TRACER_INITIALIZED = false
- @MATHN_INITIALIZED = false
-
- # default configurations
- unless ap_path and @CONF[:AP_NAME]
- ap_path = File.join(File.dirname(File.dirname(__FILE__)), "irb.rb")
- end
- @CONF[:AP_NAME] = File::basename(ap_path, ".rb")
-
- @CONF[:IRB_NAME] = "irb"
- @CONF[:IRB_LIB_PATH] = File.dirname(__FILE__)
-
- @CONF[:RC] = true
- @CONF[:LOAD_MODULES] = []
- @CONF[:IRB_RC] = nil
-
- @CONF[:MATH_MODE] = false
- @CONF[:USE_READLINE] = false unless defined?(ReadlineInputMethod)
- @CONF[:INSPECT_MODE] = nil
- @CONF[:USE_TRACER] = false
- @CONF[:USE_LOADER] = false
- @CONF[:IGNORE_SIGINT] = true
- @CONF[:IGNORE_EOF] = false
-
- @CONF[:BACK_TRACE_LIMIT] = 16
-
- @CONF[:PROMPT] = {
- :NULL => {
- :PROMPT_I => nil,
- :PROMPT_S => nil,
- :PROMPT_C => nil,
- :RETURN => "%s\n"
- },
- :DEFAULT => {
- :PROMPT_I => "%N(%m):%03n:%i> ",
- :PROMPT_S => "%N(%m):%03n:%i%l ",
- :PROMPT_C => "%N(%m):%03n:%i* ",
- :RETURN => "%s\n"
- },
- :SIMPLE => {
- :PROMPT_I => ">> ",
- :PROMPT_S => nil,
- :PROMPT_C => "?> ",
- :RETURN => "=> %s\n"
- },
- :INF_RUBY => {
- :PROMPT_I => "%N(%m):%03n:%i> ",
- :PROMPT_S => nil,
- :PROMPT_C => nil,
- :RETURN => "%s\n",
- :AUTO_INDENT => true
- },
- :XMP => {
- :PROMPT_I => nil,
- :PROMPT_S => nil,
- :PROMPT_C => nil,
- :RETURN => " ==>%s\n"
- }
- }
-
- @CONF[:PROMPT_MODE] = :DEFAULT
- @CONF[:AUTO_INDENT] = false
-
- @CONF[:CONTEXT_MODE] = 3 # use binding in function on TOPLEVEL_BINDING
- @CONF[:SINGLE_IRB] = false
-
-# @CONF[:LC_MESSAGES] = "en"
- @CONF[:LC_MESSAGES] = Locale.new
-
- @CONF[:DEBUG_LEVEL] = 1
- @CONF[:VERBOSE] = true
- end
-
- def IRB.init_error
- @CONF[:LC_MESSAGES].load("irb/error.rb")
- end
-
- # option analyzing
- def IRB.parse_opts
- while opt = ARGV.shift
- case opt
- when "-f"
- opt = ARGV.shift
- @CONF[:RC] = false
- when "-m"
- @CONF[:MATH_MODE] = true
- when "-d"
- $DEBUG = true
- when "-r"
- opt = ARGV.shift
- @CONF[:LOAD_MODULES].push opt if opt
- when "--inspect"
- @CONF[:INSPECT_MODE] = true
- when "--noinspect"
- @CONF[:INSPECT_MODE] = false
- when "--readline"
- @CONF[:USE_READLINE] = true
- when "--noreadline"
- @CONF[:USE_READLINE] = false
-
- when "--prompt-mode", "--prompt"
- prompt_mode = ARGV.shift.upcase.tr("-", "_").intern
- IRB.fail(UndefinedPromptMode,
- prompt_mode.id2name) unless @CONF[:PROMPT][prompt_mode]
- @CONF[:PROMPT_MODE] = prompt_mode
- when "--noprompt"
- @CONF[:PROMPT_MODE] = :NULL
- when "--inf-ruby-mode"
- @CONF[:PROMPT_MODE] = :INF_RUBY
- when "--sample-book-mode", "--simple-prompt"
- @CONF[:PROMPT_MODE] = :SIMPLE
-
- when "--tracer"
- @CONF[:USE_TRACER] = true
- when "--back-trace-limit"
- @CONF[:BACK_TRACE_LIMIT] = ARGV.shift.to_i
- when "--context-mode"
- @CONF[:CONTEXT_MODE] = ARGV.shift.to_i
- when "--single-irb"
- @CONF[:SINGLE_IRB] = true
- when "--irb_debug"
- @CONF[:DEBUG_LEVEL] = ARGV.shift.to_i
- when "-v", "--version"
- print IRB.version, "\n"
- exit 0
- when "-h", "--help"
- require "irb/help"
- IRB.print_usage
- exit 0
- when /^-/
- IRB.fail UnrecognizedSwitch, opt
- else
- @CONF[:USE_READLINE] = false
- @CONF[:SCRIPT] = opt
- $0 = opt
- break
- end
- end
- end
-
- # running config
- def IRB.run_config
- if @CONF[:RC]
- rcs = []
- rcs.push File.expand_path("~/.irbrc") if ENV.key?("HOME")
- rcs.push ".irbrc"
- rcs.push "irb.rc"
- rcs.push "_irbrc"
- rcs.push "$irbrc"
- catch(:EXIT) do
- for rc in rcs
- begin
- load rc
- throw :EXIT
- rescue LoadError, Errno::ENOENT
- rescue
- print "load error: #{rc}\n"
- print $!.type, ": ", $!, "\n"
- for err in $@[0, $@.size - 2]
- print "\t", err, "\n"
- end
- throw :EXIT
- end
- end
- end
- end
- end
-
- # loading modules
- def IRB.load_modules
- for m in @CONF[:LOAD_MODULES]
- begin
- require m
- rescue
- print $@[0], ":", $!.type, ": ", $!, "\n"
- end
- end
- end
-
- # initialize tracing function
- def IRB.initialize_tracer
- unless @TRACER_INITIALIZED
- require("tracer")
- Tracer.verbose = false
- Tracer.add_filter {
- |event, file, line, id, binding|
- File::dirname(file) != @CONF[:IRB_LIB_PATH]
- }
- @TRACER_INITIALIZED = true
- end
- end
-
- # initialize mathn function
- def IRB.initialize_mathn
- unless @MATHN_INITIALIZED
- require "mathn"
- @MATHN_INITIALIZED = true
- end
- end
-
- # initialize loader function
- def IRB.initialize_loader
- unless @LOADER_INITIALIZED
- require "irb/loader"
- @LOADER_INITIALIZED = true
- end
- end
-end
diff --git a/lib/irb/input-method.rb b/lib/irb/input-method.rb
deleted file mode 100644
index ffbc6d9edc..0000000000
--- a/lib/irb/input-method.rb
+++ /dev/null
@@ -1,118 +0,0 @@
-#
-# irb/input-method.rb - input methods using irb
-# $Release Version: 0.7.3$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-#
-# --
-#
-#
-#
-module IRB
- #
- # InputMethod
- # StdioInputMethod
- # FileInputMethod
- # (ReadlineInputMethod)
- #
- STDIN_FILE_NAME = "(line)"
- class InputMethod
- @RCS_ID='-$Id$-'
-
- def initialize(file = STDIN_FILE_NAME)
- @file_name = file
- end
- attr_reader :file_name
-
- attr_accessor :prompt
-
- def gets
- IRB.fail NotImplementError, "gets"
- end
- public :gets
-
- def readable_atfer_eof?
- false
- end
- end
-
- class StdioInputMethod < InputMethod
- def initialize
- super
- @line_no = 0
- @line = []
- end
-
- def gets
- print @prompt
- @line[@line_no += 1] = $stdin.gets
- end
-
- def eof?
- $stdin.eof?
- end
-
- def readable_atfer_eof?
- true
- end
-
- def line(line_no)
- @line[line_no]
- end
- end
-
- class FileInputMethod < InputMethod
- def initialize(file)
- super
- @io = open(file)
- end
- attr_reader :file_name
-
- def eof?
- @io.eof?
- end
-
- def gets
- l = @io.gets
- print @prompt, l
- l
- end
- end
-
- begin
- require "readline"
- class ReadlineInputMethod < InputMethod
- include Readline
- def initialize
- super
-
- @line_no = 0
- @line = []
- @eof = false
- end
-
- def gets
- if l = readline(@prompt, true)
- @line[@line_no += 1] = l + "\n"
- else
- @eof = true
- l
- end
- end
-
- def eof?
- @eof
- end
-
- def readable_atfer_eof?
- true
- end
-
- def line(line_no)
- @line[line_no]
- end
- end
- rescue LoadError
- end
-end
diff --git a/lib/irb/lc/error.rb b/lib/irb/lc/error.rb
deleted file mode 100644
index de38f29978..0000000000
--- a/lib/irb/lc/error.rb
+++ /dev/null
@@ -1,30 +0,0 @@
-#
-# irb/lc/error.rb -
-# $Release Version: 0.7.3$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-#
-# --
-#
-#
-#
-require "e2mmap"
-
-module IRB
-
- # exceptions
- extend Exception2MessageMapper
- def_exception :UnrecognizedSwitch, "Unrecognized switch: %s"
- def_exception :NotImplementError, "Need to define `%s'"
- def_exception :CantRetuenNormalMode, "Can't return normal mode."
- def_exception :IllegalParameter, "Illegal parameter(%s)."
- def_exception :IrbAlreadyDead, "Irb is already dead."
- def_exception :IrbSwitchToCurrentThread, "Change to current thread."
- def_exception :NoSuchJob, "No such job(%s)."
- def_exception :CanNotGoMultiIrbMode, "Can't go multi irb mode."
- def_exception :CanNotChangeBinding, "Can't change binding to (%s)."
- def_exception :UndefinedPromptMode, "Undefined prompt mode(%s)."
-
-end
-
diff --git a/lib/irb/lc/help-message b/lib/irb/lc/help-message
deleted file mode 100644
index daede5ec21..0000000000
--- a/lib/irb/lc/help-message
+++ /dev/null
@@ -1,34 +0,0 @@
-#
-# irb/lc/help-message.rb -
-# $Release Version: 0.7.3$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-#
-# --
-#
-#
-#
-Usage: irb.rb [options] [programfile] [arguments]
- -f suppress read ~/.irbrc
- -m bc mode (load mathn, fraction or matrix are available)
- -d set $DEBUG to true (same as `ruby -d')
- -r load-module same as `ruby -r'
- --inspect uses `inspect' for output (the default except bc mode)
- --noinspect doesn't uses inspect for output
- --readline uses Readline extension module
- --noreadline doesn't use Readline extension module
- --prompt prompt-mode
- --prompt-mode prompt-mode
- switches prompt mode. Pre-defined prompt modes are
- `default', `simple', `xmp' and `inf-ruby'
- --inf-ruby-mode uses prompt appreciate for inf-ruby-mode on emacs.
- Suppresses --readline.
- --simple-prompt simple prompt mode
- --noprompt no prompt
- --tracer display trace for each execution of commands.
- --back-trace-limit n
- displayes backtrace top n and tail n. The default
- value is 16.
- --irb_debug n sets internal debug level to n (It shouldn't be used)
- -v, --version prints the version of irb
diff --git a/lib/irb/lc/ja/error.rb b/lib/irb/lc/ja/error.rb
deleted file mode 100644
index d5aef0a7c8..0000000000
--- a/lib/irb/lc/ja/error.rb
+++ /dev/null
@@ -1,29 +0,0 @@
-#
-# irb/lc/ja/error.rb -
-# $Release Version: 0.7.3$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-#
-# --
-#
-#
-#
-require "e2mmap"
-
-module IRB
- # exceptions
- extend Exception2MessageMapper
- def_exception :UnrecognizedSwitch, '$B%9%$%C%A(B(%s)$B$,J,$j$^$;$s(B'
- def_exception :NotImplementError, '`%s\'$B$NDj5A$,I,MW$G$9(B'
- def_exception :CantRetuenNormalMode, 'Normal$B%b!<%I$KLa$l$^$;$s(B.'
- def_exception :IllegalParameter, '$B%Q%i%a!<%?(B(%s)$B$,4V0c$C$F$$$^$9(B.'
- def_exception :IrbAlreadyDead, 'Irb$B$O4{$K;`$s$G$$$^$9(B.'
- def_exception :IrbSwitchToCurrentThread, 'Change to current thread.'
- def_exception :NoSuchJob, '$B$=$N$h$&$J%8%g%V(B(%s)$B$O$"$j$^$;$s(B.'
- def_exception :CanNotGoMultiIrbMode, 'multi-irb mode$B$K0\$l$^$;$s(B.'
- def_exception :CanNotChangeBinding, '$B%P%$%s%G%#%s%0(B(%s)$B$KJQ99$G$-$^$;$s(B.'
- def_exception :UndefinedPromptMode, '$B%W%m%s%W%H%b!<%I(B(%s)$B$ODj5A$5$l$F$$$^$;$s(B.'
-end
-
-
diff --git a/lib/irb/lc/ja/help-message b/lib/irb/lc/ja/help-message
deleted file mode 100644
index 9fa3952a0b..0000000000
--- a/lib/irb/lc/ja/help-message
+++ /dev/null
@@ -1,35 +0,0 @@
-#
-# irb/lc/ja/help-message.rb -
-# $Release Version: 0.7.3$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-#
-# --
-#
-#
-#
-Usage: irb.rb [options] [programfile] [arguments]
- -f ~/.irbrc $B$rFI$_9~$^$J$$(B.
- -m bc$B%b!<%I(B($BJ,?t(B, $B9TNs$N7W;;$,$G$-$k(B)
- -d $DEBUG $B$r(Btrue$B$K$9$k(B(ruby -d $B$HF1$8(B)
- -r load-module ruby -r $B$HF1$8(B.
- --inspect $B7k2L=PNO$K(Binspect$B$rMQ$$$k(B(bc$B%b!<%I0J30$O%G%U%)%k%H(B).
- --noinspect $B7k2L=PNO$K(Binspect$B$rMQ$$$J$$(B.
- --readline readline$B%i%$%V%i%j$rMxMQ$9$k(B.
- --noreadline readline$B%i%$%V%i%j$rMxMQ$7$J$$(B.
- --prompt prompt-mode/--prompt-mode prompt-mode
- $B%W%m%s%W%H%b!<%I$r@ZBX$($^$9(B. $B8=:_Dj5A$5$l$F$$$k%W(B
- $B%m%s%W%H%b!<%I$O(B, default, simple, xmp, inf-ruby$B$,(B
- $BMQ0U$5$l$F$$$^$9(B.
- --inf-ruby-mode emacs$B$N(Binf-ruby-mode$BMQ$N%W%m%s%W%HI=<($r9T$J$&(B. $BFC(B
- $B$K;XDj$,$J$$8B$j(B, readline$B%i%$%V%i%j$O;H$o$J$/$J$k(B.
- --simple-prompt $BHs>o$K%7%s%W%k$J%W%m%s%W%H$rMQ$$$k%b!<%I$G$9(B.
- --noprompt $B%W%m%s%W%HI=<($r9T$J$o$J$$(B.
- --tracer $B%3%^%s%I<B9T;~$K%H%l!<%9$r9T$J$&(B.
- --back-trace-limit n
- $B%P%C%/%H%l!<%9I=<($r%P%C%/%H%l!<%9$NF,$+$i(B n, $B8e$m(B
- $B$+$i(Bn$B$@$19T$J$&(B. $B%G%U%)%k%H$O(B16
- --irb_debug n irb$B$N%G%P%C%0%G%P%C%0%l%Y%k$r(Bn$B$K@_Dj$9$k(B($BMxMQ$7$J(B
- $B$$J}$,L5Fq$G$7$g$&(B).
- -v, --version irb$B$N%P!<%8%g%s$rI=<($9$k(B
diff --git a/lib/irb/loader.rb b/lib/irb/loader.rb
deleted file mode 100644
index 6e7a89e454..0000000000
--- a/lib/irb/loader.rb
+++ /dev/null
@@ -1,118 +0,0 @@
-#
-# irb/loader.rb - irb loader
-# $Release Version: 0.7.3$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-#
-# --
-#
-#
-#
-
-module IRB
- class LoadAbort < GlobalExit;end
-
- module Loader
- @RCS_ID='-$Id$-'
-
- alias ruby_load load
- alias ruby_require require
-
- def irb_load(file_name)
- return ruby_load(file_name) unless IRB.conf[:USE_LOADER]
-
- load_sub(file_name)
- return true
- end
-
- def irb_require(file_name)
- return ruby_require(file_name) unless IRB.conf[:USE_LOADER]
-
- rex = Regexp.new("#{Regexp.quote(file_name)}(\.o|\.rb)?")
- return false if $".find{|f| f =~ rex}
-
- case file_name
- when /\.rb$/
- begin
- load_sub(file_name)
- $".push file_name
- return true
- rescue LoadError
- end
- when /\.(so|o|sl)$/
- return ruby_require(file_name)
- end
-
- begin
- load_sub(f = file_name + ".rb")
- $".push f
- return true
- rescue LoadError
- return ruby_require(file_name)
- end
- end
-
- def load_sub(fn)
- if fn =~ /^#{Regexp.quote(File::Separator)}/
- return false unless File.exist?(fn)
- return irb_context.load_file(fn)
- end
-
- for path in $:
- if File.exist?(f = File.join(path, fn))
- return irb_context.load_file(f)
- end
- end
- raise LoadError, "No such file to load -- #{file_name}"
- end
-
- alias load irb_load
- alias require irb_require
- end
-
-# class Context
-# def load_from(file_name)
-# io = FileInputMethod.new(file_name)
-# @irb.signal_status(:IN_LOAD) do
-# switch_io(io, file_name) do
-# eval_input
-# end
-# end
-# end
-# end
-
- class Context
- def load_file(path)
- back_io = @io
- back_path = @irb_path
- back_name = @irb_name
- back_scanner = @irb.scanner
- begin
- @io = FileInputMethod.new(path)
- @irb_name = File.basename(path)
- @irb_path = path
- @irb.signal_status(:IN_LOAD) do
- if back_io.kind_of?(FileInputMethod)
- @irb.eval_input
- else
- begin
- @irb.eval_input
- rescue LoadAbort
- print "load abort!!\n"
- end
- end
- end
- ensure
- @io = back_io
- @irb_name = back_name
- @irb_path = back_path
- @irb.scanner = back_scanner
- end
- end
- end
-
- module ExtendCommand
- include Loader
- end
-end
diff --git a/lib/irb/locale.rb b/lib/irb/locale.rb
deleted file mode 100644
index e0a44f3421..0000000000
--- a/lib/irb/locale.rb
+++ /dev/null
@@ -1,186 +0,0 @@
-#
-# irb/locale.rb - internationalization module
-# $Release Version: 0.7.4$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-#
-# --
-#
-#
-#
-
-autoload :Tempfile, "tempfile"
-autoload :Kconv, "kconv"
-
-module IRB
- class Locale
- @RCS_ID='-$Id$-'
-
- JPDefaultLocale = "ja"
- LOCALE_DIR = "/lc/"
-
- def initialize(locale = nil)
- @lang = locale || ENV["IRB_LANG"] || ENV["LC_MESSAGES"] || ENV["LC_ALL"] || ENV["LANG"]
- @lang = "C" unless @lang
- end
-
- attr_reader :lang
-
- def String(mes)
- mes = super(mes)
- case @lang
- when /^ja/
- @@LC2KCONV = {
- # "ja" => Kconv::JIS,
- # "ja_JP" => Kconv::JIS,
- "ja_JP.ujis" => Kconv::EUC,
- "ja_JP.euc" => Kconv::EUC,
- "ja_JP.eucJP" => Kconv::EUC,
- "ja_JP.sjis" => Kconv::SJIS,
- "ja_JP.SJIS" => Kconv::SJIS,
- } unless defined? @@LC2KCONV
-
- mes = Kconv::kconv(mes, @@LC2KCONV[@lang])
- else
- mes
- end
- mes
- end
-
- def format(*opts)
- String(super(*opts))
- end
-
- def gets(*rs)
- String(super(*rs))
- end
-
- def readline(*rs)
- String(super(*rs))
- end
-
- def print(*opts)
- ary = opts.collect{|opt| String(opt)}
- super(*ary)
- end
-
- def printf(*opts)
- s = format(*opts)
- print s
- end
-
- def puts(*opts)
- ary = opts.collect{|opt| String(opts)}
- super(*ary)
- end
-
- def require(file, priv = nil)
- rex = Regexp.new("lc/#{Regexp.quote(file)}\.(so|o|sl|rb)?")
- return false if $".find{|f| f =~ rex}
-
- case file
- when /\.rb$/
- begin
- load(file, priv)
- $".push file
- return true
- rescue LoadError
- end
- when /\.(so|o|sl)$/
- return super
- end
-
- begin
- load(f = file + ".rb")
- $".push f #"
- return true
- rescue LoadError
- return ruby_require(file)
- end
- end
-
- alias toplevel_load load
-
- def load(file, priv=nil)
- dir = File.dirname(file)
- dir = "" if dir == "."
- base = File.basename(file)
-
- if /^ja(_JP)?$/ =~ @lang
- back, @lang = @lang, "C"
- end
- begin
- if dir[0] == ?/ #/
- lc_path = search_file(dir, base)
- return real_load(lc_path, priv) if lc_path
- end
-
- for path in $:
- lc_path = search_file(path + "/" + dir, base)
- return real_load(lc_path, priv) if lc_path
- end
- ensure
- @lang = back if back
- end
- raise LoadError, "No such file to load -- #{file}"
- end
-
- def real_load(path, priv)
- tmp_base = path.tr("./:", "___")
- lc_file = Tempfile.new(tmp_base)
- File.foreach(path) do |line|
- line = self.String(line)
- lc_file.print(line)
- end
- lc_file.close
- toplevel_load lc_file.path, priv
- end
- private :real_load
-
- def find(file , paths = $:)
- dir = File.dirname(file)
- dir = "" if dir == "."
- base = File.basename(file)
- if dir[0] == ?/ #/
- return lc_path = search_file(dir, base)
- else
- for path in $:
- if lc_path = search_file(path + "/" + dir, base)
- return lc_path
- end
- end
- end
- nil
- end
-
- def search_file(path, file)
- if File.exists?(p1 = path + lc_path(file, "C"))
- if File.exists?(p2 = path + lc_path(file))
- return p2
- else
- end
- return p1
- else
- end
- nil
- end
- private :search_file
-
- def lc_path(file = "", lc = @lang)
- case lc
- when "C"
- LOCALE_DIR + file
- when /^ja/
- LOCALE_DIR + "ja/" + file
- else
- LOCALE_DIR + @lang + "/" + file
- end
- end
- private :lc_path
- end
-end
-
-
-
-
diff --git a/lib/irb/multi-irb.rb b/lib/irb/multi-irb.rb
deleted file mode 100644
index 77d9921ea8..0000000000
--- a/lib/irb/multi-irb.rb
+++ /dev/null
@@ -1,232 +0,0 @@
-#
-# irb/multi-irb.rb - multiple irb module
-# $Release Version: 0.7.3$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-#
-# --
-#
-#
-#
-IRB.fail CanNotGoMultiIrbMode unless defined?(Thread)
-require "thread"
-
-module IRB
- # job management class
- class JobManager
- @RCS_ID='-$Id$-'
-
- def initialize
- # @jobs = [[thread, irb],...]
- @jobs = []
- @current_job = nil
- end
-
- attr_accessor :current_job
-
- def n_jobs
- @jobs.size
- end
-
- def thread(key)
- th, irb = search(key)
- th
- end
-
- def irb(key)
- th, irb = search(key)
- irb
- end
-
- def main_thread
- @jobs[0][0]
- end
-
- def main_irb
- @jobs[0][1]
- end
-
- def insert(irb)
- @jobs.push [Thread.current, irb]
- end
-
- def switch(key)
- th, irb = search(key)
- IRB.fail IrbAlreadyDead unless th.alive?
- IRB.fail IrbSwitchToCurrentThread if th == Thread.current
- @current_job = irb
- th.run
- Thread.stop
- @current_job = irb(Thread.current)
- end
-
- def kill(*keys)
- for key in keys
- th, irb = search(key)
- IRB.fail IrbAlreadyDead unless th.alive?
- th.exit
- end
- end
-
- def search(key)
- case key
- when Integer
- @jobs[key]
- when Irb
- @jobs.find{|k, v| v.equal?(key)}
- when Thread
- @jobs.assoc(key)
- else
- assoc = @jobs.find{|k, v| v.context.main.equal?(key)}
- IRB.fail NoSuchJob, key if assoc.nil?
- assoc
- end
- end
-
- def delete(key)
- case key
- when Integer
- IRB.fail NoSuchJob, key unless @jobs[key]
- @jobs[key] = nil
- else
- catch(:EXISTS) do
- @jobs.each_index do
- |i|
- if @jobs[i] and (@jobs[i][0] == key ||
- @jobs[i][1] == key ||
- @jobs[i][1].context.main.equal?(key))
- @jobs[i] = nil
- throw :EXISTS
- end
- end
- IRB.fail NoSuchJob, key
- end
- end
- until assoc = @jobs.pop; end unless @jobs.empty?
- @jobs.push assoc
- end
-
- def inspect
- ary = []
- @jobs.each_index do
- |i|
- th, irb = @jobs[i]
- next if th.nil?
-
- if th.alive?
- if th.stop?
- t_status = "stop"
- else
- t_status = "running"
- end
- else
- t_status = "exited"
- end
- ary.push format("#%d->%s on %s (%s: %s)",
- i,
- irb.context.irb_name,
- irb.context.main,
- th,
- t_status)
- end
- ary.join("\n")
- end
- end
-
- @JobManager = JobManager.new
-
- def IRB.JobManager
- @JobManager
- end
-
- # invoke multi-irb
- def IRB.irb(file = nil, *main)
- workspace = WorkSpace.new(*main)
- parent_thread = Thread.current
- Thread.start do
- begin
- irb = Irb.new(workspace, file)
- rescue
- print "Subirb can't start with context(self): ", workspace.main.inspect, "\n"
- print "return to main irb\n"
- Thread.pass
- Thread.main.wakeup
- Thread.exit
- end
- @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC]
- @JobManager.insert(irb)
- @JobManager.current_job = irb
- begin
- system_exit = false
- catch(:IRB_EXIT) do
- irb.eval_input
- end
- rescue SystemExit
- system_exit = true
- raise
- #fail
- ensure
- unless system_exit
- @JobManager.delete(irb)
- if parent_thread.alive?
- @JobManager.current_job = @JobManager.irb(parent_thread)
- parent_thread.run
- else
- @JobManager.current_job = @JobManager.main_irb
- @JobManager.main_thread.run
- end
- end
- end
- end
- Thread.stop
- @JobManager.current_job = @JobManager.irb(Thread.current)
- end
-
- class Context
- def _=(value)
- @_ = value
- @workspace.evaluate "_ = IRB.JobManager.irb(Thread.current).context._"
- end
- end
-
- module ExtendCommand
- def irb_context
- IRB.JobManager.irb(Thread.current).context
- end
-# alias conf irb_context
- end
-
- @CONF[:SINGLE_IRB_MODE] = false
- @JobManager.insert(@CONF[:MAIN_CONTEXT].irb)
- @JobManager.current_job = @CONF[:MAIN_CONTEXT].irb
-
- class Irb
- def signal_handle
- unless @context.ignore_sigint?
- print "\nabort!!\n" if @context.verbose?
- exit
- end
-
- case @signal_status
- when :IN_INPUT
- print "^C\n"
- IRB.JobManager.thread(self).raise RubyLex::TerminateLineInput
- when :IN_EVAL
- IRB.irb_abort(self)
- when :IN_LOAD
- IRB.irb_abort(self, LoadAbort)
- when :IN_IRB
- # ignore
- else
- # ignore
- end
- end
- end
-
- trap("SIGINT") do
- @JobManager.current_job.signal_handle
- Thread.stop
- end
-
-end
diff --git a/lib/irb/ruby-lex.rb b/lib/irb/ruby-lex.rb
deleted file mode 100644
index 3647617849..0000000000
--- a/lib/irb/ruby-lex.rb
+++ /dev/null
@@ -1,971 +0,0 @@
-#
-# irb/ruby-lex.rb - ruby lexcal analizer
-# $Release Version: 0.7.3$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-#
-# --
-#
-#
-#
-
-require "e2mmap"
-require "irb/slex"
-require "irb/ruby-token"
-
-class RubyLex
- @RCS_ID='-$Id$-'
-
- extend Exception2MessageMapper
- def_exception(:AlreadyDefinedToken, "Already defined token(%s)")
- def_exception(:TkReading2TokenNoKey, "key nothing(key='%s')")
- def_exception(:TkSymbol2TokenNoKey, "key nothing(key='%s')")
- def_exception(:TkReading2TokenDuplicateError,
- "key duplicate(token_n='%s', key='%s')")
- def_exception(:SyntaxError, "%s")
-
- def_exception(:TerminateLineInput, "Terminate Line Input")
-
- include RubyToken
-
- class << self
- attr_accessor :debug_level
- def debug?
- @debug_level > 0
- end
- end
- @debug_level = 0
-
- def initialize
- lex_init
- set_input(STDIN)
-
- @seek = 0
- @exp_line_no = @line_no = 1
- @base_char_no = 0
- @char_no = 0
- @rests = []
- @readed = []
- @here_readed = []
-
- @indent = 0
-
- @skip_space = false
- @readed_auto_clean_up = false
- @exception_on_syntax_error = true
- end
-
- attr_accessor :skip_space
- attr_accessor :readed_auto_clean_up
- attr_accessor :exception_on_syntax_error
-
- attr_reader :seek
- attr_reader :char_no
- attr_reader :line_no
- attr_reader :indent
-
- # io functions
- def set_input(io, p = nil)
- @io = io
- if p.kind_of?(Proc)
- @input = p
- elsif iterator?
- @input = proc
- else
- @input = proc{@io.gets}
- end
- end
-
- def get_readed
- if idx = @readed.reverse.index("\n")
- @base_char_no = idx
- else
- @base_char_no += @readed.size
- end
-
- readed = @readed.join("")
- @readed = []
- readed
- end
-
- def getc
- while @rests.empty?
- return nil unless buf_input
- end
- c = @rests.shift
- if @here_header
- @here_readed.push c
- else
- @readed.push c
- end
- @seek += 1
- if c == "\n"
- @line_no += 1
- @char_no = 0
- else
- @char_no += 1
- end
- c
- end
-
- def gets
- l = ""
- while c = getc
- l.concat c
- break if c == "\n"
- end
- l
- end
-
- def eof?
- @io.eof?
- end
-
- def getc_of_rests
- if @rests.empty?
- nil
- else
- getc
- end
- end
-
- def ungetc(c = nil)
- if @here_readed.empty?
- c2 = @readed.pop
- else
- c2 = @here_readed.pop
- end
- c = c2 unless c
- @rests.unshift c #c =
- @seek -= 1
- if c == "\n"
- @line_no -= 1
- if idx = @readed.reverse.index("\n")
- @char_no = @readed.size - idx
- else
- @char_no = @base_char_no + @readed.size
- end
- else
- @char_no -= 1
- end
- end
-
- def peek_equal?(str)
- chrs = str.split(//)
- until @rests.size >= chrs.size
- return false unless buf_input
- end
- @rests[0, chrs.size] == chrs
- end
-
- def peek_match?(regexp)
- while @rests.empty?
- return false unless buf_input
- end
- regexp =~ @rests.join("")
- end
-
- def peek(i = 0)
- while @rests.size <= i
- return nil unless buf_input
- end
- @rests[i]
- end
-
- def buf_input
- prompt
- line = @input.call
- return nil unless line
- @rests.concat line.split(//)
- true
- end
- private :buf_input
-
- def set_prompt(p = proc)
- if p.kind_of?(Proc)
- @prompt = p
- else
- @prompt = proc{print p}
- end
- end
-
- def prompt
- if @prompt
- @prompt.call(@ltype, @indent, @continue, @line_no)
- end
- end
-
- def initialize_input
- @ltype = nil
- @quoted = nil
- @indent = 0
- @lex_state = EXPR_BEG
- @space_seen = false
- @here_header = false
-
- @continue = false
- prompt
-
- @line = ""
- @exp_line_no = @line_no
- end
-
- def each_top_level_statement
- initialize_input
- catch(:TERM_INPUT) do
- loop do
- begin
- @continue = false
- prompt
- unless l = lex
- throw :TERM_INPUT if @line == ''
- else
- #p l
- @line.concat l
- if @ltype or @continue or @indent > 0
- next
- end
- end
- if @line != "\n"
- yield @line, @exp_line_no
- end
- break unless l
- @line = ''
- @exp_line_no = @line_no
-
- @indent = 0
- prompt
- rescue TerminateLineInput
- initialize_input
- prompt
- get_readed
- end
- end
- end
- end
-
- def lex
- until (((tk = token).kind_of?(TkNL) || tk.kind_of?(TkEND_OF_SCRIPT)) &&
- !@continue or
- tk.nil?)
- #p tk
- #p self
- end
- line = get_readed
- # print self.inspect
- if line == "" and tk.kind_of?(TkEND_OF_SCRIPT) || tk.nil?
- nil
- else
- line
- end
- end
-
- def token
- # require "tracer"
- # Tracer.on
- @prev_seek = @seek
- @prev_line_no = @line_no
- @prev_char_no = @char_no
- begin
- begin
- tk = @OP.match(self)
- @space_seen = tk.kind_of?(TkSPACE)
- rescue SyntaxError
- abort if @exception_on_syntax_error
- tk = TkError.new(@seek, @line_no, @char_no)
- end
- end while @skip_space and tk.kind_of?(TkSPACE)
- if @readed_auto_clean_up
- get_readed
- end
- # Tracer.off
- tk
- end
-
- ENINDENT_CLAUSE = [
- "case", "class", "def", "do", "for", "if",
- "module", "unless", "until", "while", "begin" #, "when"
- ]
- DEINDENT_CLAUSE = ["end" #, "when"
- ]
-
- PERCENT_LTYPE = {
- "q" => "\'",
- "Q" => "\"",
- "x" => "\`",
- "r" => "\/",
- "w" => "]"
- }
-
- PERCENT_PAREN = {
- "{" => "}",
- "[" => "]",
- "<" => ">",
- "(" => ")"
- }
-
- Ltype2Token = {
- "\'" => TkSTRING,
- "\"" => TkSTRING,
- "\`" => TkXSTRING,
- "\/" => TkREGEXP,
- "]" => TkDSTRING
- }
- DLtype2Token = {
- "\"" => TkDSTRING,
- "\`" => TkDXSTRING,
- "\/" => TkDREGEXP,
- }
-
- def lex_init()
- @OP = SLex.new
- @OP.def_rules("\0", "\004", "\032") do
- Token(TkEND_OF_SCRIPT)
- end
-
- @OP.def_rules(" ", "\t", "\f", "\r", "\13") do
- @space_seen = true
- while getc =~ /[ \t\f\r\13]/; end
- ungetc
- Token(TkSPACE)
- end
-
- @OP.def_rule("#") do
- |op, io|
- identify_comment
- end
-
- @OP.def_rule("=begin", proc{@prev_char_no == 0 && peek(0) =~ /\s/}) do
- |op, io|
- @ltype = "="
- until getc == "\n"; end
- until peek_equal?("=end") && peek(4) =~ /\s/
- until getc == "\n"; end
- end
- gets
- @ltype = nil
- Token(TkRD_COMMENT)
- end
-
- @OP.def_rule("\n") do
- print "\\n\n" if RubyLex.debug?
- case @lex_state
- when EXPR_BEG, EXPR_FNAME, EXPR_DOT
- @continue = true
- else
- @continue = false
- @lex_state = EXPR_BEG
- end
- @here_header = false
- @here_readed = []
- Token(TkNL)
- end
-
- @OP.def_rules("*", "**",
- "!", "!=", "!~",
- "=", "==", "===",
- "=~", "<=>",
- "<", "<=",
- ">", ">=", ">>") do
- |op, io|
- @lex_state = EXPR_BEG
- Token(op)
- end
-
- @OP.def_rules("<<") do
- |op, io|
- if @lex_state != EXPR_END && @lex_state != EXPR_CLASS &&
- (@lex_state != EXPR_ARG || @space_seen)
- c = peek(0)
- if /\S/ =~ c && (/["'`]/ =~ c || /[\w_]/ =~ c || c == "-")
- tk = identify_here_document
- end
- else
- tk = Token(op)
- end
- tk
- end
-
- @OP.def_rules("'", '"') do
- |op, io|
- identify_string(op)
- end
-
- @OP.def_rules("`") do
- |op, io|
- if @lex_state == EXPR_FNAME
- Token(op)
- else
- identify_string(op)
- end
- end
-
- @OP.def_rules('?') do
- |op, io|
- if @lex_state == EXPR_END
- @lex_state = EXPR_BEG
- Token(TkQUESTION)
- else
- ch = getc
- if @lex_state == EXPR_ARG && ch !~ /\s/
- ungetc
- @lex_state = EXPR_BEG;
- Token(TkQUESTION)
- else
- if (ch == '\\')
- read_escape
- end
- @lex_state = EXPR_END
- Token(TkINTEGER)
- end
- end
- end
-
- @OP.def_rules("&", "&&", "|", "||") do
- |op, io|
- @lex_state = EXPR_BEG
- Token(op)
- end
-
- @OP.def_rules("+=", "-=", "*=", "**=",
- "&=", "|=", "^=", "<<=", ">>=", "||=", "&&=") do
- |op, io|
- @lex_state = EXPR_BEG
- op =~ /^(.*)=$/
- Token(TkOPASGN, $1)
- end
-
- @OP.def_rule("+@", proc{@lex_state == EXPR_FNAME}) do
- Token(TkUPLUS)
- end
-
- @OP.def_rule("-@", proc{@lex_state == EXPR_FNAME}) do
- Token(TkUMINUS)
- end
-
- @OP.def_rules("+", "-") do
- |op, io|
- catch(:RET) do
- if @lex_state == EXPR_ARG
- if @space_seen and peek(0) =~ /[0-9]/
- throw :RET, identify_number
- else
- @lex_state = EXPR_BEG
- end
- elsif @lex_state != EXPR_END and peek(0) =~ /[0-9]/
- throw :RET, identify_number
- else
- @lex_state = EXPR_BEG
- end
- Token(op)
- end
- end
-
- @OP.def_rule(".") do
- @lex_state = EXPR_BEG
- if peek(0) =~ /[0-9]/
- ungetc
- identify_number
- else
- # for "obj.if" etc.
- @lex_state = EXPR_DOT
- Token(TkDOT)
- end
- end
-
- @OP.def_rules("..", "...") do
- |op, io|
- @lex_state = EXPR_BEG
- Token(op)
- end
-
- lex_int2
- end
-
- def lex_int2
- @OP.def_rules("]", "}", ")") do
- |op, io|
- @lex_state = EXPR_END
- @indent -= 1
- Token(op)
- end
-
- @OP.def_rule(":") do
- if @lex_state == EXPR_END || peek(0) =~ /\s/
- @lex_state = EXPR_BEG
- Token(TkCOLON)
- else
- @lex_state = EXPR_FNAME;
- Token(TkSYMBEG)
- end
- end
-
- @OP.def_rule("::") do
-# p @lex_state.id2name, @space_seen
- if @lex_state == EXPR_BEG or @lex_state == EXPR_ARG && @space_seen
- @lex_state = EXPR_BEG
- Token(TkCOLON3)
- else
- @lex_state = EXPR_DOT
- Token(TkCOLON2)
- end
- end
-
- @OP.def_rule("/") do
- |op, io|
- if @lex_state == EXPR_BEG || @lex_state == EXPR_MID
- identify_string(op)
- elsif peek(0) == '='
- getc
- @lex_state = EXPR_BEG
- Token(TkOPASGN, :/) #/)
- elsif @lex_state == EXPR_ARG and @space_seen and peek(0) !~ /\s/
- identify_string(op)
- else
- @lex_state = EXPR_BEG
- Token("/") #/)
- end
- end
-
- @OP.def_rules("^") do
- @lex_state = EXPR_BEG
- Token("^")
- end
-
- # @OP.def_rules("^=") do
- # @lex_state = EXPR_BEG
- # Token(OP_ASGN, :^)
- # end
-
- @OP.def_rules(",", ";") do
- |op, io|
- @lex_state = EXPR_BEG
- Token(op)
- end
-
- @OP.def_rule("~") do
- @lex_state = EXPR_BEG
- Token("~")
- end
-
- @OP.def_rule("~@", proc{@lex_state = EXPR_FNAME}) do
- @lex_state = EXPR_BEG
- Token("~")
- end
-
- @OP.def_rule("(") do
- @indent += 1
- if @lex_state == EXPR_BEG || @lex_state == EXPR_MID
- @lex_state = EXPR_BEG
- Token(TkfLPAREN)
- else
- @lex_state = EXPR_BEG
- Token(TkLPAREN)
- end
- end
-
- @OP.def_rule("[]", proc{@lex_state == EXPR_FNAME}) do
- Token("[]")
- end
-
- @OP.def_rule("[]=", proc{@lex_state == EXPR_FNAME}) do
- Token("[]=")
- end
-
- @OP.def_rule("[") do
- @indent += 1
- if @lex_state == EXPR_FNAME
- Token(TkfLBRACK)
- else
- if @lex_state == EXPR_BEG || @lex_state == EXPR_MID
- t = Token(TkLBRACK)
- elsif @lex_state == EXPR_ARG && @space_seen
- t = Token(TkLBRACK)
- else
- t = Token(TkfLBRACK)
- end
- @lex_state = EXPR_BEG
- t
- end
- end
-
- @OP.def_rule("{") do
- @indent += 1
- if @lex_state != EXPR_END && @lex_state != EXPR_ARG
- t = Token(TkLBRACE)
- else
- t = Token(TkfLBRACE)
- end
- @lex_state = EXPR_BEG
- t
- end
-
- @OP.def_rule('\\') do
- if getc == "\n"
- @space_seen = true
- @continue = true
- Token(TkSPACE)
- else
- ungetc
- Token("\\")
- end
- end
-
- @OP.def_rule('%') do
- |op, io|
- if @lex_state == EXPR_BEG || @lex_state == EXPR_MID
- identify_quotation
- elsif peek(0) == '='
- getc
- Token(TkOPASGN, :%)
- elsif @lex_state == EXPR_ARG and @space_seen and peek(0) !~ /\s/
- identify_quotation
- else
- @lex_state = EXPR_BEG
- Token("%") #))
- end
- end
-
- @OP.def_rule('$') do
- identify_gvar
- end
-
- @OP.def_rule('@') do
- if peek(0) =~ /[\w_]/
- ungetc
- identify_identifier
- else
- Token("@")
- end
- end
-
- # @OP.def_rule("def", proc{|op, io| /\s/ =~ io.peek(0)}) do
- # |op, io|
- # @indent += 1
- # @lex_state = EXPR_FNAME
- # # @lex_state = EXPR_END
- # # until @rests[0] == "\n" or @rests[0] == ";"
- # # rests.shift
- # # end
- # end
-
- @OP.def_rule("") do
- |op, io|
- printf "MATCH: start %s: %s\n", op, io.inspect if RubyLex.debug?
- if peek(0) =~ /[0-9]/
- t = identify_number
- elsif peek(0) =~ /[\w_]/
- t = identify_identifier
- end
- printf "MATCH: end %s: %s\n", op, io.inspect if RubyLex.debug?
- t
- end
-
- p @OP if RubyLex.debug?
- end
-
- def identify_gvar
- @lex_state = EXPR_END
-
- case ch = getc
- when /[~_*$?!@\/\\;,=:<>".]/ #"
- Token(TkGVAR, "$" + ch)
- when "-"
- Token(TkGVAR, "$-" + getc)
- when "&", "`", "'", "+"
- Token(TkBACK_REF, "$"+ch)
- when /[1-9]/
- while getc =~ /[0-9]/; end
- ungetc
- Token(TkNTH_REF)
- when /\w/
- ungetc
- ungetc
- identify_identifier
- else
- ungetc
- Token("$")
- end
- end
-
- def identify_identifier
- token = ""
- token.concat getc if peek(0) =~ /[$@]/
- while (ch = getc) =~ /\w|_/
- print ":", ch, ":" if RubyLex.debug?
- token.concat ch
- end
- ungetc
-
- if ch == "!" or ch == "?"
- token.concat getc
- end
- # almost fix token
-
- case token
- when /^\$/
- return Token(TkGVAR, token)
- when /^\@/
- @lex_state = EXPR_END
- return Token(TkIVAR, token)
- end
-
- if @lex_state != EXPR_DOT
- print token, "\n" if RubyLex.debug?
-
- token_c, *trans = TkReading2Token[token]
- if token_c
- # reserved word?
-
- if (@lex_state != EXPR_BEG &&
- @lex_state != EXPR_FNAME &&
- trans[1])
- # modifiers
- token_c = TkSymbol2Token[trans[1]]
- @lex_state = trans[0]
- else
- if @lex_state != EXPR_FNAME
- if ENINDENT_CLAUSE.include?(token)
- @indent += 1
- elsif DEINDENT_CLAUSE.include?(token)
- @indent -= 1
- end
- @lex_state = trans[0]
- else
- @lex_state = EXPR_END
- end
- end
- return Token(token_c, token)
- end
- end
-
- if @lex_state == EXPR_FNAME
- @lex_state = EXPR_END
- if peek(0) == '='
- token.concat getc
- end
- elsif @lex_state == EXPR_BEG || @lex_state == EXPR_DOT
- @lex_state = EXPR_ARG
- else
- @lex_state = EXPR_END
- end
-
- if token[0, 1] =~ /[A-Z]/
- return Token(TkCONSTANT, token)
- elsif token[token.size - 1, 1] =~ /[!?]/
- return Token(TkFID, token)
- else
- return Token(TkIDENTIFIER, token)
- end
- end
-
- def identify_here_document
- ch = getc
-# if lt = PERCENT_LTYPE[ch]
- if ch == "-"
- ch = getc
- indent = true
- end
- if /['"`]/ =~ ch
- lt = ch
- quoted = ""
- while (c = getc) && c != lt
- quoted.concat c
- end
- else
- lt = '"'
- quoted = ch.dup
- while (c = getc) && c =~ /\w/
- quoted.concat c
- end
- ungetc
- end
-
- ltback, @ltype = @ltype, lt
- reserve = []
- while ch = getc
- reserve.push ch
- if ch == "\\"
- reserve.push ch = getc
- elsif ch == "\n"
- break
- end
- end
-
- @here_header = false
- while (l = gets.chomp) && (indent ? l.strip : l) != quoted
- end
-
- @here_header = true
- @here_readed.concat reserve
- while ch = reserve.pop
- ungetc ch
- end
-
- @ltype = ltback
- @lex_state = EXPR_END
- Token(Ltype2Token[lt])
- end
-
- def identify_quotation
- ch = getc
- if lt = PERCENT_LTYPE[ch]
- ch = getc
- elsif ch =~ /\W/
- lt = "\""
- else
- RubyLex.fail SyntaxError, "unknown type of %string"
- end
-# if ch !~ /\W/
-# ungetc
-# next
-# end
- #@ltype = lt
- @quoted = ch unless @quoted = PERCENT_PAREN[ch]
- identify_string(lt, @quoted)
- end
-
- def identify_number
- @lex_state = EXPR_END
-
- if ch = getc
- if peek(0) == "x"
- ch = getc
- match = /[0-9a-f_]/
- else
- match = /[0-7_]/
- end
- while ch = getc
- if ch !~ match
- ungetc
- break
- end
- end
- return Token(TkINTEGER)
- end
-
- type = TkINTEGER
- allow_point = true
- allow_e = true
- while ch = getc
- case ch
- when /[0-9_]/
- when allow_point && "."
- type = TkFLOAT
- if peek(0) !~ /[0-9]/
- ungetc
- break
- end
- allow_point = false
- when allow_e && "e", allow_e && "E"
- type = TkFLOAT
- if peek(0) =~ /[+-]/
- getc
- end
- allow_e = false
- allow_point = false
- else
- ungetc
- break
- end
- end
- Token(type)
- end
-
- def identify_string(ltype, quoted = ltype)
- @ltype = ltype
- @quoted = quoted
- subtype = nil
- begin
- while ch = getc
- if @quoted == ch
- break
- elsif @ltype != "'" && @ltype != "]" and ch == "#"
- subtype = true
- elsif ch == '\\' #'
- read_escape
- end
- end
- if @ltype == "/"
- if peek(0) =~ /i|o|n|e|s/
- getc
- end
- end
- if subtype
- Token(DLtype2Token[ltype])
- else
- Token(Ltype2Token[ltype])
- end
- ensure
- @ltype = nil
- @quoted = nil
- @lex_state = EXPR_END
- end
- end
-
- def identify_comment
- @ltype = "#"
-
- while ch = getc
- if ch == "\\" #"
- read_escape
- end
- if ch == "\n"
- @ltype = nil
- ungetc
- break
- end
- end
- return Token(TkCOMMENT)
- end
-
- def read_escape
- case ch = getc
- when "\n", "\r", "\f"
- when "\\", "n", "t", "r", "f", "v", "a", "e", "b" #"
- when /[0-7]/
- ungetc ch
- 3.times do
- case ch = getc
- when /[0-7]/
- when nil
- break
- else
- ungetc
- break
- end
- end
-
- when "x"
- 2.times do
- case ch = getc
- when /[0-9a-fA-F]/
- when nil
- break
- else
- ungetc
- break
- end
- end
-
- when "M"
- if (ch = getc) != '-'
- ungetc
- else
- if (ch = getc) == "\\" #"
- read_escape
- end
- end
-
- when "C", "c", "^"
- if ch == "C" and (ch = getc) != "-"
- ungetc
- elsif (ch = getc) == "\\" #"
- read_escape
- end
- else
- # other characters
- end
- end
-end
diff --git a/lib/irb/ruby-token.rb b/lib/irb/ruby-token.rb
deleted file mode 100644
index 373c8defea..0000000000
--- a/lib/irb/ruby-token.rb
+++ /dev/null
@@ -1,271 +0,0 @@
-#
-# irb/ruby-token.rb - ruby tokens
-# $Release Version: 0.7.3$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-#
-# --
-#
-#
-#
-module RubyToken
- EXPR_BEG = :EXPR_BEG
- EXPR_MID = :EXPR_MID
- EXPR_END = :EXPR_END
- EXPR_ARG = :EXPR_ARG
- EXPR_FNAME = :EXPR_FNAME
- EXPR_DOT = :EXPR_DOT
- EXPR_CLASS = :EXPR_CLASS
-
- # for ruby 1.4X
- if !defined?(Symbol)
- Symbol = Integer
- end
-
- class Token
- def initialize(seek, line_no, char_no)
- @seek = seek
- @line_no = line_no
- @char_no = char_no
- end
- attr :seek
- attr :line_no
- attr :char_no
- end
-
- class TkNode < Token
- def initialize(seek, line_no, char_no)
- super
- end
- attr :node
- end
-
- class TkId < Token
- def initialize(seek, line_no, char_no, name)
- super(seek, line_no, char_no)
- @name = name
- end
- attr :name
- end
-
- class TkVal < Token
- def initialize(seek, line_no, char_no, value = nil)
- super(seek, line_no, char_no)
- @value = value
- end
- attr :value
- end
-
- class TkOp < Token
- attr :name, true
- end
-
- class TkOPASGN < TkOp
- def initialize(seek, line_no, char_no, op)
- super(seek, line_no, char_no)
- op = TkReading2Token[op] unless op.kind_of?(Symbol)
- @op = op
- end
- attr :op
- end
-
- class TkUnknownChar < Token
- def initialize(seek, line_no, char_no, id)
- super(seek, line_no, char_no)
- @name = name
- end
- attr :name
- end
-
- class TkError < Token
- end
-
- def Token(token, value = nil)
- case token
- when String
- if (tk = TkReading2Token[token]).nil?
- IRB.fail TkReading2TokenNoKey, token
- end
- tk = Token(tk[0], value)
- if tk.kind_of?(TkOp)
- tk.name = token
- end
- return tk
- when Symbol
- if (tk = TkSymbol2Token[token]).nil?
- IRB.fail TkSymbol2TokenNoKey, token
- end
- return Token(tk[0], value)
- else
- if (token.ancestors & [TkId, TkVal, TkOPASGN, TkUnknownChar]).empty?
- token.new(@prev_seek, @prev_line_no, @prev_char_no)
- else
- token.new(@prev_seek, @prev_line_no, @prev_char_no, value)
- end
- end
- end
-
- TokenDefinitions = [
- [:TkCLASS, TkId, "class", EXPR_CLASS],
- [:TkMODULE, TkId, "module", EXPR_BEG],
- [:TkDEF, TkId, "def", EXPR_FNAME],
- [:TkUNDEF, TkId, "undef", EXPR_FNAME],
- [:TkBEGIN, TkId, "begin", EXPR_BEG],
- [:TkRESCUE, TkId, "rescue", EXPR_MID],
- [:TkENSURE, TkId, "ensure", EXPR_BEG],
- [:TkEND, TkId, "end", EXPR_END],
- [:TkIF, TkId, "if", EXPR_BEG, :TkIF_MOD],
- [:TkUNLESS, TkId, "unless", EXPR_BEG, :TkUNLESS_MOD],
- [:TkTHEN, TkId, "then", EXPR_BEG],
- [:TkELSIF, TkId, "elsif", EXPR_BEG],
- [:TkELSE, TkId, "else", EXPR_BEG],
- [:TkCASE, TkId, "case", EXPR_BEG],
- [:TkWHEN, TkId, "when", EXPR_BEG],
- [:TkWHILE, TkId, "while", EXPR_BEG, :TkWHILE_MOD],
- [:TkUNTIL, TkId, "until", EXPR_BEG, :TkUNTIL_MOD],
- [:TkFOR, TkId, "for", EXPR_BEG],
- [:TkBREAK, TkId, "break", EXPR_END],
- [:TkNEXT, TkId, "next", EXPR_END],
- [:TkREDO, TkId, "redo", EXPR_END],
- [:TkRETRY, TkId, "retry", EXPR_END],
- [:TkIN, TkId, "in", EXPR_BEG],
- [:TkDO, TkId, "do", EXPR_BEG],
- [:TkRETURN, TkId, "return", EXPR_MID],
- [:TkYIELD, TkId, "yield", EXPR_END],
- [:TkSUPER, TkId, "super", EXPR_END],
- [:TkSELF, TkId, "self", EXPR_END],
- [:TkNIL, TkId, "nil", EXPR_END],
- [:TkTRUE, TkId, "true", EXPR_END],
- [:TkFALSE, TkId, "false", EXPR_END],
- [:TkAND, TkId, "and", EXPR_BEG],
- [:TkOR, TkId, "or", EXPR_BEG],
- [:TkNOT, TkId, "not", EXPR_BEG],
- [:TkIF_MOD, TkId],
- [:TkUNLESS_MOD, TkId],
- [:TkWHILE_MOD, TkId],
- [:TkUNTIL_MOD, TkId],
- [:TkALIAS, TkId, "alias", EXPR_FNAME],
- [:TkDEFINED, TkId, "defined?", EXPR_END],
- [:TklBEGIN, TkId, "BEGIN", EXPR_END],
- [:TklEND, TkId, "END", EXPR_END],
- [:Tk__LINE__, TkId, "__LINE__", EXPR_END],
- [:Tk__FILE__, TkId, "__FILE__", EXPR_END],
-
- [:TkIDENTIFIER, TkId],
- [:TkFID, TkId],
- [:TkGVAR, TkId],
- [:TkIVAR, TkId],
- [:TkCONSTANT, TkId],
-
- [:TkINTEGER, TkVal],
- [:TkFLOAT, TkVal],
- [:TkSTRING, TkVal],
- [:TkXSTRING, TkVal],
- [:TkREGEXP, TkVal],
-
- [:TkDSTRING, TkNode],
- [:TkDXSTRING, TkNode],
- [:TkDREGEXP, TkNode],
- [:TkNTH_REF, TkNode],
- [:TkBACK_REF, TkNode],
-
- [:TkUPLUS, TkOp, "+@"],
- [:TkUMINUS, TkOp, "-@"],
- [:TkPOW, TkOp, "**"],
- [:TkCMP, TkOp, "<=>"],
- [:TkEQ, TkOp, "=="],
- [:TkEQQ, TkOp, "==="],
- [:TkNEQ, TkOp, "!="],
- [:TkGEQ, TkOp, ">="],
- [:TkLEQ, TkOp, "<="],
- [:TkANDOP, TkOp, "&&"],
- [:TkOROP, TkOp, "||"],
- [:TkMATCH, TkOp, "=~"],
- [:TkNMATCH, TkOp, "!~"],
- [:TkDOT2, TkOp, ".."],
- [:TkDOT3, TkOp, "..."],
- [:TkAREF, TkOp, "[]"],
- [:TkASET, TkOp, "[]="],
- [:TkLSHFT, TkOp, "<<"],
- [:TkRSHFT, TkOp, ">>"],
- [:TkCOLON2, TkOp],
- [:TkCOLON3, TkOp],
-# [:OPASGN, TkOp], # +=, -= etc. #
- [:TkASSOC, TkOp, "=>"],
- [:TkQUESTION, TkOp, "?"], #?
- [:TkCOLON, TkOp, ":"], #:
-
- [:TkfLPAREN], # func( #
- [:TkfLBRACK], # func[ #
- [:TkfLBRACE], # func{ #
- [:TkSTAR], # *arg
- [:TkAMPER], # &arg #
- [:TkSYMBEG], # :SYMBOL
-
- [:TkGT, TkOp, ">"],
- [:TkLT, TkOp, "<"],
- [:TkPLUS, TkOp, "+"],
- [:TkMINUS, TkOp, "-"],
- [:TkMULT, TkOp, "*"],
- [:TkDIV, TkOp, "/"],
- [:TkMOD, TkOp, "%"],
- [:TkBITOR, TkOp, "|"],
- [:TkBITXOR, TkOp, "^"],
- [:TkBITAND, TkOp, "&"],
- [:TkBITNOT, TkOp, "~"],
- [:TkNOTOP, TkOp, "!"],
-
- [:TkBACKQUOTE, TkOp, "`"],
-
- [:TkASSIGN, Token, "="],
- [:TkDOT, Token, "."],
- [:TkLPAREN, Token, "("], #(exp)
- [:TkLBRACK, Token, "["], #[arry]
- [:TkLBRACE, Token, "{"], #{hash}
- [:TkRPAREN, Token, ")"],
- [:TkRBRACK, Token, "]"],
- [:TkRBRACE, Token, "}"],
- [:TkCOMMA, Token, ","],
- [:TkSEMICOLON, Token, ";"],
-
- [:TkCOMMENT],
- [:TkRD_COMMENT],
- [:TkSPACE],
- [:TkNL],
- [:TkEND_OF_SCRIPT],
-
- [:TkBACKSLASH, TkUnknownChar, "\\"],
- [:TkAT, TkUnknownChar, "@"],
- [:TkDOLLAR, TkUnknownChar, "$"],
- ]
-
- # {reading => token_class}
- # {reading => [token_class, *opt]}
- TkReading2Token = {}
- TkSymbol2Token = {}
-
- def RubyToken.def_token(token_n, super_token = Token, reading = nil, *opts)
- token_n = token_n.id2name if token_n.kind_of?(Symbol)
- if RubyToken.const_defined?(token_n)
- IRB.fail AlreadyDefinedToken, token_n
- end
- token_c = eval("class #{token_n} < #{super_token}; end; #{token_n}")
-
- if reading
- if TkReading2Token[reading]
- IRB.fail TkReading2TokenDuplicateError, token_n, reading
- end
- if opts.empty?
- TkReading2Token[reading] = [token_c]
- else
- TkReading2Token[reading] = [token_c].concat(opts)
- end
- end
- TkSymbol2Token[token_n.intern] = token_c
- end
-
- for defs in TokenDefinitions
- def_token(*defs)
- end
-end
diff --git a/lib/irb/slex.rb b/lib/irb/slex.rb
deleted file mode 100644
index 26008906e5..0000000000
--- a/lib/irb/slex.rb
+++ /dev/null
@@ -1,279 +0,0 @@
-#
-# irb/slex.rb - symple lex analizer
-# $Release Version: 0.7.3$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(keiju@ishituska.com)
-#
-# --
-#
-#
-#
-
-require "e2mmap"
-
-class SLex
- @RCS_ID='-$Id$-'
-
- extend Exception2MessageMapper
- def_exception :ErrNodeNothing, "node nothing"
- def_exception :ErrNodeAlreadyExists, "node already exists"
-
- class << self
- attr_accessor :debug_level
- def debug?
- debug_level > 0
- end
- end
- @debug_level = 0
-
- def initialize
- @head = Node.new("")
- end
-
- def def_rule(token, preproc = nil, postproc = nil)
- # print node.inspect, "\n" if SLex.debug?
- postproc = proc if iterator?
- node = create(token, preproc, postproc)
- end
-
- def def_rules(*tokens)
- if iterator?
- p = proc
- end
- for token in tokens
- def_rule(token, nil, p)
- end
- end
-
- def preporc(token, proc)
- node = search(token)
- node.preproc=proc
- end
-
- def postproc(token)
- node = search(token, proc)
- node.postproc=proc
- end
-
- 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)
- case token
- when Array
- when String
- token = token.split(//)
- match(token.split(//))
- else
- return @head.match_io(token)
- end
- ret = @head.match(token)
- printf "match end: %s:%s", ret, token.inspect if SLex.debug?
- ret
- end
-
- def inspect
- format("<SLex: @head = %s>", @head.inspect)
- end
-
- #----------------------------------------------------------------------
- #
- # class Node -
- #
- #----------------------------------------------------------------------
- class Node
- # if postproc is nil, this node is an abstract node.
- # if postproc is non-nil, this node is a real node.
- def initialize(preproc = nil, postproc = nil)
- @Tree = {}
- @preproc = preproc
- @postproc = postproc
- end
-
- attr_accessor :preproc
- attr_accessor :postproc
-
- def search(chrs, opt = nil)
- return self if chrs.empty?
- ch = chrs.shift
- if node = @Tree[ch]
- node.search(chrs, opt)
- else
- if opt
- chrs.unshift ch
- self.create_subnode(chrs)
- else
- SLex.fail ErrNodeNothing
- end
- end
- end
-
- def create_subnode(chrs, preproc = nil, postproc = nil)
- if chrs.empty?
- if @postproc
- p node
- SLex.fail ErrNodeAlreadyExists
- else
- print "Warn: change abstruct node to real node\n" if SLex.debug?
- @preproc = preproc
- @postproc = postproc
- end
- return self
- end
-
- ch = chrs.shift
- if node = @Tree[ch]
- if chrs.empty?
- if node.postproc
- p node
- p self
- p ch
- p chrs
- SLex.fail ErrNodeAlreadyExists
- else
- print "Warn: change abstruct node to real node\n" if SLex.debug?
- node.preproc = preproc
- node.postproc = postproc
- end
- else
- node.create_subnode(chrs, preproc, postproc)
- end
- else
- if chrs.empty?
- node = Node.new(preproc, postproc)
- else
- node = Node.new
- node.create_subnode(chrs, preproc, postproc)
- end
- @Tree[ch] = node
- end
- node
- end
-
- #
- # chrs: String
- # character array
- # io must have getc()/ungetc(); and ungetc() must be
- # able to be called arbitrary number of times.
- #
- def match(chrs, op = "")
- print "match>: ", chrs, "op:", op, "\n" if SLex.debug?
- if chrs.empty?
- if @preproc.nil? || @preproc.call(op, chrs)
- printf "op1: %s\n", op if SLex.debug?
- @postproc.call(op, chrs)
- else
- nil
- end
- else
- ch = chrs.shift
- if node = @Tree[ch]
- if ret = node.match(chrs, op+ch)
- return ret
- else
- chrs.unshift ch
- if @postproc and @preproc.nil? || @preproc.call(op, chrs)
- printf "op2: %s\n", op.inspect if SLex.debug?
- ret = @postproc.call(op, chrs)
- return ret
- else
- return nil
- end
- end
- else
- chrs.unshift ch
- if @postproc and @preproc.nil? || @preproc.call(op, chrs)
- printf "op3: %s\n", op if SLex.debug?
- @postproc.call(op, chrs)
- return ""
- else
- return nil
- end
- end
- end
- end
-
- def match_io(io, op = "")
- if op == ""
- ch = io.getc
- if ch == nil
- return nil
- end
- else
- ch = io.getc_of_rests
- end
- if ch.nil?
- if @preproc.nil? || @preproc.call(op, io)
- printf "op1: %s\n", op if SLex.debug?
- @postproc.call(op, io)
- else
- nil
- end
- else
- if node = @Tree[ch]
- if ret = node.match_io(io, op+ch)
- ret
- else
- io.ungetc ch
- if @postproc and @preproc.nil? || @preproc.call(op, io)
- printf "op2: %s\n", op.inspect if SLex.debug?
- @postproc.call(op, io)
- else
- nil
- end
- end
- else
- io.ungetc ch
- if @postproc and @preproc.nil? || @preproc.call(op, io)
- printf "op3: %s\n", op if SLex.debug?
- @postproc.call(op, io)
- else
- nil
- end
- end
- end
- end
- end
-end
-
-if $0 == __FILE__
- # Tracer.on
- case $1
- when "1"
- tr = SLex.new
- print "0: ", tr.inspect, "\n"
- tr.def_rule("=") {print "=\n"}
- print "1: ", tr.inspect, "\n"
- tr.def_rule("==") {print "==\n"}
- print "2: ", tr.inspect, "\n"
-
- print "case 1:\n"
- print tr.match("="), "\n"
- print "case 2:\n"
- print tr.match("=="), "\n"
- print "case 3:\n"
- print tr.match("=>"), "\n"
-
- when "2"
- tr = SLex.new
- print "0: ", tr.inspect, "\n"
- tr.def_rule("=") {print "=\n"}
- print "1: ", tr.inspect, "\n"
- tr.def_rule("==", proc{false}) {print "==\n"}
- print "2: ", tr.inspect, "\n"
-
- print "case 1:\n"
- print tr.match("="), "\n"
- print "case 2:\n"
- print tr.match("=="), "\n"
- print "case 3:\n"
- print tr.match("=>"), "\n"
- end
- exit
-end
diff --git a/lib/irb/version.rb b/lib/irb/version.rb
deleted file mode 100644
index 367cc21046..0000000000
--- a/lib/irb/version.rb
+++ /dev/null
@@ -1,16 +0,0 @@
-#
-# irb/version.rb - irb version definition file
-# $Release Version: 0.7.4$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-#
-# --
-#
-#
-#
-
-module IRB
- @RELEASE_VERSION = "0.7.4"
- @LAST_UPDATE_DATE = "01/05/08"
-end
diff --git a/lib/irb/workspace.rb b/lib/irb/workspace.rb
deleted file mode 100644
index 68559a1173..0000000000
--- a/lib/irb/workspace.rb
+++ /dev/null
@@ -1,106 +0,0 @@
-#
-# irb/workspace-binding.rb -
-# $Release Version: 0.7.3$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-#
-# --
-#
-#
-#
-module IRB
- class WorkSpace
- # create new workspace.
- # set self to main if specified, otherwise inherit main
- # from TOPLEVEL_BINDING.
- def initialize(*main)
- if IRB.conf[:SINGLE_IRB]
- @binding = TOPLEVEL_BINDING
- else
- case IRB.conf[:CONTEXT_MODE]
- when 0 # binding in proc on TOPLEVEL_BINDING
- @binding = eval("proc{binding}.call",
- TOPLEVEL_BINDING,
- __FILE__,
- __LINE__)
- when 1 # binding in loaded file
- require "tempfile"
- f = Tempfile.open("irb-binding")
- f.print <<EOF
- $binding = binding
-EOF
- f.close
- load f.path
- @binding = $binding
-
- when 2 # binding in loaded file(thread use)
- unless defined? BINDING_QUEUE
- require "thread"
-
- IRB.const_set("BINDING_QUEUE", SizedQueue.new(1))
- Thread.abort_on_exception = true
- Thread.start do
- eval "require \"irb/ws-for-case-2\"", TOPLEVEL_BINDING, __FILE__, __LINE__
- end
- Thread.pass
- end
- @binding = BINDING_QUEUE.pop
-
- when 3 # binging in function on TOPLEVEL_BINDING(default)
- @binding = eval("def irb_binding; binding; end; irb_binding",
- TOPLEVEL_BINDING,
- __FILE__,
- __LINE__ - 3)
- end
- end
- if main.empty?
- @main = eval "self", @binding
- else
- @main = main[0]
- IRB.conf[:__MAIN__] = @main
- case @main
- when Module
- @binding = eval("IRB.conf[:__MAIN__].module_eval('binding', __FILE__, __LINE__)", @binding, __FILE__, __LINE__)
- else
- begin
- @binding = eval("IRB.conf[:__MAIN__].instance_eval('binding', __FILE__, __LINE__)", @binding, __FILE__, __LINE__)
- rescue TypeError
- IRB.fail CanNotChangeBinding, @main.inspect
- end
- end
- end
- eval("_=nil", @binding)
- end
-
- attr_reader :binding
- attr_reader :main
-
- def evaluate(statements, file = __FILE__, line = __LINE__)
- eval statements, @binding, file, line
- end
-
- # error message manupilator
- def filter_backtrace(bt)
- case IRB.conf[:CONTEXT_MODE]
- when 0
- return nil if bt =~ /\(irb_local_binding\)/
- when 1
- if(bt =~ %r!/tmp/irb-binding! or
- bt =~ %r!irb/.*\.rb! or
- bt =~ /irb\.rb/)
- return nil
- end
- when 2
- return nil if bt =~ /irb\/.*\.rb/
- when 3
- return nil if bt =~ /irb\/.*\.rb/
- bt.sub!(/:\s*in `irb_binding'/){""}
- end
- bt
- end
-
- def IRB.delete_caller
- end
- end
-end
diff --git a/lib/irb/ws-for-case-2.rb b/lib/irb/ws-for-case-2.rb
deleted file mode 100644
index 8cfa87ae3d..0000000000
--- a/lib/irb/ws-for-case-2.rb
+++ /dev/null
@@ -1,15 +0,0 @@
-#
-# irb/ws-for-case-2.rb -
-# $Release Version: 0.7.3$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-#
-# --
-#
-#
-#
-
-while true
- IRB::BINDING_QUEUE.push b = binding
-end
diff --git a/lib/irb/xmp.rb b/lib/irb/xmp.rb
deleted file mode 100644
index e0bcee4bdb..0000000000
--- a/lib/irb/xmp.rb
+++ /dev/null
@@ -1,84 +0,0 @@
-#
-# xmp.rb - irb version of gotoken xmp
-# $Release Version: 0.7.1$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(Nippon Rational Inc.)
-#
-# --
-#
-#
-#
-
-require "irb/irb"
-require "irb/frame"
-
-class XMP
- @RCS_ID='-$Id$-'
-
- def initialize(bind = nil)
- #IRB.parse_opts
- #IRB.load_modules
-
- bind = IRB::Frame.top(1) unless bind
- main = eval("self", bind)
- @io = StringInputMethod.new
- @irb = IRB::Irb.new(main, bind, @io)
- @irb.context.prompt_mode = :XMP
- @irb.context.ignore_sigint = false
-
-# IRB.conf[:IRB_RC].call(@irb.context) if IRB.conf[:IRB_RC]
- IRB.conf[:MAIN_CONTEXT] = @irb.context
- end
-
- def puts(exps)
- @io.puts exps
-
- if @irb.context.ignore_sigint
- begin
- trap_proc_b = trap("SIGINT"){@irb.signal_handle}
- catch(:IRB_EXIT) do
- @irb.eval_input
- end
- ensure
- trap("SIGINT", trap_proc_b)
- end
- else
- catch(:IRB_EXIT) do
- @irb.eval_input
- end
- end
- end
-
- class StringInputMethod < IRB::InputMethod
- def initialize
- super
- @exps = []
- end
-
- def eof?
- @exps.empty?
- end
-
- def gets
- while l = @exps.shift
- next if /^\s+$/ =~ l
- l.concat "\n"
- print @prompt, l
- break
- end
- l
- end
-
- def puts(exps)
- @exps.concat exps.split(/\n/)
- end
- end
-end
-
-def xmp(exps, bind = nil)
- bind = IRB::Frame.top(1) unless bind
- xmp = XMP.new(bind)
- xmp.puts exps
- xmp
-end
diff --git a/lib/jcode.rb b/lib/jcode.rb
deleted file mode 100644
index 0d796a2b01..0000000000
--- a/lib/jcode.rb
+++ /dev/null
@@ -1,216 +0,0 @@
-# jcode.rb - ruby code to handle japanese (EUC/SJIS) string
-
-if $VERBOSE && $KCODE == "NONE"
- STDERR.puts "Warning: $KCODE is NONE."
-end
-
-$vsave, $VERBOSE = $VERBOSE, false
-class String
- printf STDERR, "feel free for some warnings:\n" if $VERBOSE
-
- def _regex_quote(str)
- str.gsub(/(\\[][\-\\])|\\(.)|([][\\])/) do
- $1 || $2 || '\\' + $3
- end
- end
- private :_regex_quote
-
- PATTERN_SJIS = '[\x81-\x9f\xe0-\xef][\x40-\x7e\x80-\xfc]'
- PATTERN_EUC = '[\xa1-\xfe][\xa1-\xfe]'
- PATTERN_UTF8 = '[\xc0-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf][\x80-\xbf]'
-
- RE_SJIS = Regexp.new(PATTERN_SJIS, 'n')
- RE_EUC = Regexp.new(PATTERN_EUC, 'n')
- RE_UTF8 = Regexp.new(PATTERN_UTF8, 'n')
-
- SUCC = {}
- SUCC['s'] = Hash.new(1)
- for i in 0 .. 0x3f
- SUCC['s'][i.chr] = 0x40 - i
- end
- SUCC['s']["\x7e"] = 0x80 - 0x7e
- SUCC['s']["\xfd"] = 0x100 - 0xfd
- SUCC['s']["\xfe"] = 0x100 - 0xfe
- SUCC['s']["\xff"] = 0x100 - 0xff
- SUCC['e'] = Hash.new(1)
- for i in 0 .. 0xa0
- SUCC['e'][i.chr] = 0xa1 - i
- end
- SUCC['e']["\xfe"] = 2
- SUCC['u'] = Hash.new(1)
- for i in 0 .. 0x7f
- SUCC['u'][i.chr] = 0x80 - i
- end
- SUCC['u']["\xbf"] = 0x100 - 0xbf
-
- def mbchar?
- case $KCODE[0]
- when ?s, ?S
- self =~ RE_SJIS
- when ?e, ?E
- self =~ RE_EUC
- when ?u, ?U
- self =~ RE_UTF8
- else
- nil
- end
- end
-
- def end_regexp
- case $KCODE[0]
- when ?s, ?S
- /#{PATTERN_SJIS}$/o
- when ?e, ?E
- /#{PATTERN_EUC}$/o
- when ?u, ?U
- /#{PATTERN_UTF8}$/o
- else
- /.$/o
- end
- end
-
- alias original_succ! succ!
- private :original_succ!
-
- alias original_succ succ
- private :original_succ
-
- def succ!
- reg = end_regexp
- if self =~ reg
- succ_table = SUCC[$KCODE[0,1].downcase]
- begin
- self[-1] += succ_table[self[-1]]
- self[-2] += 1 if self[-1] == 0
- end while self !~ reg
- self
- else
- original_succ!
- end
- end
-
- def succ
- (str = self.dup).succ! or str
- end
-
- private
-
- def _expand_ch str
- a = []
- str.scan(/(?:\\(.)|([^\\]))-(?:\\(.)|([^\\]))|(?:\\(.)|(.))/m) do
- from = $1 || $2
- to = $3 || $4
- one = $5 || $6
- if one
- a.push one
- elsif from.length != to.length
- next
- elsif from.length == 1
- from[0].upto(to[0]) { |c| a.push c.chr }
- else
- from.upto(to) { |c| a.push c }
- end
- end
- a
- end
-
- def expand_ch_hash from, to
- h = {}
- afrom = _expand_ch(from)
- ato = _expand_ch(to)
- afrom.each_with_index do |x,i| h[x] = ato[i] || ato[-1] end
- h
- end
-
- HashCache = {}
- TrPatternCache = {}
- DeletePatternCache = {}
- SqueezePatternCache = {}
-
- public
-
- def tr!(from, to)
- return self.delete!(from) if to.length == 0
-
- pattern = TrPatternCache[from] ||= /[#{_regex_quote(from)}]/
- if from[0] == ?^
- last = /.$/.match(to)[0]
- self.gsub!(pattern, last)
- else
- h = HashCache[from + "1-0" + to] ||= expand_ch_hash(from, to)
- self.gsub!(pattern) do |c| h[c] end
- end
- end
-
- def tr(from, to)
- (str = self.dup).tr!(from, to) or str
- end
-
- def delete!(del)
- self.gsub!(DeletePatternCache[del] ||= /[#{_regex_quote(del)}]+/, '')
- end
-
- def delete(del)
- (str = self.dup).delete!(del) or str
- end
-
- def squeeze!(del=nil)
- pattern =
- if del
- SqueezePatternCache[del] ||= /([#{_regex_quote(del)}])\1+/
- else
- /(.|\n)\1+/
- end
- self.gsub!(pattern, '\1')
- end
-
- def squeeze(del=nil)
- (str = self.dup).squeeze!(del) or str
- end
-
- def tr_s!(from, to)
- return self.delete!(from) if to.length == 0
-
- pattern = SqueezePatternCache[from] ||= /([#{_regex_quote(from)}])\1+/
- if from[0] == ?^
- last = /.$/.match(to)[0]
- self.gsub!(pattern, last)
- else
- h = HashCache[from + "1-0" + to] ||= expand_ch_hash(from, to)
- self.gsub!(pattern) do h[$1] end
- end
- end
-
- def tr_s(from, to)
- (str = self.dup).tr_s!(from,to) or str
- end
-
- def chop!
- self.gsub!(/(?:.|\r?\n)\z/, '')
- end
-
- def chop
- (str = self.dup).chop! or str
- end
-
- def jlength
- self.gsub(/[^\Wa-zA-Z_\d]/, ' ').length
- end
- alias jsize jlength
-
- def jcount(str)
- self.delete("^#{str}").jlength
- end
-
- def each_char
- if block_given?
- scan(/./m) do |x|
- yield x
- end
- else
- scan(/./m)
- end
- end
-
-end
-$VERBOSE = $vsave
diff --git a/lib/mailread.rb b/lib/mailread.rb
deleted file mode 100644
index 7573d03ed4..0000000000
--- a/lib/mailread.rb
+++ /dev/null
@@ -1,48 +0,0 @@
-class Mail
-
- def initialize(f)
- unless defined? f.gets
- f = open(f, "r")
- opened = true
- end
-
- @header = {}
- @body = []
- begin
- while line = f.gets()
- line.chop!
- next if /^From /=~line # skip From-line
- break if /^$/=~line # end of header
-
- if /^(\S+?):\s*(.*)/=~line
- (attr = $1).capitalize!
- @header[attr] = $2
- elsif attr
- line.sub!(/^\s*/, '')
- @header[attr] += "\n" + line
- end
- end
-
- return unless line
-
- while line = f.gets()
- break if /^From /=~line
- @body.push(line)
- end
- ensure
- f.close if opened
- end
- end
-
- def header
- return @header
- end
-
- def body
- return @body
- end
-
- def [](field)
- @header[field.capitalize]
- end
-end
diff --git a/lib/mathn.rb b/lib/mathn.rb
deleted file mode 100644
index f3f7a95a48..0000000000
--- a/lib/mathn.rb
+++ /dev/null
@@ -1,313 +0,0 @@
-#
-# mathn.rb -
-# $Release Version: 0.5 $
-# $Revision: 1.1.1.1.4.1 $
-# $Date: 1998/01/16 12:36:05 $
-# by Keiju ISHITSUKA(SHL Japan Inc.)
-#
-# --
-#
-#
-#
-
-require "rational.rb"
-require "complex.rb"
-require "matrix.rb"
-
-class Integer
-
- def gcd2(int)
- a = self.abs
- b = int.abs
- a, b = b, a if a < b
-
- pd_a = a.prime_division
- pd_b = b.prime_division
-
- gcd = 1
- for pair in pd_a
- as = pd_b.assoc(pair[0])
- if as
- gcd *= as[0] ** [as[1], pair[1]].min
- end
- end
- return gcd
- end
-
- def Integer.from_prime_division(pd)
- value = 1
- for prime, index in pd
- value *= prime**index
- end
- value
- end
-
- def prime_division
- ps = Prime.new
- value = self
- pv = []
- for prime in ps
- count = 0
- while (value1, mod = value.divmod(prime)
- mod) == 0
- value = value1
- count += 1
- end
- if count != 0
- pv.push [prime, count]
- end
- break if prime * prime >= value
- end
- if value > 1
- pv.push [value, 1]
- end
- return pv
- end
-end
-
-class Prime
- include Enumerable
-
- def initialize
- @seed = 1
- @primes = []
- @counts = []
- end
-
- def succ
- i = -1
- size = @primes.size
- while i < size
- if i == -1
- @seed += 1
- i += 1
- else
- while @seed > @counts[i]
- @counts[i] += @primes[i]
- end
- if @seed != @counts[i]
- i += 1
- else
- i = -1
- end
- end
- end
- @primes.push @seed
- @counts.push @seed + @seed
- return @seed
- end
- alias next succ
-
- def each
- loop do
- yield succ
- end
- end
-end
-
-class Fixnum
- alias divmod! divmod
- alias / rdiv
- def divmod(other)
- a = self.div(other)
- b = self % other
- return a,b
- end
-end
-
-class Bignum
- alias divmod! divmod
- alias / rdiv
-end
-
-class Rational
- Unify = true
-
- def inspect
- format "%s/%s", @numerator.inspect, @denominator.inspect
- end
-
- alias power! **
-
- def ** (other)
- if other.kind_of?(Rational)
- if self < 0
- return Complex(self, 0) ** other
- elsif other == 0
- return Rational(1,1)
- elsif self == 0
- return Rational(0,1)
- elsif self == 1
- return Rational(1,1)
- end
-
- npd = @numerator.prime_division
- dpd = @denominator.prime_division
- if other < 0
- other = -other
- npd, dpd = dpd, npd
- end
-
- for elm in npd
- elm[1] = elm[1] * other
- if !elm[1].kind_of?(Integer) and elm[1].denominator != 1
- return Float(self) ** other
- end
- elm[1] = elm[1].to_i
- end
-
- for elm in dpd
- elm[1] = elm[1] * other
- if !elm[1].kind_of?(Integer) and elm[1].denominator != 1
- return Float(self) ** other
- end
- elm[1] = elm[1].to_i
- end
-
- num = Integer.from_prime_division(npd)
- den = Integer.from_prime_division(dpd)
-
- Rational(num,den)
-
- elsif other.kind_of?(Integer)
- if other > 0
- num = @numerator ** other
- den = @denominator ** other
- elsif other < 0
- num = @denominator ** -other
- den = @numerator ** -other
- elsif other == 0
- num = 1
- den = 1
- end
- Rational.new!(num, den)
- elsif other.kind_of?(Float)
- Float(self) ** other
- else
- x , y = other.coerce(self)
- x ** y
- end
- end
-
- def power2(other)
- if other.kind_of?(Rational)
- if self < 0
- return Complex(self, 0) ** other
- elsif other == 0
- return Rational(1,1)
- elsif self == 0
- return Rational(0,1)
- elsif self == 1
- return Rational(1,1)
- end
-
- dem = nil
- x = self.denominator.to_f.to_i
- neard = self.denominator.to_f ** (1.0/other.denominator.to_f)
- loop do
- if (neard**other.denominator == self.denominator)
- dem = neaed
- break
- end
- end
- nearn = self.numerator.to_f ** (1.0/other.denominator.to_f)
- Rational(num,den)
-
- elsif other.kind_of?(Integer)
- if other > 0
- num = @numerator ** other
- den = @denominator ** other
- elsif other < 0
- num = @denominator ** -other
- den = @numerator ** -other
- elsif other == 0
- num = 1
- den = 1
- end
- Rational.new!(num, den)
- elsif other.kind_of?(Float)
- Float(self) ** other
- else
- x , y = other.coerce(self)
- x ** y
- end
- end
-end
-
-module Math
- def sqrt(a)
- if a.kind_of?(Complex)
- abs = sqrt(a.real*a.real + a.image*a.image)
-# if not abs.kind_of?(Rational)
-# return a**Rational(1,2)
-# end
- x = sqrt((a.real + abs)/Rational(2))
- y = sqrt((-a.real + abs)/Rational(2))
-# if !(x.kind_of?(Rational) and y.kind_of?(Rational))
-# return a**Rational(1,2)
-# end
- if a.image >= 0
- Complex(x, y)
- else
- Complex(x, -y)
- end
- elsif a >= 0
- rsqrt(a)
- else
- Complex(0,rsqrt(-a))
- end
- end
-
- def rsqrt(a)
- if a.kind_of?(Float)
- sqrt!(a)
- elsif a.kind_of?(Rational)
- rsqrt(a.numerator)/rsqrt(a.denominator)
- else
- src = a
- max = 2 ** 32
- byte_a = [src & 0xffffffff]
- # ruby's bug
- while (src >= max) and (src >>= 32)
- byte_a.unshift src & 0xffffffff
- end
-
- answer = 0
- main = 0
- side = 0
- for elm in byte_a
- main = (main << 32) + elm
- side <<= 16
- if answer != 0
- if main * 4 < side * side
- applo = main.div(side)
- else
- applo = ((sqrt!(side * side + 4 * main) - side)/2.0).to_i + 1
- end
- else
- applo = sqrt!(main).to_i + 1
- end
-
- while (x = (side + applo) * applo) > main
- applo -= 1
- end
- main -= x
- answer = (answer << 16) + applo
- side += applo * 2
- end
- if main == 0
- answer
- else
- sqrt!(a)
- end
- end
- end
-
- module_function :sqrt
- module_function :rsqrt
-end
-
-class Complex
- Unify = true
-end
-
diff --git a/lib/matrix.rb b/lib/matrix.rb
deleted file mode 100644
index 8e092b0d0b..0000000000
--- a/lib/matrix.rb
+++ /dev/null
@@ -1,1023 +0,0 @@
-#!/usr/local/bin/ruby
-#
-# matrix.rb -
-# $Release Version: 1.0$
-# $Revision: 1.11 $
-# $Date: 1999/10/06 11:01:53 $
-# Original Version from Smalltalk-80 version
-# on July 23, 1985 at 8:37:17 am
-# by Keiju ISHITSUKA
-#
-# --
-#
-# Matrix[[1,2,3],
-# :
-# [3,4,5]]
-# Matrix[row0,
-# row1,
-# :
-# rown]
-#
-#
-# module ExceptionForMatrix::
-# Exceptions:
-# ErrDimensionMismatch
-# number of column/row do not match
-# ErrNotRegular
-# not a regular matrix
-# ErrOperationNotDefined
-# specified operator is not defined (yet)
-#
-# class Matrix
-# include ExceptionForMatrix
-#
-# Methods:
-# class methods:
-# Matrix.[](*rows)
-# creates a matrix where `rows' indicates rows.
-# `rows' is an array of arrays,
-# e.g, Matrix[[11, 12], [21, 22]]
-# Matrix.rows(rows, copy = true)
-# creates a matrix where `rows' indicates rows.
-# if optional argument `copy' is false, use the array as
-# internal structure of the metrix without copying.
-# Matrix.columns(columns)
-# creates a new matrix using `columns` as set of colums vectors.
-# Matrix.diagonal(*values)
-# creates a matrix where `columns' indicates columns.
-# Matrix.scalar(n, value)
-# creates a diagonal matrix such that the diagal compornents is
-# given by `values'.
-# Matrix.scalar(n, value)
-# creates an n-by-n scalar matrix such that the diagal compornent is
-# given by `value'.
-# Matrix.identity(n)
-# Matrix.unit(n)
-# Matrix.I(n)
-# creates an n-by-n unit matrix.
-# Matrix.zero(n)
-# creates an n-by-n zero matrix.
-# Matrix.row_vector(row)
-# creates a 1-by-n matrix such the row vector is `row'.
-# `row' is specifed as a Vector or an Array.
-# Matrix.column_vector(column)
-# creates a 1-by-n matrix such that column vector is `column'.
-# `column' is specifed as a Vector or an Array.
-# accessing:
-# [](i, j)
-# returns (i,j) compornent
-# row_size
-# returns the number of rows
-# column_size
-# returns the number of columns
-# row(i)
-# returns the i-th row vector.
-# when the block is supplied for the method, the block is iterated
-# over all row vectors.
-# column(j)
-# returns the jth column vector.
-# when the block is supplied for the method, the block is iterated
-# over all column vectors.
-# collect
-# map
-# creates a matrix which is the result of iteration of given
-# block over all compornents.
-# minor(*param)
-# returns sub matrix. parameter is specified as the following:
-# 1. from_row, row_size, from_col, size_col
-# 2. from_row..to_row, from_col..to_col
-# TESTING:
-# regular?
-# Is regular?
-# singular?
-# Is singular? i.e. Is non-regular?
-# square?
-# Is square?
-# ARITHMETIC:
-# *(m)
-# times
-# +(m)
-# plus
-# -(m)
-# minus
-# /(m)
-# self * m.inv
-# inverse
-# inv
-# inverse
-# **
-# power
-# Matrix functions:
-# determinant
-# det
-# returns the determinant
-# rank
-# returns the rank
-# trace
-# tr
-# returns the trace
-# transpose
-# t
-# returns the transposed
-# CONVERTING:
-# coerce(other)
-# row_vectors
-# array of row vectors
-# column_vectors
-# array of column vectors
-# to_a
-# converts each element to Array
-# to_f
-# converts each element to Float
-# to_i
-# converts each element to Integer
-# to_r
-# converts each element to Rational
-# PRINTING:
-# to_s
-# returns string representation
-# inspect
-#
-# class Vector
-# include ExceptionForMatrix
-#
-# INSTANCE CREATION:
-# Vector.[](*array)
-# Vector.elements(array, copy = true)
-# ACCSESSING:
-# [](i)
-# size
-# ENUMRATIONS:
-# each2(v)
-# collect2(v)
-# ARITHMETIC:
-# *(x) "is matrix or number"
-# +(v)
-# -(v)
-# VECTOR FUNCTIONS:
-# inner_product(v)
-# collect
-# map
-# map2(v)
-# r
-# CONVERTING:
-# covector
-# to_a
-# to_f
-# to_i
-# to_r
-# coerce(other)
-# PRINTING:
-# to_s
-# inspect
-
-require "e2mmap.rb"
-
-module ExceptionForMatrix
- extend Exception2MessageMapper
- def_e2message(TypeError, "wrong argument type %s (expected %s)")
- def_e2message(ArgumentError, "Wrong # of arguments(%d for %d)")
-
- def_exception("ErrDimensionMismatch", "\#{self.name} dimension mismatch")
- def_exception("ErrNotRegular", "Not Regular Matrix")
- def_exception("ErrOperationNotDefined", "This operation(%s) can\\'t defined")
-end
-
-class Matrix
- @RCS_ID='-$Id: matrix.rb,v 1.11 1999/10/06 11:01:53 keiju Exp keiju $-'
-
-# extend Exception2MessageMapper
- include ExceptionForMatrix
-
- # instance creations
- private_class_method :new
-
- def Matrix.[](*rows)
- new(:init_rows, rows, false)
- end
-
- def Matrix.rows(rows, copy = true)
- new(:init_rows, rows, copy)
- end
-
- def Matrix.columns(columns)
- rows = (0 .. columns[0].size - 1).collect {
- |i|
- (0 .. columns.size - 1).collect {
- |j|
- columns[j][i]
- }
- }
- Matrix.rows(rows, false)
- end
-
- def Matrix.diagonal(*values)
- size = values.size
- rows = (0 .. size - 1).collect {
- |j|
- row = Array.new(size).fill(0, 0, size)
- row[j] = values[j]
- row
- }
- rows(rows, false)
- end
-
- def Matrix.scalar(n, value)
- Matrix.diagonal(*Array.new(n).fill(value, 0, n))
- end
-
- def Matrix.identity(n)
- Matrix.scalar(n, 1)
- end
- class << Matrix
- alias unit identity
- alias I identity
- end
-
- def Matrix.zero(n)
- Matrix.scalar(n, 0)
- end
-
- def Matrix.row_vector(row)
- case row
- when Vector
- Matrix.rows([row.to_a], false)
- when Array
- Matrix.rows([row.dup], false)
- else
- Matrix.row([[row]], false)
- end
- end
-
- def Matrix.column_vector(column)
- case column
- when Vector
- Matrix.columns([column.to_a])
- when Array
- Matrix.columns([column])
- else
- Matrix.columns([[column]])
- end
- end
-
- # initializing
- def initialize(init_method, *argv)
- self.send(init_method, *argv)
- end
-
- def init_rows(rows, copy)
- if copy
- @rows = rows.collect{|row| row.dup}
- else
- @rows = rows
- end
- self
- end
- private :init_rows
-
- #accessing
- def [](i, j)
- @rows[i][j]
- end
-
- def row_size
- @rows.size
- end
-
- def column_size
- @rows[0].size
- end
-
- def row(i)
- if block_given?
- for e in @rows[i]
- yield e
-
- end
- else
- Vector.elements(@rows[i])
- end
- end
-
- def column(j)
- if block_given?
- 0.upto(row_size - 1) do
- |i|
- yield @rows[i][j]
- end
- else
- col = (0 .. row_size - 1).collect {
- |i|
- @rows[i][j]
- }
- Vector.elements(col, false)
- end
- end
-
- def collect
- rows = @rows.collect{|row| row.collect{|e| yield e}}
- Matrix.rows(rows, false)
- end
- alias map collect
-
- #
- # param: (from_row, row_size, from_col, size_col)
- # (from_row..to_row, from_col..to_col)
- #
- def minor(*param)
- case param.size
- when 2
- from_row = param[0].first
- size_row = param[0].size
- from_col = param[1].first
- size_col = param[1].size
- when 4
- from_row = param[0]
- size_row = param[1]
- from_col = param[2]
- size_col = param[3]
- else
- Matrix.Raise ArgumentError, param.inspect
- end
-
- rows = @rows[from_row, size_row].collect{
- |row|
- row[from_col, size_col]
- }
- Matrix.rows(rows, false)
- end
-
- # TESTING
- def regular?
- square? and rank == column_size
- end
-
- def singular?
- not regular?
- end
-
- def square?
- column_size == row_size
- end
-
- # COMPARING
- def ==(other)
- return false unless Matrix === other
-
- other.compare_by_row_vectors(@rows)
- end
- alias eql? ==
-
- def compare_by_row_vectors(rows)
- return false unless @rows.size == rows.size
-
- 0.upto(@rows.size - 1) do
- |i|
- return false unless @rows[i] == rows[i]
- end
- true
- end
-
- def clone
- Matrix.rows(@rows)
- end
-
- def hash
- value = 0
- for row in @rows
- for e in row
- value ^= e.hash
- end
- end
- return value
- end
-
- # ARITHMETIC
-
- def *(m) # m is matrix or vector or number
- case(m)
- when Numeric
- rows = @rows.collect {
- |row|
- row.collect {
- |e|
- e * m
- }
- }
- return Matrix.rows(rows, false)
- when Vector
- m = Matrix.column_vector(m)
- r = self * m
- return r.column(0)
- when Matrix
- Matrix.Raise ErrDimensionMismatch if column_size != m.row_size
-
- rows = (0 .. row_size - 1).collect {
- |i|
- (0 .. m.column_size - 1).collect {
- |j|
- vij = 0
- 0.upto(column_size - 1) do
- |k|
- vij += self[i, k] * m[k, j]
- end
- vij
- }
- }
- return Matrix.rows(rows, false)
- else
- x, y = m.coerce(self)
- return x * y
- end
- end
-
- def +(m)
- case m
- when Numeric
- Matrix.Raise ErrOperationNotDefined, "+"
- when Vector
- m = Matrix.column_vector(m)
- when Matrix
- else
- x, y = m.coerce(self)
- return x + y
- end
-
- Matrix.Raise ErrDimensionMismatch unless row_size == m.row_size and column_size == m.column_size
-
- rows = (0 .. row_size - 1).collect {
- |i|
- (0 .. column_size - 1).collect {
- |j|
- self[i, j] + m[i, j]
- }
- }
- Matrix.rows(rows, false)
- end
-
- def -(m)
- case m
- when Numeric
- Matrix.Raise ErrOperationNotDefined, "-"
- when Vector
- m = Matrix.column_vector(m)
- when Matrix
- else
- x, y = m.coerce(self)
- return x - y
- end
-
- Matrix.Raise ErrDimensionMismatch unless row_size == m.row_size and column_size == m.column_size
-
- rows = (0 .. row_size - 1).collect {
- |i|
- (0 .. column_size - 1).collect {
- |j|
- self[i, j] - m[i, j]
- }
- }
- Matrix.rows(rows, false)
- end
-
- def /(other)
- case other
- when Numeric
- rows = @rows.collect {
- |row|
- row.collect {
- |e|
- e / other
- }
- }
- return Matrix.rows(rows, false)
- when Matrix
- return self * other.inverse
- else
- x, y = other.coerce(self)
- rerurn x / y
- end
- end
-
- def inverse
- Matrix.Raise ErrDimensionMismatch unless square?
- Matrix.I(row_size).inverse_from(self)
- end
- alias inv inverse
-
- def inverse_from(src)
- size = row_size - 1
- a = src.to_a
-
- for k in 0..size
- if (akk = a[k][k]) == 0
- i = k
- begin
- Matrix.Raise ErrNotRegular if (i += 1) > size
- end while a[i][k] == 0
- a[i], a[k] = a[k], a[i]
- @rows[i], @rows[k] = @rows[k], @rows[i]
- akk = a[k][k]
- end
-
- for i in 0 .. size
- next if i == k
- q = a[i][k] / akk
- a[i][k] = 0
-
- (k + 1).upto(size) do
- |j|
- a[i][j] -= a[k][j] * q
- end
- 0.upto(size) do
- |j|
- @rows[i][j] -= @rows[k][j] * q
- end
- end
-
- (k + 1).upto(size) do
- |j|
- a[k][j] /= akk
- end
- 0.upto(size) do
- |j|
- @rows[k][j] /= akk
- end
- end
- self
- end
- #alias reciprocal inverse
-
- def ** (other)
- if other.kind_of?(Integer)
- x = self
- if other <= 0
- x = self.inverse
- return Matrix.identity(self.column_size) if other == 0
- other = -other
- end
- z = x
- n = other - 1
- while n != 0
- while (div, mod = n.divmod(2)
- mod == 0)
- x = x * x
- n = div
- end
- z *= x
- n -= 1
- end
- z
- elsif other.kind_of?(Float) || defined?(Rational) && other.kind_of?(Rational)
- Matrix.Raise ErrOperationNotDefined, "**"
- else
- Matrix.Raise ErrOperationNotDefined, "**"
- end
- end
-
- # Matrix functions
-
- def determinant
- return 0 unless square?
-
- size = row_size - 1
- a = to_a
-
- det = 1
- k = 0
- begin
- if (akk = a[k][k]) == 0
- i = k
- begin
- return 0 if (i += 1) > size
- end while a[i][k] == 0
- a[i], a[k] = a[k], a[i]
- akk = a[k][k]
- det *= -1
- end
- (k + 1).upto(size) do
- |i|
- q = a[i][k] / akk
- (k + 1).upto(size) do
- |j|
- a[i][j] -= a[k][j] * q
- end
- end
- det *= akk
- end while (k += 1) <= size
- det
- end
- alias det determinant
-
- def rank
- if column_size > row_size
- a = transpose.to_a
- a_column_size = row_size
- a_row_size = column_size
- else
- a = to_a
- a_column_size = column_size
- a_row_size = row_size
- end
- rank = 0
- k = 0
- begin
- if (akk = a[k][k]) == 0
- i = k
- exists = true
- begin
- if (i += 1) > a_column_size - 1
- exists = false
- break
- end
- end while a[i][k] == 0
- if exists
- a[i], a[k] = a[k], a[i]
- akk = a[k][k]
- else
- i = k
- exists = true
- begin
- if (i += 1) > a_row_size - 1
- exists = false
- break
- end
- end while a[k][i] == 0
- if exists
- k.upto(a_column_size - 1) do
- |j|
- a[j][k], a[j][i] = a[j][i], a[j][k]
- end
- akk = a[k][k]
- else
- next
- end
- end
- end
- (k + 1).upto(a_row_size - 1) do
- |i|
- q = a[i][k] / akk
- (k + 1).upto(a_column_size - 1) do
- |j|
- a[i][j] -= a[k][j] * q
- end
- end
- rank += 1
- end while (k += 1) <= a_column_size - 1
- return rank
- end
-
- def trace
- tr = 0
- 0.upto(column_size - 1) do
- |i|
- tr += @rows[i][i]
- end
- tr
- end
- alias tr trace
-
- def transpose
- Matrix.columns(@rows)
- end
- alias t transpose
-
- # CONVERTING
-
- def coerce(other)
- case other
- when Numeric
- return Scalar.new(other), self
- else
- raise TypeError, "#{type} can't be coerced into #{other.type}"
- end
- end
-
- def row_vectors
- rows = (0 .. row_size - 1).collect {
- |i|
- row(i)
- }
- rows
- end
-
- def column_vectors
- columns = (0 .. column_size - 1).collect {
- |i|
- column(i)
- }
- columns
- end
-
- def to_a
- @rows.collect{|row| row.collect{|e| e}}
- end
-
- def to_f
- collect{|e| e.to_f}
- end
-
- def to_i
- collect{|e| e.to_i}
- end
-
- def to_r
- collect{|e| e.to_r}
- end
-
- # PRINTING
- def to_s
- "Matrix[" + @rows.collect{
- |row|
- "[" + row.collect{|e| e.to_s}.join(", ") + "]"
- }.join(", ")+"]"
- end
-
- def inspect
- "Matrix"+@rows.inspect
- end
-
- # Private CLASS
-
- class Scalar < Numeric
- include ExceptionForMatrix
-
- def initialize(value)
- @value = value
- end
-
- # ARITHMETIC
- def +(other)
- case other
- when Numeric
- Scalar.new(@value + other)
- when Vector, Matrix
- Scalar.Raise WrongArgType, other.type, "Numeric or Scalar"
- when Scalar
- Scalar.new(@value + other.value)
- else
- x, y = other.coerce(self)
- x + y
- end
- end
-
- def -(other)
- case other
- when Numeric
- Scalar.new(@value - other)
- when Vector, Matrix
- Scalar.Raise WrongArgType, other.type, "Numeric or Scalar"
- when Scalar
- Scalar.new(@value - other.value)
- else
- x, y = other.coerce(self)
- x - y
- end
- end
-
- def *(other)
- case other
- when Numeric
- Scalar.new(@value * other)
- when Vector, Matrix
- other.collect{|e| @value * e}
- else
- x, y = other.coerce(self)
- x * y
- end
- end
-
- def / (other)
- case other
- when Numeric
- Scalar.new(@value / other)
- when Vector
- Scalar.Raise WrongArgType, other.type, "Numeric or Scalar or Matrix"
- when Matrix
- self * _M.inverse
- else
- x, y = other.coerce(self)
- x / y
- end
- end
-
- def ** (other)
- case other
- when Numeric
- Scalar.new(@value ** other)
- when Vector
- Scalar.Raise WrongArgType, other.type, "Numeric or Scalar or Matrix"
- when Matrix
- other.powered_by(self)
- else
- x, y = other.coerce(self)
- x ** y
- end
- end
- end
-end
-
-#----------------------------------------------------------------------
-#
-# -
-#
-#----------------------------------------------------------------------
-class Vector
- include ExceptionForMatrix
-
- #INSTANCE CREATION
-
- private_class_method :new
- def Vector.[](*array)
- new(:init_elements, array, copy = false)
- end
-
- def Vector.elements(array, copy = true)
- new(:init_elements, array, copy)
- end
-
- def initialize(method, array, copy)
- self.send(method, array, copy)
- end
-
- def init_elements(array, copy)
- if copy
- @elements = array.dup
- else
- @elements = array
- end
- end
-
- # ACCSESSING
-
- def [](i)
- @elements[i]
- end
-
- def size
- @elements.size
- end
-
- # ENUMRATIONS
- def each2(v)
- Vector.Raise ErrDimensionMismatch if size != v.size
- 0.upto(size - 1) do
- |i|
- yield @elements[i], v[i]
- end
- end
-
- def collect2(v)
- Vector.Raise ErrDimensionMismatch if size != v.size
- (0 .. size - 1).collect do
- |i|
- yield @elements[i], v[i]
- end
- end
-
- # COMPARING
- def ==(other)
- return false unless Vector === other
-
- other.compare_by(@elements)
- end
- alias eqn? ==
-
- def compare_by(elements)
- @elements == elements
- end
-
- def clone
- Vector.elements(@elements)
- end
-
- def hash
- @elements.hash
- end
-
- # ARITHMETIC
-
- def *(x) #x is matrix or number
- case x
- when Numeric
- els = @elements.collect{|e| e * x}
- Vector.elements(els, false)
- when Matrix
- Matrix.column_vector(self) * x
- else
- s, x = x.coerce(self)
- s * x
- end
- end
-
- def +(v)
- case v
- when Vector
- Vector.Raise ErrDimensionMismatch if size != v.size
- els = collect2(v) {
- |v1, v2|
- v1 + v2
- }
- Vector.elements(els, false)
- when Matrix
- Matrix.column_vector(self) + v
- else
- s, x = v.coerce(self)
- s + x
- end
- end
-
- def -(v)
- case v
- when Vector
- Vector.Raise ErrDimensionMismatch if size != v.size
- els = collect2(v) {
- |v1, v2|
- v1 - v2
- }
- Vector.elements(els, false)
- when Matrix
- Matrix.column_vector(self) - v
- else
- s, x = v.coerce(self)
- s - x
- end
- end
-
- # VECTOR FUNCTIONS
-
- def inner_product(v)
- Vector.Raise ErrDimensionMismatch if size != v.size
-
- p = 0
- each2(v) {
- |v1, v2|
- p += v1 * v2
- }
- p
- end
-
- def collect
- els = @elements.collect {
- |v|
- yield v
- }
- Vector.elements(els, false)
- end
- alias map collect
-
- def map2(v)
- els = collect2(v) {
- |v1, v2|
- yield v1, v2
- }
- Vector.elements(els, false)
- end
-
- def r
- v = 0
- for e in @elements
- v += e*e
- end
- return Math.sqrt(v)
- end
-
- # CONVERTING
- def covector
- Matrix.row_vector(self)
- end
-
- def to_a
- @elements.dup
- end
-
- def to_f
- collect{|e| e.to_f}
- end
-
- def to_i
- collect{|e| e.to_i}
- end
-
- def to_r
- collect{|e| e.to_r}
- end
-
- def coerce(other)
- case other
- when Numeric
- return Scalar.new(other), self
- else
- raise TypeError, "#{type} can't be coerced into #{other.type}"
- end
- end
-
- # PRINTING
-
- def to_s
- "Vector[" + @elements.join(", ") + "]"
- end
-
- def inspect
- str = "Vector"+@elements.inspect
- end
-end
diff --git a/lib/mkmf.rb b/lib/mkmf.rb
deleted file mode 100644
index 8b8363af82..0000000000
--- a/lib/mkmf.rb
+++ /dev/null
@@ -1,612 +0,0 @@
-# module to create Makefile for extension modules
-# invoke like: ruby -r mkmf extconf.rb
-
-require 'rbconfig'
-require 'find'
-
-CONFIG = Config::MAKEFILE_CONFIG
-ORIG_LIBPATH = ENV['LIB']
-
-SRC_EXT = ["c", "cc", "m", "cxx", "cpp", "C"]
-
-$config_cache = CONFIG["compile_dir"]+"/ext/config.cache"
-
-$srcdir = CONFIG["srcdir"]
-$libdir = CONFIG["libdir"]
-$rubylibdir = CONFIG["rubylibdir"]
-$archdir = CONFIG["archdir"]
-$sitedir = CONFIG["sitedir"]
-$sitelibdir = CONFIG["sitelibdir"]
-$sitearchdir = CONFIG["sitearchdir"]
-
-if File.exist? Config::CONFIG["archdir"] + "/ruby.h"
- $hdrdir = $archdir
-elsif File.exist? $srcdir + "/ruby.h"
- $hdrdir = $srcdir
-else
- STDERR.print "can't find header files for ruby.\n"
- exit 1
-end
-$topdir = $hdrdir
-# $hdrdir.gsub!('/', '\\') if RUBY_PLATFORM =~ /mswin32/
-
-CFLAGS = CONFIG["CFLAGS"]
-if RUBY_PLATFORM == "m68k-human"
- CFLAGS.gsub!(/-c..-stack=[0-9]+ */, '')
-elsif RUBY_PLATFORM =~ /-nextstep|-rhapsody|-darwin/
- CFLAGS.gsub!( /-arch\s\w*/, '' )
-end
-
-$log = open('mkmf.log', 'w')
-
-if /mswin32/ =~ RUBY_PLATFORM
- OUTFLAG = '-Fe'
-else
- OUTFLAG = '-o '
-end
-LINK = "#{CONFIG['CC']} #{OUTFLAG}conftest -I#{$hdrdir} #{CFLAGS} -I#{CONFIG['includedir']} %s %s #{CONFIG['LDFLAGS']} %s conftest.c %s %s #{CONFIG['LIBS']}"
-CPP = "#{CONFIG['CPP']} -E %s -I#{$hdrdir} #{CFLAGS} -I#{CONFIG['includedir']} %s %s conftest.c"
-
-def rm_f(*files)
- targets = []
- for file in files
- targets.concat Dir[file]
- end
- if not targets.empty?
- File::chmod(0777, *targets)
- File::unlink(*targets)
- end
-end
-
-$orgerr = $stderr.dup
-$orgout = $stdout.dup
-def xsystem command
- Config.expand(command)
- if $DEBUG
- puts command
- return system(command)
- end
- $stderr.reopen($log)
- $stdout.reopen($log)
- puts command
- r = system(command)
- $stderr.reopen($orgerr)
- $stdout.reopen($orgout)
- return r
-end
-
-def try_link0(src, opt="")
- cfile = open("conftest.c", "w")
- cfile.print src
- cfile.close
- ldflags = $LDFLAGS
- if /mswin32/ =~ RUBY_PLATFORM and !$LIBPATH.empty?
- ENV['LIB'] = ($LIBPATH + [ORIG_LIBPATH]).compact.join(';')
- else
- $LDFLAGS = ldflags.dup
- $LIBPATH.each {|d| $LDFLAGS << " -L" + d}
- end
- begin
- xsystem(format(LINK, $CFLAGS, $CPPFLAGS, $LDFLAGS, opt, $LOCAL_LIBS))
- ensure
- $LDFLAGS = ldflags
- ENV['LIB'] = ORIG_LIBPATH if /mswin32/ =~ RUBY_PLATFORM
- end
-end
-
-def try_link(src, opt="")
- begin
- try_link0(src, opt)
- ensure
- rm_f "conftest*"
- end
-end
-
-def try_cpp(src, opt="")
- cfile = open("conftest.c", "w")
- cfile.print src
- cfile.close
- begin
- xsystem(format(CPP, $CPPFLAGS, $CFLAGS, opt))
- ensure
- rm_f "conftest*"
- end
-end
-
-def egrep_cpp(pat, src, opt="")
- cfile = open("conftest.c", "w")
- cfile.print src
- cfile.close
- begin
- xsystem(format(CPP+"|egrep #{pat}", $CPPFLAGS, $CFLAGS, opt))
- ensure
- rm_f "conftest*"
- end
-end
-
-def try_run(src, opt="")
- begin
- if try_link0(src, opt)
- if xsystem("./conftest")
- true
- else
- false
- end
- else
- nil
- end
- ensure
- rm_f "conftest*"
- end
-end
-
-def install_rb(mfile, dest, srcdir = nil)
- libdir = "lib"
- libdir = srcdir + "/" + libdir if srcdir
- path = []
- dir = []
- if File.directory? libdir
- Find.find(libdir) do |f|
- next unless /\.rb$/ =~ f
- f = f[libdir.length+1..-1]
- path.push f
- dir |= [File.dirname(f)]
- end
- end
- for f in dir
- if f == "."
- mfile.printf "\t@$(RUBY) -r ftools -e 'File::makedirs(*ARGV)' %s\n", dest
- else
- mfile.printf "\t@$(RUBY) -r ftools -e 'File::makedirs(*ARGV)' %s/%s\n", dest, f
- end
- end
- for f in path
- d = '/' + File::dirname(f)
- d = '' if d == '/.'
- mfile.printf "\t@$(RUBY) -r ftools -e 'File::install(ARGV[0], ARGV[1], 0644, true)' %s/%s %s%s\n", libdir, f, dest, d
- end
-end
-
-def append_library(libs, lib)
- if /mswin32/ =~ RUBY_PLATFORM
- lib + ".lib " + libs
- else
- "-l" + lib + " " + libs
- end
-end
-
-def have_library(lib, func="main")
- printf "checking for %s() in -l%s... ", func, lib
- STDOUT.flush
-
- if func && func != ""
- libs = append_library($libs, lib)
- if /mswin32|mingw/ =~ RUBY_PLATFORM
- if lib == 'm'
- print "yes\n"
- return true
- end
- r = try_link(<<"SRC", libs)
-#include <windows.h>
-#include <winsock.h>
-int main() { return 0; }
-int t() { #{func}(); return 0; }
-SRC
- unless r
- r = try_link(<<"SRC", libs)
-#include <windows.h>
-#include <winsock.h>
-int main() { return 0; }
-int t() { void ((*p)()); p = (void ((*)()))#{func}; return 0; }
-SRC
- end
- else
- r = try_link(<<"SRC", libs)
-int main() { return 0; }
-int t() { #{func}(); return 0; }
-SRC
- end
- unless r
- print "no\n"
- return false
- end
- else
- libs = append_library($libs, lib)
- end
-
- $libs = libs
- print "yes\n"
- return true
-end
-
-def find_library(lib, func, *paths)
- printf "checking for %s() in -l%s... ", func, lib
- STDOUT.flush
-
- libpath = $LIBPATH
- libs = append_library($libs, lib)
- until try_link(<<"SRC", libs)
-int main() { return 0; }
-int t() { #{func}(); return 0; }
-SRC
- if paths.size == 0
- $LIBPATH = libpath
- print "no\n"
- return false
- end
- $LIBPATH = libpath | [paths.shift]
- end
- $libs = libs
- print "yes\n"
- return true
-end
-
-def have_func(func, header=nil)
- printf "checking for %s()... ", func
- STDOUT.flush
-
- libs = $libs
- src =
- if /mswin32|mingw/ =~ RUBY_PLATFORM
- r = <<"SRC"
-#include <windows.h>
-#include <winsock.h>
-SRC
- else
- ""
- end
- unless header.nil?
- src << <<"SRC"
-#include <#{header}>
-SRC
- end
- r = try_link(src + <<"SRC", libs)
-int main() { return 0; }
-int t() { #{func}(); return 0; }
-SRC
- unless r
- r = try_link(src + <<"SRC", libs)
-int main() { return 0; }
-int t() { void ((*p)()); p = (void ((*)()))#{func}; return 0; }
-SRC
- end
- unless r
- print "no\n"
- return false
- end
- $defs.push(format("-DHAVE_%s", func.upcase))
- print "yes\n"
- return true
-end
-
-def have_header(header)
- printf "checking for %s... ", header
- STDOUT.flush
-
- unless try_cpp(<<"SRC")
-#include <#{header}>
-SRC
- print "no\n"
- return false
- end
- $defs.push(format("-DHAVE_%s", header.tr("a-z./\055", "A-Z___")))
- print "yes\n"
- return true
-end
-
-def arg_config(config, default=nil)
- unless defined? $configure_args
- $configure_args = {}
- for arg in CONFIG["configure_args"].split + ARGV
- next unless /^--/ =~ arg
- arg, val = arg.split('=', 2)
- $configure_args[arg] = val || true
- end
- end
- $configure_args.fetch(config, default)
-end
-
-def with_config(config, default=nil)
- unless /^--with-/ =~ config
- config = '--with-' + config
- end
- arg_config(config, default)
-end
-
-def enable_config(config, default=nil)
- if arg_config("--enable-"+config, default)
- true
- elsif arg_config("--disable-"+config, false)
- false
- else
- default
- end
-end
-
-def create_header()
- print "creating extconf.h\n"
- STDOUT.flush
- if $defs.length > 0
- hfile = open("extconf.h", "w")
- for line in $defs
- line =~ /^-D(.*)/
- hfile.printf "#define %s 1\n", $1
- end
- hfile.close
- end
-end
-
-def dir_config(target, idefault=nil, ldefault=nil)
- if dir = with_config(target + "-dir", (idefault unless ldefault))
- idefault = dir + "/include"
- ldefault = dir + "/lib"
- end
-
- idir = with_config(target + "-include", idefault)
- ldir = with_config(target + "-lib", ldefault)
-
- if idir
- idircflag = "-I" + idir
- $CPPFLAGS += " " + idircflag unless $CPPFLAGS.split.include?(idircflag)
- end
-
- if ldir
- $LIBPATH << ldir unless $LIBPATH.include?(ldir)
- end
-
- [idir, ldir]
-end
-
-def with_destdir(dir)
- /^\$[\(\{]/ =~ dir ? dir : "$(DESTDIR)"+dir
-end
-
-def create_makefile(target, srcdir = File.dirname($0))
- save_libs = $libs.dup
- save_libpath = $LIBPATH.dup
- print "creating Makefile\n"
- rm_f "conftest*"
- STDOUT.flush
- if target.include?('/')
- target_prefix, target = File.split(target)
- target_prefix[0,0] = '/'
- else
- target_prefix = ""
- end
- if CONFIG["DLEXT"] == $OBJEXT
- libs = $libs.split
- for lib in libs
- lib.sub!(/-l(.*)/, '"lib\1.a"')
- end
- $defs.push(format("-DEXTLIB='%s'", libs.join(",")))
- end
- $DLDFLAGS = CONFIG["DLDFLAGS"]
-
- $libs = CONFIG["LIBRUBYARG"] + " " + $libs
- $configure_args['--enable-shared'] or $LIBPATH |= [$topdir]
- $LIBPATH |= [CONFIG["libdir"]]
-
- defflag = ''
- if RUBY_PLATFORM =~ /cygwin|mingw/
- deffile = target + '.def'
- if not File.exist? deffile
- if File.exist? File.join srcdir, deffile
- deffile = File.join srcdir, deffile
- else
- open(deffile, 'wb') do |f|
- f.print "EXPORTS\n", "Init_", target, "\n"
- end
- end
- end
- defflag = "--def=" + deffile
- end
-
- if RUBY_PLATFORM =~ /mswin32/
- libpath = $LIBPATH.join(';')
- else
- $LIBPATH.each {|d| $DLDFLAGS << " -L" << d}
- if /netbsdelf/ =~ RUBY_PLATFORM
- $LIBPATH.each {|d| $DLDFLAGS << " -Wl,-R" + d}
- end
- end
- drive = File::PATH_SEPARATOR == ';' ? /\A\w:/ : /\A/
-
- unless $objs then
- $objs = []
- for f in Dir[File.join(srcdir || ".", "*.{#{SRC_EXT.join(%q{,})}}")]
- f = File.basename(f)
- f.sub!(/(#{SRC_EXT.join(%q{|})})$/, $OBJEXT)
- $objs.push f
- end
- else
- for i in $objs
- i.sub!(/\.o\z/, ".#{$OBJEXT}")
- end
- end
- $objs = $objs.join(" ")
-
- mfile = open("Makefile", "w")
- mfile.binmode if /mingw/ =~ RUBY_PLATFORM
- mfile.print <<EOMF
-SHELL = /bin/sh
-
-#### Start of system configuration section. ####
-
-srcdir = #{srcdir || $srcdir}
-topdir = #{$topdir}
-hdrdir = #{$hdrdir}
-VPATH = $(srcdir)
-
-CC = #{CONFIG["CC"]}
-
-CFLAGS = #{CONFIG["CCDLFLAGS"]} #{CFLAGS} #{$CFLAGS}
-CPPFLAGS = -I. -I$(hdrdir) -I$(srcdir) -I#{CONFIG["includedir"]} #{$defs.join(" ")} #{CONFIG["CPPFLAGS"]} #{$CPPFLAGS}
-CXXFLAGS = $(CFLAGS)
-DLDFLAGS = #{$DLDFLAGS} #{$LDFLAGS}
-LDSHARED = #{CONFIG["LDSHARED"]} #{defflag}
-LIBPATH = #{libpath}
-
-RUBY_INSTALL_NAME = #{CONFIG["RUBY_INSTALL_NAME"]}
-RUBY_SO_NAME = #{CONFIG["RUBY_SO_NAME"]}
-arch = #{CONFIG["arch"]}
-ruby_version = #{Config::CONFIG["ruby_version"]}
-#{
-if destdir = CONFIG["prefix"].scan(drive)[0] and !destdir.empty?
- "\nDESTDIR = " + destdir
-else
- ""
-end
-}
-prefix = #{with_destdir CONFIG["prefix"].sub(drive, '')}
-exec_prefix = #{with_destdir CONFIG["exec_prefix"].sub(drive, '')}
-libdir = #{with_destdir $libdir.sub(drive, '')}
-rubylibdir = #{with_destdir $rubylibdir.sub(drive, '')}
-archdir = #{with_destdir $archdir.sub(drive, '')}
-sitedir = #{with_destdir $sitedir.sub(drive, '')}
-sitelibdir = #{with_destdir $sitelibdir.sub(drive, '')}
-sitearchdir = #{with_destdir $sitearchdir.sub(drive, '')}
-target_prefix = #{target_prefix}
-
-#### End of system configuration section. ####
-
-LOCAL_LIBS = #{$LOCAL_LIBS} #{$local_flags}
-LIBS = #{$libs}
-OBJS = #{$objs}
-
-TARGET = #{target}
-DLLIB = $(TARGET).#{CONFIG["DLEXT"]}
-
-RUBY = #{CONFIG["ruby_install_name"]}
-RM = $(RUBY) -rftools -e "File::rm_f(*ARGV.map{|x|Dir[x]}.flatten.uniq)"
-
-EXEEXT = #{CONFIG["EXEEXT"]}
-
-all: $(DLLIB)
-
-clean:; @$(RM) *.#{$OBJEXT} *.so *.sl *.a $(DLLIB)
- @$(RM) $(TARGET).lib $(TARGET).exp $(TARGET).ilk *.pdb $(CLEANFILES)
-
-distclean: clean
- @$(RM) Makefile extconf.h conftest.* mkmf.log
- @$(RM) core ruby$(EXEEXT) *~ $(DISTCLEANFILES)
-
-realclean: distclean
-
-install: $(archdir)$(target_prefix)/$(DLLIB)
-
-site-install: $(sitearchdir)$(target_prefix)/$(DLLIB)
-
-$(archdir)$(target_prefix)/$(DLLIB): $(DLLIB)
- @$(RUBY) -r ftools -e 'File::makedirs(*ARGV)' $(rubylibdir) $(archdir)$(target_prefix)
- @$(RUBY) -r ftools -e 'File::install(ARGV[0], ARGV[1], 0555, true)' $(DLLIB) $(archdir)$(target_prefix)/$(DLLIB)
-EOMF
- install_rb(mfile, "$(rubylibdir)$(target_prefix)", srcdir)
- mfile.printf "\n"
-
- mfile.printf <<EOMF
-$(sitearchdir)$(target_prefix)/$(DLLIB): $(DLLIB)
- @$(RUBY) -r ftools -e 'File::makedirs(*ARGV)' $(sitearchdir)$(target_prefix)
- @$(RUBY) -r ftools -e 'File::install(ARGV[0], ARGV[1], 0555, true)' $(DLLIB) $(sitearchdir)$(target_prefix)/$(DLLIB)
-EOMF
- install_rb(mfile, "$(sitelibdir)$(target_prefix)", srcdir)
- mfile.printf "\n"
-
- unless /mswin32/ =~ RUBY_PLATFORM
- src = '$<'
- copt = cxxopt = ''
- else
- if /nmake/i =~ $make
- src = '$(<:\\=/)'
- else
- src = '$(subst /,\\\\,$<)'
- end
- copt = '-Tc'
- cxxopt = '-Tp'
- end
- unless /nmake/i =~ $make
- mfile.puts "
-.cc.#{$OBJEXT}:
- $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c #{cxxopt}#{src}
-.cpp.#{$OBJEXT}:
- $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c #{cxxopt}#{src}
-.cxx.#{$OBJEXT}:
- $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c #{cxxopt}#{src}
-.C.#{$OBJEXT}:
- $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c #{cxxopt}#{src}
-.c.#{$OBJEXT}:
- $(CC) $(CFLAGS) $(CPPFLAGS) -c #{copt}#{src}
-"
- else
- mfile.print "
-{$(srcdir)}.c{}.#{$OBJEXT}:
- $(CC) -I. -I$(<D) $(CFLAGS) $(CPPFLAGS) -c #{copt}#{src}
-.c.#{$OBJEXT}:
- $(CC) $(CFLAGS) $(CPPFLAGS) -c #{copt}#{src}
-{$(srcdir)}.cc{}.#{$OBJEXT}:
- $(CXX) -I. -I$(<D) $(CXXFLAGS) $(CPPFLAGS) -c #{cxxopt}#{src}
-.cc.#{$OBJEXT}:
- $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c #{cxxopt}#{src}
-{$(srcdir)}.cpp{}.#{$OBJEXT}:
- $(CXX) -I. -I$(<D) $(CXXFLAGS) $(CPPFLAGS) -c #{cxxopt}#{src}
-.cpp.#{$OBJEXT}:
- $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c #{cxxopt}#{src}
-{$(srcdir)}.cxx{}.#{$OBJEXT}:
- $(CXX) -I. -I$(<D) $(CXXFLAGS) $(CPPFLAGS) -c #{cxxopt}#{src}
-.cxx.#{$OBJEXT}:
- $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c #{cxxopt}#{src}
-"
- end
-
- if CONFIG["DLEXT"] != $OBJEXT
- mfile.print "$(DLLIB): $(OBJS)\n"
- if /mswin32/ =~ RUBY_PLATFORM
- if /nmake/i =~ $make
- mfile.print "\tset LIB=$(LIBPATH:/=\\);$(LIB)\n"
- else
- mfile.print "\tenv LIB='$(subst /,\\\\,$(LIBPATH));$(LIB)' \\\n"
- end
- end
- mfile.print "\t$(LDSHARED) $(DLDFLAGS) #{OUTFLAG}$(DLLIB) $(OBJS) $(LIBS) $(LOCAL_LIBS)\n"
- elsif not File.exist?(target + ".c") and not File.exist?(target + ".cc")
- mfile.print "$(DLLIB): $(OBJS)\n"
- case RUBY_PLATFORM
- when "m68k-human"
- mfile.printf "ar cru $(DLLIB) $(OBJS)\n"
- else
- mfile.printf "ld $(DLDFLAGS) -r -o $(DLLIB) $(OBJS)\n"
- end
- end
-
- depend = File.join(srcdir, "depend")
- if File.exist?(depend)
- dfile = open(depend, "r")
- mfile.printf "###\n"
- while line = dfile.gets()
- mfile.printf "%s", line.gsub(/\.o\b/, ".#{$OBJEXT}")
- end
- dfile.close
- end
- mfile.close
- $libs = save_libs
- $LIBPATH = save_libpath
-end
-
-$OBJEXT = CONFIG["OBJEXT"]
-$objs = nil
-$libs = CONFIG["DLDLIBS"]
-$local_flags = ""
-case RUBY_PLATFORM
-when /mswin32/
- $local_flags = "-link /INCREMENTAL:no /EXPORT:Init_$(TARGET)"
-end
-$LOCAL_LIBS = ""
-$defs = []
-
-$make = with_config("make-prog", ENV["MAKE"] || "make")
-
-$CFLAGS = with_config("cflags", "")
-$CPPFLAGS = with_config("cppflags", "")
-$LDFLAGS = with_config("ldflags", "")
-$LIBPATH = []
-
-dir_config("opt")
diff --git a/lib/monitor.rb b/lib/monitor.rb
deleted file mode 100644
index 721c51a9f5..0000000000
--- a/lib/monitor.rb
+++ /dev/null
@@ -1,249 +0,0 @@
-=begin
-
-= monitor.rb
-
-Copyright (C) 2001 Shugo Maeda <shugo@ruby-lang.org>
-
-This library is distributed under the terms of the Ruby license.
-You can freely distribute/modify this library.
-
-== example
-
-This is a simple example.
-
- require 'monitor.rb'
-
- buf = []
- buf.extend(MonitorMixin)
- empty_cond = buf.new_cond
-
- # consumer
- Thread.start do
- loop do
- buf.synchronize do
- empty_cond.wait_while { buf.empty? }
- print buf.shift
- end
- end
- end
-
- # producer
- while line = ARGF.gets
- buf.synchronize do
- buf.push(line)
- empty_cond.signal
- end
- end
-
-The consumer thread waits for the producer thread to push a line
-to buf while buf.empty?, and the producer thread (main thread)
-reads a line from ARGF and push it to buf, then call
-empty_cond.signal.
-
-=end
-
-module MonitorMixin
- module Accessible
- protected
- attr_accessor :mon_owner, :mon_count
- attr_reader :mon_entering_queue, :mon_waiting_queue
- end
-
- module Initializable
- protected
- def mon_initialize
- @mon_owner = nil
- @mon_count = 0
- @mon_entering_queue = []
- @mon_waiting_queue = []
- end
- end
-
- class ConditionVariable
- class Timeout < Exception; end
-
- include Accessible
-
- def wait(timeout = nil)
- if @monitor.mon_owner != Thread.current
- raise ThreadError, "current thread not owner"
- end
-
- if timeout
- ct = Thread.current
- timeout_thread = Thread.start {
- Thread.pass
- sleep(timeout)
- ct.raise(Timeout.new)
- }
- end
-
- Thread.critical = true
- count = @monitor.mon_count
- @monitor.mon_count = 0
- @monitor.mon_owner = nil
- if @monitor.mon_waiting_queue.empty?
- t = @monitor.mon_entering_queue.shift
- else
- t = @monitor.mon_waiting_queue.shift
- end
- t.wakeup if t
- @waiters.push(Thread.current)
-
- begin
- Thread.stop
- rescue Timeout
- ensure
- Thread.critical = true
- if timeout && timeout_thread.alive?
- Thread.kill(timeout_thread)
- end
- if @waiters.include?(Thread.current) # interrupted?
- @waiters.delete(Thread.current)
- end
- while @monitor.mon_owner &&
- @monitor.mon_owner != Thread.current
- @monitor.mon_waiting_queue.push(Thread.current)
- Thread.stop
- Thread.critical = true
- end
- @monitor.mon_owner = Thread.current
- @monitor.mon_count = count
- Thread.critical = false
- end
- end
-
- def wait_while
- while yield
- wait
- end
- end
-
- def wait_until
- until yield
- wait
- end
- end
-
- def signal
- if @monitor.mon_owner != Thread.current
- raise ThreadError, "current thread not owner"
- end
- Thread.critical = true
- t = @waiters.shift
- t.wakeup if t
- Thread.critical = false
- Thread.pass
- end
-
- def broadcast
- if @monitor.mon_owner != Thread.current
- raise ThreadError, "current thread not owner"
- end
- Thread.critical = true
- for t in @waiters
- t.wakeup
- end
- @waiters.clear
- Thread.critical = false
- Thread.pass
- end
-
- def count_waiters
- return @waiters.length
- end
-
- private
- def initialize(monitor)
- @monitor = monitor
- @waiters = []
- end
- end
-
- include Accessible
- include Initializable
- extend Initializable
-
- def self.extend_object(obj)
- super(obj)
- obj.mon_initialize
- end
-
- def try_mon_enter
- result = false
- Thread.critical = true
- if mon_owner.nil?
- self.mon_owner = Thread.current
- end
- if mon_owner == Thread.current
- self.mon_count += 1
- result = true
- end
- Thread.critical = false
- return result
- end
-
- def mon_enter
- Thread.critical = true
- while mon_owner != nil && mon_owner != Thread.current
- mon_entering_queue.push(Thread.current)
- Thread.stop
- Thread.critical = true
- end
- self.mon_owner = Thread.current
- self.mon_count += 1
- Thread.critical = false
- end
-
- def mon_exit
- if mon_owner != Thread.current
- raise ThreadError, "current thread not owner"
- end
- Thread.critical = true
- self.mon_count -= 1
- if mon_count == 0
- self.mon_owner = nil
- if mon_waiting_queue.empty?
- t = mon_entering_queue.shift
- else
- t = mon_waiting_queue.shift
- end
- end
- t.wakeup if t
- Thread.critical = false
- Thread.pass
- end
-
- def mon_synchronize
- mon_enter
- begin
- yield
- ensure
- mon_exit
- end
- end
- alias synchronize mon_synchronize
-
- def new_cond
- return ConditionVariable.new(self)
- end
-
-private
- def initialize(*args)
- super
- mon_initialize
- end
-end
-
-class Monitor
- include MonitorMixin
- alias try_enter try_mon_enter
- alias enter mon_enter
- alias exit mon_exit
- alias owner mon_owner
-end
-
-# Local variables:
-# mode: Ruby
-# tab-width: 8
-# End:
diff --git a/lib/mutex_m.rb b/lib/mutex_m.rb
deleted file mode 100644
index 0192d83bee..0000000000
--- a/lib/mutex_m.rb
+++ /dev/null
@@ -1,118 +0,0 @@
-#
-# mutex_m.rb -
-# $Release Version: 3.0$
-# $Revision: 1.7 $
-# $Date: 1998/02/27 04:28:57 $
-# Original from mutex.rb
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-# modified by matz
-# patched by akira yamada
-#
-# --
-# Usage:
-# require "mutex_m.rb"
-# obj = Object.new
-# obj.extend Mutex_m
-# ...
-# extended object can be handled like Mutex
-# or
-# class Foo
-# include Mutex_m
-# ...
-# end
-# obj = Foo.new
-# this obj can be handled like Mutex
-#
-
-module Mutex_m
- def Mutex_m.define_aliases(cl)
- cl.module_eval %q{
- alias locked? mu_locked?
- alias lock mu_lock
- alias unlock mu_unlock
- alias try_lock mu_try_lock
- alias synchronize mu_synchronize
- }
- end
-
- def Mutex_m.append_features(cl)
- super
- define_aliases(cl) unless cl.instance_of?(Module)
- end
-
- def Mutex_m.extend_object(obj)
- super
- obj.mu_extended
- end
-
- def mu_extended
- unless (defined? locked? and
- defined? lock and
- defined? unlock and
- defined? try_lock and
- defined? synchronize)
- Mutex_m.define_aliases(class<<self;self;end)
- end
- mu_initialize
- end
-
- # locking
- def mu_synchronize
- begin
- mu_lock
- yield
- ensure
- mu_unlock
- end
- end
-
- def mu_locked?
- @mu_locked
- end
-
- def mu_try_lock
- result = false
- Thread.critical = true
- unless @mu_locked
- @mu_locked = true
- result = true
- end
- Thread.critical = false
- result
- end
-
- def mu_lock
- while (Thread.critical = true; @mu_locked)
- @mu_waiting.push Thread.current
- Thread.stop
- end
- @mu_locked = true
- Thread.critical = false
- self
- end
-
- def mu_unlock
- return unless @mu_locked
- Thread.critical = true
- wait = @mu_waiting
- @mu_waiting = []
- @mu_locked = false
- Thread.critical = false
- for w in wait
- w.run
- end
- self
- end
-
- private
-
- def mu_initialize
- @mu_waiting = []
- @mu_locked = false;
- end
-
- def initialize(*args)
- mu_initialize
- super
- end
-end
diff --git a/lib/net/ftp.rb b/lib/net/ftp.rb
deleted file mode 100644
index 88361b9ddb..0000000000
--- a/lib/net/ftp.rb
+++ /dev/null
@@ -1,671 +0,0 @@
-=begin
-
-= net/ftp.rb
-
-written by Shugo Maeda <shugo@ruby-lang.org>
-
-This library is distributed under the terms of the Ruby license.
-You can freely distribute/modify this library.
-
-=end
-
-require "socket"
-require "monitor"
-
-module Net
-
- class FTPError < StandardError; end
- class FTPReplyError < FTPError; end
- class FTPTempError < FTPError; end
- class FTPPermError < FTPError; end
- class FTPProtoError < FTPError; end
-
- class FTP
- include MonitorMixin
-
- FTP_PORT = 21
- CRLF = "\r\n"
-
- DEFAULT_BLOCKSIZE = 4096
-
- attr_accessor :passive, :return_code, :debug_mode, :resume
- attr_reader :welcome, :lastresp
-
- def FTP.open(host, user = nil, passwd = nil, acct = nil)
- new(host, user, passwd, acct)
- end
-
- def initialize(host = nil, user = nil, passwd = nil, acct = nil)
- super()
- @passive = false
- @return_code = "\n"
- @debug_mode = false
- @resume = false
- if host
- connect(host)
- if user
- login(user, passwd, acct)
- end
- end
- end
-
- def open_socket(host, port)
- if defined? SOCKSsocket and ENV["SOCKS_SERVER"]
- @passive = true
- return SOCKSsocket.open(host, port)
- else
- return TCPsocket.open(host, port)
- end
- end
- private :open_socket
-
- def connect(host, port = FTP_PORT)
- if @debug_mode
- print "connect: ", host, ", ", port, "\n"
- end
- synchronize do
- @sock = open_socket(host, port)
- voidresp
- end
- end
-
- def sanitize(s)
- if s =~ /^PASS /i
- return s[0, 5] + "*" * (s.length - 5)
- else
- return s
- end
- end
- private :sanitize
-
- def putline(line)
- if @debug_mode
- print "put: ", sanitize(line), "\n"
- end
- line = line + CRLF
- @sock.write(line)
- end
- private :putline
-
- def getline
- line = @sock.readline # if get EOF, raise EOFError
- if line[-2, 2] == CRLF
- line = line[0 .. -3]
- elsif line[-1] == ?\r or
- line[-1] == ?\n
- line = line[0 .. -2]
- end
- if @debug_mode
- print "get: ", sanitize(line), "\n"
- end
- return line
- end
- private :getline
-
- def getmultiline
- line = getline
- buff = line
- if line[3] == ?-
- code = line[0, 3]
- begin
- line = getline
- buff << "\n" << line
- end until line[0, 3] == code and line[3] != ?-
- end
- return buff << "\n"
- end
- private :getmultiline
-
- def getresp
- resp = getmultiline
- @lastresp = resp[0, 3]
- c = resp[0]
- case c
- when ?1, ?2, ?3
- return resp
- when ?4
- raise FTPTempError, resp
- when ?5
- raise FTPPermError, resp
- else
- raise FTPProtoError, resp
- end
- end
- private :getresp
-
- def voidresp
- resp = getresp
- if resp[0] != ?2
- raise FTPReplyError, resp
- end
- end
- private :voidresp
-
- def sendcmd(cmd)
- synchronize do
- putline(cmd)
- return getresp
- end
- end
-
- def voidcmd(cmd)
- synchronize do
- putline(cmd)
- voidresp
- end
- end
-
- def sendport(host, port)
- af = (@sock.peeraddr)[0]
- if af == "AF_INET"
- hbytes = host.split(".")
- pbytes = [port / 256, port % 256]
- bytes = hbytes + pbytes
- cmd = "PORT " + bytes.join(",")
- elsif af == "AF_INET6"
- cmd = "EPRT |2|" + host + "|" + sprintf("%d", port) + "|"
- else
- raise FTPProtoError, host
- end
- voidcmd(cmd)
- end
- private :sendport
-
- def makeport
- sock = TCPserver.open(@sock.addr[3], 0)
- port = sock.addr[1]
- host = sock.addr[3]
- resp = sendport(host, port)
- return sock
- end
- private :makeport
-
- def makepasv
- if @sock.peeraddr[0] == "AF_INET"
- host, port = parse227(sendcmd("PASV"))
- else
- host, port = parse229(sendcmd("EPSV"))
- # host, port = parse228(sendcmd("LPSV"))
- end
- return host, port
- end
- private :makepasv
-
- def transfercmd(cmd, rest_offset = nil)
- if @passive
- host, port = makepasv
- conn = open_socket(host, port)
- if @resume and rest_offset
- resp = sendcmd("REST " + rest_offset.to_s)
- if resp[0] != ?3
- raise FTPReplyError, resp
- end
- end
- resp = sendcmd(cmd)
- if resp[0] != ?1
- raise FTPReplyError, resp
- end
- else
- sock = makeport
- if @resume and rest_offset
- resp = sendcmd("REST " + rest_offset.to_s)
- if resp[0] != ?3
- raise FTPReplyError, resp
- end
- end
- resp = sendcmd(cmd)
- if resp[0] != ?1
- raise FTPReplyError, resp
- end
- conn = sock.accept
- sock.close
- end
- return conn
- end
- private :transfercmd
-
- def getaddress
- thishost = Socket.gethostname
- if not thishost.index(".")
- thishost = Socket.gethostbyname(thishost)[0]
- end
- if ENV.has_key?("LOGNAME")
- realuser = ENV["LOGNAME"]
- elsif ENV.has_key?("USER")
- realuser = ENV["USER"]
- else
- realuser = "anonymous"
- end
- return realuser + "@" + thishost
- end
- private :getaddress
-
- def login(user = "anonymous", passwd = nil, acct = nil)
- if user == "anonymous" and passwd == nil
- passwd = getaddress
- end
-
- resp = ""
- synchronize do
- resp = sendcmd('USER ' + user)
- if resp[0] == ?3
- resp = sendcmd('PASS ' + passwd)
- end
- if resp[0] == ?3
- resp = sendcmd('ACCT ' + acct)
- end
- end
- if resp[0] != ?2
- raise FTPReplyError, resp
- end
- @welcome = resp
- end
-
- def retrbinary(cmd, blocksize, rest_offset = nil, callback = Proc.new)
- synchronize do
- voidcmd("TYPE I")
- conn = transfercmd(cmd, rest_offset)
- loop do
- data = conn.read(blocksize)
- break if data == nil
- callback.call(data)
- end
- conn.close
- voidresp
- end
- end
-
- def retrlines(cmd, callback = nil)
- if block_given?
- callback = Proc.new
- elsif not callback.is_a?(Proc)
- callback = Proc.new {|line| print line, "\n"}
- end
- synchronize do
- voidcmd("TYPE A")
- conn = transfercmd(cmd)
- loop do
- line = conn.gets
- break if line == nil
- if line[-2, 2] == CRLF
- line = line[0 .. -3]
- elsif line[-1] == ?\n
- line = line[0 .. -2]
- end
- callback.call(line)
- end
- conn.close
- voidresp
- end
- end
-
- def storbinary(cmd, file, blocksize, rest_offset = nil, callback = nil)
- if block_given?
- callback = Proc.new
- end
- use_callback = callback.is_a?(Proc)
- synchronize do
- voidcmd("TYPE I")
- conn = transfercmd(cmd, rest_offset)
- loop do
- buf = file.read(blocksize)
- break if buf == nil
- conn.write(buf)
- callback.call(buf) if use_callback
- end
- conn.close
- voidresp
- end
- end
-
- def storlines(cmd, file, callback = nil)
- if block_given?
- callback = Proc.new
- end
- use_callback = callback.is_a?(Proc)
- synchronize do
- voidcmd("TYPE A")
- conn = transfercmd(cmd)
- loop do
- buf = file.gets
- break if buf == nil
- if buf[-2, 2] != CRLF
- buf = buf.chomp + CRLF
- end
- conn.write(buf)
- callback.call(buf) if use_callback
- end
- conn.close
- voidresp
- end
- end
-
- def getbinaryfile(remotefile, localfile,
- blocksize = DEFAULT_BLOCKSIZE, callback = nil)
- if block_given?
- callback = Proc.new
- end
- use_callback = callback.is_a?(Proc)
- if @resume
- rest_offset = File.size?(localfile)
- f = open(localfile, "a")
- else
- rest_offset = nil
- f = open(localfile, "w")
- end
- begin
- f.binmode
- retrbinary("RETR " + remotefile, blocksize, rest_offset) do |data|
- f.write(data)
- callback.call(data) if use_callback
- end
- ensure
- f.close
- end
- end
-
- def gettextfile(remotefile, localfile, callback = nil)
- if block_given?
- callback = Proc.new
- end
- use_callback = callback.is_a?(Proc)
- f = open(localfile, "w")
- begin
- retrlines("RETR " + remotefile) do |line|
- line = line + @return_code
- f.write(line)
- callback.call(line) if use_callback
- end
- ensure
- f.close
- end
- end
-
- def putbinaryfile(localfile, remotefile,
- blocksize = DEFAULT_BLOCKSIZE, callback = nil)
- if block_given?
- callback = Proc.new
- end
- use_callback = callback.is_a?(Proc)
- if @resume
- rest_offset = size(remotefile)
- else
- rest_offset = nil
- end
- f = open(localfile)
- begin
- f.binmode
- storbinary("STOR " + remotefile, f, blocksize, rest_offset) do |data|
- callback.call(data) if use_callback
- end
- ensure
- f.close
- end
- end
-
- def puttextfile(localfile, remotefile, callback = nil)
- if block_given?
- callback = Proc.new
- end
- use_callback = callback.is_a?(Proc)
- f = open(localfile)
- begin
- storlines("STOR " + remotefile, f) do |line|
- callback.call(line) if use_callback
- end
- ensure
- f.close
- end
- end
-
- def acct(account)
- cmd = "ACCT " + account
- voidcmd(cmd)
- end
-
- def nlst(dir = nil)
- cmd = "NLST"
- if dir
- cmd = cmd + " " + dir
- end
- files = []
- retrlines(cmd) do |line|
- files.push(line)
- end
- return files
- end
-
- def list(*args, &block)
- cmd = "LIST"
- args.each do |arg|
- cmd = cmd + " " + arg
- end
- if block
- retrlines(cmd, &block)
- else
- lines = []
- retrlines(cmd) do |line|
- lines << line
- end
- return lines
- end
- end
- alias ls list
- alias dir list
-
- def rename(fromname, toname)
- resp = sendcmd("RNFR " + fromname)
- if resp[0] != ?3
- raise FTPReplyError, resp
- end
- voidcmd("RNTO " + toname)
- end
-
- def delete(filename)
- resp = sendcmd("DELE " + filename)
- if resp[0, 3] == "250"
- return
- elsif resp[0] == ?5
- raise FTPPermError, resp
- else
- raise FTPReplyError, resp
- end
- end
-
- def chdir(dirname)
- if dirname == ".."
- begin
- voidcmd("CDUP")
- return
- rescue FTPPermError
- if $![0, 3] != "500"
- raise FTPPermError, $!
- end
- end
- end
- cmd = "CWD " + dirname
- voidcmd(cmd)
- end
-
- def size(filename)
- voidcmd("TYPE I")
- resp = sendcmd("SIZE " + filename)
- if resp[0, 3] != "213"
- raise FTPReplyError, resp
- end
- return resp[3..-1].strip.to_i
- end
-
- MDTM_REGEXP = /^(\d\d\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/
-
- def mtime(filename, local = false)
- str = mdtm(filename)
- ary = str.scan(MDTM_REGEXP)[0].collect {|i| i.to_i}
- return local ? Time.local(*ary) : Time.gm(*ary)
- end
-
- def mkdir(dirname)
- resp = sendcmd("MKD " + dirname)
- return parse257(resp)
- end
-
- def rmdir(dirname)
- voidcmd("RMD " + dirname)
- end
-
- def pwd
- resp = sendcmd("PWD")
- return parse257(resp)
- end
- alias getdir pwd
-
- def system
- resp = sendcmd("SYST")
- if resp[0, 3] != "215"
- raise FTPReplyError, resp
- end
- return resp[4 .. -1]
- end
-
- def abort
- line = "ABOR" + CRLF
- print "put: ABOR\n" if @debug_mode
- @sock.send(line, Socket::MSG_OOB)
- resp = getmultiline
- unless ["426", "226", "225"].include?(resp[0, 3])
- raise FTPProtoError, resp
- end
- return resp
- end
-
- def status
- line = "STAT" + CRLF
- print "put: STAT\n" if @debug_mode
- @sock.send(line, Socket::MSG_OOB)
- return getresp
- end
-
- def mdtm(filename)
- resp = sendcmd("MDTM " + filename)
- if resp[0, 3] == "213"
- return resp[3 .. -1].strip
- end
- end
-
- def help(arg = nil)
- cmd = "HELP"
- if arg
- cmd = cmd + " " + arg
- end
- sendcmd(cmd)
- end
-
- def quit
- voidcmd("QUIT")
- end
-
- def close
- @sock.close if @sock and not @sock.closed?
- end
-
- def closed?
- @sock == nil or @sock.closed?
- end
-
- def parse227(resp)
- if resp[0, 3] != "227"
- raise FTPReplyError, resp
- end
- left = resp.index("(")
- right = resp.index(")")
- if left == nil or right == nil
- raise FTPProtoError, resp
- end
- numbers = resp[left + 1 .. right - 1].split(",")
- if numbers.length != 6
- raise FTPProtoError, resp
- end
- host = numbers[0, 4].join(".")
- port = (numbers[4].to_i << 8) + numbers[5].to_i
- return host, port
- end
- private :parse227
-
- def parse228(resp)
- if resp[0, 3] != "228"
- raise FTPReplyError, resp
- end
- left = resp.index("(")
- right = resp.index(")")
- if left == nil or right == nil
- raise FTPProtoError, resp
- end
- numbers = resp[left + 1 .. right - 1].split(",")
- if numbers[0] == "4"
- if numbers.length != 9 || numbers[1] != "4" || numbers[2 + 4] != "2"
- raise FTPProtoError, resp
- end
- host = numbers[2, 4].join(".")
- port = (numbers[7].to_i << 8) + numbers[8].to_i
- elsif numbers[0] == "6"
- if numbers.length != 21 || numbers[1] != "16" || numbers[2 + 16] != "2"
- raise FTPProtoError, resp
- end
- v6 = ["", "", "", "", "", "", "", ""]
- for i in 0 .. 7
- v6[i] = sprintf("%02x%02x", numbers[(i * 2) + 2].to_i,
- numbers[(i * 2) + 3].to_i)
- end
- host = v6[0, 8].join(":")
- port = (numbers[19].to_i << 8) + numbers[20].to_i
- end
- return host, port
- end
- private :parse228
-
- def parse229(resp)
- if resp[0, 3] != "229"
- raise FTPReplyError, resp
- end
- left = resp.index("(")
- right = resp.index(")")
- if left == nil or right == nil
- raise FTPProtoError, resp
- end
- numbers = resp[left + 1 .. right - 1].split(resp[left + 1, 1])
- if numbers.length != 4
- raise FTPProtoError, resp
- end
- port = numbers[3].to_i
- host = (@sock.peeraddr())[3]
- return host, port
- end
- private :parse229
-
- def parse257(resp)
- if resp[0, 3] != "257"
- raise FTPReplyError, resp
- end
- if resp[3, 2] != ' "'
- return ""
- end
- dirname = ""
- i = 5
- n = resp.length
- while i < n
- c = resp[i, 1]
- i = i + 1
- if c == '"'
- if i > n or resp[i, 1] != '"'
- break
- end
- i = i + 1
- end
- dirname = dirname + c
- end
- return dirname
- end
- private :parse257
- end
-
-end
diff --git a/lib/net/http.rb b/lib/net/http.rb
deleted file mode 100644
index 6a33fd4918..0000000000
--- a/lib/net/http.rb
+++ /dev/null
@@ -1,1473 +0,0 @@
-=begin
-
-= net/http.rb
-
-Copyright (c) 1999-2002 Yukihiro Matsumoto
-
-written & maintained by Minero Aoki <aamine@loveruby.net>
-This file is derived from "http-access.rb".
-
-This program is free software. You can re-distribute and/or
-modify this program under the same terms as Ruby itself,
-Ruby Distribute License or GNU General Public License.
-
-NOTE: You can find Japanese version of this document in
-the doc/net directory of the standard ruby interpreter package.
-
-$Id$
-
-== What is this module?
-
-This module provide your program the functions to access WWW
-documents via HTTP, Hyper Text Transfer Protocol version 1.1.
-For details of HTTP, refer [RFC2616]
-((<URL:http://www.ietf.org/rfc/rfc2616.txt>)).
-
-== Examples
-
-=== Getting Document From Server
-
-Be care to ',' (comma) putted after "response".
-This is required for compatibility.
-
- require 'net/http'
- Net::HTTP.start( 'some.www.server', 80 ) {|http|
- response , = http.get('/index.html')
- puts response.body
- }
-
-(shorter version)
-
- require 'net/http'
- Net::HTTP.get_print 'some.www.server', '/index.html'
-
-=== Posting Form Data
-
- require 'net/http'
- Net::HTTP.start( 'some.www.server', 80 ) {|http|
- response , = http.post( '/cgi-bin/any.rhtml',
- 'querytype=subject&target=ruby' )
- }
-
-=== Accessing via Proxy
-
-Net::HTTP.Proxy() creates http proxy class. It has same
-methods of Net::HTTP but its instances always connect to
-proxy, instead of given host.
-
- require 'net/http'
-
- $proxy_addr = 'your.proxy.addr'
- $proxy_port = 8080
- :
- Net::HTTP::Proxy($proxy_addr, $proxy_port).start( 'some.www.server' ) {|http|
- # always connect to your.proxy.addr:8080
- :
- }
-
-Since Net::HTTP.Proxy() returns Net::HTTP itself when $proxy_addr is nil,
-there's no need to change code if there's proxy or not.
-
-=== Redirect
-
- require 'net/http'
- Net::HTTP.version_1_1
-
- host = 'www.ruby-lang.org'
- path = '/'
- begin
- Net::HTTP.start( host, 80 ) {|http|
- response , = http.get(path)
- print response.body
- }
- rescue Net::ProtoRetriableError => err
- if m = %r<http://([^/]+)>.match( err.response['location'] ) then
- host = m[1].strip
- path = m.post_match
- retry
- end
- end
-
-NOTE: This code is using ad-hoc way to extract host name, but in future
-URI class will be included in ruby standard library.
-
-=== Basic Authentication
-
- require 'net/http'
-
- Net::HTTP.start( 'auth.some.domain' ) {|http|
- response , = http.get( '/need-auth.cgi',
- 'Authorization' => 'Basic ' + ["#{account}:#{password}"].pack('m').strip )
- print response.body
- }
-
-In version 1.2 (Ruby 1.7 or later), you can write like this:
-
- require 'net/http'
-
- req = Net::HTTP::Get.new('/need-auth.cgi')
- req.basic_auth 'account', 'password'
- Net::HTTP.start( 'auth.some.domain' ) {|http|
- response = http.request(req)
- print response.body
- }
-
-== Switching Net::HTTP versions
-
-You can use old Net::HTTP (in Ruby 1.6) features by calling
-HTTP.version_1_1. And calling Net::HTTP.version_1_2 allows
-you to use 1.2 features again.
-
- # example
- Net::HTTP.start {|http1| ...(http1 has 1.2 features)... }
-
- Net::HTTP.version_1_1
- Net::HTTP.start {|http2| ...(http2 has 1.1 features)... }
-
- Net::HTTP.version_1_2
- Net::HTTP.start {|http3| ...(http3 has 1.2 features)... }
-
-Yes, this is not thread-safe.
-
-== class Net::HTTP
-
-=== Class Methods
-
-: new( address, port = 80, proxy_addr = nil, proxy_port = nil )
- creates a new Net::HTTP object.
- If proxy_addr is given, creates an Net::HTTP object with proxy support.
-
-: start( address, port = 80, proxy_addr = nil, proxy_port = nil )
-: start( address, port = 80, proxy_addr = nil, proxy_port = nil ) {|http| .... }
- is equals to
-
- Net::HTTP.new(address, port, proxy_addr, proxy_port).start(&block)
-
-: get( address, path, port = 80 )
- gets entity body from path and returns it.
- return value is a String.
-
-: get_print( address, path, port = 80 )
- gets entity body from path and output it to $stdout.
-
-: Proxy( address, port = 80 )
- creates a HTTP proxy class.
- Arguments are address/port of proxy host.
- You can replace HTTP class with created proxy class.
-
- If ADDRESS is nil, this method returns self (Net::HTTP).
-
- # example
- proxy_class = Net::HTTP::Proxy( 'proxy.foo.org', 8080 )
- :
- proxy_class.start( 'www.ruby-lang.org' ) {|http|
- # connecting proxy.foo.org:8080
- :
- }
-
-: proxy_class?
- If self is HTTP, false.
- If self is a class which was created by HTTP::Proxy(), true.
-
-: port
- default HTTP port (80).
-
-=== Instance Methods
-
-: start
-: start {|http| .... }
- creates a new Net::HTTP object and starts HTTP session.
-
- When this method is called with block, gives a HTTP object to block
- and close the HTTP session after block call finished.
-
-: active?
- true if HTTP session is started.
-
-: address
- the address to connect
-
-: port
- the port number to connect
-
-: open_timeout
-: open_timeout=(n)
- seconds to wait until connection is opened.
- If HTTP object cannot open a conection in this seconds,
- it raises TimeoutError exception.
-
-: read_timeout
-: read_timeout=(n)
- seconds to wait until reading one block (by one read(1) call).
- If HTTP object cannot open a conection in this seconds,
- it raises TimeoutError exception.
-
-: finish
- finishes HTTP session.
- If HTTP session had not started, raises an IOError.
-
-: proxy?
- true if self is a HTTP proxy class
-
-: proxy_address
- address of proxy host. If self does not use a proxy, nil.
-
-: proxy_port
- port number of proxy host. If self does not use a proxy, nil.
-
-: get( path, header = nil )
-: get( path, header = nil ) {|str| .... }
- gets data from PATH on the connecting host.
- HEADER must be a Hash like { 'Accept' => '*/*', ... }.
-
- In version 1.1, this method returns a pair of objects,
- a Net::HTTPResponse object and entity body string.
- In version 1.2, this method returns a Net::HTTPResponse
- object.
-
- If called with block, gives entity body string to the block
- little by little.
-
- In version 1.1, this method might raises exception for also
- 3xx (redirect). On the case you can get a HTTPResponse object
- by "anException.response".
- In version 1.2, this method never raises exception.
-
- # version 1.1 (bundled with Ruby 1.6)
- response, body = http.get( '/index.html' )
-
- # version 1.2 (bundled with Ruby 1.7 or later)
- response = http.get( '/index.html' )
-
- # compatible in both version
- response , = http.get( '/index.html' )
- response.body
-
- # using block
- File.open( 'save.txt', 'w' ) {|f|
- http.get( '/~foo/', nil ) do |str|
- f.write str
- end
- }
-
-: head( path, header = nil )
- gets only header from PATH on the connecting host.
- HEADER is a Hash like { 'Accept' => '*/*', ... }.
-
- This method returns a Net::HTTPResponse object.
-
- In version 1.1, this method might raises exception for also
- 3xx (redirect). On the case you can get a HTTPResponse object
- by "anException.response".
- In version 1.2, this method never raises exception.
-
- response = nil
- Net::HTTP.start( 'some.www.server', 80 ) {|http|
- response = http.head( '/index.html' )
- }
- p response['content-type']
-
-: post( path, data, header = nil )
-: post( path, data, header = nil ) {|str| .... }
- posts DATA (must be String) to PATH. HEADER must be a Hash
- like { 'Accept' => '*/*', ... }.
-
- In version 1.1, this method returns a pair of objects, a
- Net::HTTPResponse object and an entity body string.
- In version 1.2, this method returns a Net::HTTPReponse object.
-
- If called with block, gives a part of entity body string.
-
- In version 1.1, this method might raises exception for also
- 3xx (redirect). On the case you can get a HTTPResponse object
- by "anException.response".
- In version 1.2, this method never raises exception.
-
- # version 1.1
- response, body = http.post( '/cgi-bin/search.rb', 'query=subject&target=ruby' )
-
- # version 1.2
- response = http.post( '/cgi-bin/search.rb', 'query=subject&target=ruby' )
-
- # compatible in both version
- response , = http.post( '/cgi-bin/search.rb', 'query=subject&target=ruby' )
-
- # using block
- File.open( 'save.html', 'w' ) {|f|
- http.post( '/cgi-bin/search.rb',
- 'query=subject&target=ruby' ) do |str|
- f.write str
- end
- }
-
-: request_get( path, header = nil )
-: request_get( path, header = nil ) {|response| .... }
- gets entity from PATH. This method returns a HTTPResponse object.
-
- When called with block, keep connection while block is executed
- and gives a HTTPResponse object to the block.
-
- This method never raises Net::* exceptions.
-
- # example
- response = http.request_get( '/index.html' )
- p response['content-type']
- puts response.body # body is already read
-
- # using block
- http.request_get( '/index.html' ) {|response|
- p response['content-type']
- response.read_body do |str| # read body now
- print str
- end
- }
-
-: request_post( path, data, header = nil )
-: request_post( path, data, header = nil ) {|response| .... }
- posts data to PATH. This method returns a HTTPResponse object.
-
- When called with block, gives a HTTPResponse object to the block
- before reading entity body, with keeping connection.
-
- This method never raises Net::* exceptions.
-
- # example
- response = http.post2( '/cgi-bin/nice.rb', 'datadatadata...' )
- p response.status
- puts response.body # body is already read
-
- # using block
- http.post2( '/cgi-bin/nice.rb', 'datadatadata...' ) {|response|
- p response.status
- p response['content-type']
- response.read_body do |str| # read body now
- print str
- end
- }
-
-: request( request [, data] )
-: request( request [, data] ) {|response| .... }
- sends a HTTPRequest object REQUEST to the HTTP server.
- This method also writes DATA string if REQUEST is a post/put request.
- Giving DATA for get/head request causes ArgumentError.
-
- If called with block, this method passes a HTTPResponse object to
- the block, without reading entity body.
-
- This method never raises Net::* exceptions.
-
-== class Net::HTTP::Get, Head, Post
-
-HTTP request classes. These classes wraps request header and
-entity path. All arguments named "key" is case-insensitive.
-
-=== Class Methods
-
-: new
- creats HTTP request object.
-
-=== Instance Methods
-
-: self[ key ]
- returns the header field corresponding to the case-insensitive key.
- For example, a key of "Content-Type" might return "text/html"
-
-: self[ key ] = val
- sets the header field corresponding to the case-insensitive key.
-
-: each {|name, val| .... }
- iterates for each field name and value pair.
-
-: basic_auth( account, password )
- set Authorization: header for basic auth.
-
-: range
- returns a Range object which represents Range: header field.
-
-: range = r
-: set_range( i, len )
- set Range: header from Range (arg r) or beginning index and
- length from it (arg i&len).
-
-: content_length
- returns a Integer object which represents Content-Length: header field.
-
-: content_range
- returns a Range object which represents Content-Range: header field.
-
-== class Net::HTTPResponse
-
-HTTP response class. This class wraps response header and entity.
-All arguments named KEY is case-insensitive.
-
-=== Instance Methods
-
-: self[ key ]
- returns the header field corresponding to the case-insensitive key.
- For example, a key of "Content-Type" might return "text/html".
- A key of "Content-Length" might do "2045".
-
- More than one fields which has same names are joined with ','.
-
-: self[ key ] = val
- sets the header field corresponding to the case-insensitive key.
-
-: key?( key )
- true if key exists.
- KEY is case insensitive.
-
-: each {|name,value| .... }
- iterates for each field name and value pair.
-
-: canonical_each {|name,value| .... }
- iterates for each "canonical" field name and value pair.
-
-: code
- HTTP result code string. For example, '302'.
-
-: message
- HTTP result message. For example, 'Not Found'.
-
-: read_body( dest = '' )
- gets entity body and write it into DEST using "<<" method.
- If this method is called twice or more, nothing will be done
- and returns first DEST.
-
-: read_body {|str| .... }
- gets entity body little by little and pass it to block.
-
-: body
- response body. If #read_body has been called, this method returns
- arg of #read_body DEST. Else gets body as String and returns it.
-
-=end
-
-require 'net/protocol'
-
-
-module Net
-
- class HTTPBadResponse < StandardError; end
- class HTTPHeaderSyntaxError < StandardError; end
-
-
- class HTTP < Protocol
-
- HTTPVersion = '1.1'
-
-
- #
- # for backward compatibility
- #
-
- @@newimpl = true
-
- def HTTP.version_1_2
- @@newimpl = true
- end
-
- def HTTP.version_1_1
- @@newimpl = false
- end
-
- def HTTP.is_version_1_2?
- @@newimpl
- end
-
- def HTTP.setimplversion( obj )
- f = @@newimpl
- obj.instance_eval { @newimpl = f }
- end
- private_class_method :setimplversion
-
-
- #
- # short cut methods
- #
-
- def HTTP.get( addr, path, port = nil )
- req = Get.new( path )
- resp = nil
- new( addr, port || HTTP.default_port ).start {|http|
- resp = http.request( req )
- }
- resp.body
- end
-
- def HTTP.get_print( addr, path, port = nil )
- new( addr, port || HTTP.port ).start {|http|
- http.get path, nil, $stdout
- }
- nil
- end
-
-
- #
- # connection
- #
-
- protocol_param :default_port, '80'
- protocol_param :socket_type, '::Net::InternetMessageIO'
-
- class << HTTP
- def start( address, port = nil, p_addr = nil, p_port = nil, &block )
- new( address, port, p_addr, p_port ).start( &block )
- end
-
- alias newobj new
-
- def new( address, port = nil, p_addr = nil, p_port = nil )
- obj = Proxy(p_addr, p_port).newobj(address, port)
- setimplversion obj
- obj
- end
- end
-
- def initialize( addr, port = nil )
- super
- @curr_http_version = HTTPVersion
- @seems_1_0_server = false
- end
-
- private
-
- def do_start
- conn_socket
- end
-
- def do_finish
- disconn_socket
- end
-
-
- #
- # proxy
- #
-
- public
-
- # no proxy
- @is_proxy_class = false
- @proxy_addr = nil
- @proxy_port = nil
-
- def HTTP.Proxy( p_addr, p_port = nil )
- p_addr or return self
-
- p_port ||= port()
- delta = ProxyDelta
- proxyclass = Class.new(self)
- proxyclass.module_eval {
- include delta
- # with proxy
- @is_proxy_class = true
- @proxy_address = p_addr
- @proxy_port = p_port
- }
- proxyclass
- end
-
- class << HTTP
- def proxy_class?
- @is_proxy_class
- end
-
- attr_reader :proxy_address
- attr_reader :proxy_port
- end
-
- def proxy?
- type.proxy_class?
- end
-
- def proxy_address
- type.proxy_address
- end
-
- def proxy_port
- type.proxy_port
- end
-
- alias proxyaddr proxy_address
- alias proxyport proxy_port
-
- private
-
- # no proxy
-
- def conn_address
- address
- end
-
- def conn_port
- port
- end
-
- def edit_path( path )
- path
- end
-
- module ProxyDelta
- private
-
- # with proxy
-
- def conn_address
- proxy_address
- end
-
- def conn_port
- proxy_port
- end
-
- def edit_path( path )
- 'http://' + addr_port() + path
- end
- end
-
-
- #
- # http operations
- #
-
- public
-
- def get( path, initheader = nil, dest = nil, &block )
- res = nil
- request( Get.new(path,initheader) ) {|res|
- res.read_body dest, &block
- }
- unless @newimpl then
- res.value
- return res, res.body
- end
-
- res
- end
-
- def head( path, initheader = nil )
- res = request( Head.new(path,initheader) )
- @newimpl or res.value
- res
- end
-
- def post( path, data, initheader = nil, dest = nil, &block )
- res = nil
- request( Post.new(path,initheader), data ) {|res|
- res.read_body dest, &block
- }
- unless @newimpl then
- res.value
- return res, res.body
- end
-
- res
- end
-
- def put( path, data, initheader = nil )
- res = request( Put.new(path,initheader), data )
- @newimpl or res.value
- res
- end
-
-
- def request_get( path, initheader = nil, &block )
- request Get.new(path,initheader), &block
- end
-
- def request_head( path, initheader = nil, &block )
- request Head.new(path,initheader), &block
- end
-
- def request_post( path, data, initheader = nil, &block )
- request Post.new(path,initheader), data, &block
- end
-
- def request_put( path, data, initheader = nil, &block )
- request Put.new(path,initheader), data, &block
- end
-
- alias get2 request_get
- alias head2 request_head
- alias post2 request_post
- alias put2 request_put
-
-
- def send_request( name, path, body = nil, header = nil )
- r = HTTPGenericRequest.new( name, (body ? true : false), true,
- path, header )
- request r, body
- end
-
-
- def request( req, body = nil, &block )
- unless active? then
- start {
- req['connection'] = 'close'
- return request(req, body, &block)
- }
- end
-
- begin_transport req
- req.__send__(:exec,
- @socket, @curr_http_version, edit_path(req.path), body)
- begin
- res = HTTPResponse.read_new(@socket, req.response_body_permitted?)
- end while HTTPContinue === res
- yield res if block_given?
- end_transport req, res
-
- res
- end
-
- private
-
- def begin_transport( req )
- if @socket.closed? then
- reconn_socket
- end
- if not req.body_exist? or @seems_1_0_server then
- req['connection'] = 'close'
- end
- req['host'] = addr_port()
- end
-
- def end_transport( req, res )
- res.__send__ :terminate
- @curr_http_version = res.http_version
-
- if not res.body then
- @socket.close
- elsif keep_alive? req, res then
- D 'Conn keep-alive'
- if @socket.closed? then # (only) read stream had been closed
- D 'Conn (but seems 1.0 server)'
- @seems_1_0_server = true
- @socket.close
- end
- else
- D 'Conn close'
- @socket.close
- end
- end
-
- def keep_alive?( req, res )
- /close/i === req['connection'].to_s and return false
- @seems_1_0_server and return false
-
- /keep-alive/i === res['connection'].to_s and return true
- /close/i === res['connection'].to_s and return false
- /keep-alive/i === res['proxy-connection'].to_s and return true
- /close/i === res['proxy-connection'].to_s and return false
-
- @curr_http_version == '1.1' and return true
- false
- end
-
-
- #
- # utils
- #
-
- private
-
- def addr_port
- address + (port == HTTP.default_port ? '' : ":#{port}")
- end
-
- def D( msg )
- if @dout then
- @dout << msg
- @dout << "\n"
- end
- end
-
- end
-
- HTTPSession = HTTP
-
-
- ###
- ### header
- ###
-
- module HTTPHeader
-
- def size
- @header.size
- end
-
- alias length size
-
- def []( key )
- @header[ key.downcase ]
- end
-
- def []=( key, val )
- @header[ key.downcase ] = val
- end
-
- def each_header( &block )
- @header.each( &block )
- end
-
- alias each each_header
-
- def each_key( &block )
- @header.each_key( &block )
- end
-
- def each_value( &block )
- @header.each_value( &block )
- end
-
- def delete( key )
- @header.delete key.downcase
- end
-
- def key?( key )
- @header.key? key.downcase
- end
-
- def to_hash
- @header.dup
- end
-
- def canonical_each
- @header.each do |k,v|
- yield canonical(k), v
- end
- end
-
- def canonical( k )
- k.split('-').collect {|i| i.capitalize }.join('-')
- end
-
- def range
- s = @header['range'] or return nil
- s.split(',').collect {|spec|
- m = /bytes\s*=\s*(\d+)?\s*-\s*(\d+)?/i.match(spec) or
- raise HTTPHeaderSyntaxError, "wrong Range: #{spec}"
- d1 = m[1].to_i
- d2 = m[2].to_i
- if m[1] and m[2] then d1..d2
- elsif m[1] then d1..-1
- elsif m[2] then -d2..-1
- else
- raise HTTPHeaderSyntaxError, 'range is not specified'
- end
- }
- end
-
- def range=( r, fin = nil )
- r = (r ... r + fin) if fin
-
- case r
- when Numeric
- s = r > 0 ? "0-#{r - 1}" : "-#{-r}"
- when Range
- first = r.first
- last = r.last
- if r.exclude_end? then
- last -= 1
- end
-
- if last == -1 then
- s = first > 0 ? "#{first}-" : "-#{-first}"
- else
- first >= 0 or raise HTTPHeaderSyntaxError, 'range.first is negative'
- last > 0 or raise HTTPHeaderSyntaxError, 'range.last is negative'
- first < last or raise HTTPHeaderSyntaxError, 'must be .first < .last'
- s = "#{first}-#{last}"
- end
- else
- raise TypeError, 'Range/Integer is required'
- end
-
- @header['range'] = "bytes=#{s}"
- r
- end
-
- alias set_range range=
-
- def content_length
- s = @header['content-length']
- s or return nil
-
- m = /\d+/.match(s)
- m or raise HTTPHeaderSyntaxError, 'wrong Content-Length format'
- m[0].to_i
- end
-
- def chunked?
- s = @header['transfer-encoding']
- (s and /(?:\A|[^\-\w])chunked(?:[^\-\w]|\z)/i === s) ? true : false
- end
-
- def content_range
- s = @header['content-range']
- s or return nil
-
- m = %r<bytes\s+(\d+)-(\d+)/(?:\d+|\*)>i.match( s )
- m or raise HTTPHeaderSyntaxError, 'wrong Content-Range format'
-
- m[1].to_i .. m[2].to_i + 1
- end
-
- def range_length
- r = content_range
- r and r.length
- end
-
- def basic_auth( acc, pass )
- @header['authorization'] = 'Basic ' + ["#{acc}:#{pass}"].pack('m').strip
- end
-
- end
-
-
- ###
- ### request
- ###
-
- class HTTPGenericRequest
-
- include HTTPHeader
-
- def initialize( m, reqbody, resbody, path, initheader = nil )
- @method = m
- @request_has_body = reqbody
- @response_has_body = resbody
- @path = path
-
- @header = tmp = {}
- return unless initheader
- initheader.each do |k,v|
- key = k.downcase
- if tmp.key? key then
- $stderr.puts "WARNING: duplicated HTTP header: #{k}" if $VERBOSE
- end
- tmp[ key ] = v.strip
- end
- tmp['accept'] ||= '*/*'
- end
-
- attr_reader :method
- attr_reader :path
-
- def inspect
- "\#<#{self.type} #{@method}>"
- end
-
- def request_body_permitted?
- @request_has_body
- end
-
- def response_body_permitted?
- @response_has_body
- end
-
- alias body_exist? response_body_permitted?
-
- #
- # write
- #
-
- private
-
- def exec( sock, ver, path, body )
- if body then
- check_body_premitted
- send_request_with_body sock, ver, path, body
- else
- request sock, ver, path
- end
- end
-
- def check_body_premitted
- request_body_permitted? or
- raise ArgumentError, 'HTTP request body is not premitted'
- end
-
- def send_request_with_body( sock, ver, path, body )
- if block_given? then
- ac = Accumulator.new
- yield ac # must be yield, DO NOT USE block.call
- data = ac.terminate
- else
- data = body
- end
- @header['content-length'] = data.size.to_s
- @header.delete 'transfer-encoding'
-
- unless @header['content-type'] then
- $stderr.puts 'Content-Type did not set; using application/x-www-form-urlencoded' if $VERBOSE
- @header['content-type'] = 'application/x-www-form-urlencoded'
- end
-
- request sock, ver, path
- sock.write data
- end
-
- def request( sock, ver, path )
- sock.writeline sprintf('%s %s HTTP/%s', @method, path, ver)
- canonical_each do |k,v|
- sock.writeline k + ': ' + v
- end
- sock.writeline ''
- end
-
- end
-
-
- class HTTPRequest < HTTPGenericRequest
-
- def initialize( path, initheader = nil )
- super type::METHOD,
- type::REQUEST_HAS_BODY,
- type::RESPONSE_HAS_BODY,
- path, initheader
- end
-
- end
-
-
- class HTTP
-
- class Get < HTTPRequest
- METHOD = 'GET'
- REQUEST_HAS_BODY = false
- RESPONSE_HAS_BODY = true
- end
-
- class Head < HTTPRequest
- METHOD = 'HEAD'
- REQUEST_HAS_BODY = false
- RESPONSE_HAS_BODY = false
- end
-
- class Post < HTTPRequest
- METHOD = 'POST'
- REQUEST_HAS_BODY = true
- RESPONSE_HAS_BODY = true
- end
-
- class Put < HTTPRequest
- METHOD = 'PUT'
- REQUEST_HAS_BODY = true
- RESPONSE_HAS_BODY = true
- end
-
- end
-
-
-
- ###
- ### response
- ###
-
- class HTTPResponse
- # predefine HTTPResponse class to allow inheritance
-
- def self.body_permitted?
- self::HAS_BODY
- end
-
- def self.exception_type
- self::EXCEPTION_TYPE
- end
- end
-
-
- class HTTPUnknownResponse < HTTPResponse
- HAS_BODY = true
- EXCEPTION_TYPE = ProtocolError
- end
- class HTTPInformation < HTTPResponse
- HAS_BODY = false
- EXCEPTION_TYPE = ProtocolError
- end
- class HTTPSuccess < HTTPResponse
- HAS_BODY = true
- EXCEPTION_TYPE = ProtocolError
- end
- class HTTPRedirection < HTTPResponse
- HAS_BODY = true
- EXCEPTION_TYPE = ProtoRetriableError
- end
- class HTTPClientError < HTTPResponse
- HAS_BODY = true
- EXCEPTION_TYPE = ProtoFatalError
- end
- class HTTPServerError < HTTPResponse
- HAS_BODY = true
- EXCEPTION_TYPE = ProtoServerError
- end
- class HTTPContinue < HTTPInformation
- HAS_BODY = false
- end
- class HTTPSwitchProtocol < HTTPInformation
- HAS_BODY = false
- end
- class HTTPOK < HTTPSuccess
- HAS_BODY = true
- end
- class HTTPCreated < HTTPSuccess
- HAS_BODY = true
- end
- class HTTPAccepted < HTTPSuccess
- HAS_BODY = true
- end
- class HTTPNonAuthoritativeInformation < HTTPSuccess
- HAS_BODY = true
- end
- class HTTPNoContent < HTTPSuccess
- HAS_BODY = false
- end
- class HTTPResetContent < HTTPSuccess
- HAS_BODY = false
- end
- class HTTPPartialContent < HTTPSuccess
- HAS_BODY = true
- end
- class HTTPMultipleChoice < HTTPRedirection
- HAS_BODY = true
- end
- class HTTPMovedPermanently < HTTPRedirection
- HAS_BODY = true
- end
- class HTTPMovedTemporarily < HTTPRedirection
- HAS_BODY = true
- end
- class HTTPNotModified < HTTPRedirection
- HAS_BODY = false
- end
- class HTTPUseProxy < HTTPRedirection
- HAS_BODY = false
- end
- class HTTPBadRequest < HTTPClientError
- HAS_BODY = true
- end
- class HTTPUnauthorized < HTTPClientError
- HAS_BODY = true
- end
- class HTTPPaymentRequired < HTTPClientError
- HAS_BODY = true
- end
- class HTTPForbidden < HTTPClientError
- HAS_BODY = true
- end
- class HTTPNotFound < HTTPClientError
- HAS_BODY = true
- end
- class HTTPMethodNotAllowed < HTTPClientError
- HAS_BODY = true
- end
- class HTTPNotAcceptable < HTTPClientError
- HAS_BODY = true
- end
- class HTTPProxyAuthenticationRequired < HTTPClientError
- HAS_BODY = true
- end
- class HTTPRequestTimeOut < HTTPClientError
- HAS_BODY = true
- end
- class HTTPConflict < HTTPClientError
- HAS_BODY = true
- end
- class HTTPGone < HTTPClientError
- HAS_BODY = true
- end
- class HTTPLengthRequired < HTTPClientError
- HAS_BODY = true
- end
- class HTTPPreconditionFailed < HTTPClientError
- HAS_BODY = true
- end
- class HTTPRequestEntityTooLarge < HTTPClientError
- HAS_BODY = true
- end
- class HTTPRequestURITooLarge < HTTPClientError
- HAS_BODY = true
- end
- class HTTPUnsupportedMediaType < HTTPClientError
- HAS_BODY = true
- end
- class HTTPInternalServerError < HTTPServerError
- HAS_BODY = true
- end
- class HTTPNotImplemented < HTTPServerError
- HAS_BODY = true
- end
- class HTTPBadGateway < HTTPServerError
- HAS_BODY = true
- end
- class HTTPServiceUnavailable < HTTPServerError
- HAS_BODY = true
- end
- class HTTPGatewayTimeOut < HTTPServerError
- HAS_BODY = true
- end
- class HTTPVersionNotSupported < HTTPServerError
- HAS_BODY = true
- end
-
-
- class HTTPResponse # redefine
-
- CODE_CLASS_TO_OBJ = {
- '1' => HTTPInformation,
- '2' => HTTPSuccess,
- '3' => HTTPRedirection,
- '4' => HTTPClientError,
- '5' => HTTPServerError
- }
- CODE_TO_OBJ = {
- '100' => HTTPContinue,
- '101' => HTTPSwitchProtocol,
-
- '200' => HTTPOK,
- '201' => HTTPCreated,
- '202' => HTTPAccepted,
- '203' => HTTPNonAuthoritativeInformation,
- '204' => HTTPNoContent,
- '205' => HTTPResetContent,
- '206' => HTTPPartialContent,
-
- '300' => HTTPMultipleChoice,
- '301' => HTTPMovedPermanently,
- '302' => HTTPMovedTemporarily,
- '304' => HTTPNotModified,
- '305' => HTTPUseProxy,
-
- '400' => HTTPBadRequest,
- '401' => HTTPUnauthorized,
- '402' => HTTPPaymentRequired,
- '403' => HTTPForbidden,
- '404' => HTTPNotFound,
- '405' => HTTPMethodNotAllowed,
- '406' => HTTPNotAcceptable,
- '407' => HTTPProxyAuthenticationRequired,
- '408' => HTTPRequestTimeOut,
- '409' => HTTPConflict,
- '410' => HTTPGone,
- '411' => HTTPLengthRequired,
- '412' => HTTPPreconditionFailed,
- '413' => HTTPRequestEntityTooLarge,
- '414' => HTTPRequestURITooLarge,
- '415' => HTTPUnsupportedMediaType,
-
- '501' => HTTPInternalServerError,
- '501' => HTTPNotImplemented,
- '502' => HTTPBadGateway,
- '503' => HTTPServiceUnavailable,
- '504' => HTTPGatewayTimeOut,
- '505' => HTTPVersionNotSupported
- }
-
-
- class << self
-
- def read_new( sock, hasbody )
- httpv, code, msg = read_status_line(sock)
- res = response_class(code).new( httpv, code, msg, sock, hasbody )
- each_response_header(sock) do |k,v|
- if res.key? k then
- res[k] << ', ' << v
- else
- res[k] = v
- end
- end
-
- res
- end
-
- private
-
- def read_status_line( sock )
- str = sock.readline
- m = /\AHTTP(?:\/(\d+\.\d+))?\s+(\d\d\d)\s*(.*)\z/in.match(str) or
- raise HTTPBadResponse, "wrong status line: #{str.dump}"
- m.to_a[1,3]
- end
-
- def response_class( code )
- CODE_TO_OBJ[code] or
- CODE_CLASS_TO_OBJ[code[0,1]] or
- HTTPUnknownResponse
- end
-
- def each_response_header( sock )
- while true do
- line = sock.readuntil( "\n", true ) # ignore EOF
- line.sub!( /\s+\z/, '' ) # don't use chop!
- break if line.empty?
-
- m = /\A([^:]+):\s*/.match(line) or
- raise HTTPBadResponse, 'wrong header line format'
- yield m[1], m.post_match
- end
- end
-
- end
-
-
- include HTTPHeader
-
- def initialize( httpv, code, msg, sock, hasbody )
- @http_version = httpv
- @code = code
- @message = msg
- @socket = sock
- @body_exist = hasbody
-
- @header = {}
- @body = nil
- @read = false
- end
-
- attr_reader :http_version
- attr_reader :code
- attr_reader :message
- alias msg message
-
- def inspect
- "#<#{type} #{@code} readbody=#{@read}>"
- end
-
- #
- # response <-> exception relationship
- #
-
- def code_type
- self.type
- end
-
- def error!
- raise error_type.new(@code + ' ' + @message.dump, self)
- end
-
- def error_type
- type::EXCEPTION_TYPE
- end
-
- def value
- HTTPSuccess === self or error!
- end
-
- #
- # header (for backward compatibility)
- #
-
- def response
- self
- end
-
- alias header response
- alias read_header response
-
- #
- # body
- #
-
- def read_body( dest = nil, &block )
- if @read then
- (dest or block) and
- raise IOError, "#{type}\#read_body called twice with argument"
- return @body
- end
-
- to = procdest(dest, block)
- stream_check
- if @body_exist and self.type.body_permitted? then
- read_body_0 to
- @body = to
- else
- @body = nil
- end
- @read = true
-
- @body
- end
-
- alias body read_body
- alias entity read_body
-
- private
-
- def terminate
- read_body
- end
-
- def read_body_0( dest )
- if chunked? then
- read_chunked dest
- else
- clen = content_length
- if clen then
- @socket.read clen, dest, true # ignore EOF
- else
- clen = range_length
- if clen then
- @socket.read clen, dest
- else
- @socket.read_all dest
- end
- end
- end
- end
-
- def read_chunked( dest )
- len = nil
- total = 0
-
- while true do
- line = @socket.readline
- m = /[0-9a-fA-F]+/.match(line)
- m or raise HTTPBadResponse, "wrong chunk size line: #{line}"
- len = m[0].hex
- break if len == 0
- @socket.read len, dest; total += len
- @socket.read 2 # \r\n
- end
- until @socket.readline.empty? do
- # none
- end
- end
-
- def stream_check
- @socket.closed? and raise IOError, 'try to read body out of block'
- end
-
- def procdest( dest, block )
- (dest and block) and
- raise ArgumentError, 'both of arg and block are given for HTTP method'
- if block then
- ReadAdapter.new(block)
- else
- dest || ''
- end
- end
-
- end
-
-
-
- # for backward compatibility
-
- module NetPrivate
- HTTPResponse = ::Net::HTTPResponse
- HTTPGenericRequest = ::Net::HTTPGenericRequest
- HTTPRequest = ::Net::HTTPRequest
- HTTPHeader = ::Net::HTTPHeader
- end
- HTTPInformationCode = HTTPInformation
- HTTPSuccessCode = HTTPSuccess
- HTTPRedirectionCode = HTTPRedirection
- HTTPRetriableCode = HTTPRedirection
- HTTPClientErrorCode = HTTPClientError
- HTTPFatalErrorCode = HTTPClientError
- HTTPServerErrorCode = HTTPServerError
- HTTPResponceReceiver = HTTPResponse
-
-end # module Net
diff --git a/lib/net/imap.rb b/lib/net/imap.rb
deleted file mode 100644
index e31b80a461..0000000000
--- a/lib/net/imap.rb
+++ /dev/null
@@ -1,2878 +0,0 @@
-=begin
-
-= net/imap.rb
-
-Copyright (C) 2000 Shugo Maeda <shugo@ruby-lang.org>
-
-This library is distributed under the terms of the Ruby license.
-You can freely distribute/modify this library.
-
-== Net::IMAP
-
-Net::IMAP implements Internet Message Access Protocol (IMAP) clients.
-(The protocol is described in ((<[IMAP]>)).)
-
-Net::IMAP supports multiple commands. For example,
-
- imap = Net::IMAP.new("imap.foo.net", "imap2")
- imap.authenticate("cram-md5", "bar", "password")
- imap.select("inbox")
- fetch_thread = Thread.start { imap.fetch(1..-1, "UID") }
- search_result = imap.search(["BODY", "hello"])
- fetch_result = fetch_thread.value
- imap.disconnect
-
-This script invokes the FETCH command and the SEARCH command concurrently.
-
-=== Super Class
-
-Object
-
-=== Class Methods
-
-: new(host, port = 143, usessl = false, certs = nil, verify = false)
- Creates a new Net::IMAP object and connects it to the specified
- port on the named host. If usessl is true, then an attempt will
- be made to use SSL (now TLS) to connect to the server. For this
- to work OpenSSL((<[OSSL]>)) and the Ruby OpenSSL((<[RSSL]>))
- extension need to be installed. The certs parameter indicates
- the path or file containing the CA cert of the server, and the
- verify parameter is for the OpenSSL verification callback.
-
-: debug
- Returns the debug mode.
-
-: debug = val
- Sets the debug mode.
-
-: add_authenticator(auth_type, authenticator)
- Adds an authenticator for Net::IMAP#authenticate.
-
-=== Methods
-
-: greeting
- Returns an initial greeting response from the server.
-
-: responses
- Returns recorded untagged responses.
-
- ex).
- imap.select("inbox")
- p imap.responses["EXISTS"][-1]
- #=> 2
- p imap.responses["UIDVALIDITY"][-1]
- #=> 968263756
-
-: disconnect
- Disconnects from the server.
-
-: capability
- Sends a CAPABILITY command, and returns a listing of
- capabilities that the server supports.
-
-: noop
- Sends a NOOP command to the server. It does nothing.
-
-: logout
- Sends a LOGOUT command to inform the server that the client is
- done with the connection.
-
-: authenticate(auth_type, arg...)
- Sends an AUTEHNTICATE command to authenticate the client.
- The auth_type parameter is a string that represents
- the authentication mechanism to be used. Currently Net::IMAP
- supports "LOGIN" and "CRAM-MD5" for the auth_type.
-
- ex).
- imap.authenticate('LOGIN', user, password)
-
-: login(user, password)
- Sends a LOGIN command to identify the client and carries
- the plaintext password authenticating this user.
-
-: select(mailbox)
- Sends a SELECT command to select a mailbox so that messages
- in the mailbox can be accessed.
-
-: examine(mailbox)
- Sends a EXAMINE command to select a mailbox so that messages
- in the mailbox can be accessed. However, the selected mailbox
- is identified as read-only.
-
-: create(mailbox)
- Sends a CREATE command to create a new mailbox.
-
-: delete(mailbox)
- Sends a DELETE command to remove the mailbox.
-
-: rename(mailbox, newname)
- Sends a RENAME command to change the name of the mailbox to
- the newname.
-
-: subscribe(mailbox)
- Sends a SUBSCRIBE command to add the specified mailbox name to
- the server's set of "active" or "subscribed" mailboxes.
-
-: unsubscribe(mailbox)
- Sends a UNSUBSCRIBE command to remove the specified mailbox name
- from the server's set of "active" or "subscribed" mailboxes.
-
-: list(refname, mailbox)
- Sends a LIST command, and returns a subset of names from
- the complete set of all names available to the client.
- The return value is an array of ((<Net::IMAP::MailboxList>)).
-
- ex).
- imap.create("foo/bar")
- imap.create("foo/baz")
- p imap.list("", "foo/%")
- #=> [#<Net::IMAP::MailboxList attr=[:Noselect], delim="/", name="foo/">, #<Net::IMAP::MailboxList attr=[:Noinferiors, :Marked], delim="/", name="foo/bar">, #<Net::IMAP::MailboxList attr=[:Noinferiors], delim="/", name="foo/baz">]
-
-: lsub(refname, mailbox)
- Sends a LSUB command, and returns a subset of names from the set
- of names that the user has declared as being "active" or
- "subscribed".
- The return value is an array of ((<Net::IMAP::MailboxList>)).
-
-: status(mailbox, attr)
- Sends a STATUS command, and returns the status of the indicated
- mailbox.
- The return value is a hash of attributes.
-
- ex).
- p imap.status("inbox", ["MESSAGES", "RECENT"])
- #=> {"RECENT"=>0, "MESSAGES"=>44}
-
-: append(mailbox, message, flags = nil, date_time = nil)
- Sends a APPEND command to append the message to the end of
- the mailbox.
-
- ex).
- imap.append("inbox", <<EOF.gsub(/\n/, "\r\n"), [:Seen], Time.now)
- Subject: hello
- From: shugo@ruby-lang.org
- To: shugo@ruby-lang.org
-
- hello world
- EOF
-
-: check
- Sends a CHECK command to request a checkpoint of the currently
- selected mailbox.
-
-: close
- Sends a CLOSE command to close the currently selected mailbox.
- The CLOSE command permanently removes from the mailbox all
- messages that have the \Deleted flag set.
-
-: expunge
- Sends a EXPUNGE command to permanently remove from the currently
- selected mailbox all messages that have the \Deleted flag set.
-
-: search(keys, charset = nil)
-: uid_search(keys, charset = nil)
- Sends a SEARCH command to search the mailbox for messages that
- match the given searching criteria, and returns message sequence
- numbers (search) or unique identifiers (uid_search).
-
- ex).
- p imap.search(["SUBJECT", "hello"])
- #=> [1, 6, 7, 8]
- p imap.search('SUBJECT "hello"')
- #=> [1, 6, 7, 8]
-
-: fetch(set, attr)
-: uid_fetch(set, attr)
- Sends a FETCH command to retrieve data associated with a message
- in the mailbox. the set parameter is a number or an array of
- numbers or a Range object. the number is a message sequence
- number (fetch) or a unique identifier (uid_fetch).
- The return value is an array of ((<Net::IMAP::FetchData>)).
-
- ex).
- p imap.fetch(6..8, "UID")
- #=> [#<Net::IMAP::FetchData seqno=6, attr={"UID"=>98}>, #<Net::IMAP::FetchData seqno=7, attr={"UID"=>99}>, #<Net::IMAP::FetchData seqno=8, attr={"UID"=>100}>]
- p imap.fetch(6, "BODY[HEADER.FIELDS (SUBJECT)]")
- #=> [#<Net::IMAP::FetchData seqno=6, attr={"BODY[HEADER.FIELDS (SUBJECT)]"=>"Subject: test\r\n\r\n"}>]
- data = imap.uid_fetch(98, ["RFC822.SIZE", "INTERNALDATE"])[0]
- p data.seqno
- #=> 6
- p data.attr["RFC822.SIZE"]
- #=> 611
- p data.attr["INTERNALDATE"]
- #=> "12-Oct-2000 22:40:59 +0900"
- p data.attr["UID"]
- #=> 98
-
-: store(set, attr, flags)
-: uid_store(set, attr, flags)
- Sends a STORE command to alter data associated with a message
- in the mailbox. the set parameter is a number or an array of
- numbers or a Range object. the number is a message sequence
- number (store) or a unique identifier (uid_store).
- The return value is an array of ((<Net::IMAP::FetchData>)).
-
- ex).
- p imap.store(6..8, "+FLAGS", [:Deleted])
- #=> [#<Net::IMAP::FetchData seqno=6, attr={"FLAGS"=>[:Seen, :Deleted]}>, #<Net::IMAP::FetchData seqno=7, attr={"FLAGS"=>[:Seen, :Deleted]}>, #<Net::IMAP::FetchData seqno=8, attr={"FLAGS"=>[:Seen, :Deleted]}>]
-
-: copy(set, mailbox)
-: uid_copy(set, mailbox)
- Sends a COPY command to copy the specified message(s) to the end
- of the specified destination mailbox. the set parameter is
- a number or an array of numbers or a Range object. the number is
- a message sequence number (copy) or a unique identifier (uid_copy).
-
-: sort(sort_keys, search_keys, charset)
-: uid_sort(sort_keys, search_keys, charset)
- Sends a SORT command to sort messages in the mailbox.
-
- ex).
- p imap.sort(["FROM"], ["ALL"], "US-ASCII")
- #=> [1, 2, 3, 5, 6, 7, 8, 4, 9]
- p imap.sort(["DATE"], ["SUBJECT", "hello"], "US-ASCII")
- #=> [6, 7, 8, 1]
-
-: setquota(mailbox, quota)
- Sends a SETQUOTA command along with the specified mailbox and
- quota. If quota is nil, then quota will be unset for that
- mailbox. Typically one needs to be logged in as server admin
- for this to work. The IMAP quota commands are described in
- ((<[RFC-2087]>)).
-
-: getquota(mailbox)
- Sends the GETQUOTA command along with specified mailbox.
- If this mailbox exists, then an array containing a
- ((<Net::IMAP::MailboxQuota>)) object is returned. This
- command generally is only available to server admin.
-
-: getquotaroot(mailbox)
- Sends the GETQUOTAROOT command along with specified mailbox.
- This command is generally available to both admin and user.
- If mailbox exists, returns an array containing objects of
- ((<Net::IMAP::MailboxQuotaRoot>)) and ((<Net::IMAP::MailboxQuota>)).
-
-: setacl(mailbox, user, rights)
- Sends the SETACL command along with mailbox, user and the
- rights that user is to have on that mailbox. If rights is nil,
- then that user will be stripped of any rights to that mailbox.
- The IMAP ACL commands are described in ((<[RFC-2086]>)).
-
-: getacl(mailbox)
- Send the GETACL command along with specified mailbox.
- If this mailbox exists, an array containing objects of
- ((<Net::IMAP::MailboxACLItem>)) will be returned.
-
-: add_response_handler(handler = Proc.new)
- Adds a response handler.
-
- ex).
- imap.add_response_handler do |resp|
- p resp
- end
-
-: remove_response_handler(handler)
- Removes the response handler.
-
-: response_handlers
- Returns all response handlers.
-
-== Net::IMAP::ContinuationRequest
-
-Net::IMAP::ContinuationRequest represents command continuation requests.
-
-The command continuation request response is indicated by a "+" token
-instead of a tag. This form of response indicates that the server is
-ready to accept the continuation of a command from the client. The
-remainder of this response is a line of text.
-
- continue_req ::= "+" SPACE (resp_text / base64)
-
-=== Super Class
-
-Struct
-
-=== Methods
-
-: data
- Returns the data (Net::IMAP::ResponseText).
-
-: raw_data
- Returns the raw data string.
-
-== Net::IMAP::UntaggedResponse
-
-Net::IMAP::UntaggedResponse represents untagged responses.
-
-Data transmitted by the server to the client and status responses
-that do not indicate command completion are prefixed with the token
-"*", and are called untagged responses.
-
- response_data ::= "*" SPACE (resp_cond_state / resp_cond_bye /
- mailbox_data / message_data / capability_data)
-
-=== Super Class
-
-Struct
-
-=== Methods
-
-: name
- Returns the name such as "FLAGS", "LIST", "FETCH"....
-
-: data
- Returns the data such as an array of flag symbols,
- a ((<Net::IMAP::MailboxList>)) object....
-
-: raw_data
- Returns the raw data string.
-
-== Net::IMAP::TaggedResponse
-
-Net::IMAP::TaggedResponse represents tagged responses.
-
-The server completion result response indicates the success or
-failure of the operation. It is tagged with the same tag as the
-client command which began the operation.
-
- response_tagged ::= tag SPACE resp_cond_state CRLF
-
- tag ::= 1*<any ATOM_CHAR except "+">
-
- resp_cond_state ::= ("OK" / "NO" / "BAD") SPACE resp_text
-
-=== Super Class
-
-Struct
-
-=== Methods
-
-: tag
- Returns the tag.
-
-: name
- Returns the name. the name is one of "OK", "NO", "BAD".
-
-: data
- Returns the data. See ((<Net::IMAP::ResponseText>)).
-
-: raw_data
- Returns the raw data string.
-
-== Net::IMAP::ResponseText
-
-Net::IMAP::ResponseText represents texts of responses.
-The text may be prefixed by the response code.
-
- resp_text ::= ["[" resp_text_code "]" SPACE] (text_mime2 / text)
- ;; text SHOULD NOT begin with "[" or "="
-
-=== Super Class
-
-Struct
-
-=== Methods
-
-: code
- Returns the response code. See ((<Net::IMAP::ResponseCode>)).
-
-: text
- Returns the text.
-
-== Net::IMAP::ResponseCode
-
-Net::IMAP::ResponseCode represents response codes.
-
- resp_text_code ::= "ALERT" / "PARSE" /
- "PERMANENTFLAGS" SPACE "(" #(flag / "\*") ")" /
- "READ-ONLY" / "READ-WRITE" / "TRYCREATE" /
- "UIDVALIDITY" SPACE nz_number /
- "UNSEEN" SPACE nz_number /
- atom [SPACE 1*<any TEXT_CHAR except "]">]
-
-=== SuperClass
-
-Struct
-
-=== Methods
-
-: name
- Returns the name such as "ALERT", "PERMANENTFLAGS", "UIDVALIDITY"....
-
-: data
- Returns the data if it exists.
-
-== Net::IMAP::MailboxList
-
-Net::IMAP::MailboxList represents contents of the LIST response.
-
- mailbox_list ::= "(" #("\Marked" / "\Noinferiors" /
- "\Noselect" / "\Unmarked" / flag_extension) ")"
- SPACE (<"> QUOTED_CHAR <"> / nil) SPACE mailbox
-
-=== Super Class
-
-Struct
-
-=== Methods
-
-: attr
- Returns the name attributes. Each name attribute is a symbol
- capitalized by String#capitalize, such as :Noselect (not :NoSelect).
-
-: delim
- Returns the hierarchy delimiter
-
-: name
- Returns the mailbox name.
-
-== Net::IMAP::MailboxQuota
-
-Net::IMAP::MailboxQuota represents contents of GETQUOTA response.
-This object can also be a response to GETQUOTAROOT. In the syntax
-specification below, the delimiter used with the "#" construct is a
-single space (SPACE).
-
- quota_list ::= "(" #quota_resource ")"
-
- quota_resource ::= atom SPACE number SPACE number
-
- quota_response ::= "QUOTA" SPACE astring SPACE quota_list
-
-=== Super Class
-
-Struct
-
-=== Methods
-
-: mailbox
- The mailbox with the associated quota.
-
-: usage
- Current storage usage of mailbox.
-
-: quota
- Quota limit imposed on mailbox.
-
-== Net::IMAP::MailboxQuotaRoot
-
-Net::IMAP::MailboxQuotaRoot represents part of the GETQUOTAROOT
-response. (GETQUOTAROOT can also return Net::IMAP::MailboxQuota.)
-
- quotaroot_response
- ::= "QUOTAROOT" SPACE astring *(SPACE astring)
-
-=== Super Class
-
-Struct
-
-=== Methods
-
-: mailbox
- The mailbox with the associated quota.
-
-: quotaroots
- Zero or more quotaroots that effect the quota on the
- specified mailbox.
-
-== Net::IMAP::MailboxACLItem
-
-Net::IMAP::MailboxACLItem represents response from GETACL.
-
- acl_data ::= "ACL" SPACE mailbox *(SPACE identifier SPACE
- rights)
-
- identifier ::= astring
-
- rights ::= astring
-
-=== Super Class
-
-Struct
-
-=== Methods
-
-: user
- Login name that has certain rights to the mailbox
- that was specified with the getacl command.
-
-: rights
- The access rights the indicated user has to the
- mailbox.
-
-== Net::IMAP::StatusData
-
-Net::IMAP::StatusData represents contents of the STATUS response.
-
-=== Super Class
-
-Object
-
-=== Methods
-
-: mailbox
- Returns the mailbox name.
-
-: attr
- Returns a hash. Each key is one of "MESSAGES", "RECENT", "UIDNEXT",
- "UIDVALIDITY", "UNSEEN". Each value is a number.
-
-== Net::IMAP::FetchData
-
-Net::IMAP::FetchData represents contents of the FETCH response.
-
-=== Super Class
-
-Object
-
-=== Methods
-
-: seqno
- Returns the message sequence number.
- (Note: not the unique identifier, even for the UID command response.)
-
-: attr
- Returns a hash. Each key is a data item name, and each value is
- its value.
-
- The current data items are:
-
- : BODY
- A form of BODYSTRUCTURE without extension data.
- : BODY[<section>]<<origin_octet>>
- A string expressing the body contents of the specified section.
- : BODYSTRUCTURE
- An object that describes the ((<[MIME-IMB]>)) body structure of a message.
- See ((<Net::IMAP::BodyTypeBasic>)), ((<Net::IMAP::BodyTypeText>)),
- ((<Net::IMAP::BodyTypeMessage>)), ((<Net::IMAP::BodyTypeMultipart>)).
- : ENVELOPE
- A ((<Net::IMAP::Envelope>)) object that describes the envelope
- structure of a message.
- : FLAGS
- A array of flag symbols that are set for this message. flag symbols
- are capitalized by String#capitalize.
- : INTERNALDATE
- A string representing the internal date of the message.
- : RFC822
- Equivalent to BODY[].
- : RFC822.HEADER
- Equivalent to BODY.PEEK[HEADER].
- : RFC822.SIZE
- A number expressing the ((<[RFC-822]>)) size of the message.
- : RFC822.TEXT
- Equivalent to BODY[TEXT].
- : UID
- A number expressing the unique identifier of the message.
-
-== Net::IMAP::Envelope
-
-Net::IMAP::Envelope represents envelope structures of messages.
-
-=== Super Class
-
-Struct
-
-=== Methods
-
-: date
- Retunns a string that represents the date.
-
-: subject
- Retunns a string that represents the subject.
-
-: from
- Retunns an array of ((<Net::IMAP::Address>)) that represents the from.
-
-: sender
- Retunns an array of ((<Net::IMAP::Address>)) that represents the sender.
-
-: reply_to
- Retunns an array of ((<Net::IMAP::Address>)) that represents the reply-to.
-
-: to
- Retunns an array of ((<Net::IMAP::Address>)) that represents the to.
-
-: cc
- Retunns an array of ((<Net::IMAP::Address>)) that represents the cc.
-
-: bcc
- Retunns an array of ((<Net::IMAP::Address>)) that represents the bcc.
-
-: in_reply_to
- Retunns a string that represents the in-reply-to.
-
-: message_id
- Retunns a string that represents the message-id.
-
-== Net::IMAP::Address
-
-((<Net::IMAP::Address>)) represents electronic mail addresses.
-
-=== Super Class
-
-Struct
-
-=== Methods
-
-: name
- Returns the phrase from ((<[RFC-822]>)) mailbox.
-
-: route
- Returns the route from ((<[RFC-822]>)) route-addr.
-
-: mailbox
- nil indicates end of ((<[RFC-822]>)) group.
- If non-nil and host is nil, returns ((<[RFC-822]>)) group name.
- Otherwise, returns ((<[RFC-822]>)) local-part
-
-: host
- nil indicates ((<[RFC-822]>)) group syntax.
- Otherwise, returns ((<[RFC-822]>)) domain name.
-
-== Net::IMAP::ContentDisposition
-
-Net::IMAP::ContentDisposition represents Content-Disposition fields.
-
-=== Super Class
-
-Struct
-
-=== Methods
-
-: dsp_type
- Returns the disposition type.
-
-: param
- Returns a hash that represents parameters of the Content-Disposition
- field.
-
-== Net::IMAP::BodyTypeBasic
-
-Net::IMAP::BodyTypeBasic represents basic body structures of messages.
-
-=== Super Class
-
-Struct
-
-=== Methods
-
-: media_type
- Returns the content media type name as defined in ((<[MIME-IMB]>)).
-
-: subtype
- Returns the content subtype name as defined in ((<[MIME-IMB]>)).
-
-: param
- Returns a hash that represents parameters as defined in
- ((<[MIME-IMB]>)).
-
-: content_id
- Returns a string giving the content id as defined in ((<[MIME-IMB]>)).
-
-: description
- Returns a string giving the content description as defined in
- ((<[MIME-IMB]>)).
-
-: encoding
- Returns a string giving the content transfer encoding as defined in
- ((<[MIME-IMB]>)).
-
-: size
- Returns a number giving the size of the body in octets.
-
-: md5
- Returns a string giving the body MD5 value as defined in ((<[MD5]>)).
-
-: disposition
- Returns a ((<Net::IMAP::ContentDisposition>)) object giving
- the content disposition.
-
-: language
- Returns a string or an array of strings giving the body
- language value as defined in [LANGUAGE-TAGS].
-
-: extension
- Returns extension data.
-
-: multipart?
- Returns false.
-
-== Net::IMAP::BodyTypeText
-
-Net::IMAP::BodyTypeText represents TEXT body structures of messages.
-
-=== Super Class
-
-Struct
-
-=== Methods
-
-: lines
- Returns the size of the body in text lines.
-
-And Net::IMAP::BodyTypeText has all methods of ((<Net::IMAP::BodyTypeBasic>)).
-
-== Net::IMAP::BodyTypeMessage
-
-Net::IMAP::BodyTypeMessage represents MESSAGE/RFC822 body structures of messages.
-
-=== Super Class
-
-Struct
-
-=== Methods
-
-: envelope
- Returns a ((<Net::IMAP::Envelope>)) giving the envelope structure.
-
-: body
- Returns an object giving the body structure.
-
-And Net::IMAP::BodyTypeMessage has all methods of ((<Net::IMAP::BodyTypeText>)).
-
-== Net::IMAP::BodyTypeText
-
-=== Super Class
-
-Struct
-
-=== Methods
-
-: media_type
- Returns the content media type name as defined in ((<[MIME-IMB]>)).
-
-: subtype
- Returns the content subtype name as defined in ((<[MIME-IMB]>)).
-
-: parts
- Returns multiple parts.
-
-: param
- Returns a hash that represents parameters as defined in
- ((<[MIME-IMB]>)).
-
-: disposition
- Returns a ((<Net::IMAP::ContentDisposition>)) object giving
- the content disposition.
-
-: language
- Returns a string or an array of strings giving the body
- language value as defined in [LANGUAGE-TAGS].
-
-: extension
- Returns extension data.
-
-: multipart?
- Returns true.
-
-== References
-
-: [IMAP]
- M. Crispin, "INTERNET MESSAGE ACCESS PROTOCOL - VERSION 4rev1",
- RFC 2060, December 1996.
-
-: [LANGUAGE-TAGS]
- Alvestrand, H., "Tags for the Identification of
- Languages", RFC 1766, March 1995.
-
-: [MD5]
- Myers, J., and M. Rose, "The Content-MD5 Header Field", RFC
- 1864, October 1995.
-
-: [MIME-IMB]
- Freed, N., and N. Borenstein, "MIME (Multipurpose Internet
- Mail Extensions) Part One: Format of Internet Message Bodies", RFC
- 2045, November 1996.
-
-: [RFC-822]
- Crocker, D., "Standard for the Format of ARPA Internet Text
- Messages", STD 11, RFC 822, University of Delaware, August 1982.
-
-: [RFC-2087]
- Myers, J., "IMAP4 QUOTA extension", RFC 2087, January 1997.
-
-: [RFC-2086]
- Myers, J., "IMAP4 ACL extension", RFC 2086, January 1997.
-
-: [OSSL]
- http://www.openssl.org
-
-: [RSSL]
- http://savannah.gnu.org/projects/rubypki
-
-=end
-
-require "socket"
-require "monitor"
-require "digest/md5"
-begin
- require "openssl"
-rescue LoadError
-end
-
-module Net
- class IMAP
- include MonitorMixin
- if defined?(OpenSSL)
- include OpenSSL
- include SSL
- end
-
- attr_reader :greeting, :responses, :response_handlers
-
- SEEN = :Seen
- ANSWERED = :Answered
- FLAGGED = :Flagged
- DELETED = :Deleted
- DRAFT = :Draft
- RECENT = :Recent
-
- NOINFERIORS = :Noinferiors
- NOSELECT = :Noselect
- MARKED = :Marked
- UNMARKED = :Unmarked
-
- def self.debug
- return @@debug
- end
-
- def self.debug=(val)
- return @@debug = val
- end
-
- def self.add_authenticator(auth_type, authenticator)
- @@authenticators[auth_type] = authenticator
- end
-
- def disconnect
- @sock.shutdown unless @usessl
- @receiver_thread.join
- @sock.close
- end
-
- def capability
- synchronize do
- send_command("CAPABILITY")
- return @responses.delete("CAPABILITY")[-1]
- end
- end
-
- def noop
- send_command("NOOP")
- end
-
- def logout
- send_command("LOGOUT")
- end
-
- def authenticate(auth_type, *args)
- auth_type = auth_type.upcase
- unless @@authenticators.has_key?(auth_type)
- raise ArgumentError,
- format('unknown auth type - "%s"', auth_type)
- end
- authenticator = @@authenticators[auth_type].new(*args)
- send_command("AUTHENTICATE", auth_type) do |resp|
- if resp.instance_of?(ContinuationRequest)
- data = authenticator.process(resp.data.text.unpack("m")[0])
- send_data([data].pack("m").chomp)
- end
- end
- end
-
- def login(user, password)
- send_command("LOGIN", user, password)
- end
-
- def select(mailbox)
- synchronize do
- @responses.clear
- send_command("SELECT", mailbox)
- end
- end
-
- def examine(mailbox)
- synchronize do
- @responses.clear
- send_command("EXAMINE", mailbox)
- end
- end
-
- def create(mailbox)
- send_command("CREATE", mailbox)
- end
-
- def delete(mailbox)
- send_command("DELETE", mailbox)
- end
-
- def rename(mailbox, newname)
- send_command("RENAME", mailbox, newname)
- end
-
- def subscribe(mailbox)
- send_command("SUBSCRIBE", mailbox)
- end
-
- def unsubscribe(mailbox)
- send_command("UNSUBSCRIBE", mailbox)
- end
-
- def list(refname, mailbox)
- synchronize do
- send_command("LIST", refname, mailbox)
- return @responses.delete("LIST")
- end
- end
-
- def getquotaroot(mailbox)
- synchronize do
- send_command("GETQUOTAROOT", mailbox)
- result = []
- result.concat(@responses.delete("QUOTAROOT"))
- result.concat(@responses.delete("QUOTA"))
- return result
- end
- end
-
- def getquota(mailbox)
- synchronize do
- send_command("GETQUOTA", mailbox)
- return @responses.delete("QUOTA")
- end
- end
-
- # setquota(mailbox, nil) will unset quota.
- def setquota(mailbox, quota)
- if quota.nil?
- data = '()'
- else
- data = '(STORAGE ' + quota.to_s + ')'
- end
- send_command("SETQUOTA", mailbox, RawData.new(data))
- end
-
- # setacl(mailbox, user, nil) will remove rights.
- def setacl(mailbox, user, rights)
- if rights.nil?
- send_command("SETACL", mailbox, user, "")
- else
- send_command("SETACL", mailbox, user, rights)
- end
- end
-
- def getacl(mailbox)
- synchronize do
- send_command("GETACL", mailbox)
- return @responses.delete("ACL")[-1]
- end
- end
-
- def lsub(refname, mailbox)
- synchronize do
- send_command("LSUB", refname, mailbox)
- return @responses.delete("LSUB")
- end
- end
-
- def status(mailbox, attr)
- synchronize do
- send_command("STATUS", mailbox, attr)
- return @responses.delete("STATUS")[-1].attr
- end
- end
-
- def append(mailbox, message, flags = nil, date_time = nil)
- args = []
- if flags
- args.push(flags)
- end
- args.push(date_time) if date_time
- args.push(Literal.new(message))
- send_command("APPEND", mailbox, *args)
- end
-
- def check
- send_command("CHECK")
- end
-
- def close
- send_command("CLOSE")
- end
-
- def expunge
- synchronize do
- send_command("EXPUNGE")
- return @responses.delete("EXPUNGE")
- end
- end
-
- def search(keys, charset = nil)
- return search_internal("SEARCH", keys, charset)
- end
-
- def uid_search(keys, charset = nil)
- return search_internal("UID SEARCH", keys, charset)
- end
-
- def fetch(set, attr)
- return fetch_internal("FETCH", set, attr)
- end
-
- def uid_fetch(set, attr)
- return fetch_internal("UID FETCH", set, attr)
- end
-
- def store(set, attr, flags)
- return store_internal("STORE", set, attr, flags)
- end
-
- def uid_store(set, attr, flags)
- return store_internal("UID STORE", set, attr, flags)
- end
-
- def copy(set, mailbox)
- copy_internal("COPY", set, mailbox)
- end
-
- def uid_copy(set, mailbox)
- copy_internal("UID COPY", set, mailbox)
- end
-
- def sort(sort_keys, search_keys, charset)
- return sort_internal("SORT", sort_keys, search_keys, charset)
- end
-
- def uid_sort(sort_keys, search_keys, charset)
- return sort_internal("UID SORT", sort_keys, search_keys, charset)
- end
-
- def add_response_handler(handler = Proc.new)
- @response_handlers.push(handler)
- end
-
- def remove_response_handler(handler)
- @response_handlers.delete(handler)
- end
-
- private
-
- CRLF = "\r\n"
- PORT = 143
-
- @@debug = false
- @@authenticators = {}
-
- def initialize(host, port = PORT, usessl = false, certs = nil, verify = false)
- super()
- @host = host
- @port = port
- @tag_prefix = "RUBY"
- @tagno = 0
- @parser = ResponseParser.new
- @sock = TCPSocket.open(host, port)
- if usessl
- unless defined?(OpenSSL)
- raise "SSL extension not installed"
- end
- @usessl = true
- @sock = SSLSocket.new(@sock)
-
- # verify the server.
- @sock.ca_file = certs if certs && FileTest::file?(certs)
- @sock.ca_path = certs if certs && FileTest::directory?(certs)
- @sock.verify_mode = VERIFY_PEER if verify
- @sock.verify_callback = VerifyCallbackProc if defined?(VerifyCallbackProc)
-
- @sock.connect # start ssl session.
- else
- @usessl = false
- end
- @responses = Hash.new([].freeze)
- @tagged_responses = {}
- @response_handlers = []
- @tag_arrival = new_cond
-
- @greeting = get_response
- if /\ABYE\z/ni =~ @greeting.name
- @sock.close
- raise ByeResponseError, resp[0]
- end
-
- @receiver_thread = Thread.start {
- receive_responses
- }
- end
-
- def receive_responses
- while resp = get_response
- synchronize do
- case resp
- when TaggedResponse
- @tagged_responses[resp.tag] = resp
- @tag_arrival.broadcast
- when UntaggedResponse
- record_response(resp.name, resp.data)
- if resp.data.instance_of?(ResponseText) &&
- (code = resp.data.code)
- record_response(code.name, code.data)
- end
- end
- @response_handlers.each do |handler|
- handler.call(resp)
- end
- end
- end
- end
-
- def get_tagged_response(tag, cmd)
- until @tagged_responses.key?(tag)
- @tag_arrival.wait
- end
- resp = @tagged_responses.delete(tag)
- case resp.name
- when /\A(?:NO)\z/ni
- raise NoResponseError, resp.data.text
- when /\A(?:BAD)\z/ni
- raise BadResponseError, resp.data.text
- else
- return resp
- end
- end
-
- def get_response
- buff = ""
- while true
- s = @sock.gets(CRLF)
- break unless s
- buff.concat(s)
- if /\{(\d+)\}\r\n/n =~ s
- s = @sock.read($1.to_i)
- buff.concat(s)
- else
- break
- end
- end
- return nil if buff.length == 0
- if @@debug
- $stderr.print(buff.gsub(/^/n, "S: "))
- end
- return @parser.parse(buff)
- end
-
- def record_response(name, data)
- unless @responses.has_key?(name)
- @responses[name] = []
- end
- @responses[name].push(data)
- end
-
- def send_command(cmd, *args, &block)
- synchronize do
- tag = generate_tag
- data = args.collect {|i| format_data(i)}.join(" ")
- if data.length > 0
- put_line(tag + " " + cmd + " " + data)
- else
- put_line(tag + " " + cmd)
- end
- if block
- add_response_handler(block)
- end
- begin
- return get_tagged_response(tag, cmd)
- ensure
- if block
- remove_response_handler(block)
- end
- end
- end
- end
-
- def generate_tag
- @tagno += 1
- return format("%s%04d", @tag_prefix, @tagno)
- end
-
- def send_data(*args)
- data = args.collect {|i| format_data(i)}.join(" ")
- put_line(data)
- end
-
- def put_line(line)
- line = line + CRLF
- @sock.print(line)
- if @@debug
- $stderr.print(line.gsub(/^/n, "C: "))
- end
- end
-
- def format_data(data)
- case data
- when nil
- return "NIL"
- when String
- return format_string(data)
- when Integer
- return format_number(data)
- when Array
- return format_list(data)
- when Time
- return format_time(data)
- when Symbol
- return format_symbol(data)
- else
- return data.format_data
- end
- end
-
- def format_string(str)
- case str
- when ""
- return '""'
- when /[\x80-\xff\r\n]/n
- # literal
- return "{" + str.length.to_s + "}" + CRLF + str
- when /[(){ \x00-\x1f\x7f%*"\\]/n
- # quoted string
- return '"' + str.gsub(/["\\]/n, "\\\\\\&") + '"'
- else
- # atom
- return str
- end
- end
-
- def format_number(num)
- if num < 0 || num >= 4294967296
- raise DataFormatError, num.to_s
- end
- return num.to_s
- end
-
- def format_list(list)
- contents = list.collect {|i| format_data(i)}.join(" ")
- return "(" + contents + ")"
- end
-
- DATE_MONTH = %w(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)
-
- def format_time(time)
- t = time.dup.gmtime
- return format('"%2d-%3s-%4d %02d:%02d:%02d +0000"',
- t.day, DATE_MONTH[t.month - 1], t.year,
- t.hour, t.min, t.sec)
- end
-
- def format_symbol(symbol)
- return "\\" + symbol.to_s
- end
-
- def search_internal(cmd, keys, charset)
- if keys.instance_of?(String)
- keys = [RawData.new(keys)]
- else
- normalize_searching_criteria(keys)
- end
- synchronize do
- if charset
- send_command(cmd, "CHARSET", charset, *keys)
- else
- send_command(cmd, *keys)
- end
- return @responses.delete("SEARCH")[-1]
- end
- end
-
- def fetch_internal(cmd, set, attr)
- if attr.instance_of?(String)
- attr = RawData.new(attr)
- end
- synchronize do
- @responses.delete("FETCH")
- send_command(cmd, MessageSet.new(set), attr)
- return @responses.delete("FETCH")
- end
- end
-
- def store_internal(cmd, set, attr, flags)
- if attr.instance_of?(String)
- attr = RawData.new(attr)
- end
- synchronize do
- @responses.delete("FETCH")
- send_command(cmd, MessageSet.new(set), attr, flags)
- return @responses.delete("FETCH")
- end
- end
-
- def copy_internal(cmd, set, mailbox)
- send_command(cmd, MessageSet.new(set), mailbox)
- end
-
- def sort_internal(cmd, sort_keys, search_keys, charset)
- if search_keys.instance_of?(String)
- search_keys = [RawData.new(search_keys)]
- else
- normalize_searching_criteria(search_keys)
- end
- normalize_searching_criteria(search_keys)
- synchronize do
- send_command(cmd, sort_keys, charset, *search_keys)
- return @responses.delete("SORT")[-1]
- end
- end
-
- def normalize_searching_criteria(keys)
- keys.collect! do |i|
- case i
- when -1, Range, Array
- MessageSet.new(i)
- else
- i
- end
- end
- end
-
- class RawData
- def format_data
- return @data
- end
-
- private
-
- def initialize(data)
- @data = data
- end
- end
-
- class Atom
- def format_data
- return @data
- end
-
- private
-
- def initialize(data)
- @data = data
- end
- end
-
- class QuotedString
- def format_data
- return '"' + @data.gsub(/["\\]/n, "\\\\\\&") + '"'
- end
-
- private
-
- def initialize(data)
- @data = data
- end
- end
-
- class Literal
- def format_data
- return "{" + @data.length.to_s + "}" + CRLF + @data
- end
-
- private
-
- def initialize(data)
- @data = data
- end
- end
-
- class MessageSet
- def format_data
- return format_internal(@data)
- end
-
- private
-
- def initialize(data)
- @data = data
- end
-
- def format_internal(data)
- case data
- when "*"
- return data
- when Integer
- ensure_nz_number(data)
- if data == -1
- return "*"
- else
- return data.to_s
- end
- when Range
- return format_internal(data.first) +
- ":" + format_internal(data.last)
- when Array
- return data.collect {|i| format_internal(i)}.join(",")
- else
- raise DataFormatError, data.inspect
- end
- end
-
- def ensure_nz_number(num)
- if num < -1 || num == 0 || num >= 4294967296
- raise DataFormatError, num.inspect
- end
- end
- end
-
- ContinuationRequest = Struct.new(:data, :raw_data)
- UntaggedResponse = Struct.new(:name, :data, :raw_data)
- TaggedResponse = Struct.new(:tag, :name, :data, :raw_data)
- ResponseText = Struct.new(:code, :text)
- ResponseCode = Struct.new(:name, :data)
- MailboxList = Struct.new(:attr, :delim, :name)
- MailboxQuota = Struct.new(:mailbox, :usage, :quota)
- MailboxQuotaRoot = Struct.new(:mailbox, :quotaroots)
- MailboxACLItem = Struct.new(:user, :rights)
- StatusData = Struct.new(:mailbox, :attr)
- FetchData = Struct.new(:seqno, :attr)
- Envelope = Struct.new(:date, :subject, :from, :sender, :reply_to,
- :to, :cc, :bcc, :in_reply_to, :message_id)
- Address = Struct.new(:name, :route, :mailbox, :host)
- ContentDisposition = Struct.new(:dsp_type, :param)
-
- class BodyTypeBasic < Struct.new(:media_type, :subtype,
- :param, :content_id,
- :description, :encoding, :size,
- :md5, :disposition, :language,
- :extension)
- def multipart?
- return false
- end
-
- def media_subtype
- $stderr.printf("warning: media_subtype is obsolete.\n")
- $stderr.printf(" use subtype instead.\n")
- return subtype
- end
- end
-
- class BodyTypeText < Struct.new(:media_type, :subtype,
- :param, :content_id,
- :description, :encoding, :size,
- :lines,
- :md5, :disposition, :language,
- :extension)
- def multipart?
- return false
- end
-
- def media_subtype
- $stderr.printf("warning: media_subtype is obsolete.\n")
- $stderr.printf(" use subtype instead.\n")
- return subtype
- end
- end
-
- class BodyTypeMessage < Struct.new(:media_type, :subtype,
- :param, :content_id,
- :description, :encoding, :size,
- :envelope, :body, :lines,
- :md5, :disposition, :language,
- :extension)
- def multipart?
- return false
- end
-
- def media_subtype
- $stderr.printf("warning: media_subtype is obsolete.\n")
- $stderr.printf(" use subtype instead.\n")
- return subtype
- end
- end
-
- class BodyTypeMultipart < Struct.new(:media_type, :subtype,
- :parts,
- :param, :disposition, :language,
- :extension)
- def multipart?
- return true
- end
-
- def media_subtype
- $stderr.printf("warning: media_subtype is obsolete.\n")
- $stderr.printf(" use subtype instead.\n")
- return subtype
- end
- end
-
- class ResponseParser
- def parse(str)
- @str = str
- @pos = 0
- @lex_state = EXPR_BEG
- @token = nil
- return response
- end
-
- private
-
- EXPR_BEG = :EXPR_BEG
- EXPR_DATA = :EXPR_DATA
- EXPR_TEXT = :EXPR_TEXT
- EXPR_RTEXT = :EXPR_RTEXT
- EXPR_CTEXT = :EXPR_CTEXT
-
- T_SPACE = :SPACE
- T_NIL = :NIL
- T_NUMBER = :NUMBER
- T_ATOM = :ATOM
- T_QUOTED = :QUOTED
- T_LPAR = :LPAR
- T_RPAR = :RPAR
- T_BSLASH = :BSLASH
- T_STAR = :STAR
- T_LBRA = :LBRA
- T_RBRA = :RBRA
- T_LITERAL = :LITERAL
- T_PLUS = :PLUS
- T_PERCENT = :PERCENT
- T_CRLF = :CRLF
- T_EOF = :EOF
- T_TEXT = :TEXT
-
- BEG_REGEXP = /\G(?:\
-(?# 1: SPACE )( )|\
-(?# 2: NIL )(NIL)(?=[\x80-\xff(){ \x00-\x1f\x7f%*"\\\[\]+])|\
-(?# 3: NUMBER )(\d+)(?=[\x80-\xff(){ \x00-\x1f\x7f%*"\\\[\]+])|\
-(?# 4: ATOM )([^\x80-\xff(){ \x00-\x1f\x7f%*"\\\[\]+]+)|\
-(?# 5: QUOTED )"((?:[^\x80-\xff\x00\r\n"\\]|\\["\\])*)"|\
-(?# 6: LPAR )(\()|\
-(?# 7: RPAR )(\))|\
-(?# 8: BSLASH )(\\)|\
-(?# 9: STAR )(\*)|\
-(?# 10: LBRA )(\[)|\
-(?# 11: RBRA )(\])|\
-(?# 12: LITERAL )\{(\d+)\}\r\n|\
-(?# 13: PLUS )(\+)|\
-(?# 14: PERCENT )(%)|\
-(?# 15: CRLF )(\r\n)|\
-(?# 16: EOF )(\z))/ni
-
- DATA_REGEXP = /\G(?:\
-(?# 1: SPACE )( )|\
-(?# 2: NIL )(NIL)|\
-(?# 3: NUMBER )(\d+)|\
-(?# 4: QUOTED )"((?:[^\x80-\xff\x00\r\n"\\]|\\["\\])*)"|\
-(?# 5: LITERAL )\{(\d+)\}\r\n|\
-(?# 6: LPAR )(\()|\
-(?# 7: RPAR )(\)))/ni
-
- TEXT_REGEXP = /\G(?:\
-(?# 1: TEXT )([^\x00\x80-\xff\r\n]*))/ni
-
- RTEXT_REGEXP = /\G(?:\
-(?# 1: LBRA )(\[)|\
-(?# 2: TEXT )([^\x00\x80-\xff\r\n]*))/ni
-
- CTEXT_REGEXP = /\G(?:\
-(?# 1: TEXT )([^\x00\x80-\xff\r\n\]]*))/ni
-
- Token = Struct.new(:symbol, :value)
-
- def response
- token = lookahead
- case token.symbol
- when T_PLUS
- result = continue_req
- when T_STAR
- result = response_untagged
- else
- result = response_tagged
- end
- match(T_CRLF)
- match(T_EOF)
- return result
- end
-
- def continue_req
- match(T_PLUS)
- match(T_SPACE)
- return ContinuationRequest.new(resp_text, @str)
- end
-
- def response_untagged
- match(T_STAR)
- match(T_SPACE)
- token = lookahead
- if token.symbol == T_NUMBER
- return numeric_response
- elsif token.symbol == T_ATOM
- case token.value
- when /\A(?:OK|NO|BAD|BYE|PREAUTH)\z/ni
- return response_cond
- when /\A(?:FLAGS)\z/ni
- return flags_response
- when /\A(?:LIST|LSUB)\z/ni
- return list_response
- when /\A(?:QUOTA)\z/ni
- return getquota_response
- when /\A(?:QUOTAROOT)\z/ni
- return getquotaroot_response
- when /\A(?:ACL)\z/ni
- return getacl_response
- when /\A(?:SEARCH|SORT)\z/ni
- return search_response
- when /\A(?:STATUS)\z/ni
- return status_response
- when /\A(?:CAPABILITY)\z/ni
- return capability_response
- else
- return text_response
- end
- else
- parse_error("unexpected token %s", token.symbol)
- end
- end
-
- def response_tagged
- tag = atom
- match(T_SPACE)
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- return TaggedResponse.new(tag, name, resp_text, @str)
- end
-
- def response_cond
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- return UntaggedResponse.new(name, resp_text, @str)
- end
-
- def numeric_response
- n = number
- match(T_SPACE)
- token = match(T_ATOM)
- name = token.value.upcase
- case name
- when "EXISTS", "RECENT", "EXPUNGE"
- return UntaggedResponse.new(name, n, @str)
- when "FETCH"
- shift_token
- match(T_SPACE)
- data = FetchData.new(n, msg_att)
- return UntaggedResponse.new(name, data, @str)
- end
- end
-
- def msg_att
- match(T_LPAR)
- attr = {}
- while true
- token = lookahead
- case token.symbol
- when T_RPAR
- shift_token
- break
- when T_SPACE
- shift_token
- token = lookahead
- end
- case token.value
- when /\A(?:ENVELOPE)\z/ni
- name, val = envelope_data
- when /\A(?:FLAGS)\z/ni
- name, val = flags_data
- when /\A(?:INTERNALDATE)\z/ni
- name, val = internaldate_data
- when /\A(?:RFC822(?:\.HEADER|\.TEXT)?)\z/ni
- name, val = rfc822_text
- when /\A(?:RFC822\.SIZE)\z/ni
- name, val = rfc822_size
- when /\A(?:BODY(?:STRUCTURE)?)\z/ni
- name, val = body_data
- when /\A(?:UID)\z/ni
- name, val = uid_data
- else
- parse_error("unknown attribute `%s'", token.value)
- end
- attr[name] = val
- end
- return attr
- end
-
- def envelope_data
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- return name, envelope
- end
-
- def envelope
- @lex_state = EXPR_DATA
- match(T_LPAR)
- date = nstring
- match(T_SPACE)
- subject = nstring
- match(T_SPACE)
- from = address_list
- match(T_SPACE)
- sender = address_list
- match(T_SPACE)
- reply_to = address_list
- match(T_SPACE)
- to = address_list
- match(T_SPACE)
- cc = address_list
- match(T_SPACE)
- bcc = address_list
- match(T_SPACE)
- in_reply_to = nstring
- match(T_SPACE)
- message_id = nstring
- match(T_RPAR)
- @lex_state = EXPR_BEG
- return Envelope.new(date, subject, from, sender, reply_to,
- to, cc, bcc, in_reply_to, message_id)
- end
-
- def flags_data
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- return name, flag_list
- end
-
- def internaldate_data
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- token = match(T_QUOTED)
- return name, token.value
- end
-
- def rfc822_text
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- return name, nstring
- end
-
- def rfc822_size
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- return name, number
- end
-
- def body_data
- token = match(T_ATOM)
- name = token.value.upcase
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- return name, body
- end
- name.concat(section)
- token = lookahead
- if token.symbol == T_ATOM
- name.concat(token.value)
- shift_token
- end
- match(T_SPACE)
- data = nstring
- return name, data
- end
-
- def body
- @lex_state = EXPR_DATA
- match(T_LPAR)
- token = lookahead
- if token.symbol == T_LPAR
- result = body_type_mpart
- else
- result = body_type_1part
- end
- match(T_RPAR)
- @lex_state = EXPR_BEG
- return result
- end
-
- def body_type_1part
- token = lookahead
- case token.value
- when /\A(?:TEXT)\z/ni
- return body_type_text
- when /\A(?:MESSAGE)\z/ni
- return body_type_msg
- else
- return body_type_basic
- end
- end
-
- def body_type_basic
- mtype, msubtype = media_type
- match(T_SPACE)
- param, content_id, desc, enc, size = body_fields
- md5, disposition, language, extension = body_ext_1part
- return BodyTypeBasic.new(mtype, msubtype,
- param, content_id,
- desc, enc, size,
- md5, disposition, language, extension)
- end
-
- def body_type_text
- mtype, msubtype = media_type
- match(T_SPACE)
- param, content_id, desc, enc, size = body_fields
- match(T_SPACE)
- lines = number
- md5, disposition, language, extension = body_ext_1part
- return BodyTypeText.new(mtype, msubtype,
- param, content_id,
- desc, enc, size,
- lines,
- md5, disposition, language, extension)
- end
-
- def body_type_msg
- mtype, msubtype = media_type
- match(T_SPACE)
- param, content_id, desc, enc, size = body_fields
- match(T_SPACE)
- env = envelope
- match(T_SPACE)
- b = body
- match(T_SPACE)
- lines = number
- md5, disposition, language, extension = body_ext_1part
- return BodyTypeMessage.new(mtype, msubtype,
- param, content_id,
- desc, enc, size,
- env, b, lines,
- md5, disposition, language, extension)
- end
-
- def body_type_mpart
- parts = []
- while true
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- break
- end
- parts.push(body)
- end
- mtype = "MULTIPART"
- msubtype = string.upcase
- param, disposition, language, extension = body_ext_mpart
- return BodyTypeMultipart.new(mtype, msubtype, parts,
- param, disposition, language,
- extension)
- end
-
- def media_type
- mtype = string.upcase
- match(T_SPACE)
- msubtype = string.upcase
- return mtype, msubtype
- end
-
- def body_fields
- param = body_fld_param
- match(T_SPACE)
- content_id = nstring
- match(T_SPACE)
- desc = nstring
- match(T_SPACE)
- enc = string.upcase
- match(T_SPACE)
- size = number
- return param, content_id, desc, enc, size
- end
-
- def body_fld_param
- token = lookahead
- if token.symbol == T_NIL
- shift_token
- return nil
- end
- match(T_LPAR)
- param = {}
- while true
- token = lookahead
- case token.symbol
- when T_RPAR
- shift_token
- break
- when T_SPACE
- shift_token
- end
- name = string.upcase
- match(T_SPACE)
- val = string
- param[name] = val
- end
- return param
- end
-
- def body_ext_1part
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- else
- return nil
- end
- md5 = nstring
-
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- else
- return md5
- end
- disposition = body_fld_dsp
-
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- else
- return md5, disposition
- end
- language = body_fld_lang
-
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- else
- return md5, disposition, language
- end
-
- extension = body_extensions
- return md5, disposition, language, extension
- end
-
- def body_ext_mpart
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- else
- return nil
- end
- param = body_fld_param
-
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- else
- return param
- end
- disposition = body_fld_dsp
- match(T_SPACE)
- language = body_fld_lang
-
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- else
- return param, disposition, language
- end
-
- extension = body_extensions
- return param, disposition, language, extension
- end
-
- def body_fld_dsp
- token = lookahead
- if token.symbol == T_NIL
- shift_token
- return nil
- end
- match(T_LPAR)
- dsp_type = string.upcase
- match(T_SPACE)
- param = body_fld_param
- match(T_RPAR)
- return ContentDisposition.new(dsp_type, param)
- end
-
- def body_fld_lang
- token = lookahead
- if token.symbol == T_LPAR
- shift_token
- result = []
- while true
- token = lookahead
- case token.symbol
- when T_RPAR
- shift_token
- return result
- when T_SPACE
- shift_token
- end
- result.push(string.upcase)
- end
- else
- lang = nstring
- if lang
- return lang.upcase
- else
- return lang
- end
- end
- end
-
- def body_extensions
- result = []
- while true
- token = lookahead
- case token.symbol
- when T_RPAR
- return result
- when T_SPACE
- shift_token
- end
- result.push(body_extension)
- end
- end
-
- def body_extension
- token = lookahead
- case token.symbol
- when T_LPAR
- shift_token
- result = body_extensions
- match(T_RPAR)
- return result
- when T_NUMBER
- return number
- else
- return nstring
- end
- end
-
- def section
- str = ""
- token = match(T_LBRA)
- str.concat(token.value)
- token = match(T_ATOM, T_NUMBER, T_RBRA)
- if token.symbol == T_RBRA
- str.concat(token.value)
- return str
- end
- str.concat(token.value)
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- str.concat(token.value)
- token = match(T_LPAR)
- str.concat(token.value)
- while true
- token = lookahead
- case token.symbol
- when T_RPAR
- str.concat(token.value)
- shift_token
- break
- when T_SPACE
- shift_token
- str.concat(token.value)
- end
- str.concat(format_string(astring))
- end
- end
- token = match(T_RBRA)
- str.concat(token.value)
- return str
- end
-
- def format_string(str)
- case str
- when ""
- return '""'
- when /[\x80-\xff\r\n]/n
- # literal
- return "{" + str.length.to_s + "}" + CRLF + str
- when /[(){ \x00-\x1f\x7f%*"\\]/n
- # quoted string
- return '"' + str.gsub(/["\\]/n, "\\\\\\&") + '"'
- else
- # atom
- return str
- end
- end
-
- def uid_data
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- return name, number
- end
-
- def text_response
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- @lex_state = EXPR_TEXT
- token = match(T_TEXT)
- @lex_state = EXPR_BEG
- return UntaggedResponse.new(name, token.value)
- end
-
- def flags_response
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- return UntaggedResponse.new(name, flag_list, @str)
- end
-
- def list_response
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- return UntaggedResponse.new(name, mailbox_list, @str)
- end
-
- def mailbox_list
- attr = flag_list
- match(T_SPACE)
- token = match(T_QUOTED, T_NIL)
- if token.symbol == T_NIL
- delim = nil
- else
- delim = token.value
- end
- match(T_SPACE)
- name = astring
- return MailboxList.new(attr, delim, name)
- end
-
- def getquota_response
- # If quota never established, get back
- # `NO Quota root does not exist'.
- # If quota removed, get `()' after the
- # folder spec with no mention of `STORAGE'.
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- mailbox = astring
- match(T_SPACE)
- match(T_LPAR)
- token = lookahead
- case token.symbol
- when T_RPAR
- shift_token
- data = MailboxQuota.new(mailbox, nil, nil)
- return UntaggedResponse.new(name, data, @str)
- when T_ATOM
- shift_token
- match(T_SPACE)
- token = match(T_NUMBER)
- usage = token.value
- match(T_SPACE)
- token = match(T_NUMBER)
- quota = token.value
- match(T_RPAR)
- data = MailboxQuota.new(mailbox, usage, quota)
- return UntaggedResponse.new(name, data, @str)
- else
- parse_error("unexpected token %s", token.symbol)
- end
- end
-
- def getquotaroot_response
- # Similar to getquota, but only admin can use getquota.
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- mailbox = astring
- quotaroots = []
- while true
- token = lookahead
- break unless token.symbol == T_SPACE
- shift_token
- quotaroots.push(astring)
- end
- data = MailboxQuotaRoot.new(mailbox, quotaroots)
- return UntaggedResponse.new(name, data, @str)
- end
-
- def getacl_response
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- mailbox = astring
- data = []
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- while true
- token = lookahead
- case token.symbol
- when T_CRLF
- break
- when T_SPACE
- shift_token
- end
- user = astring
- match(T_SPACE)
- rights = astring
- ##XXX data.push([user, rights])
- data.push(MailboxACLItem.new(user, rights))
- end
- end
- return UntaggedResponse.new(name, data, @str)
- end
-
- def search_response
- token = match(T_ATOM)
- name = token.value.upcase
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- data = []
- while true
- token = lookahead
- case token.symbol
- when T_CRLF
- break
- when T_SPACE
- shift_token
- end
- data.push(number)
- end
- else
- data = []
- end
- return UntaggedResponse.new(name, data, @str)
- end
-
- def status_response
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- mailbox = astring
- match(T_SPACE)
- match(T_LPAR)
- attr = {}
- while true
- token = lookahead
- case token.symbol
- when T_RPAR
- shift_token
- break
- when T_SPACE
- shift_token
- end
- token = match(T_ATOM)
- key = token.value.upcase
- match(T_SPACE)
- val = number
- attr[key] = val
- end
- data = StatusData.new(mailbox, attr)
- return UntaggedResponse.new(name, data, @str)
- end
-
- def capability_response
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- data = []
- while true
- token = lookahead
- case token.symbol
- when T_CRLF
- break
- when T_SPACE
- shift_token
- end
- data.push(atom.upcase)
- end
- return UntaggedResponse.new(name, data, @str)
- end
-
- def resp_text
- @lex_state = EXPR_RTEXT
- token = lookahead
- if token.symbol == T_LBRA
- code = resp_text_code
- else
- code = nil
- end
- token = match(T_TEXT)
- @lex_state = EXPR_BEG
- return ResponseText.new(code, token.value)
- end
-
- def resp_text_code
- @lex_state = EXPR_BEG
- match(T_LBRA)
- token = match(T_ATOM)
- name = token.value.upcase
- case name
- when /\A(?:ALERT|PARSE|READ-ONLY|READ-WRITE|TRYCREATE)\z/n
- result = ResponseCode.new(name, nil)
- when /\A(?:PERMANENTFLAGS)\z/n
- match(T_SPACE)
- result = ResponseCode.new(name, flag_list)
- when /\A(?:UIDVALIDITY|UIDNEXT|UNSEEN)\z/n
- match(T_SPACE)
- result = ResponseCode.new(name, number)
- else
- match(T_SPACE)
- @lex_state = EXPR_CTEXT
- token = match(T_TEXT)
- @lex_state = EXPR_BEG
- result = ResponseCode.new(name, token.value)
- end
- match(T_RBRA)
- @lex_state = EXPR_RTEXT
- return result
- end
-
- def address_list
- token = lookahead
- if token.symbol == T_NIL
- shift_token
- return nil
- else
- result = []
- match(T_LPAR)
- while true
- token = lookahead
- case token.symbol
- when T_RPAR
- shift_token
- break
- when T_SPACE
- shift_token
- end
- result.push(address)
- end
- return result
- end
- end
-
- ADDRESS_REGEXP = /\G\
-(?# 1: NAME )(?:NIL|"((?:[^\x80-\xff\x00\r\n"\\]|\\["\\])*)") \
-(?# 2: ROUTE )(?:NIL|"((?:[^\x80-\xff\x00\r\n"\\]|\\["\\])*)") \
-(?# 3: MAILBOX )(?:NIL|"((?:[^\x80-\xff\x00\r\n"\\]|\\["\\])*)") \
-(?# 4: HOST )(?:NIL|"((?:[^\x80-\xff\x00\r\n"\\]|\\["\\])*)")\
-\)/ni
-
- def address
- match(T_LPAR)
- if @str.index(ADDRESS_REGEXP, @pos)
- # address does not include literal.
- @pos = $~.end(0)
- name = $1
- route = $2
- mailbox = $3
- host = $4
- for s in [name, route, mailbox, host]
- if s
- s.gsub!(/\\(["\\])/n, "\\1")
- end
- end
- else
- name = nstring
- match(T_SPACE)
- route = nstring
- match(T_SPACE)
- mailbox = nstring
- match(T_SPACE)
- host = nstring
- match(T_RPAR)
- end
- return Address.new(name, route, mailbox, host)
- end
-
-# def flag_list
-# result = []
-# match(T_LPAR)
-# while true
-# token = lookahead
-# case token.symbol
-# when T_RPAR
-# shift_token
-# break
-# when T_SPACE
-# shift_token
-# end
-# result.push(flag)
-# end
-# return result
-# end
-
-# def flag
-# token = lookahead
-# if token.symbol == T_BSLASH
-# shift_token
-# token = lookahead
-# if token.symbol == T_STAR
-# shift_token
-# return token.value.intern
-# else
-# return atom.intern
-# end
-# else
-# return atom
-# end
-# end
-
- FLAG_REGEXP = /\
-(?# FLAG )\\([^\x80-\xff(){ \x00-\x1f\x7f%"\\]+)|\
-(?# ATOM )([^\x80-\xff(){ \x00-\x1f\x7f%*"\\]+)/n
-
- def flag_list
- if @str.index(/\(([^)]*)\)/ni, @pos)
- @pos = $~.end(0)
- return $1.scan(FLAG_REGEXP).collect { |flag, atom|
- atom || flag.capitalize.intern
- }
- else
- parse_error("invalid flag list")
- end
- end
-
- def nstring
- token = lookahead
- if token.symbol == T_NIL
- shift_token
- return nil
- else
- return string
- end
- end
-
- def astring
- token = lookahead
- if string_token?(token)
- return string
- else
- return atom
- end
- end
-
- def string
- token = match(T_QUOTED, T_LITERAL)
- return token.value
- end
-
- STRING_TOKENS = [T_QUOTED, T_LITERAL]
-
- def string_token?(token)
- return STRING_TOKENS.include?(token.symbol)
- end
-
- def atom
- result = ""
- while true
- token = lookahead
- if atom_token?(token)
- result.concat(token.value)
- shift_token
- else
- if result.empty?
- parse_error("unexpected token %s", token.symbol)
- else
- return result
- end
- end
- end
- end
-
- ATOM_TOKENS = [
- T_ATOM,
- T_NUMBER,
- T_NIL,
- T_LBRA,
- T_RBRA,
- T_PLUS
- ]
-
- def atom_token?(token)
- return ATOM_TOKENS.include?(token.symbol)
- end
-
- def number
- token = match(T_NUMBER)
- return token.value.to_i
- end
-
- def nil_atom
- match(T_NIL)
- return nil
- end
-
- def match(*args)
- token = lookahead
- unless args.include?(token.symbol)
- parse_error('unexpected token %s (expected %s)',
- token.symbol.id2name,
- args.collect {|i| i.id2name}.join(" or "))
- end
- shift_token
- return token
- end
-
- def lookahead
- unless @token
- @token = next_token
- end
- return @token
- end
-
- def shift_token
- @token = nil
- end
-
- def next_token
- case @lex_state
- when EXPR_BEG
- if @str.index(BEG_REGEXP, @pos)
- @pos = $~.end(0)
- if $1
- return Token.new(T_SPACE, $+)
- elsif $2
- return Token.new(T_NIL, $+)
- elsif $3
- return Token.new(T_NUMBER, $+)
- elsif $4
- return Token.new(T_ATOM, $+)
- elsif $5
- return Token.new(T_QUOTED,
- $+.gsub(/\\(["\\])/n, "\\1"))
- elsif $6
- return Token.new(T_LPAR, $+)
- elsif $7
- return Token.new(T_RPAR, $+)
- elsif $8
- return Token.new(T_BSLASH, $+)
- elsif $9
- return Token.new(T_STAR, $+)
- elsif $10
- return Token.new(T_LBRA, $+)
- elsif $11
- return Token.new(T_RBRA, $+)
- elsif $12
- len = $+.to_i
- val = @str[@pos, len]
- @pos += len
- return Token.new(T_LITERAL, val)
- elsif $13
- return Token.new(T_PLUS, $+)
- elsif $14
- return Token.new(T_PERCENT, $+)
- elsif $15
- return Token.new(T_CRLF, $+)
- elsif $16
- return Token.new(T_EOF, $+)
- else
- parse_error("[Net::IMAP BUG] BEG_REGEXP is invalid")
- end
- else
- @str.index(/\S*/n, @pos)
- parse_error("unknown token - %s", $&.dump)
- end
- when EXPR_DATA
- if @str.index(DATA_REGEXP, @pos)
- @pos = $~.end(0)
- if $1
- return Token.new(T_SPACE, $+)
- elsif $2
- return Token.new(T_NIL, $+)
- elsif $3
- return Token.new(T_NUMBER, $+)
- elsif $4
- return Token.new(T_QUOTED,
- $+.gsub(/\\(["\\])/n, "\\1"))
- elsif $5
- len = $+.to_i
- val = @str[@pos, len]
- @pos += len
- return Token.new(T_LITERAL, val)
- elsif $6
- return Token.new(T_LPAR, $+)
- elsif $7
- return Token.new(T_RPAR, $+)
- else
- parse_error("[Net::IMAP BUG] BEG_REGEXP is invalid")
- end
- else
- @str.index(/\S*/n, @pos)
- parse_error("unknown token - %s", $&.dump)
- end
- when EXPR_TEXT
- if @str.index(TEXT_REGEXP, @pos)
- @pos = $~.end(0)
- if $1
- return Token.new(T_TEXT, $+)
- else
- parse_error("[Net::IMAP BUG] TEXT_REGEXP is invalid")
- end
- else
- @str.index(/\S*/n, @pos)
- parse_error("unknown token - %s", $&.dump)
- end
- when EXPR_RTEXT
- if @str.index(RTEXT_REGEXP, @pos)
- @pos = $~.end(0)
- if $1
- return Token.new(T_LBRA, $+)
- elsif $2
- return Token.new(T_TEXT, $+)
- else
- parse_error("[Net::IMAP BUG] RTEXT_REGEXP is invalid")
- end
- else
- @str.index(/\S*/n, @pos)
- parse_error("unknown token - %s", $&.dump)
- end
- when EXPR_CTEXT
- if @str.index(CTEXT_REGEXP, @pos)
- @pos = $~.end(0)
- if $1
- return Token.new(T_TEXT, $+)
- else
- parse_error("[Net::IMAP BUG] CTEXT_REGEXP is invalid")
- end
- else
- @str.index(/\S*/n, @pos) #/
- parse_error("unknown token - %s", $&.dump)
- end
- else
- parse_error("illegal @lex_state - %s", @lex_state.inspect)
- end
- end
-
- def parse_error(fmt, *args)
- if IMAP.debug
- $stderr.printf("@str: %s\n", @str.dump)
- $stderr.printf("@pos: %d\n", @pos)
- $stderr.printf("@lex_state: %s\n", @lex_state)
- if @token.symbol
- $stderr.printf("@token.symbol: %s\n", @token.symbol)
- $stderr.printf("@token.value: %s\n", @token.value.inspect)
- end
- end
- raise ResponseParseError, format(fmt, *args)
- end
- end
-
- class LoginAuthenticator
- def process(data)
- case @state
- when STATE_USER
- @state = STATE_PASSWORD
- return @user
- when STATE_PASSWORD
- return @password
- end
- end
-
- private
-
- STATE_USER = :USER
- STATE_PASSWORD = :PASSWORD
-
- def initialize(user, password)
- @user = user
- @password = password
- @state = STATE_USER
- end
- end
- add_authenticator "LOGIN", LoginAuthenticator
-
- class CramMD5Authenticator
- def process(challenge)
- digest = hmac_md5(challenge, @password)
- return @user + " " + digest
- end
-
- private
-
- def initialize(user, password)
- @user = user
- @password = password
- end
-
- def hmac_md5(text, key)
- if key.length > 64
- key = Digest::MD5.digest(key)
- end
-
- k_ipad = key + "\0" * (64 - key.length)
- k_opad = key + "\0" * (64 - key.length)
- for i in 0..63
- k_ipad[i] ^= 0x36
- k_opad[i] ^= 0x5c
- end
-
- digest = Digest::MD5.digest(k_ipad + text)
-
- return Digest::MD5.hexdigest(k_opad + digest)
- end
- end
- add_authenticator "CRAM-MD5", CramMD5Authenticator
-
- class Error < StandardError
- end
-
- class DataFormatError < Error
- end
-
- class ResponseParseError < Error
- end
-
- class ResponseError < Error
- end
-
- class NoResponseError < ResponseError
- end
-
- class BadResponseError < ResponseError
- end
-
- class ByeResponseError < ResponseError
- end
- end
-end
-
-if __FILE__ == $0
- require "getoptlong"
-
- $stdout.sync = true
- $port = "imap2"
- $user = ENV["USER"] || ENV["LOGNAME"]
- $auth = "cram-md5"
-
- def usage
- $stderr.print <<EOF
-usage: #{$0} [options] <host>
-
- --help print this message
- --port=PORT specifies port
- --user=USER specifies user
- --auth=AUTH specifies auth type
-EOF
- end
-
- def get_password
- print "password: "
- system("stty", "-echo")
- begin
- return gets.chop
- ensure
- system("stty", "echo")
- print "\n"
- end
- end
-
- def get_command
- printf("%s@%s> ", $user, $host)
- if line = gets
- return line.strip.split(/\s+/)
- else
- return nil
- end
- end
-
- parser = GetoptLong.new
- parser.set_options(['--help', GetoptLong::NO_ARGUMENT],
- ['--port', GetoptLong::REQUIRED_ARGUMENT],
- ['--user', GetoptLong::REQUIRED_ARGUMENT],
- ['--auth', GetoptLong::REQUIRED_ARGUMENT])
- begin
- parser.each_option do |name, arg|
- case name
- when "--port"
- $port = arg
- when "--user"
- $user = arg
- when "--auth"
- $auth = arg
- when "--help"
- usage
- exit(1)
- end
- end
- rescue
- usage
- exit(1)
- end
-
- $host = ARGV.shift
- unless $host
- usage
- exit(1)
- end
-
- imap = Net::IMAP.new($host, $port)
- begin
- password = get_password
- imap.authenticate($auth, $user, password)
- while true
- cmd, *args = get_command
- break unless cmd
- begin
- case cmd
- when "list"
- for mbox in imap.list("", args[0] || "*")
- if mbox.attr.include?(Net::IMAP::NOSELECT)
- prefix = "!"
- elsif mbox.attr.include?(Net::IMAP::MARKED)
- prefix = "*"
- else
- prefix = " "
- end
- print prefix, mbox.name, "\n"
- end
- when "select"
- imap.select(args[0] || "inbox")
- print "ok\n"
- when "close"
- imap.close
- print "ok\n"
- when "summary"
- unless messages = imap.responses["EXISTS"][-1]
- puts "not selected"
- next
- end
- if messages > 0
- for data in imap.fetch(1..-1, ["ENVELOPE"])
- print data.seqno, ": ", data.attr["ENVELOPE"].subject, "\n"
- end
- else
- puts "no message"
- end
- when "fetch"
- if args[0]
- data = imap.fetch(args[0].to_i, ["RFC822.HEADER", "RFC822.TEXT"])[0]
- puts data.attr["RFC822.HEADER"]
- puts data.attr["RFC822.TEXT"]
- else
- puts "missing argument"
- end
- when "logout", "exit", "quit"
- break
- when "help", "?"
- print <<EOF
-list [pattern] list mailboxes
-select [mailbox] select mailbox
-close close mailbox
-summary display summary
-fetch [msgno] display message
-logout logout
-help, ? display help message
-EOF
- else
- print "unknown command: ", cmd, "\n"
- end
- rescue Net::IMAP::Error
- puts $!
- end
- end
- ensure
- imap.logout
- imap.disconnect
- end
-end
diff --git a/lib/net/pop.rb b/lib/net/pop.rb
deleted file mode 100644
index af32e8835a..0000000000
--- a/lib/net/pop.rb
+++ /dev/null
@@ -1,631 +0,0 @@
-=begin
-
-= net/pop.rb
-
-Copyright (c) 1999-2002 Yukihiro Matsumoto
-
-written & maintained by Minero Aoki <aamine@loveruby.net>
-
-This program is free software. You can re-distribute and/or
-modify this program under the same terms as Ruby itself,
-Ruby Distribute License or GNU General Public License.
-
-NOTE: You can find Japanese version of this document in
-the doc/net directory of the standard ruby interpreter package.
-
-$Id$
-
-== What is This Module?
-
-This module provides your program the functions to retrieve
-mails via POP3, Post Office Protocol version 3. For details
-of POP3, refer [RFC1939] ((<URL:http://www.ietf.org/rfc/rfc1939.txt>)).
-
-== Examples
-
-=== Retrieving Mails
-
-This example retrieves mails from server and delete it (on server).
-Mails are written in file named 'inbox/1', 'inbox/2', ....
-Replace 'pop3.server.address' your POP3 server address.
-
- require 'net/pop'
-
- pop = Net::POP3.new( 'pop3.server.address', 110 )
- pop.start( 'YourAccount', 'YourPassword' ) ###
- if pop.mails.empty? then
- puts 'no mail.'
- else
- i = 0
- pop.each_mail do |m| # or "pop.mails.each ..."
- File.open( 'inbox/' + i.to_s, 'w' ) {|f|
- f.write m.pop
- }
- m.delete
- i += 1
- end
- puts "#{pop.mails.size} mails popped."
- end
- pop.finish ###
-
-(1) call Net::POP3#start and start POP session
-(2) access mails by using POP3#each_mail and/or POP3#mails
-(3) close POP session by calling POP3#finish or use block form #start.
-
-This example is using block form #start to close the session.
-=== Enshort Code
-
-The example above is very verbose. You can enshort code by using
-some utility methods. At first, block form of Net::POP3.start can
-alternates POP3.new, POP3#start and POP3#finish.
-
- require 'net/pop'
-
- Net::POP3.start( 'pop3.server.address', 110 )
- 'YourAccount', 'YourPassword' )
- if pop.mails.empty? then
- puts 'no mail.'
- else
- i = 0
- pop.each_mail do |m| # or "pop.mails.each ..."
- File.open( 'inbox/' + i.to_s, 'w' ) {|f|
- f.write m.pop
- }
- m.delete
- i += 1
- end
- puts "#{pop.mails.size} mails popped."
- end
- }
-
-POP3#delete_all alternates #each_mail and m.delete.
-
- require 'net/pop'
-
- Net::POP3.start( 'pop3.server.address', 110,
- 'YourAccount', 'YourPassword' ) {|pop|
- if pop.mails.empty? then
- puts 'no mail.'
- else
- i = 0
- pop.delete_all do |m|
- File.open( 'inbox/' + i.to_s, 'w' ) {|f|
- f.write m.pop
- }
- i += 1
- end
- end
- }
-
-And here is more shorter example.
-
- require 'net/pop'
-
- i = 0
- Net::POP3.delete_all( 'pop3.server.address', 110,
- 'YourAccount', 'YourPassword' ) do |m|
- File.open( 'inbox/' + i.to_s, 'w' ) {|f|
- f.write m.pop
- }
- i += 1
- end
-
-=== Writing to File directly
-
-All examples above get mail as one big string.
-This example does not create such one.
-
- require 'net/pop'
- Net::POP3.delete_all( 'pop3.server.address', 110,
- 'YourAccount', 'YourPassword' ) do |m|
- File.open( 'inbox', 'w' ) {|f|
- m.pop f ####
- }
- end
-
-=== Using APOP
-
-The net/pop library supports APOP authentication.
-To use APOP, use Net::APOP class instead of Net::POP3 class.
-You can use utility method, Net::POP3.APOP(). Example:
-
- require 'net/pop'
-
- # use APOP authentication if $isapop == true
- pop = Net::POP3.APOP($isapop).new( 'apop.server.address', 110 )
- pop.start( YourAccount', 'YourPassword' ) {|pop|
- # Rest code is same.
- }
-
-
-== Net::POP3 class
-
-=== Class Methods
-
-: new( address, port = 110, apop = false )
- creates a new Net::POP3 object.
- This method does not open TCP connection yet.
-
-: start( address, port = 110, account, password )
-: start( address, port = 110, account, password ) {|pop| .... }
- equals to Net::POP3.new( address, port ).start( account, password )
-
- Net::POP3.start( addr, port, account, password ) {|pop|
- pop.each_mail do |m|
- file.write m.pop
- m.delete
- end
- }
-
-: APOP( is_apop )
- returns Net::APOP class object if IS_APOP is true.
- returns Net::POP3 class object if false.
- Use this method like:
-
- # example 1
- pop = Net::POP3::APOP($isapop).new( addr, port )
-
- # example 2
- Net::POP3::APOP($isapop).start( addr, port ) {|pop|
- ....
- }
-
-: foreach( address, port = 110, account, password ) {|mail| .... }
- starts POP3 protocol and iterates for each POPMail object.
- This method equals to
-
- Net::POP3.start( address, port, account, password ) {|pop|
- pop.each_mail do |m|
- yield m
- end
- }
-
- # example
- Net::POP3.foreach( 'your.pop.server', 110,
- 'YourAccount', 'YourPassword' ) do |m|
- file.write m.pop
- m.delete if $DELETE
- end
-
-: delete_all( address, port = 110, account, password )
-: delete_all( address, port = 110, account, password ) {|mail| .... }
- starts POP3 session and delete all mails.
- If block is given, iterates for each POPMail object before delete.
-
- # example
- Net::POP3.delete_all( addr, nil, 'YourAccount', 'YourPassword' ) do |m|
- m.pop file
- end
-
-: auth_only( address, port = 110, account, password )
- (just for POP-before-SMTP)
- opens POP3 session and does autholize and quit.
- This method must not be called while POP3 session is opened.
-
- # example
- Net::POP3.auth_only( 'your.pop3.server',
- nil, # using default (110)
- 'YourAccount',
- 'YourPassword' )
-
-=== Instance Methods
-
-: start( account, password )
-: start( account, password ) {|pop| .... }
- starts POP3 session.
-
- When called with block, gives a POP3 object to block and
- closes the session after block call finish.
-
-: active?
- true if POP3 session is started.
-
-: address
- the address to connect
-
-: port
- the port number to connect
-
-: open_timeout
-: open_timeout=(n)
- seconds to wait until connection is opened.
- If POP3 object cannot open a conection in this seconds,
- it raises TimeoutError exception.
-
-: read_timeout
-: read_timeout=(n)
- seconds to wait until reading one block (by one read(1) call).
- If POP3 object cannot open a conection in this seconds,
- it raises TimeoutError exception.
-
-: finish
- finishes POP3 session.
- If POP3 session had not be started, raises an IOError.
-
-: mails
- an array of Net::POPMail objects.
- This array is renewed when session started.
-
-: each_mail {|popmail| .... }
-: each {|popmail| .... }
- is equals to "pop3.mails.each"
-
-: delete_all
-: delete_all {|popmail| .... }
- deletes all mails on server.
- If called with block, gives mails to the block before deleting.
-
- # example
- n = 1
- pop.delete_all do |m|
- File.open("inbox/#{n}") {|f| f.write m.pop }
- n += 1
- end
-
-: auth_only( account, password )
- (just for POP-before-SMTP)
- opens POP3 session and does autholize and quit.
- This method must not be called while POP3 session is opened.
- # example
- pop = Net::POP3.new( 'your.pop3.server' )
- pop.auth_only 'YourAccount', 'YourPassword'
-
-: reset
- reset the session. All "deleted mark" are removed.
-
-== Net::APOP
-
-This class defines no new methods.
-Only difference from POP3 is using APOP authentification.
-
-=== Super Class
-Net::POP3
-
-== Net::POPMail
-
-A class of mail which exists on POP server.
-
-=== Instance Methods
-
-: pop( dest = '' )
- This method fetches a mail and write to 'dest' using '<<' method.
-
- # example
- allmails = nil
- POP3.start( 'your.pop3.server', 110,
- 'YourAccount, 'YourPassword' ) {|pop|
- allmails = pop.mails.collect {|popmail| popmail.pop }
- }
-
-: pop {|str| .... }
- gives the block part strings of a mail.
-
- # example
- POP3.start( 'localhost', 110 ) {|pop3|
- pop3.each_mail do |m|
- m.pop do |str|
- # do anything
- end
- end
- }
-
-: header
- This method fetches only mail header.
-
-: top( lines )
- This method fetches mail header and LINES lines of body.
-
-: delete
- deletes mail on server.
-
-: size
- mail size (bytes)
-
-: deleted?
- true if mail was deleted
-
-=end
-
-require 'net/protocol'
-require 'digest/md5'
-
-
-module Net
-
- class POP3 < Protocol
-
- protocol_param :default_port, '110'
- protocol_param :command_type, '::Net::POP3Command'
- protocol_param :apop_command_type, '::Net::APOPCommand'
- protocol_param :mail_type, '::Net::POPMail'
- protocol_param :socket_type, '::Net::InternetMessageIO'
-
-
- def POP3.APOP( bool )
- bool ? APOP : POP3
- end
-
- def POP3.foreach( address, port = nil,
- account = nil, password = nil, &block )
- start( address, port, account, password ) {|pop|
- pop.each_mail( &block )
- }
- end
-
- def POP3.delete_all( address, port = nil,
- account = nil, password = nil, &block )
- start( address, port, account, password ) {|pop|
- pop.delete_all( &block )
- }
- end
-
- def POP3.auth_only( address, port = nil,
- account = nil, password = nil )
- new( address, port ).auth_only account, password
- end
-
-
- def auth_only( account, password )
- raise IOError, 'opening already opened POP session' if active?
- start( account, password ) {
- # none
- }
- end
-
-
- #
- # connection
- #
-
- def initialize( addr, port = nil, apop = false )
- super addr, port
- @mails = nil
- @apop = false
- end
-
- private
-
- def do_start( account, password )
- conn_socket
- @command = (@apop ? type.apop_command_type : type.command_type).new(socket())
- @command.auth account, password
- end
-
- def do_finish
- @mails = nil
- disconn_command
- disconn_socket
- end
-
-
- #
- # POP operations
- #
-
- public
-
- def mails
- return @mails if @mails
-
- mails = []
- mtype = type.mail_type
- command().list.each_with_index do |size,idx|
- mails.push mtype.new(idx, size, command()) if size
- end
- @mails = mails.freeze
- end
-
- def each_mail( &block )
- mails().each( &block )
- end
-
- alias each each_mail
-
- def delete_all
- mails().each do |m|
- yield m if block_given?
- m.delete unless m.deleted?
- end
- end
-
- def reset
- command().rset
- mails().each do |m|
- m.instance_eval { @deleted = false }
- end
- end
-
-
- def command
- io_check
- super
- end
-
- def io_check
- (not socket() or socket().closed?) and
- raise IOError, 'POP session is not opened yet'
- end
-
- end
-
- POP = POP3
- POPSession = POP3
- POP3Session = POP3
-
-
- class APOP < POP3
- def APOP.command_type
- APOPCommand
- end
- end
-
- APOPSession = APOP
-
-
- class POPMail
-
- def initialize( n, s, cmd )
- @num = n
- @size = s
- @command = cmd
-
- @deleted = false
- end
-
- attr :size
-
- def inspect
- "#<#{type} #{@num}#{@deleted ? ' deleted' : ''}>"
- end
-
- def pop( dest = '', &block )
- if block then
- dest = ReadAdapter.new(block)
- end
- @command.retr @num, dest
- end
-
- alias all pop
- alias mail pop
-
- def top( lines, dest = '' )
- @command.top @num, lines, dest
- end
-
- def header( dest = '' )
- top 0, dest
- end
-
- def delete
- @command.dele @num
- @deleted = true
- end
-
- alias delete! delete
-
- def deleted?
- @deleted
- end
-
- def uidl
- @command.uidl @num
- end
-
- end
-
-
- class POP3Command < Command
-
- def initialize( sock )
- super
- atomic {
- check_reply SuccessCode
- }
- end
-
- def auth( account, pass )
- atomic {
- @socket.writeline 'USER ' + account
- check_reply_auth
-
- @socket.writeline 'PASS ' + pass
- check_reply_auth
- }
- end
-
- def list
- arr = []
- atomic {
- getok 'LIST'
- @socket.each_list_item do |line|
- m = /\A(\d+)[ \t]+(\d+)/.match(line) or
- raise BadResponse, "illegal response: #{line}"
- arr[ m[1].to_i ] = m[2].to_i
- end
- }
- arr
- end
-
- def rset
- atomic {
- getok 'RSET'
- }
- end
-
-
- def top( num, lines = 0, dest = '' )
- atomic {
- getok sprintf('TOP %d %d', num, lines)
- @socket.read_message_to dest
- }
- end
-
- def retr( num, dest = '' )
- atomic {
- getok sprintf('RETR %d', num)
- @socket.read_message_to dest
- }
- end
-
- def dele( num )
- atomic {
- getok sprintf('DELE %d', num)
- }
- end
-
- def uidl( num )
- atomic {
- getok( sprintf('UIDL %d', num) ).message.split(' ')[1]
- }
- end
-
- def quit
- atomic {
- getok 'QUIT'
- }
- end
-
- private
-
- def check_reply_auth
- begin
- return check_reply(SuccessCode)
- rescue ProtocolError => err
- raise ProtoAuthError.new('Fail to POP authentication', err.response)
- end
- end
-
- def get_reply
- str = @socket.readline
-
- if /\A\+/ === str then
- Response.new( SuccessCode, str[0,3], str[3, str.size - 3].strip )
- else
- Response.new( ErrorCode, str[0,4], str[4, str.size - 4].strip )
- end
- end
-
- end
-
-
- class APOPCommand < POP3Command
-
- def initialize( sock )
- response = super(sock)
- m = /<.+>/.match(response.msg) or
- raise ProtoAuthError.new("not APOP server: cannot login", nil)
- @stamp = m[0]
- end
-
- def auth( account, pass )
- atomic {
- @socket.writeline sprintf('APOP %s %s',
- account,
- Digest::MD5.hexdigest(@stamp + pass))
- check_reply_auth
- }
- end
-
- end
-
-end # module Net
diff --git a/lib/net/protocol.rb b/lib/net/protocol.rb
deleted file mode 100644
index b95df2d2d8..0000000000
--- a/lib/net/protocol.rb
+++ /dev/null
@@ -1,780 +0,0 @@
-=begin
-
-= net/protocol.rb
-
-Copyright (c) 1999-2002 Yukihiro Matsumoto
-
-written & maintained by Minero Aoki <aamine@loveruby.net>
-
-This program is free software. You can re-distribute and/or
-modify this program under the same terms as Ruby itself,
-Ruby Distribute License or GNU General Public License.
-
-NOTE: You can find Japanese version of this document in
-the doc/net directory of the standard ruby interpreter package.
-
-$Id$
-
-=end
-
-require 'socket'
-require 'timeout'
-
-
-module Net
-
- class Protocol
-
- Version = '1.2.3'
- Revision = %q$Revision$.split(/\s+/)[1]
-
-
- class << self
-
- def port
- default_port
- end
-
- private
-
- def protocol_param( name, val )
- module_eval <<-End, __FILE__, __LINE__ + 1
- def self.#{name.id2name}
- #{val}
- end
- End
- end
-
- end
-
-
- #
- # --- Configuration Staffs for Sub Classes ---
- #
- # class method default_port
- # class method command_type
- # class method socket_type
- #
- # private method do_start
- # private method do_finish
- #
- # private method conn_address
- # private method conn_port
- #
-
-
- def Protocol.start( address, port = nil, *args )
- instance = new(address, port)
-
- if block_given? then
- instance.start(*args) { return yield(instance) }
- else
- instance.start(*args)
- instance
- end
- end
-
- def initialize( addr, port = nil )
- @address = addr
- @port = port || type.default_port
-
- @command = nil
- @socket = nil
-
- @active = false
-
- @open_timeout = 30
- @read_timeout = 60
-
- @dout = nil
- end
-
- attr_reader :address
- attr_reader :port
-
- attr_reader :command
- attr_reader :socket
-
- attr_accessor :open_timeout
- attr_reader :read_timeout
-
- def read_timeout=( sec )
- @socket.read_timeout = sec if @socket
- @read_timeout = sec
- end
-
- def active?
- @active
- end
-
- def set_debug_output( arg ) # un-documented
- @dout = arg
- end
-
- alias set_pipe set_debug_output
-
- def inspect
- "#<#{type} #{address}:#{port} open=#{active?}>"
- end
-
- #
- # open
- #
-
- def start( *args )
- @active and raise IOError, 'protocol has been opened already'
-
- if block_given? then
- begin
- do_start( *args )
- @active = true
- return yield(self)
- ensure
- finish if @active
- end
- end
-
- do_start( *args )
- @active = true
- nil
- end
-
- private
-
- # abstract do_start()
-
- def conn_socket
- @socket = type.socket_type.open(
- conn_address(), conn_port(),
- @open_timeout, @read_timeout, @dout )
- on_connect
- end
-
- alias conn_address address
- alias conn_port port
-
- def reconn_socket
- @socket.reopen @open_timeout
- on_connect
- end
-
- def conn_command
- @command = type.command_type.new(@socket)
- end
-
- def on_connect
- end
-
- #
- # close
- #
-
- public
-
- def finish
- active? or raise IOError, 'closing already closed protocol'
- do_finish
- @active = false
- nil
- end
-
- private
-
- # abstract do_finish()
-
- def disconn_command
- @command.quit if @command and not @command.critical?
- @command = nil
- end
-
- def disconn_socket
- if @socket and not @socket.closed? then
- @socket.close
- end
- @socket = nil
- end
-
- end
-
- Session = Protocol
-
-
- class Response
-
- def initialize( ctype, code, msg )
- @code_type = ctype
- @code = code
- @message = msg
- super()
- end
-
- attr_reader :code_type, :code, :message
- alias msg message
-
- def inspect
- "#<#{type} #{code}>"
- end
-
- def error!
- raise @code_type.error_type.new( code + ' ' + msg.dump, self )
- end
-
- end
-
-
- class ProtocolError < StandardError; end
- class ProtoSyntaxError < ProtocolError; end
- class ProtoFatalError < ProtocolError; end
- class ProtoUnknownError < ProtocolError; end
- class ProtoServerError < ProtocolError; end
- class ProtoAuthError < ProtocolError; end
- class ProtoCommandError < ProtocolError; end
- class ProtoRetriableError < ProtocolError; end
- ProtocRetryError = ProtoRetriableError
-
- class ProtocolError
-
- def initialize( msg, resp )
- super msg
- @response = resp
- end
-
- attr_reader :response
- alias data response
-
- def inspect
- "#<#{type}>"
- end
-
- end
-
-
- class Code
-
- def initialize( paren, err )
- @parents = [self] + paren
- @err = err
- end
-
- def parents
- @parents.dup
- end
-
- def inspect
- "#<#{type} #{sprintf '0x%x', __id__}>"
- end
-
- def error_type
- @err
- end
-
- def ===( response )
- response.code_type.parents.each {|c| return true if c == self }
- false
- end
-
- def mkchild( err = nil )
- type.new( @parents, err || @err )
- end
-
- end
-
- ReplyCode = Code.new( [], ProtoUnknownError )
- InformationCode = ReplyCode.mkchild( ProtoUnknownError )
- SuccessCode = ReplyCode.mkchild( ProtoUnknownError )
- ContinueCode = ReplyCode.mkchild( ProtoUnknownError )
- ErrorCode = ReplyCode.mkchild( ProtocolError )
- SyntaxErrorCode = ErrorCode.mkchild( ProtoSyntaxError )
- FatalErrorCode = ErrorCode.mkchild( ProtoFatalError )
- ServerErrorCode = ErrorCode.mkchild( ProtoServerError )
- AuthErrorCode = ErrorCode.mkchild( ProtoAuthError )
- RetriableCode = ReplyCode.mkchild( ProtoRetriableError )
- UnknownCode = ReplyCode.mkchild( ProtoUnknownError )
-
-
- class Command
-
- def initialize( sock )
- @socket = sock
- @last_reply = nil
- @atomic = false
- end
-
- attr_accessor :socket
- attr_reader :last_reply
-
- def inspect
- "#<#{type}>"
- end
-
- # abstract quit()
-
- private
-
- def check_reply( *oks )
- @last_reply = get_reply()
- reply_must @last_reply, *oks
- end
-
- # abstract get_reply()
-
- def reply_must( rep, *oks )
- oks.each do |i|
- return rep if i === rep
- end
- rep.error!
- end
-
- def getok( line, expect = SuccessCode )
- @socket.writeline line
- check_reply expect
- end
-
- #
- # error handle
- #
-
- public
-
- def critical?
- @atomic
- end
-
- def error_ok
- @atomic = false
- end
-
- private
-
- def atomic
- @atomic = true
- ret = yield
- @atomic = false
- ret
- end
-
- end
-
-
- class InternetMessageIO
-
- class << self
- alias open new
- end
-
- def initialize( addr, port, otime = nil, rtime = nil, dout = nil )
- @address = addr
- @port = port
- @read_timeout = rtime
- @debugout = dout
-
- @socket = nil
- @rbuf = nil
-
- connect otime
- D 'opened'
- end
-
- attr_reader :address
- attr_reader :port
-
- def ip_address
- @socket or return ''
- @socket.addr[3]
- end
-
- attr_accessor :read_timeout
-
- attr_reader :socket
-
- def connect( otime )
- D "opening connection to #{@address}..."
- timeout( otime ) {
- @socket = TCPsocket.new( @address, @port )
- }
- @rbuf = ''
- end
- private :connect
-
- def close
- if @socket then
- @socket.close
- D 'closed'
- else
- D 'close call for already closed socket'
- end
- @socket = nil
- @rbuf = ''
- end
-
- def reopen( otime = nil )
- D 'reopening...'
- close
- connect otime
- D 'reopened'
- end
-
- def closed?
- not @socket
- end
-
- def inspect
- "#<#{type} #{closed? ? 'closed' : 'opened'}>"
- end
-
- ###
- ### READ
- ###
-
- public
-
- def read( len, dest = '', ignore = false )
- D_off "reading #{len} bytes..."
-
- rsize = 0
- begin
- while rsize + @rbuf.size < len do
- rsize += rbuf_moveto(dest, @rbuf.size)
- rbuf_fill
- end
- rbuf_moveto dest, len - rsize
- rescue EOFError
- raise unless ignore
- end
-
- D_on "read #{len} bytes"
- dest
- end
-
- def read_all( dest = '' )
- D_off 'reading all...'
-
- rsize = 0
- begin
- while true do
- rsize += rbuf_moveto(dest, @rbuf.size)
- rbuf_fill
- end
- rescue EOFError
- ;
- end
-
- D_on "read #{rsize} bytes"
- dest
- end
-
- def readuntil( target, ignore = false )
- dest = ''
- begin
- while true do
- idx = @rbuf.index(target)
- break if idx
- rbuf_fill
- end
- rbuf_moveto dest, idx + target.size
- rescue EOFError
- raise unless ignore
- rbuf_moveto dest, @rbuf.size
- end
- dest
- end
-
- def readline
- ret = readuntil("\n")
- ret.chop!
- ret
- end
-
- private
-
- BLOCK_SIZE = 1024
-
- def rbuf_fill
- until IO.select [@socket], nil, nil, @read_timeout do
- on_read_timeout
- end
- @rbuf << @socket.sysread(BLOCK_SIZE)
- end
-
- def on_read_timeout
- raise TimeoutError, "socket read timeout (#{@read_timeout} sec)"
- end
-
- def rbuf_moveto( dest, len )
- dest << (s = @rbuf.slice!(0, len))
- @debugout << %Q[-> #{s.dump}\n] if @debugout
- len
- end
-
- #
- # message read
- #
-
- public
-
- def read_message_to( dest )
- D_off 'reading text...'
-
- rsize = 0
- while (str = readuntil("\r\n")) != ".\r\n" do
- rsize += str.size
- dest << str.sub(/\A\./, '')
- end
-
- D_on "read #{rsize} bytes"
- dest
- end
-
- # private use only (cannot handle 'break')
- def each_list_item
- while (str = readuntil("\r\n")) != ".\r\n" do
- yield str.chop
- end
- end
-
-
- ###
- ### WRITE
- ###
-
- #
- # basic write
- #
-
- public
-
- def write( str )
- writing {
- do_write str
- }
- end
-
- def writeline( str )
- writing {
- do_write str + "\r\n"
- }
- end
-
- private
-
- def writing
- @writtensize = 0
- @debugout << '<- ' if @debugout
- yield
- @socket.flush
- @debugout << "\n" if @debugout
- @writtensize
- end
-
- def do_write( str )
- @debugout << str.dump if @debugout
- @writtensize += (n = @socket.write(str))
- n
- end
-
- #
- # message write
- #
-
- public
-
- def write_message( src )
- D_off "writing text from #{src.type}"
-
- wsize = using_each_crlf_line {
- wpend_in src
- }
-
- D_on "wrote #{wsize} bytes text"
- wsize
- end
-
- def through_message
- D_off 'writing text from block'
-
- wsize = using_each_crlf_line {
- yield WriteAdapter.new(self, :wpend_in)
- }
-
- D_on "wrote #{wsize} bytes text"
- wsize
- end
-
- private
-
- def wpend_in( src )
- line = nil
- pre = @writtensize
- each_crlf_line( src ) do |line|
- do_write '.' if line[0] == ?.
- do_write line
- end
-
- @writtensize - pre
- end
-
- def using_each_crlf_line
- writing {
- @wbuf = ''
-
- yield
-
- if not @wbuf.empty? then # unterminated last line
- if @wbuf[-1] == ?\r then
- @wbuf.chop!
- end
- @wbuf.concat "\r\n"
- do_write @wbuf
- elsif @writtensize == 0 then # empty src
- do_write "\r\n"
- end
- do_write ".\r\n"
-
- @wbuf = nil
- }
- end
-
- def each_crlf_line( src )
- str = m = beg = nil
-
- adding( src ) do
- beg = 0
- buf = @wbuf
- while buf.index( /\n|\r\n|\r/, beg ) do
- m = Regexp.last_match
- if m.begin(0) == buf.size - 1 and buf[-1] == ?\r then
- # "...\r" : can follow "\n..."
- break
- end
- str = buf[ beg ... m.begin(0) ]
- str.concat "\r\n"
- yield str
- beg = m.end(0)
- end
- @wbuf = buf[ beg ... buf.size ]
- end
- end
-
- def adding( src )
- i = nil
-
- case src
- when String
- 0.step( src.size - 1, 2048 ) do |i|
- @wbuf << src[i,2048]
- yield
- end
-
- when File
- while true do
- i = src.read(2048)
- break unless i
- i[0,0] = @wbuf
- @wbuf = i
- yield
- end
-
- else
- src.each do |i|
- @wbuf << i
- if @wbuf.size > 2048 then
- yield
- end
- end
- yield unless @wbuf.empty?
- end
- end
-
- ###
- ### DEBUG
- ###
-
- private
-
- def D_off( msg )
- D msg
- @savedo, @debugout = @debugout, nil
- end
-
- def D_on( msg )
- @debugout = @savedo
- D msg
- end
-
- def D( msg )
- @debugout or return
- @debugout << msg
- @debugout << "\n"
- end
-
- end
-
-
- class WriteAdapter
-
- def initialize( sock, mid )
- @socket = sock
- @mid = mid
- end
-
- def inspect
- "#<#{type} socket=#{@socket.inspect}>"
- end
-
- def write( str )
- @socket.__send__ @mid, str
- end
-
- alias print write
-
- def <<( str )
- write str
- self
- end
-
- def puts( str = '' )
- write str.sub(/\n?/, "\n")
- end
-
- def printf( *args )
- write sprintf(*args)
- end
-
- end
-
-
- class ReadAdapter
-
- def initialize( block )
- @block = block
- end
-
- def inspect
- "#<#{type}>"
- end
-
- def <<( str )
- call_block str, &@block if @block
- end
-
- private
-
- def call_block( str )
- yield str
- end
-
- end
-
-
- # for backward compatibility
- module NetPrivate
- Response = ::Net::Response
- Command = ::Net::Command
- Socket = ::Net::InternetMessageIO
- BufferedSocket = ::Net::InternetMessageIO
- WriteAdapter = ::Net::WriteAdapter
- ReadAdapter = ::Net::ReadAdapter
- end
- BufferedSocket = ::Net::InternetMessageIO
-
-end # module Net
diff --git a/lib/net/smtp.rb b/lib/net/smtp.rb
deleted file mode 100644
index 8652f0f5d0..0000000000
--- a/lib/net/smtp.rb
+++ /dev/null
@@ -1,442 +0,0 @@
-=begin
-
-= net/smtp.rb
-
-Copyright (c) 1999-2002 Yukihiro Matsumoto
-
-written & maintained by Minero Aoki <aamine@loveruby.net>
-
-This program is free software. You can re-distribute and/or
-modify this program under the same terms as Ruby itself,
-Ruby Distribute License or GNU General Public License.
-
-NOTE: You can find Japanese version of this document in
-the doc/net directory of the standard ruby interpreter package.
-
-$Id$
-
-== What is This Module?
-
-This module provides your program the functions to send internet
-mail via SMTP, Simple Mail Transfer Protocol. For details of
-SMTP itself, refer [RFC2821] ((<URL:http://www.ietf.org/rfc/rfc2821.txt>)).
-
-== What This Module is NOT?
-
-This module does NOT provide the functions to compose internet
-mail. You must create it by yourself. For details of internet mail
-format, see [RFC2822] ((<URL:http://www.ietf.org/rfc/rfc2822.txt>)).
-
-== Examples
-
-=== Sending Mail
-
-You must open connection to SMTP server before sending mails.
-First argument is the address of SMTP server, and second argument
-is port number. Using SMTP.start with block is the most simple way
-to do it. SMTP Connection is closed automatically after block is
-executed.
-
- require 'net/smtp'
- Net::SMTP.start( 'your.smtp.server', 25 ) {|smtp|
- # use smtp object only in this block
- }
-
-Replace 'your.smtp.server' by your SMTP server. Normally
-your system manager or internet provider is supplying a server
-for you.
-
-Then you can send mail.
-
- require 'net/smtp'
-
- Net::SMTP.start( 'your.smtp.server', 25 ) {|smtp|
- smtp.send_mail <<EndOfMail, 'your@mail.address', 'to@some.domain'
- From: Your Name <your@mail.address>
- To: Dest Address <to@some.domain>
- Subject: test mail
- Date: Sat, 23 Jun 2001 16:26:43 +0900
- Message-Id: <unique.message.id.string@some.domain>
-
- This is test mail.
- EndOfMail
- }
-
-=== Closing Session
-
-You MUST close SMTP session after sending mails, by calling #finish
-method. You can also use block form of SMTP.start/SMTP#start, which
-closes session automatically. I strongly recommend later one. It is
-more beautiful and simple.
-
- # using SMTP#finish
- smtp = Net::SMTP.start( 'your.smtp.server', 25 )
- smtp.send_mail mail_string, 'from@address', 'to@address'
- smtp.finish
-
- # using block form of SMTP.start
- Net::SMTP.start( 'your.smtp.server', 25 ) {|smtp|
- smtp.send_mail mail_string, 'from@address', 'to@address'
- }
-
-=== Sending Mails from Any Sources
-
-In an example above I sent mail from String (here document literal).
-SMTP#send_mail accepts any objects which has "each" method
-like File and Array.
-
- require 'net/smtp'
- Net::SMTP.start( 'your.smtp.server', 25 ) {|smtp|
- File.open( 'Mail/draft/1' ) {|f|
- smtp.send_mail f, 'your@mail.address', 'to@some.domain'
- }
- }
-
-=== HELO domain
-
-In almost all situation, you must designate the third argument
-of SMTP.start/SMTP#start. It is the domain name which you are on
-(the host to send mail from). It is called "HELO domain".
-SMTP server will judge if he/she should send or reject
-the SMTP session by inspecting HELO domain.
-
- Net::SMTP.start( 'your.smtp.server', 25,
- 'mail.from.domain' ) {|smtp|
-
-
-== class Net::SMTP
-
-=== Class Methods
-
-: new( address, port = 25 )
- creates a new Net::SMTP object.
-
-: start( address, port = 25, helo_domain = 'localhost.localdomain', account = nil, password = nil, authtype = nil )
-: start( address, port = 25, helo_domain = 'localhost.localdomain', account = nil, password = nil, authtype = nil ) {|smtp| .... }
- is equal to
- Net::SMTP.new(address,port).start(helo_domain,account,password,authtype)
-
- # example
- Net::SMTP.start( 'your.smtp.server' ) {
- smtp.send_mail mail_string, 'from@mail.address', 'dest@mail.address'
- }
-
-=== Instance Methods
-
-: start( helo_domain = <local host name>, account = nil, password = nil, authtype = nil )
-: start( helo_domain = <local host name>, account = nil, password = nil, authtype = nil ) {|smtp| .... }
- opens TCP connection and starts SMTP session.
- HELO_DOMAIN is a domain that you'll dispatch mails from.
- If protocol had been started, raises IOError.
-
- When this methods is called with block, give a SMTP object to block and
- close session after block call finished.
-
- If both of account and password are given, is trying to get
- authentication by using AUTH command. :plain or :cram_md5 is
- allowed for AUTHTYPE.
-
-: active?
- true if SMTP session is started.
-
-: address
- the address to connect
-
-: port
- the port number to connect
-
-: open_timeout
-: open_timeout=(n)
- seconds to wait until connection is opened.
- If SMTP object cannot open a conection in this seconds,
- it raises TimeoutError exception.
-
-: read_timeout
-: read_timeout=(n)
- seconds to wait until reading one block (by one read(1) call).
- If SMTP object cannot open a conection in this seconds,
- it raises TimeoutError exception.
-
-: finish
- finishes SMTP session.
- If SMTP session had not started, raises an IOError.
-
-: send_mail( mailsrc, from_addr, *to_addrs )
- This method sends MAILSRC as mail. A SMTP object read strings
- from MAILSRC by calling "each" iterator, with converting them
- into CRLF ("\r\n") terminated string when write.
-
- FROM_ADDR must be a String, representing source mail address.
- TO_ADDRS must be Strings or an Array of Strings, representing
- destination mail addresses.
-
- # example
- Net::SMTP.start( 'your.smtp.server' ) {|smtp|
- smtp.send_mail mail_string,
- 'from@mail.address',
- 'dest@mail.address' 'dest2@mail.address'
- }
-
-: ready( from_addr, *to_addrs ) {|adapter| .... }
- This method stands by the SMTP object for sending mail and
- gives adapter object to the block. ADAPTER has these 5 methods:
-
- puts print printf write <<
-
- FROM_ADDR must be a String, representing source mail address.
- TO_ADDRS must be Strings or an Array of Strings, representing
- destination mail addresses.
-
- # example
- Net::SMTP.start( 'your.smtp.server', 25 ) {|smtp|
- smtp.ready( 'from@mail.addr', 'dest@mail.addr' ) {|f|
- f.puts 'From: aamine@loveruby.net'
- f.puts 'To: someone@somedomain.org'
- f.puts 'Subject: test mail'
- f.puts
- f.puts 'This is test mail.'
- }
- }
-
-== Exceptions
-
-SMTP objects raise these exceptions:
-: Net::ProtoSyntaxError
- syntax error (errno.500)
-: Net::ProtoFatalError
- fatal error (errno.550)
-: Net::ProtoUnknownError
- unknown error. (is probably bug)
-: Net::ProtoServerBusy
- temporary error (errno.420/450)
-
-=end
-
-require 'net/protocol'
-require 'digest/md5'
-
-
-module Net
-
- class SMTP < Protocol
-
- protocol_param :default_port, '25'
- protocol_param :command_type, '::Net::SMTPCommand'
- protocol_param :socket_type, '::Net::InternetMessageIO'
-
-
- def initialize( addr, port = nil )
- super
- @esmtp = true
- end
-
- def esmtp?
- @esmtp
- end
-
- def esmtp=( bool )
- @esmtp = bool
- end
-
- alias esmtp esmtp?
-
- private
-
- def do_start( helo = 'localhost.localdomain',
- user = nil, secret = nil, authtype = nil )
- conn_socket
- conn_command
-
- begin
- if @esmtp then
- command().ehlo helo
- else
- command().helo helo
- end
- rescue ProtocolError
- if @esmtp then
- @esmtp = false
- command().error_ok
- retry
- else
- raise
- end
- end
-
- if user or secret then
- (user and secret) or
- raise ArgumentError, 'both of account and password are required'
-
- mid = 'auth_' + (authtype || 'cram_md5').to_s
- command().respond_to? mid or
- raise ArgumentError, "wrong auth type #{authtype.to_s}"
-
- command().__send__ mid, user, secret
- end
- end
-
- def do_finish
- disconn_command
- disconn_socket
- end
-
-
- #
- # SMTP operations
- #
-
- public
-
- def send_mail( mailsrc, from_addr, *to_addrs )
- do_ready from_addr, to_addrs.flatten
- command().write_mail mailsrc
- end
-
- alias sendmail send_mail
-
- def ready( from_addr, *to_addrs, &block )
- do_ready from_addr, to_addrs.flatten
- command().through_mail &block
- end
-
- private
-
- def do_ready( from_addr, to_addrs )
- raise ArgumentError, 'mail destination does not given' if to_addrs.empty?
- command().mailfrom from_addr
- command().rcpt to_addrs
- end
-
- end
-
- SMTPSession = SMTP
-
-
- class SMTPCommand < Command
-
- def initialize( sock )
- super
- atomic {
- check_reply SuccessCode
- }
- end
-
- def helo( domain )
- atomic {
- getok sprintf('HELO %s', domain)
- }
- end
-
- def ehlo( domain )
- atomic {
- getok sprintf('EHLO %s', domain)
- }
- end
-
- # "PLAIN" authentication [RFC2554]
- def auth_plain( user, secret )
- atomic {
- getok sprintf('AUTH PLAIN %s',
- ["\0#{user}\0#{secret}"].pack('m').chomp)
- }
- end
-
- # "CRAM-MD5" authentication [RFC2195]
- def auth_cram_md5( user, secret )
- atomic {
- rep = getok( 'AUTH CRAM-MD5', ContinueCode )
- challenge = rep.msg.split(' ')[1].unpack('m')[0]
- secret = Digest::MD5.digest(secret) if secret.size > 64
-
- isecret = secret + "\0" * (64 - secret.size)
- osecret = isecret.dup
- 0.upto( 63 ) do |i|
- isecret[i] ^= 0x36
- osecret[i] ^= 0x5c
- end
- tmp = Digest::MD5.digest( isecret + challenge )
- tmp = Digest::MD5.hexdigest( osecret + tmp )
-
- getok [user + ' ' + tmp].pack('m').chomp
- }
- end
-
- def mailfrom( fromaddr )
- atomic {
- getok sprintf('MAIL FROM:<%s>', fromaddr)
- }
- end
-
- def rcpt( toaddrs )
- toaddrs.each do |i|
- atomic {
- getok sprintf('RCPT TO:<%s>', i)
- }
- end
- end
-
- def write_mail( src )
- atomic {
- getok 'DATA', ContinueCode
- @socket.write_message src
- check_reply SuccessCode
- }
- end
-
- def through_mail( &block )
- atomic {
- getok 'DATA', ContinueCode
- @socket.through_message(&block)
- check_reply SuccessCode
- }
- end
-
- def quit
- atomic {
- getok 'QUIT'
- }
- end
-
- private
-
- def get_reply
- arr = read_reply
- stat = arr[0][0,3]
-
- klass = case stat[0]
- when ?2 then SuccessCode
- when ?3 then ContinueCode
- when ?4 then ServerErrorCode
- when ?5 then
- case stat[1]
- when ?0 then SyntaxErrorCode
- when ?3 then AuthErrorCode
- when ?5 then FatalErrorCode
- end
- end
- klass ||= UnknownCode
-
- Response.new( klass, stat, arr.join('') )
- end
-
- def read_reply
- arr = []
- while true do
- str = @socket.readline
- break unless str[3] == ?- # ex: "210-..."
- arr.push str
- end
- arr.push str
-
- arr
- end
-
- end
-
-
- # for backward compatibility
- module NetPrivate
- SMTPCommand = ::Net::SMTPCommand
- end
-
-end # module Net
diff --git a/lib/net/telnet.rb b/lib/net/telnet.rb
deleted file mode 100644
index 91c4faedbe..0000000000
--- a/lib/net/telnet.rb
+++ /dev/null
@@ -1,599 +0,0 @@
-=begin
-
-== NAME
-
-net/telnet.rb - simple telnet client library
-
-Wakou Aoyama <wakou@fsinet.or.jp>
-
-
-=== MAKE NEW TELNET OBJECT
-
- host = Net::Telnet::new({
- "Binmode" => false, # default: false
- "Host" => "localhost", # default: "localhost"
- "Output_log" => "output_log", # default: nil (no output)
- "Dump_log" => "dump_log", # default: nil (no output)
- "Port" => 23, # default: 23
- "Prompt" => /[$%#>] \z/n, # default: /[$%#>] \z/n
- "Telnetmode" => true, # default: true
- "Timeout" => 10, # default: 10
- # if ignore timeout then set "Timeout" to false.
- "Waittime" => 0, # default: 0
- "Proxy" => proxy # default: nil
- # proxy is Net::Telnet or IO object
- })
-
-Telnet object has socket class methods.
-
-if set "Telnetmode" option to false. not telnet command interpretation.
-"Waittime" is time to confirm "Prompt". There is a possibility that
-the same character as "Prompt" is included in the data, and, when
-the network or the host is very heavy, the value is enlarged.
-
-
-=== STATUS OUTPUT
-
- host = Net::Telnet::new({"Host" => "localhost"}){|c| print c }
-
-connection status output.
-
-example:
-
- Trying localhost...
- Connected to localhost.
-
-
-=== WAIT FOR MATCH
-
- line = host.waitfor(/match/)
- line = host.waitfor({"Match" => /match/,
- "String" => "string",
- "Timeout" => secs})
- # if ignore timeout then set "Timeout" to false.
-
-if set "String" option, then Match == Regexp.new(quote("string"))
-
-
-==== REALTIME OUTPUT
-
- host.waitfor(/match/){|c| print c }
- host.waitfor({"Match" => /match/,
- "String" => "string",
- "Timeout" => secs}){|c| print c}
-
-of cource, set sync=true or flush is necessary.
-
-
-=== SEND STRING AND WAIT PROMPT
-
- line = host.cmd("string")
- line = host.cmd({"String" => "string",
- "Match" => /[$%#>] \z/n,
- "Timeout" => 10})
-
-
-==== REALTIME OUTPUT
-
- host.cmd("string"){|c| print c }
- host.cmd({"String" => "string",
- "Match" => /[$%#>] \z/n,
- "Timeout" => 10}){|c| print c }
-
-of cource, set sync=true or flush is necessary.
-
-
-=== SEND STRING
-
- host.print("string")
- host.puts("string")
-
-Telnet#puts() adds "\n" to the last of "string".
-
-WARNING: Telnet#print() NOT adds "\n" to the last of "string", in the future.
-
-If "Telnetmode" option is true, then escape IAC code ("\xFF"). If
-"Binmode" option is false, then convert "\n" to EOL(end of line) code.
-
-If "WILL SGA" and "DO BIN", then EOL is CR. If "WILL SGA", then EOL is
-CR + NULL. If the other cases, EOL is CR + LF.
-
-
-=== TOGGLE TELNET COMMAND INTERPRETATION
-
- host.telnetmode # return the current status (true or false)
- host.telnetmode = true # do telnet command interpretation (default)
- host.telnetmode = false # don't telnet command interpretation
-
-
-=== TOGGLE NEWLINE TRANSLATION
-
- host.binmode # return the current status (true or false)
- host.binmode = true # no translate newline
- host.binmode = false # translate newline (default)
-
-
-=== LOGIN
-
- host.login("username", "password")
- host.login({"Name" => "username",
- "Password" => "password"})
-
-if no password prompt:
-
- host.login("username")
- host.login({"Name" => "username"})
-
-
-==== REALTIME OUTPUT
-
- host.login("username", "password"){|c| print c }
- host.login({"Name" => "username",
- "Password" => "password"}){|c| print c }
-
-of cource, set sync=true or flush is necessary.
-
-
-
-== EXAMPLE
-
-=== LOGIN AND SEND COMMAND
-
- localhost = Net::Telnet::new({"Host" => "localhost",
- "Timeout" => 10,
- "Prompt" => /[$%#>] \z/n})
- localhost.login("username", "password"){|c| print c }
- localhost.cmd("command"){|c| print c }
- localhost.close
-
-
-=== CHECKS A POP SERVER TO SEE IF YOU HAVE MAIL
-
- pop = Net::Telnet::new({"Host" => "your_destination_host_here",
- "Port" => 110,
- "Telnetmode" => false,
- "Prompt" => /^\+OK/n})
- pop.cmd("user " + "your_username_here"){|c| print c}
- pop.cmd("pass " + "your_password_here"){|c| print c}
- pop.cmd("list"){|c| print c}
-
-
-=end
-
-
-require "socket"
-require "delegate"
-require "timeout"
-require "English"
-
-module Net
- class Telnet < SimpleDelegator
-
- IAC = 255.chr # "\377" # "\xff" # interpret as command:
- DONT = 254.chr # "\376" # "\xfe" # you are not to use option
- DO = 253.chr # "\375" # "\xfd" # please, you use option
- WONT = 252.chr # "\374" # "\xfc" # I won't use option
- WILL = 251.chr # "\373" # "\xfb" # I will use option
- SB = 250.chr # "\372" # "\xfa" # interpret as subnegotiation
- GA = 249.chr # "\371" # "\xf9" # you may reverse the line
- EL = 248.chr # "\370" # "\xf8" # erase the current line
- EC = 247.chr # "\367" # "\xf7" # erase the current character
- AYT = 246.chr # "\366" # "\xf6" # are you there
- AO = 245.chr # "\365" # "\xf5" # abort output--but let prog finish
- IP = 244.chr # "\364" # "\xf4" # interrupt process--permanently
- BREAK = 243.chr # "\363" # "\xf3" # break
- DM = 242.chr # "\362" # "\xf2" # data mark--for connect. cleaning
- NOP = 241.chr # "\361" # "\xf1" # nop
- SE = 240.chr # "\360" # "\xf0" # end sub negotiation
- EOR = 239.chr # "\357" # "\xef" # end of record (transparent mode)
- ABORT = 238.chr # "\356" # "\xee" # Abort process
- SUSP = 237.chr # "\355" # "\xed" # Suspend process
- EOF = 236.chr # "\354" # "\xec" # End of file
- SYNCH = 242.chr # "\362" # "\xf2" # for telfunc calls
-
- OPT_BINARY = 0.chr # "\000" # "\x00" # Binary Transmission
- OPT_ECHO = 1.chr # "\001" # "\x01" # Echo
- OPT_RCP = 2.chr # "\002" # "\x02" # Reconnection
- OPT_SGA = 3.chr # "\003" # "\x03" # Suppress Go Ahead
- OPT_NAMS = 4.chr # "\004" # "\x04" # Approx Message Size Negotiation
- OPT_STATUS = 5.chr # "\005" # "\x05" # Status
- OPT_TM = 6.chr # "\006" # "\x06" # Timing Mark
- OPT_RCTE = 7.chr # "\a" # "\x07" # Remote Controlled Trans and Echo
- OPT_NAOL = 8.chr # "\010" # "\x08" # Output Line Width
- OPT_NAOP = 9.chr # "\t" # "\x09" # Output Page Size
- OPT_NAOCRD = 10.chr # "\n" # "\x0a" # Output Carriage-Return Disposition
- OPT_NAOHTS = 11.chr # "\v" # "\x0b" # Output Horizontal Tab Stops
- OPT_NAOHTD = 12.chr # "\f" # "\x0c" # Output Horizontal Tab Disposition
- OPT_NAOFFD = 13.chr # "\r" # "\x0d" # Output Formfeed Disposition
- OPT_NAOVTS = 14.chr # "\016" # "\x0e" # Output Vertical Tabstops
- OPT_NAOVTD = 15.chr # "\017" # "\x0f" # Output Vertical Tab Disposition
- OPT_NAOLFD = 16.chr # "\020" # "\x10" # Output Linefeed Disposition
- OPT_XASCII = 17.chr # "\021" # "\x11" # Extended ASCII
- OPT_LOGOUT = 18.chr # "\022" # "\x12" # Logout
- OPT_BM = 19.chr # "\023" # "\x13" # Byte Macro
- OPT_DET = 20.chr # "\024" # "\x14" # Data Entry Terminal
- OPT_SUPDUP = 21.chr # "\025" # "\x15" # SUPDUP
- OPT_SUPDUPOUTPUT = 22.chr # "\026" # "\x16" # SUPDUP Output
- OPT_SNDLOC = 23.chr # "\027" # "\x17" # Send Location
- OPT_TTYPE = 24.chr # "\030" # "\x18" # Terminal Type
- OPT_EOR = 25.chr # "\031" # "\x19" # End of Record
- OPT_TUID = 26.chr # "\032" # "\x1a" # TACACS User Identification
- OPT_OUTMRK = 27.chr # "\e" # "\x1b" # Output Marking
- OPT_TTYLOC = 28.chr # "\034" # "\x1c" # Terminal Location Number
- OPT_3270REGIME = 29.chr # "\035" # "\x1d" # Telnet 3270 Regime
- OPT_X3PAD = 30.chr # "\036" # "\x1e" # X.3 PAD
- OPT_NAWS = 31.chr # "\037" # "\x1f" # Negotiate About Window Size
- OPT_TSPEED = 32.chr # " " # "\x20" # Terminal Speed
- OPT_LFLOW = 33.chr # "!" # "\x21" # Remote Flow Control
- OPT_LINEMODE = 34.chr # "\"" # "\x22" # Linemode
- OPT_XDISPLOC = 35.chr # "#" # "\x23" # X Display Location
- OPT_OLD_ENVIRON = 36.chr # "$" # "\x24" # Environment Option
- OPT_AUTHENTICATION = 37.chr # "%" # "\x25" # Authentication Option
- OPT_ENCRYPT = 38.chr # "&" # "\x26" # Encryption Option
- OPT_NEW_ENVIRON = 39.chr # "'" # "\x27" # New Environment Option
- OPT_EXOPL = 255.chr # "\377" # "\xff" # Extended-Options-List
-
- NULL = "\000"
- CR = "\015"
- LF = "\012"
- EOL = CR + LF
- REVISION = '$Id$'
-
- def initialize(options)
- @options = options
- @options["Host"] = "localhost" unless @options.has_key?("Host")
- @options["Port"] = 23 unless @options.has_key?("Port")
- @options["Prompt"] = /[$%#>] \z/n unless @options.has_key?("Prompt")
- @options["Timeout"] = 10 unless @options.has_key?("Timeout")
- @options["Waittime"] = 0 unless @options.has_key?("Waittime")
- unless @options.has_key?("Binmode")
- @options["Binmode"] = false
- else
- unless (true == @options["Binmode"] or false == @options["Binmode"])
- raise ArgumentError, "Binmode option required true or false"
- end
- end
-
- unless @options.has_key?("Telnetmode")
- @options["Telnetmode"] = true
- else
- unless (true == @options["Telnetmode"] or false == @options["Telnetmode"])
- raise ArgumentError, "Telnetmode option required true or false"
- end
- end
-
- @telnet_option = { "SGA" => false, "BINARY" => false }
-
- if @options.has_key?("Output_log")
- @log = File.open(@options["Output_log"], 'a+')
- @log.sync = true
- @log.binmode
- end
-
- if @options.has_key?("Dump_log")
- @dumplog = File.open(@options["Dump_log"], 'a+')
- @dumplog.sync = true
- @dumplog.binmode
- def @dumplog.log_dump(dir, x)
- len = x.length
- addr = 0
- offset = 0
- while 0 < len
- if len < 16
- line = x[offset, len]
- else
- line = x[offset, 16]
- end
- hexvals = line.unpack('H*')[0]
- hexvals += ' ' * (32 - hexvals.length)
- hexvals = format "%s %s %s %s " * 4, *hexvals.unpack('a2' * 16)
- line = line.gsub(/[\000-\037\177-\377]/n, '.')
- printf "%s 0x%5.5x: %s%s\n", dir, addr, hexvals, line
- addr += 16
- offset += 16
- len -= 16
- end
- print "\n"
- end
- end
-
- if @options.has_key?("Proxy")
- if @options["Proxy"].kind_of?(Net::Telnet)
- @sock = @options["Proxy"].sock
- elsif @options["Proxy"].kind_of?(IO)
- @sock = @options["Proxy"]
- else
- raise "Error; Proxy is Net::Telnet or IO object."
- end
- else
- message = "Trying " + @options["Host"] + "...\n"
- yield(message) if block_given?
- @log.write(message) if @options.has_key?("Output_log")
- @dumplog.log_dump('#', message) if @options.has_key?("Dump_log")
-
- begin
- if @options["Timeout"] == false
- @sock = TCPsocket.open(@options["Host"], @options["Port"])
- else
- timeout(@options["Timeout"]) do
- @sock = TCPsocket.open(@options["Host"], @options["Port"])
- end
- end
- rescue TimeoutError
- raise TimeoutError, "timed-out; opening of the host"
- rescue
- @log.write($ERROR_INFO.to_s + "\n") if @options.has_key?("Output_log")
- @dumplog.log_dump('#', $ERROR_INFO.to_s + "\n") if @options.has_key?("Dump_log")
- raise
- end
- @sock.sync = true
- @sock.binmode
-
- message = "Connected to " + @options["Host"] + ".\n"
- yield(message) if block_given?
- @log.write(message) if @options.has_key?("Output_log")
- @dumplog.log_dump('#', message) if @options.has_key?("Dump_log")
- end
-
- super(@sock)
- end # initialize
-
- attr :sock
-
- def telnetmode(mode = nil)
- case mode
- when nil
- @options["Telnetmode"]
- when true, false
- @options["Telnetmode"] = mode
- else
- raise ArgumentError, "required true or false"
- end
- end
-
- def telnetmode=(mode)
- if (true == mode or false == mode)
- @options["Telnetmode"] = mode
- else
- raise ArgumentError, "required true or false"
- end
- end
-
- def binmode(mode = nil)
- case mode
- when nil
- @options["Binmode"]
- when true, false
- @options["Binmode"] = mode
- else
- raise ArgumentError, "required true or false"
- end
- end
-
- def binmode=(mode)
- if (true == mode or false == mode)
- @options["Binmode"] = mode
- else
- raise ArgumentError, "required true or false"
- end
- end
-
- def preprocess(string)
- # combine CR+NULL into CR
- string = string.gsub(/#{CR}#{NULL}/no, CR) if @options["Telnetmode"]
-
- # combine EOL into "\n"
- string = string.gsub(/#{EOL}/no, "\n") unless @options["Binmode"]
-
- string.gsub(/#{IAC}(
- [#{IAC}#{AO}#{AYT}#{DM}#{IP}#{NOP}]|
- [#{DO}#{DONT}#{WILL}#{WONT}]
- [#{OPT_BINARY}-#{OPT_NEW_ENVIRON}#{OPT_EXOPL}]|
- #{SB}[^#{IAC}]*#{IAC}#{SE}
- )/xno) do
- if IAC == $1 # handle escaped IAC characters
- IAC
- elsif AYT == $1 # respond to "IAC AYT" (are you there)
- self.write("nobody here but us pigeons" + EOL)
- ''
- elsif DO[0] == $1[0] # respond to "IAC DO x"
- if OPT_BINARY[0] == $1[1]
- @telnet_option["BINARY"] = true
- self.write(IAC + WILL + OPT_BINARY)
- else
- self.write(IAC + WONT + $1[1..1])
- end
- ''
- elsif DONT[0] == $1[0] # respond to "IAC DON'T x" with "IAC WON'T x"
- self.write(IAC + WONT + $1[1..1])
- ''
- elsif WILL[0] == $1[0] # respond to "IAC WILL x"
- if OPT_BINARY[0] == $1[1]
- self.write(IAC + DO + OPT_BINARY)
- elsif OPT_ECHO[0] == $1[1]
- self.write(IAC + DO + OPT_ECHO)
- elsif OPT_SGA[0] == $1[1]
- @telnet_option["SGA"] = true
- self.write(IAC + DO + OPT_SGA)
- else
- self.write(IAC + DONT + $1[1..1])
- end
- ''
- elsif WONT[0] == $1[0] # respond to "IAC WON'T x"
- if OPT_ECHO[0] == $1[1]
- self.write(IAC + DONT + OPT_ECHO)
- elsif OPT_SGA[0] == $1[1]
- @telnet_option["SGA"] = false
- self.write(IAC + DONT + OPT_SGA)
- else
- self.write(IAC + DONT + $1[1..1])
- end
- ''
- else
- ''
- end
- end
- end # preprocess
-
- def waitfor(options)
- time_out = @options["Timeout"]
- waittime = @options["Waittime"]
-
- if options.kind_of?(Hash)
- prompt = if options.has_key?("Match")
- options["Match"]
- elsif options.has_key?("Prompt")
- options["Prompt"]
- elsif options.has_key?("String")
- Regexp.new( Regexp.quote(options["String"]) )
- end
- time_out = options["Timeout"] if options.has_key?("Timeout")
- waittime = options["Waittime"] if options.has_key?("Waittime")
- else
- prompt = options
- end
-
- if time_out == false
- time_out = nil
- end
-
- line = ''
- buf = ''
- rest = ''
- until(prompt === line and not IO::select([@sock], nil, nil, waittime))
- unless IO::select([@sock], nil, nil, time_out)
- raise TimeoutError, "timed-out; wait for the next data"
- end
- begin
- c = @sock.sysread(1024 * 1024)
- @dumplog.log_dump('<', c) if @options.has_key?("Dump_log")
- if @options["Telnetmode"]
- c = rest + c
- if Integer(c.rindex(/#{IAC}#{SE}/no)) <
- Integer(c.rindex(/#{IAC}#{SB}/no))
- buf = preprocess(c[0 ... c.rindex(/#{IAC}#{SB}/no)])
- rest = c[c.rindex(/#{IAC}#{SB}/no) .. -1]
- elsif pt = c.rindex(/#{IAC}[^#{IAC}#{AO}#{AYT}#{DM}#{IP}#{NOP}]?\z/no)
- buf = preprocess(c[0 ... pt])
- rest = c[pt .. -1]
- else
- buf = preprocess(c)
- rest = ''
- end
- end
- @log.print(buf) if @options.has_key?("Output_log")
- line += buf
- yield buf if block_given?
- rescue EOFError # End of file reached
- if line == ''
- line = nil
- yield nil if block_given?
- end
- break
- end
- end
- line
- end
-
- def write(string)
- length = string.length
- while 0 < length
- IO::select(nil, [@sock])
- @dumplog.log_dump('>', string[-length..-1]) if @options.has_key?("Dump_log")
- length -= @sock.syswrite(string[-length..-1])
- end
- end
-
- def _print(string)
- string = string.gsub(/#{IAC}/no, IAC + IAC) if @options["Telnetmode"]
-
- if @options["Binmode"]
- self.write(string)
- else
- if @telnet_option["BINARY"] and @telnet_option["SGA"]
- # IAC WILL SGA IAC DO BIN send EOL --> CR
- self.write(string.gsub(/\n/n, CR))
- elsif @telnet_option["SGA"]
- # IAC WILL SGA send EOL --> CR+NULL
- self.write(string.gsub(/\n/n, CR + NULL))
- else
- # NONE send EOL --> CR+LF
- self.write(string.gsub(/\n/n, EOL))
- end
- end
- end
-
- def puts(string)
- self._print(string + "\n")
- end
-
- def print(string)
- if $VERBOSE
- $stderr.puts 'WARNING: Telnet#print("string") NOT adds "\n" to the last of "string", in the future.'
- $stderr.puts ' cf. Telnet#puts().'
- end
- self.puts(string)
- end
-
- def cmd(options)
- match = @options["Prompt"]
- time_out = @options["Timeout"]
-
- if options.kind_of?(Hash)
- string = options["String"]
- match = options["Match"] if options.has_key?("Match")
- time_out = options["Timeout"] if options.has_key?("Timeout")
- else
- string = options
- end
-
- self.puts(string)
- if block_given?
- waitfor({"Prompt" => match, "Timeout" => time_out}){|c| yield c }
- else
- waitfor({"Prompt" => match, "Timeout" => time_out})
- end
- end
-
- def login(options, password = nil)
- if options.kind_of?(Hash)
- username = options["Name"]
- password = options["Password"]
- else
- username = options
- end
-
- if block_given?
- line = waitfor(/login[: ]*\z/n){|c| yield c }
- if password
- line += cmd({"String" => username,
- "Match" => /Password[: ]*\z/n}){|c| yield c }
- line += cmd(password){|c| yield c }
- else
- line += cmd(username){|c| yield c }
- end
- else
- line = waitfor(/login[: ]*\z/n)
- if password
- line += cmd({"String" => username,
- "Match" => /Password[: ]*\z/n})
- line += cmd(password)
- else
- line += cmd(username)
- end
- end
- line
- end
-
- end
-end
-
-
-=begin
-
-== HISTORY
-
-delete. see cvs log.
-
-
-=end
diff --git a/lib/observer.rb b/lib/observer.rb
deleted file mode 100644
index e1b249e885..0000000000
--- a/lib/observer.rb
+++ /dev/null
@@ -1,46 +0,0 @@
-# Observable Mixin
-#
-# Observers must respond to update
-
-module Observable
- def add_observer(observer)
- @observer_peers = [] unless defined? @observer_peers
- unless observer.respond_to? :update
- raise NameError, "observer needs to respond to `update'"
- end
- @observer_peers.push observer
- end
- def delete_observer(observer)
- @observer_peers.delete observer if defined? @observer_peers
- end
- def delete_observers
- @observer_peers.clear if defined? @observer_peers
- end
- def count_observers
- if defined? @observer_peers
- @observer_peers.size
- else
- 0
- end
- end
- def changed(state=true)
- @observer_state = state
- end
- def changed?
- if defined? @observer_state and @observer_state
- true
- else
- false
- end
- end
- def notify_observers(*arg)
- if defined? @observer_state and @observer_state
- if defined? @observer_peers
- for i in @observer_peers.dup
- i.update(*arg)
- end
- end
- @observer_state = false
- end
- end
-end
diff --git a/lib/open3.rb b/lib/open3.rb
deleted file mode 100644
index a6e6c5d62b..0000000000
--- a/lib/open3.rb
+++ /dev/null
@@ -1,67 +0,0 @@
-# Usage:
-# require "open3"
-#
-# in, out, err = Open3.popen3('nroff -man')
-# or
-# include Open3
-# in, out, err = popen3('nroff -man')
-#
-
-module Open3
- #[stdin, stdout, stderr] = popen3(command);
- def popen3(*cmd)
- pw = IO::pipe # pipe[0] for read, pipe[1] for write
- pr = IO::pipe
- pe = IO::pipe
-
- pid = fork{
- # child
- fork{
- # grandchild
- pw[1].close
- STDIN.reopen(pw[0])
- pw[0].close
-
- pr[0].close
- STDOUT.reopen(pr[1])
- pr[1].close
-
- pe[0].close
- STDERR.reopen(pe[1])
- pe[1].close
-
- exec(*cmd)
- }
- exit!
- }
-
- pw[0].close
- pr[1].close
- pe[1].close
- Process.waitpid(pid)
- pi = [pw[1], pr[0], pe[0]]
- pw[1].sync = true
- if defined? yield
- begin
- return yield(*pi)
- ensure
- pi.each{|p| p.close unless p.closed?}
- end
- end
- pi
- end
- module_function :popen3
-end
-
-if $0 == __FILE__
- a = Open3.popen3("nroff -man")
- Thread.start do
- while line = gets
- a[0].print line
- end
- a[0].close
- end
- while line = a[1].gets
- print ":", line
- end
-end
diff --git a/lib/ostruct.rb b/lib/ostruct.rb
deleted file mode 100644
index f083677d8e..0000000000
--- a/lib/ostruct.rb
+++ /dev/null
@@ -1,55 +0,0 @@
-# ostruct.rb - Python Style Object
-# just assign to create field
-#
-# s = OpenStruct.new
-# s.foo = 25
-# p s.foo
-# s.bar = 2
-# p s.bar
-# p s
-
-class OpenStruct
- def initialize(hash=nil)
- @table = {}
- if hash
- for k,v in hash
- @table[k] = v
- end
- end
- end
-
- def method_missing(mid, *args)
- mname = mid.id2name
- len = args.length
- if mname =~ /=$/
- if len != 1
- raise ArgumentError, "wrong # of arguments (#{len} for 1)", caller(1)
- end
- mname.chop!
- @table[mname] = args[0]
- elsif args.length == 0
- @table[mname]
- else
- raise NameError, "undefined method `#{mname}'", caller(1)
- end
- end
-
- def delete_field(name)
- if name.type == Fixnum
- name = name.id2name
- end
- @table.delete name
- end
-
- def inspect
- str = "<#{self.type}"
- for k,v in @table
- str += " "
- str += k
- str += "="
- str += v.inspect
- end
- str += ">"
- str
- end
-end
diff --git a/lib/parsearg.rb b/lib/parsearg.rb
deleted file mode 100644
index b9f41d5e5f..0000000000
--- a/lib/parsearg.rb
+++ /dev/null
@@ -1,83 +0,0 @@
-#
-# parsearg.rb - parse arguments
-# $Release Version: $
-# $Revision$
-# $Date$
-# by Yasuo OHBA(SHL Japan Inc. Technology Dept.)
-#
-# --
-#
-#
-#
-
-$RCS_ID=%q$Header$
-
-require "getopts"
-
-def printUsageAndExit()
- if $USAGE
- eval($USAGE)
- end
- exit()
-end
-
-def setParenthesis(ex, opt, c)
- if opt != ""
- ex = sprintf("%s$OPT_%s%s", ex, opt, c)
- else
- ex = sprintf("%s%s", ex, c)
- end
- return ex
-end
-
-def setOrAnd(ex, opt, c)
- if opt != ""
- ex = sprintf("%s$OPT_%s %s%s ", ex, opt, c, c)
- else
- ex = sprintf("%s %s%s ", ex, c, c)
- end
- return ex
-end
-
-def setExpression(ex, opt, op)
- if !op
- ex = sprintf("%s$OPT_%s", ex, opt)
- return ex
- end
- case op.chr
- when "(", ")"
- ex = setParenthesis(ex, opt, op.chr)
- when "|", "&"
- ex = setOrAnd(ex, opt, op.chr)
- else
- return nil
- end
- return ex
-end
-
-def parseArgs(argc, nopt, single_opts, *opts)
- if (noOptions = getopts(single_opts, *opts)) == nil
- printUsageAndExit()
- end
- if nopt
- ex = nil
- pos = 0
- for o in nopt.split(/[()|&]/)
- pos += o.length
- ex = setExpression(ex, o, nopt[pos])
- pos += 1
- end
- begin
- if !eval(ex)
- printUsageAndExit()
- end
- rescue
- print "Format Error!! : \"" + nopt + "\"\t[parseArgs]\n"
- exit! -1
- end
- end
- if ARGV.length < argc
- printUsageAndExit()
- end
- return noOptions
-end
diff --git a/lib/parsedate.rb b/lib/parsedate.rb
deleted file mode 100644
index 7fc75cf0c2..0000000000
--- a/lib/parsedate.rb
+++ /dev/null
@@ -1,181 +0,0 @@
-# parsedate3.rb: Written by Tadayoshi Funaba 2000, 2001
-# $Id: parsedate3.rb,v 1.3 2001-01-18 12:09:47+09 tadf Exp $
-
-module ParseDate
-
- MONTHS = {
- 'jan' => 1, 'feb' => 2, 'mar' => 3, 'apr' => 4,
- 'may' => 5, 'jun' => 6, 'jul' => 7, 'aug' => 8,
- 'sep' => 9, 'oct' =>10, 'nov' =>11, 'dec' =>12
- }
- MONTHPAT = MONTHS.keys.join('|')
-
- DAYS = {
- 'sun' => 0, 'mon' => 1, 'tue' => 2, 'wed' => 3,
- 'thu' => 4, 'fri' => 5, 'sat' => 6
- }
- DAYPAT = DAYS.keys.join('|')
-
- def parsedate(date, cyear=false)
- date = date.dup
-
- # day
- if date.sub!(/(#{DAYPAT})\S*/ino, ' ')
- wday = DAYS[$1.downcase]
- end
-
- # time
- if date.sub!(
- /(\d+):(\d+)(?::(\d+))?
- (?:
- \s*
- ([ap])\.?m\.?
- \b
- )?
- (?:
- \s*
- (
- [a-z]+(?:\s+dst)?
- |
- [-+]\d+(?::?\d+)
- )
- \b
- )?
- /inox,
- ' ')
- hour = $1.to_i
- min = $2.to_i
- sec = $3.to_i if $3
- if $4
- hour %= 12
- if $4.downcase == 'p'
- hour += 12
- end
- end
- zone = $5
- end
-
- # eu
- if date.sub!(
- /(\d+)\S*
- \s+
- (#{MONTHPAT})\S*
- (?:
- \s+
- (\d+)
- )?
- /inox,
- ' ')
- mday = $1.to_i
- mon = MONTHS[$2.downcase]
- year = $3.to_i if $3
-
- # us
- elsif date.sub!(
- /(#{MONTHPAT})\S*
- \s+
- (\d+)\S*
- (?:
- \s+
- (\d+)
- )?
- /inox,
- ' ')
- mon = MONTHS[$1.downcase]
- mday = $2.to_i
- year = $3.to_i if $3
-
- # iso
- elsif date.sub!(/(\d+)-(\d+)-(\d+)/no, ' ')
- year = $1.to_i
- mon = $2.to_i
- mday = $3.to_i
- mday, mon, year = year, mon, mday if $3.size >= 4
-
- # jis
- elsif date.sub!(/([MTSH])(\d+)\.(\d+)\.(\d+)/no, ' ')
- e = { 'M'=>1867,
- 'T'=>1911,
- 'S'=>1925,
- 'H'=>1988
- }[$1]
- year, mon, mday = $2.to_i + e, $3.to_i, $4.to_i
-
- # vms
- elsif date.sub!(/(\d+)-(#{MONTHPAT})\S*-(\d+)/ino, ' ')
- mday = $1.to_i
- mon = MONTHS[$2.downcase]
- year = $3.to_i
- year, mon, mday = mday, mon, year if $1.size >= 4
-
- # sla
- elsif date.sub!(%r|(\d+)/(\d+)(?:/(\d+))?|no, ' ')
- mon = $1.to_i
- mday = $2.to_i
- year = $3.to_i if $3
- year, mon, mday = mon, mday, year if $1.size >= 4
-
- # ddd
- elsif date.sub!(
- /(\d{4,14})
- (?:
- \s*
- T?
- \s*
- (\d{2,6})
- )?
- (?:
- \s*
- (
- Z
- |
- [-+]\d{2,4}
- )
- \b
- )?
- /nox,
- ' ')
- case $1.size
- when 4
- mon = $1[ 0, 2].to_i
- mday = $1[ 2, 2].to_i
- when 6
- year = $1[ 0, 2].to_i
- mon = $1[ 2, 2].to_i
- mday = $1[ 4, 2].to_i
- when 8, 10, 12, 14
- year = $1[ 0, 4].to_i
- mon = $1[ 4, 2].to_i
- mday = $1[ 6, 2].to_i
- hour = $1[ 8, 2].to_i if $1.size >= 10
- min = $1[10, 2].to_i if $1.size >= 12
- sec = $1[12, 2].to_i if $1.size >= 14
- end
- if $2
- case $2.size
- when 2, 4, 6
- hour = $2[ 0, 2].to_i
- min = $2[ 2, 2].to_i if $2.size >= 4
- sec = $2[ 4, 2].to_i if $2.size >= 6
- end
- end
- zone = $3
- end
-
- if cyear and year
- if year < 100
- if year >= 69
- year += 1900
- else
- year += 2000
- end
- end
- end
-
- return year, mon, mday, hour, min, sec, zone, wday
-
- end
-
- module_function :parsedate
-
-end
diff --git a/lib/ping.rb b/lib/ping.rb
deleted file mode 100644
index d698dd0c52..0000000000
--- a/lib/ping.rb
+++ /dev/null
@@ -1,64 +0,0 @@
-#
-# ping.rb -- check a host for upness
-#
-#= SYNOPSIS
-#
-# require 'ping'
-# print "'jimmy' is alive and kicking\n" if Ping.pingecho('jimmy', 10) ;
-#
-#= DESCRIPTION
-#
-# This module contains routines to test for the reachability of remote hosts.
-# Currently the only routine implemented is pingecho().
-#
-# pingecho() uses a TCP echo (I<not> an ICMP one) to determine if the
-# remote host is reachable. This is usually adequate to tell that a remote
-# host is available to rsh(1), ftp(1), or telnet(1) onto.
-#
-#== Parameters
-#
-# : hostname
-#
-# The remote host to check, specified either as a hostname or as an
-# IP address.
-#
-# : timeout
-#
-# The timeout in seconds. If not specified it will default to 5 seconds.
-#
-# : service
-#
-# The service port to connect. The default is "echo".
-#
-#= WARNING
-#
-# pingecho() uses user-level thread to implement the timeout, so it may block
-# for long period if named does not respond for some reason.
-#
-#=end
-
-require 'timeout'
-require "socket"
-
-module Ping
- def pingecho(host, timeout=5, service="echo")
- begin
- timeout(timeout) do
- s = TCPsocket.new(host, service)
- s.close
- end
- rescue Errno::ECONNREFUSED
- return true
- rescue
- return false
- end
- return true
- end
- module_function :pingecho
-end
-
-if $0 == __FILE__
- host = ARGV[0]
- host ||= "localhost"
- printf("%s alive? - %s\n", host, Ping::pingecho(host, 5))
-end
diff --git a/lib/pp.rb b/lib/pp.rb
deleted file mode 100644
index 0a18a6f318..0000000000
--- a/lib/pp.rb
+++ /dev/null
@@ -1,564 +0,0 @@
-# $Id$
-
-=begin
-= Pretty-printer for Ruby objects.
-
-== Which seems better?
-
-non-pretty-printed output by (({p})) is:
- #<PP:0x81a0d10 @stack=[], @genspace=#<Proc:0x81a0cc0>, @nest=[0], @newline="\n", @buf=#<PrettyPrint::Group:0x81a0c98 @group=0, @tail=0, @buf=[#<PrettyPrint::Group:0x81a0ba8 @group=1, @tail=0, @buf=[#<PrettyPrint::Text:0x81a0b30 @tail=2, @width=1, @text="[">, #<PrettyPrint::Group:0x81a0a68 @group=2, @tail=1, @buf=[#<PrettyPrint::Text:0x81a09f0 @tail=1, @width=1, @text="1">], @singleline_width=1>, #<PrettyPrint::Text:0x81a0a7c @tail=0, @width=1, @text=",">, #<PrettyPrint::Breakable:0x81a0a2c @group=2, @genspace=#<Proc:0x81a0cc0>, @newline="\n", @indent=1, @tail=2, @sep=" ", @width=1>, #<PrettyPrint::Group:0x81a09c8 @group=2, @tail=1, @buf=[#<PrettyPrint::Text:0x81a0950 @tail=1, @width=1, @text="2">], @singleline_width=1>, #<PrettyPrint::Text:0x81a0af4 @tail=0, @width=1, @text="]">], @singleline_width=6>], @singleline_width=6>, @sharing_detection=false>
-
-pretty-printed output by (({pp})) is:
- #<PP:0x40d0688
- @buf=
- #<PrettyPrint::Group:0x40d064c
- @buf=
- [#<PrettyPrint::Group:0x40d05d4
- @buf=
- [#<PrettyPrint::Text:0x40d0598 @tail=2, @text="[", @width=1>,
- #<PrettyPrint::Group:0x40d0534
- @buf=[#<PrettyPrint::Text:0x40d04f8 @tail=1, @text="1", @width=1>],
- @group=2,
- @singleline_width=1,
- @tail=1>,
- #<PrettyPrint::Text:0x40d053e @tail=0, @text=",", @width=1>,
- #<PrettyPrint::Breakable:0x40d0516
- @genspace=#<Proc:0x40d0656>,
- @group=2,
- @indent=1,
- @newline="\n",
- @sep=" ",
- @tail=2,
- @width=1>,
- #<PrettyPrint::Group:0x40d04e4
- @buf=[#<PrettyPrint::Text:0x40d04a8 @tail=1, @text="2", @width=1>],
- @group=2,
- @singleline_width=1,
- @tail=1>,
- #<PrettyPrint::Text:0x40d057a @tail=0, @text="]", @width=1>],
- @group=1,
- @singleline_width=6,
- @tail=0>],
- @group=0,
- @singleline_width=6,
- @tail=0>,
- @genspace=#<Proc:0x40d0656>,
- @nest=[0],
- @newline="\n",
- @sharing_detection=false,
- @stack=[]>
-
-I like the latter. If you do too, this library is for you.
-
-== Usage
-
-: pp(obj)
- output ((|obj|)) to (({$>})) in pretty printed format.
-
-== Customized output
-To define your customized pretty printing function for your class,
-redefine a method (({pretty_print(((|pp|)))})) in the class.
-It takes an argument ((|pp|)) which is an instance of the class ((<PP>)).
-The method should use PP#text, PP#breakable, PP#nest, PP#group and
-PP#pp to print the object.
-
-= PP
-== super class
-((<PrettyPrint>))
-
-== class methods
---- PP.pp(obj[, width[, out]])
- outputs ((|obj|)) to ((|out|)) in pretty printed format of
- ((|width|)) columns in width.
-
---- PP.sharing_detection
- returns the sharing detection flag as boolean value.
- It is false by default.
-
---- PP.sharing_detection = value
- sets the sharing detection flag.
-
-== methods
---- pp(obj)
- adds ((|obj|)) to the pretty printing buffer
- using Object#pretty_print or Object#pretty_print_cycled.
-
- Object#pretty_print_cycled is used when ((|obj|)) is already
- printed, a.k.a the object reference chain has a cycle.
-
-= Object
---- pretty_print(pp)
- is a default pretty printing method for general objects.
-
- If (({self})) has a customized (redefined) (({inspect})) method,
- the result of (({self.inspect})) is used but it obviously has no
- line break hints.
-
- This module provides predefined pretty_print() methods for some of
- the most commonly used built-in classes for convenience.
-
---- pretty_print_cycled(pp)
- is a default pretty printing method for general objects that are
- detected as part of a cycle.
-=end
-
-require 'prettyprint'
-
-module Kernel
- private
- def pp(*objs)
- objs.each {|obj|
- PP.pp(obj)
- }
- end
-end
-
-class PP < PrettyPrint
- def PP.pp(obj, width=79, out=$>)
- pp = PP.new
- pp.guard_inspect_key {pp.pp obj}
- pp.format(out, width)
- #$pp = pp
- out << "\n"
- end
-
- @@sharing_detection = false
- def PP.sharing_detection
- return @@sharing_detection
- end
-
- def PP.sharing_detection=(val)
- @@sharing_detection = val
- end
-
- def initialize
- super
- @sharing_detection = @@sharing_detection
- end
-
- InspectKey = :__inspect_key__
-
- def guard_inspect_key
- if Thread.current[InspectKey] == nil
- Thread.current[InspectKey] = []
- end
-
- save = Thread.current[InspectKey]
-
- begin
- Thread.current[InspectKey] = []
- yield
- ensure
- Thread.current[InspectKey] = save
- end
- end
-
- def pp(obj)
- id = obj.__id__
-
- if Thread.current[InspectKey].include? id
- group {obj.pretty_print_cycled self}
- return
- end
-
- begin
- Thread.current[InspectKey] << id
- group {obj.pretty_print self}
- ensure
- Thread.current[InspectKey].pop unless @sharing_detection
- end
- end
-
- def pp_object(obj)
- group {
- text '#<'
- nest(1) {
- text obj.class.name
- text ':'
- text sprintf('0x%x', obj.__id__)
- first = true
- obj.instance_variables.sort.each {|v|
- if first
- first = false
- else
- text ','
- end
- breakable
- group {
- text v
- text '='
- nest(1) {
- breakable ''
- pp(obj.instance_eval v)
- }
- }
- }
- }
- text '>'
- }
- end
-
- def pp_hash(obj)
- group {
- text '{'
- nest(1) {
- first = true
- obj.each {|k, v|
- if first
- first = false
- else
- text ","
- breakable
- end
- group {
- pp k
- text '=>'
- nest(1) {
- group {
- breakable ''
- pp v
- }
- }
- }
- }
- }
- text '}'
- }
- end
-
- module ObjectMixin
- # 1. specific pretty_print
- # 2. specific inspect
- # 3. generic pretty_print
-
- Key = :__pp_instead_of_inspect__
-
- def pretty_print(pp)
- # specific pretty_print is not defined, try specific inspect.
- begin
- old = Thread.current[Key]
- result1 = sprintf('#<%s:0x%x pretty_printed>', self.class.name, self.__id__)
- Thread.current[Key] = [pp, result1]
- result2 = ObjectMixin.pp_call_inspect(self)
- ensure
- Thread.current[Key] = old
- end
-
- unless result1.equal? result2
- pp.text result2
- end
- end
-
- def ObjectMixin.pp_call_inspect(obj); obj.inspect; end
- CallInspectFrame = "#{__FILE__}:#{__LINE__ - 1}:in `pp_call_inspect'"
-
- def inspect
- if CallInspectFrame == caller[0]
- # specific inspect is also not defined, use generic pretty_print.
- pp, result = Thread.current[Key]
- pp.pp_object(self)
- result
- else
- super
- end
- end
-
- def pretty_print_cycled(pp)
- pp.text sprintf("#<%s:0x%x", self.class.name, self.__id__)
- pp.breakable
- pp.text sprintf("...>")
- end
- end
-end
-
-[Numeric, FalseClass, TrueClass, Module].each {|c|
- c.class_eval {
- def pretty_print(pp)
- pp.text self.to_s
- end
- }
-}
-
-class Array
- def pretty_print(pp)
- pp.text "["
- pp.nest(1) {
- first = true
- self.each {|v|
- if first
- first = false
- else
- pp.text ","
- pp.breakable
- end
- pp.pp v
- }
- }
- pp.text "]"
- end
-
- def pretty_print_cycled(pp)
- pp.text(empty? ? '[]' : '[...]')
- end
-end
-
-class Hash
- def pretty_print(pp)
- pp.pp_hash self
- end
-
- def pretty_print_cycled(pp)
- pp.text(empty? ? '{}' : '{...}')
- end
-end
-
-class << ENV
- def pretty_print(pp)
- pp.pp_hash self
- end
-end
-
-class Struct
- def pretty_print(pp)
- pp.text sprintf("#<%s", self.class.name)
- pp.nest(1) {
- first = true
- self.members.each {|member|
- if first
- first = false
- else
- pp.text ","
- end
- pp.breakable
- pp.group {
- pp.text member.to_s
- pp.text '='
- pp.nest(1) {
- pp.breakable ''
- pp.pp self[member]
- }
- }
- }
- }
- pp.text ">"
- end
-
- def pretty_print_cycled(pp)
- pp.text sprintf("#<%s:...>", self.class.name)
- end
-end
-
-class Range
- def pretty_print(pp)
- pp.pp self.begin
- pp.breakable ''
- pp.text(self.exclude_end? ? '...' : '..')
- pp.breakable ''
- pp.pp self.end
- end
-end
-
-class File
- class Stat
- def pretty_print(pp)
- require 'etc.so'
- pp.nest(1) {
- pp.text "#<"
- pp.text self.class.name
- pp.breakable; pp.text sprintf("dev=0x%x", self.dev); pp.text ','
- pp.breakable; pp.text "ino="; pp.pp self.ino; pp.text ','
- pp.breakable
- pp.group {
- m = self.mode
- pp.text sprintf("mode=0%o", m)
- pp.breakable
- pp.text sprintf("(%s %c%c%c%c%c%c%c%c%c)",
- self.ftype,
- (m & 0400 == 0 ? ?- : ?r),
- (m & 0200 == 0 ? ?- : ?w),
- (m & 0100 == 0 ? (m & 04000 == 0 ? ?- : ?S) :
- (m & 04000 == 0 ? ?x : ?s)),
- (m & 0040 == 0 ? ?- : ?r),
- (m & 0020 == 0 ? ?- : ?w),
- (m & 0010 == 0 ? (m & 02000 == 0 ? ?- : ?S) :
- (m & 02000 == 0 ? ?x : ?s)),
- (m & 0004 == 0 ? ?- : ?r),
- (m & 0002 == 0 ? ?- : ?w),
- (m & 0001 == 0 ? (m & 01000 == 0 ? ?- : ?T) :
- (m & 01000 == 0 ? ?x : ?t)))
- pp.text ','
- }
- pp.breakable; pp.text "nlink="; pp.pp self.nlink; pp.text ','
- pp.breakable
- pp.group {
- pp.text "uid="; pp.pp self.uid
- begin
- name = Etc.getpwuid(self.uid).name
- pp.breakable; pp.text "(#{name})"
- rescue ArgumentError
- end
- pp.text ','
- }
- pp.breakable
- pp.group {
- pp.text "gid="; pp.pp self.gid
- begin
- name = Etc.getgrgid(self.gid).name
- pp.breakable; pp.text "(#{name})"
- rescue ArgumentError
- end
- pp.text ','
- }
- pp.breakable
- pp.group {
- pp.text sprintf("rdev=0x%x", self.rdev)
- pp.breakable
- pp.text sprintf('(%d, %d)', self.rdev_major, self.rdev_minor)
- pp.text ','
- }
- pp.breakable; pp.text "size="; pp.pp self.size; pp.text ','
- pp.breakable; pp.text "blksize="; pp.pp self.blksize; pp.text ','
- pp.breakable; pp.text "blocks="; pp.pp self.blocks; pp.text ','
- pp.breakable
- pp.group {
- t = self.atime
- pp.text "atime="; pp.pp t
- pp.breakable; pp.text "(#{t.tv_sec})"
- pp.text ','
- }
- pp.breakable
- pp.group {
- t = self.mtime
- pp.text "mtime="; pp.pp t
- pp.breakable; pp.text "(#{t.tv_sec})"
- pp.text ','
- }
- pp.breakable
- pp.group {
- t = self.ctime
- pp.text "ctime="; pp.pp t
- pp.breakable; pp.text "(#{t.tv_sec})"
- }
- pp.text ">"
- }
- end
- end
-end
-
-class Object
- include PP::ObjectMixin
-end
-
-[Numeric, Symbol, FalseClass, TrueClass, NilClass, Module].each {|c|
- c.class_eval {
- alias :pretty_print_cycled :pretty_print
- }
-}
-
-if __FILE__ == $0
- require 'runit/testcase'
- require 'runit/cui/testrunner'
-
- class PPTest < RUNIT::TestCase
- def test_list0123_12
- assert_equal("[0, 1, 2, 3]\n", PP.pp([0,1,2,3], 12, ''))
- end
-
- def test_list0123_11
- assert_equal("[0,\n 1,\n 2,\n 3]\n", PP.pp([0,1,2,3], 11, ''))
- end
- end
-
- class HasInspect
- def initialize(a)
- @a = a
- end
-
- def inspect
- return "<inspect:#{@a.inspect}>"
- end
- end
-
- class HasPrettyPrint
- def initialize(a)
- @a = a
- end
-
- def pretty_print(pp)
- pp.text "<pretty_print:"
- pp.pp @a
- pp.text ">"
- end
- end
-
- class HasBoth
- def initialize(a)
- @a = a
- end
-
- def inspect
- return "<inspect:#{@a.inspect}>"
- end
-
- def pretty_print(pp)
- pp.text "<pretty_print:"
- pp.pp @a
- pp.text ">"
- end
- end
-
- class PPInspectTest < RUNIT::TestCase
- def test_hasinspect
- a = HasInspect.new(1)
- assert_equal("<inspect:1>\n", PP.pp(a, 79, ''))
- end
-
- def test_hasprettyprint
- a = HasPrettyPrint.new(1)
- assert_equal("<pretty_print:1>\n", PP.pp(a, 79, ''))
- end
-
- def test_hasboth
- a = HasBoth.new(1)
- assert_equal("<pretty_print:1>\n", PP.pp(a, 79, ''))
- end
- end
-
- class PPCycleTest < RUNIT::TestCase
- def test_array
- a = []
- a << a
- assert_equal("[[...]]\n", PP.pp(a, 79, ''))
- end
-
- def test_hash
- a = {}
- a[0] = a
- assert_equal("{0=>{...}}\n", PP.pp(a, 79, ''))
- end
-
- S = Struct.new("S", :a, :b)
- def test_struct
- a = S.new(1,2)
- a.b = a
- assert_equal("#<Struct::S a=1, b=#<Struct::S:...>>\n", PP.pp(a, 79, ''))
- end
-
- def test_object
- a = Object.new
- a.instance_eval {@a = a}
- hex = '0x' + ('%x'%a.id)
- assert_equal("#<Object:#{hex} @a=#<Object:#{hex} ...>>\n", PP.pp(a, 79, ''))
- end
-
- def test_withinspect
- a = []
- a << HasInspect.new(a)
- assert_equal("[<inspect:[...]>]\n", PP.pp(a, 79, ''))
- end
- end
-
- RUNIT::CUI::TestRunner.run(PPTest.suite)
- RUNIT::CUI::TestRunner.run(PPInspectTest.suite)
- RUNIT::CUI::TestRunner.run(PPCycleTest.suite)
-end
diff --git a/lib/prettyprint.rb b/lib/prettyprint.rb
deleted file mode 100644
index b05da3f56f..0000000000
--- a/lib/prettyprint.rb
+++ /dev/null
@@ -1,802 +0,0 @@
-# $Id$
-
-=begin
-= PrettyPrint
-The class implements pretty printing algorithm.
-It finds line breaks and nice indentations for grouped structure.
-
-By default, the class assumes that primitive elements are strings and
-each byte in the strings have single column in width.
-But it can be used for other situasions
-by giving suitable arguments for some methods:
-newline object and space generation block for (({PrettyPrint.new})),
-optional width argument for (({PrettyPrint#text})),
-(({PrettyPrint#breakable})), etc.
-There are several candidates to use them:
-text formatting using proportional fonts,
-multibyte characters which has columns diffrent to number of bytes,
-non-string formatting, etc.
-
-== class methods
---- PrettyPrint.new([newline]) [{|width| ...}]
- creates a buffer for pretty printing.
-
- ((|newline|)) is used for line breaks.
- (({"\n"})) is used if it is not specified.
-
- The block is used to generate spaces.
- (({{|width| ' ' * width}})) is used if it is not given.
-
-== methods
---- text(obj[, width])
- adds ((|obj|)) as a text of ((|width|)) columns in width.
-
- If ((|width|)) is not specified, (({((|obj|)).length})) is used.
-
---- breakable([sep[, width]])
- tells "you can break a line here if necessary", and a
- ((|width|))-column text ((|sep|)) is inserted if a line is not
- broken at the point.
-
- If ((|sep|)) is not specified, (({" "})) is used.
-
- If ((|width|)) is not specified, (({((|sep|)).length})) is used.
- You will have to specify this when ((|sep|)) is a multibyte
- character, for example.
-
---- nest(indent) {...}
- increases left margin after newline with ((|indent|)) for line breaks added in the block.
-
---- group {...}
- groups line break hints added in the block.
- The line break hints are all to be breaked or not.
-
---- fill_group {...}
- groups line break hints added in the block.
- The each line break hints may be breaked or not differently.
-
---- format(out[, width])
- outputs buffered data to ((|out|)).
- It tries to restrict the line length to ((|width|)) but it may
- overflow.
-
- If ((|width|)) is not specified, 79 is assumed.
-
- ((|out|)) must have a method named (({<<})) which accepts
- a first argument ((|obj|)) of (({PrettyPrint#text})),
- a first argument ((|sep|)) of (({PrettyPrint#breakable})),
- a first argument ((|newline|)) of (({PrettyPrint.new})),
- and
- a result of a given block for (({PrettyPrint.new})).
-
-== Bugs
-* Box based formatting? Other (better) model/algorithm?
-
-== References
-Christian Lindig, Strictly Pretty, March 2000,
-((<URL:http://www.gaertner.de/~lindig/papers/strictly-pretty.html>))
-
-Philip Wadler, A prettier printer, March 1998,
-((<URL:http://cm.bell-labs.com/cm/cs/who/wadler/topics/recent.html#prettier>))
-
-=end
-
-class PrettyPrint
- def initialize(newline="\n", &genspace)
- @newline = newline
- @genspace = genspace || lambda {|n| ' ' * n}
- @buf = Group.new
- @nest = [0]
- @stack = []
- end
-
- def text(obj, width=obj.length)
- @buf << Text.new(obj, width)
- end
-
- def breakable(sep=' ', width=sep.length)
- @buf << Breakable.new(sep, width, @nest.last, @newline, @genspace)
- end
-
- def nest(indent)
- @nest << @nest.last + indent
- begin
- yield
- ensure
- @nest.pop
- end
- end
-
- def group
- g = Group.new
- @buf << g
- @stack << @buf
- @buf = g
- begin
- yield
- ensure
- @buf = @stack.pop
- end
- end
-
- def fill_group
- g = FillGroup.new
- @buf << g
- @stack << @buf
- @buf = g
- begin
- yield
- ensure
- @buf = @stack.pop
- end
- end
-
- def format(out, width=79)
- tails = [[-1, 0]]
- @buf.update_tails(tails, 0)
- @buf.multiline_output(out, 0, 0, width)
- end
-
- class Text
- def initialize(text, width)
- @text = text
- @width = width
- end
-
- def update_tails(tails, group)
- @tail = tails[-1][1]
- tails[-1][1] += @width
- end
- attr_reader :tail
-
- def singleline_width
- return @width
- end
-
- def singleline_output(out)
- out << @text
- end
-
- def multiline_output(out, group, margin, width)
- singleline_output(out)
- return margin + singleline_width
- end
- end
-
- class Breakable
- def initialize(sep, width, indent, newline, genspace)
- @sep = sep
- @width = width
- @indent = indent
- @newline = newline
- @genspace = genspace
- end
-
- def update_tails(tails, group)
- @tail = tails[-1][1]
- if group == tails[-1][0]
- tails[-2][1] += @width + tails[-1][1]
- tails[-1][1] = 0
- else
- tails[-1][1] += @width
- tails << [group, 0]
- end
- end
- attr_reader :tail
-
- def singleline_width
- return @width
- end
-
- def singleline_output(out)
- out << @sep
- end
-
- def multiline_output(out, group, margin, width)
- out << @newline
- out << @genspace.call(@indent)
- return @indent
- end
- end
-
- class Group
- def initialize
- @buf = []
- @singleline_width = nil
- end
-
- def <<(obj)
- @buf << obj
- end
-
- def update_tails(tails, group)
- @tail = tails[-1][1]
- len = 0
- @buf.reverse_each {|obj|
- obj.update_tails(tails, group + 1)
- len += obj.singleline_width
- }
- @singleline_width = len
- while group < tails[-1][0]
- tails[-2][1] += tails[-1][1]
- tails.pop
- end
- end
- attr_reader :tail
-
- def singleline_width
- return @singleline_width
- end
-
- def singleline_output(out)
- @buf.each {|obj| obj.singleline_output(out)}
- end
-
- def multiline_output(out, group, margin, width)
- if margin + singleline_width + @tail <= width
- singleline_output(out)
- margin += @singleline_width
- else
- @buf.each {|obj|
- margin = obj.multiline_output(out, group + 1, margin, width)
- }
- end
- return margin
- end
- end
-
- class FillGroup < Group
- def multiline_output(out, group, margin, width)
- @buf.each {|obj|
- if margin + obj.singleline_width + obj.tail <= width
- obj.singleline_output(out)
- margin += obj.singleline_width
- else
- margin = obj.multiline_output(out, group + 1, margin, width)
- end
- }
- return margin
- end
- end
-end
-
-if __FILE__ == $0
- require 'runit/testcase'
- require 'runit/cui/testrunner'
-
- class WadlerExample < RUNIT::TestCase
- def setup
- @hello = PrettyPrint.new
- @hello.group {
- @hello.group {
- @hello.group {
- @hello.group {
- @hello.text 'hello'; @hello.breakable; @hello.text 'a'
- }
- @hello.breakable; @hello.text 'b'
- }
- @hello.breakable; @hello.text 'c'
- }
- @hello.breakable; @hello.text 'd'
- }
-
- @tree = Tree.new("aaaa", Tree.new("bbbbb", Tree.new("ccc"),
- Tree.new("dd")),
- Tree.new("eee"),
- Tree.new("ffff", Tree.new("gg"),
- Tree.new("hhh"),
- Tree.new("ii")))
- end
-
- def test_hello_00_06
- expected = <<'End'.chomp
-hello
-a
-b
-c
-d
-End
- @hello.format(out='', 0); assert_equal(expected, out)
- @hello.format(out='', 6); assert_equal(expected, out)
- end
-
- def test_hello_07_08
- expected = <<'End'.chomp
-hello a
-b
-c
-d
-End
- @hello.format(out='', 7); assert_equal(expected, out)
- @hello.format(out='', 8); assert_equal(expected, out)
- end
-
- def test_hello_09_10
- expected = <<'End'.chomp
-hello a b
-c
-d
-End
- @hello.format(out='', 9); assert_equal(expected, out)
- @hello.format(out='', 10); assert_equal(expected, out)
- end
-
- def test_hello_11_12
- expected = <<'End'.chomp
-hello a b c
-d
-End
- @hello.format(out='', 11); assert_equal(expected, out)
- @hello.format(out='', 12); assert_equal(expected, out)
- end
-
- def test_hello_13
- expected = <<'End'.chomp
-hello a b c d
-End
- @hello.format(out='', 13); assert_equal(expected, out)
- end
-
- def test_tree_00_19
- pp = PrettyPrint.new
- @tree.show(pp)
- expected = <<'End'.chomp
-aaaa[bbbbb[ccc,
- dd],
- eee,
- ffff[gg,
- hhh,
- ii]]
-End
- pp.format(out='', 0); assert_equal(expected, out)
- pp.format(out='', 19); assert_equal(expected, out)
- end
-
- def test_tree_20_22
- pp = PrettyPrint.new
- @tree.show(pp)
- expected = <<'End'.chomp
-aaaa[bbbbb[ccc, dd],
- eee,
- ffff[gg,
- hhh,
- ii]]
-End
- pp.format(out='', 20); assert_equal(expected, out)
- pp.format(out='', 22); assert_equal(expected, out)
- end
-
- def test_tree_23_43
- pp = PrettyPrint.new
- @tree.show(pp)
- expected = <<'End'.chomp
-aaaa[bbbbb[ccc, dd],
- eee,
- ffff[gg, hhh, ii]]
-End
- pp.format(out='', 23); assert_equal(expected, out)
- pp.format(out='', 43); assert_equal(expected, out)
- end
-
- def test_tree_44
- pp = PrettyPrint.new
- @tree.show(pp)
- pp.format(out='', 44)
- assert_equal(<<'End'.chomp, out)
-aaaa[bbbbb[ccc, dd], eee, ffff[gg, hhh, ii]]
-End
- end
-
- def test_tree_alt_00_18
- pp = PrettyPrint.new
- @tree.altshow(pp)
- expected = <<'End'.chomp
-aaaa[
- bbbbb[
- ccc,
- dd
- ],
- eee,
- ffff[
- gg,
- hhh,
- ii
- ]
-]
-End
- pp.format(out='', 0); assert_equal(expected, out)
- pp.format(out='', 18); assert_equal(expected, out)
- end
-
- def test_tree_alt_19_20
- pp = PrettyPrint.new
- @tree.altshow(pp)
- expected = <<'End'.chomp
-aaaa[
- bbbbb[ ccc, dd ],
- eee,
- ffff[
- gg,
- hhh,
- ii
- ]
-]
-End
- pp.format(out='', 19); assert_equal(expected, out)
- pp.format(out='', 20); assert_equal(expected, out)
- end
-
- def test_tree_alt_20_49
- pp = PrettyPrint.new
- @tree.altshow(pp)
- expected = <<'End'.chomp
-aaaa[
- bbbbb[ ccc, dd ],
- eee,
- ffff[ gg, hhh, ii ]
-]
-End
- pp.format(out='', 21); assert_equal(expected, out)
- pp.format(out='', 49); assert_equal(expected, out)
- end
-
- def test_tree_alt_50
- pp = PrettyPrint.new
- @tree.altshow(pp)
- expected = <<'End'.chomp
-aaaa[ bbbbb[ ccc, dd ], eee, ffff[ gg, hhh, ii ] ]
-End
- pp.format(out='', 50); assert_equal(expected, out)
- end
-
- class Tree
- def initialize(string, *children)
- @string = string
- @children = children
- end
-
- def show(pp)
- pp.group {
- pp.text @string
- pp.nest(@string.length) {
- unless @children.empty?
- pp.text '['
- pp.nest(1) {
- first = true
- @children.each {|t|
- if first
- first = false
- else
- pp.text ','
- pp.breakable
- end
- t.show(pp)
- }
- }
- pp.text ']'
- end
- }
- }
- end
-
- def altshow(pp)
- pp.group {
- pp.text @string
- unless @children.empty?
- pp.text '['
- pp.nest(2) {
- pp.breakable
- first = true
- @children.each {|t|
- if first
- first = false
- else
- pp.text ','
- pp.breakable
- end
- t.altshow(pp)
- }
- }
- pp.breakable
- pp.text ']'
- end
- }
- end
-
- end
- end
-
- class StrictPrettyExample < RUNIT::TestCase
- def setup
- @pp = PrettyPrint.new
- @pp.group {
- @pp.group {@pp.nest(2) {
- @pp.text "if"; @pp.breakable;
- @pp.group {
- @pp.nest(2) {
- @pp.group {@pp.text "a"; @pp.breakable; @pp.text "=="}
- @pp.breakable; @pp.text "b"}}}}
- @pp.breakable
- @pp.group {@pp.nest(2) {
- @pp.text "then"; @pp.breakable;
- @pp.group {
- @pp.nest(2) {
- @pp.group {@pp.text "a"; @pp.breakable; @pp.text "<<"}
- @pp.breakable; @pp.text "2"}}}}
- @pp.breakable
- @pp.group {@pp.nest(2) {
- @pp.text "else"; @pp.breakable;
- @pp.group {
- @pp.nest(2) {
- @pp.group {@pp.text "a"; @pp.breakable; @pp.text "+"}
- @pp.breakable; @pp.text "b"}}}}}
- end
-
- def test_00_04
- expected = <<'End'.chomp
-if
- a
- ==
- b
-then
- a
- <<
- 2
-else
- a
- +
- b
-End
- @pp.format(out='', 0); assert_equal(expected, out)
- @pp.format(out='', 4); assert_equal(expected, out)
- end
-
- def test_05
- expected = <<'End'.chomp
-if
- a
- ==
- b
-then
- a
- <<
- 2
-else
- a +
- b
-End
- @pp.format(out='', 5); assert_equal(expected, out)
- end
-
- def test_06
- expected = <<'End'.chomp
-if
- a ==
- b
-then
- a <<
- 2
-else
- a +
- b
-End
- @pp.format(out='', 6); assert_equal(expected, out)
- end
-
- def test_07
- expected = <<'End'.chomp
-if
- a ==
- b
-then
- a <<
- 2
-else
- a + b
-End
- @pp.format(out='', 7); assert_equal(expected, out)
- end
-
- def test_08
- expected = <<'End'.chomp
-if
- a == b
-then
- a << 2
-else
- a + b
-End
- @pp.format(out='', 8); assert_equal(expected, out)
- end
-
- def test_09
- expected = <<'End'.chomp
-if a == b
-then
- a << 2
-else
- a + b
-End
- @pp.format(out='', 9); assert_equal(expected, out)
- end
-
- def test_10
- expected = <<'End'.chomp
-if a == b
-then
- a << 2
-else a + b
-End
- @pp.format(out='', 10); assert_equal(expected, out)
- end
-
- def test_11_31
- expected = <<'End'.chomp
-if a == b
-then a << 2
-else a + b
-End
- @pp.format(out='', 11); assert_equal(expected, out)
- @pp.format(out='', 15); assert_equal(expected, out)
- @pp.format(out='', 31); assert_equal(expected, out)
- end
-
- def test_32
- expected = <<'End'.chomp
-if a == b then a << 2 else a + b
-End
- @pp.format(out='', 32); assert_equal(expected, out)
- end
-
- end
-
- class TailGroup < RUNIT::TestCase
- def test_1
- pp = PrettyPrint.new
- pp.group {
- pp.group {
- pp.text "abc"
- pp.breakable
- pp.text "def"
- }
- pp.group {
- pp.text "ghi"
- pp.breakable
- pp.text "jkl"
- }
- }
- pp.format(out='', 10)
- assert_equal("abc\ndefghi jkl", out)
- end
- end
-
- class NonString < RUNIT::TestCase
- def setup
- @pp = PrettyPrint.new('newline') {|n| "#{n} spaces"}
- @pp.text(3, 3)
- @pp.breakable(1, 1)
- @pp.text(3, 3)
- end
-
- def test_6
- @pp.format(out=[], 6)
- assert_equal([3, "newline", "0 spaces", 3], out)
- end
-
- def test_7
- @pp.format(out=[], 7)
- assert_equal([3, 1, 3], out)
- end
-
- end
-
- class Fill < RUNIT::TestCase
- def setup
- @pp = PrettyPrint.new
- @pp.fill_group {
- @pp.text 'abc'
- @pp.breakable
- @pp.text 'def'
- @pp.breakable
- @pp.text 'ghi'
- @pp.breakable
- @pp.text 'jkl'
- @pp.breakable
- @pp.text 'mno'
- @pp.breakable
- @pp.text 'pqr'
- @pp.breakable
- @pp.text 'stu'
- }
- end
-
- def test_0_6
- expected = <<'End'.chomp
-abc
-def
-ghi
-jkl
-mno
-pqr
-stu
-End
- @pp.format(out='', 0)
- assert_equal(expected, out)
- @pp.format(out='', 6)
- assert_equal(expected, out)
- end
-
- def test_7_10
- expected = <<'End'.chomp
-abc def
-ghi jkl
-mno pqr
-stu
-End
- @pp.format(out='', 7)
- assert_equal(expected, out)
- @pp.format(out='', 10)
- assert_equal(expected, out)
- end
-
- def test_11_14
- expected = <<'End'.chomp
-abc def ghi
-jkl mno pqr
-stu
-End
- @pp.format(out='', 11)
- assert_equal(expected, out)
- @pp.format(out='', 14)
- assert_equal(expected, out)
- end
-
- def test_15_18
- expected = <<'End'.chomp
-abc def ghi jkl
-mno pqr stu
-End
- @pp.format(out='', 15)
- assert_equal(expected, out)
- @pp.format(out='', 18)
- assert_equal(expected, out)
- end
-
- def test_19_22
- expected = <<'End'.chomp
-abc def ghi jkl mno
-pqr stu
-End
- @pp.format(out='', 19)
- assert_equal(expected, out)
- @pp.format(out='', 22)
- assert_equal(expected, out)
- end
-
- def test_23_26
- expected = <<'End'.chomp
-abc def ghi jkl mno pqr
-stu
-End
- @pp.format(out='', 23)
- assert_equal(expected, out)
- @pp.format(out='', 26)
- assert_equal(expected, out)
- end
-
- def test_27
- expected = <<'End'.chomp
-abc def ghi jkl mno pqr stu
-End
- @pp.format(out='', 27)
- assert_equal(expected, out)
- end
-
- end
-
- RUNIT::CUI::TestRunner.run(WadlerExample.suite)
- RUNIT::CUI::TestRunner.run(StrictPrettyExample.suite)
- RUNIT::CUI::TestRunner.run(TailGroup.suite)
- RUNIT::CUI::TestRunner.run(NonString.suite)
- RUNIT::CUI::TestRunner.run(Fill.suite)
-end
diff --git a/lib/profile.rb b/lib/profile.rb
deleted file mode 100644
index 6f772ee6d9..0000000000
--- a/lib/profile.rb
+++ /dev/null
@@ -1,56 +0,0 @@
-
-module Profiler__
- Times = if defined? Process.times then Process else Time end
- Start = Float(Times::times[0])
- top = "toplevel".intern
- Stack = [[0, 0, top]]
- MAP = {"#toplevel" => [1, 0, 0, "#toplevel"]}
-
- p = proc{|event, file, line, id, binding, klass|
- case event
- when "call", "c-call"
- now = Float(Times::times[0])
- Stack.push [now, 0.0, id]
- when "return", "c-return"
- now = Float(Times::times[0])
- tick = Stack.pop
- name = klass.to_s
- if name.nil? then name = '' end
- if klass.kind_of? Class
- name += "#"
- else
- name += "."
- end
- name += id.id2name
- data = MAP[name]
- unless data
- data = [0.0, 0.0, 0.0, name]
- MAP[name] = data
- end
- data[0] += 1
- cost = now - tick[0]
- data[1] += cost
- data[2] += cost - tick[1]
- Stack[-1][1] += cost
- end
- }
- END {
- set_trace_func nil
- total = Float(Times::times[0]) - Start
- if total == 0 then total = 0.01 end
- MAP["#toplevel"][1] = total
-# f = open("./rmon.out", "w")
- f = STDERR
- data = MAP.values.sort!{|a,b| b[2] <=> a[2]}
- sum = 0
- f.printf " %% cumulative self self total\n"
- f.printf " time seconds seconds calls ms/call ms/call name\n"
- for d in data
- sum += d[2]
- f.printf "%6.2f %8.2f %8.2f %8d ", d[2]/total*100, sum, d[2], d[0]
- f.printf "%8.2f %8.2f %s\n", d[2]*1000/d[0], d[1]*1000/d[0], d[3]
- end
- f.close
- }
- set_trace_func p
-end
diff --git a/lib/pstore.rb b/lib/pstore.rb
deleted file mode 100644
index 4a3434b283..0000000000
--- a/lib/pstore.rb
+++ /dev/null
@@ -1,159 +0,0 @@
-#
-# How to use:
-#
-# db = PStore.new("/tmp/foo")
-# db.transaction do
-# p db.roots
-# ary = db["root"] = [1,2,3,4]
-# ary[0] = [1,1.5]
-# end
-
-# db.transaction do
-# p db["root"]
-# end
-
-require "ftools"
-require "digest/md5"
-
-class PStore
- class Error < StandardError
- end
-
- def initialize(file)
- dir = File::dirname(file)
- unless File::directory? dir
- raise PStore::Error, format("directory %s does not exist", dir)
- end
- unless File::writable? dir
- raise PStore::Error, format("directory %s not writable", dir)
- end
- if File::exist? file and not File::readable? file
- raise PStore::Error, format("file %s not readable", file)
- end
- @transaction = false
- @filename = file
- @abort = false
- end
-
- def in_transaction
- raise PStore::Error, "not in transaction" unless @transaction
- end
- private :in_transaction
-
- def [](name)
- in_transaction
- unless @table.key? name
- raise PStore::Error, format("undefined root name `%s'", name)
- end
- @table[name]
- end
- def []=(name, value)
- in_transaction
- @table[name] = value
- end
- def delete(name)
- in_transaction
- @table.delete name
- end
-
- def roots
- in_transaction
- @table.keys
- end
- def root?(name)
- in_transaction
- @table.key? name
- end
- def path
- @filename
- end
-
- def commit
- in_transaction
- @abort = false
- throw :pstore_abort_transaction
- end
- def abort
- in_transaction
- @abort = true
- throw :pstore_abort_transaction
- end
-
- def transaction(read_only=false)
- raise PStore::Error, "nested transaction" if @transaction
- begin
- @transaction = true
- value = nil
- backup = @filename+"~"
- begin
- file = File::open(@filename, "rb+")
- orig = true
- rescue Errno::ENOENT
- raise if read_only
- file = File::open(@filename, "wb+")
- end
- file.flock(read_only ? File::LOCK_SH : File::LOCK_EX)
- if read_only
- @table = Marshal::load(file)
- elsif orig
- content = file.read
- @table = Marshal::load(content)
- size = content.size
- md5 = Digest::MD5.digest(content)
- content = nil # unreference huge data
- else
- @table = {}
- end
- begin
- catch(:pstore_abort_transaction) do
- value = yield(self)
- end
- rescue Exception
- @abort = true
- raise
- ensure
- if !read_only && !@abort
- file.rewind
- content = Marshal::dump(@table)
- if !md5 || size != content.size || md5 != Digest::MD5.digest(content)
- File::copy @filename, backup
- begin
- file.write(content)
- file.truncate(file.pos)
- content = nil # unreference huge data
- rescue
- File::rename backup, @filename if File::exist?(backup)
- raise
- end
- end
- end
- @abort = false
- end
- ensure
- @table = nil
- @transaction = false
- file.close if file
- end
- value
- end
-end
-
-if __FILE__ == $0
- db = PStore.new("/tmp/foo")
- db.transaction do
- p db.roots
- ary = db["root"] = [1,2,3,4]
- ary[1] = [1,1.5]
- end
-
- 1000.times do
- db.transaction do
- db["root"][0] += 1
- p db["root"][0]
- end
- end
-
- db.transaction(true) do
- p db["root"]
- end
-end
diff --git a/lib/rational.rb b/lib/rational.rb
deleted file mode 100644
index decf26b1ba..0000000000
--- a/lib/rational.rb
+++ /dev/null
@@ -1,390 +0,0 @@
-#
-# rational.rb -
-# $Release Version: 0.5 $
-# $Revision: 1.7 $
-# $Date: 1999/08/24 12:49:28 $
-# by Keiju ISHITSUKA(SHL Japan Inc.)
-#
-# --
-# Usage:
-# class Rational < Numeric
-# (include Compareable)
-#
-# Rational(a, b) --> a/b
-#
-# Rational::+
-# Rational::-
-# Rational::*
-# Rational::/
-# Rational::**
-# Rational::%
-# Rational::divmod
-# Rational::abs
-# Rational::<=>
-# Rational::to_i
-# Rational::to_f
-# Rational::to_s
-#
-# Integer::gcd
-# Integer::lcm
-# Integer::gcdlcm
-# Integer::to_r
-#
-# Fixnum::**
-# Bignum::**
-#
-#
-
-def Rational(a, b = 1)
- if a.kind_of?(Rational) && b == 1
- a
- else
- Rational.reduce(a, b)
- end
-end
-
-class Rational < Numeric
- @RCS_ID='-$Id: rational.rb,v 1.7 1999/08/24 12:49:28 keiju Exp keiju $-'
-
- def Rational.reduce(num, den = 1)
- raise ZeroDivisionError, "denometor is 0" if den == 0
-
- if den < 0
- num = -num
- den = -den
- end
- gcd = num.gcd(den)
- num = num.div(gcd)
- den = den.div(gcd)
- if den == 1 && defined?(Unify)
- num
- else
- new!(num, den)
- end
- end
-
- def Rational.new!(num, den = 1)
- new(num, den)
- end
-
- def initialize(num, den)
- if den < 0
- num = -num
- den = -den
- end
- if num.kind_of?(Integer) and den.kind_of?(Integer)
- @numerator = num
- @denominator = den
- else
- @numerator = num.to_i
- @denominator = den.to_i
- end
- end
-
- def + (a)
- if a.kind_of?(Rational)
- num = @numerator * a.denominator
- num_a = a.numerator * @denominator
- Rational(num + num_a, @denominator * a.denominator)
- elsif a.kind_of?(Integer)
- self + Rational.new!(a, 1)
- elsif a.kind_of?(Float)
- Float(self) + a
- else
- x , y = a.coerce(self)
- x + y
- end
- end
-
- def - (a)
- if a.kind_of?(Rational)
- num = @numerator * a.denominator
- num_a = a.numerator * @denominator
- Rational(num - num_a, @denominator*a.denominator)
- elsif a.kind_of?(Integer)
- self - Rational.new!(a, 1)
- elsif a.kind_of?(Float)
- Float(self) - a
- else
- x , y = a.coerce(self)
- x - y
- end
- end
-
- def * (a)
- if a.kind_of?(Rational)
- num = @numerator * a.numerator
- den = @denominator * a.denominator
- Rational(num, den)
- elsif a.kind_of?(Integer)
- self * Rational.new!(a, 1)
- elsif a.kind_of?(Float)
- Float(self) * a
- else
- x , y = a.coerce(self)
- x * y
- end
- end
-
- def / (a)
- if a.kind_of?(Rational)
- num = @numerator * a.denominator
- den = @denominator * a.numerator
- Rational(num, den)
- elsif a.kind_of?(Integer)
- raise ZeroDivisionError, "devided by 0" if a == 0
- self / Rational.new!(a, 1)
- elsif a.kind_of?(Float)
- Float(self) / a
- else
- x , y = a.coerce(self)
- x / y
- end
- end
-
- def ** (other)
- if other.kind_of?(Rational)
- Float(self) ** other
- elsif other.kind_of?(Integer)
- if other > 0
- num = @numerator ** other
- den = @denominator ** other
- elsif other < 0
- num = @denominator ** -other
- den = @numerator ** -other
- elsif other == 0
- num = 1
- den = 1
- end
- Rational.new!(num, den)
- elsif other.kind_of?(Float)
- Float(self) ** other
- else
- x , y = other.coerce(self)
- x ** y
- end
- end
-
- def % (other)
- value = (self / other).to_i
- return self - other * value
- end
-
- def divmod(other)
- value = (self / other).to_i
- return value, self - other * value
- end
-
- def abs
- if @numerator > 0
- Rational.new!(@numerator, @denominator)
- else
- Rational.new!(-@numerator, @denominator)
- end
- end
-
- def <=> (other)
- if other.kind_of?(Rational)
- num = @numerator * other.denominator
- num_a = other.numerator * @denominator
- v = num - num_a
- if v > 0
- return 1
- elsif v < 0
- return -1
- else
- return 0
- end
- elsif other.kind_of?(Integer)
- return self <=> Rational.new!(other, 1)
- elsif other.kind_of?(Float)
- return Float(self) <=> other
- else
- x , y = other.coerce(self)
- return x <=> y
- end
- end
-
- def coerce(other)
- if other.kind_of?(Float)
- return other, self.to_f
- elsif other.kind_of?(Integer)
- return Rational.new!(other, 1), self
- else
- super
- end
- end
-
- def to_i
- Integer(@numerator.div(@denominator))
- end
-
- def to_f
- @numerator.to_f/@denominator.to_f
- end
-
- def to_s
- if @denominator == 1
- @numerator.to_s
- else
- @numerator.to_s+"/"+@denominator.to_s
- end
- end
-
- def to_r
- self
- end
-
- def inspect
- sprintf("Rational(%s, %s)", @numerator.inspect, @denominator.inspect)
- end
-
- def hash
- @numerator ^ @denominator
- end
-
- attr :numerator
- attr :denominator
-
- private :initialize
-end
-
-class Integer
- def numerator
- self
- end
-
- def denomerator
- 1
- end
-
- def to_r
- Rational(self, 1)
- end
-
- def gcd(n)
- m = self.abs
- n = n.abs
-
- return n if m == 0
- return m if n == 0
-
- b = 0
- while n[0] == 0 && m[0] == 0
- b += 1; n >>= 1; m >>= 1
- end
- m >>= 1 while m[0] == 0
- n >>= 1 while n[0] == 0
- while m != n
- m, n = n, m if n > m
- m -= n; m >>= 1 while m[0] == 0
- end
- m << b
- end
-
- def gcd2(int)
- a = self.abs
- b = int.abs
-
- a, b = b, a if a < b
-
- while b != 0
- void, a = a.divmod(b)
- a, b = b, a
- end
- return a
- end
-
- def lcm(int)
- a = self.abs
- b = int.abs
- gcd = a.gcd(b)
- (a.div(gcd)) * b
- end
-
- def gcdlcm(int)
- a = self.abs
- b = int.abs
- gcd = a.gcd(b)
- return gcd, (a.div(gcd)) * b
- end
-
-end
-
-class Fixnum
- alias div! /;
- def div(other)
- if other.kind_of?(Fixnum)
- self.div!(other)
- elsif other.kind_of?(Bignum)
- x, y = other.coerce(self)
- x.div!(y)
- else
- x, y = other.coerce(self)
- x / y
- end
- end
-
-# alias divmod! divmod
-
- if not defined? Complex
- alias power! **;
- end
-
-# def rdiv(other)
-# if other.kind_of?(Fixnum)
-# Rational(self, other)
-# elsif
-# x, y = other.coerce(self)
-# if defined?(x.div())
-# x.div(y)
-# else
-# x / y
-# end
-# end
- # end
-
- def rdiv(other)
- Rational.new!(self,1) / other
- end
-
- def rpower (other)
- if other >= 0
- self.power!(other)
- else
- Rational.new!(self,1)**other
- end
- end
-
- if not defined? Complex
- alias ** rpower
- end
-end
-
-class Bignum
- alias div! /;
- alias div /;
- alias divmod! divmod
-
- if not defined? power!
- alias power! **
- end
-
- def rdiv(other)
- Rational.new!(self,1) / other
- end
-
- def rpower (other)
- if other >= 0
- self.power!(other)
- else
- Rational.new!(self, 1)**other
- end
- end
-
- if not defined? Complex
- alias ** rpower
- end
-
-end
-
diff --git a/lib/readbytes.rb b/lib/readbytes.rb
deleted file mode 100644
index d6a3b10afe..0000000000
--- a/lib/readbytes.rb
+++ /dev/null
@@ -1,36 +0,0 @@
-# readbytes.rb
-#
-# add IO#readbytes, which reads fixed sized data.
-# it guarantees read data size.
-
-class TruncatedDataError<IOError
- def initialize(mesg, data)
- @data = data
- super(mesg)
- end
- attr_reader :data
-end
-
-class IO
- def readbytes(n)
- str = read(n)
- if str == nil
- raise EOFError, "End of file reached"
- end
- if str.size < n
- raise TruncatedDataError.new("data truncated", str)
- end
- str
- end
-end
-
-if __FILE__ == $0
- begin
- loop do
- print STDIN.readbytes(6)
- end
- rescue TruncatedDataError
- p $!.data
- raise
- end
-end
diff --git a/lib/resolv-replace.rb b/lib/resolv-replace.rb
deleted file mode 100644
index ad5c97bfdf..0000000000
--- a/lib/resolv-replace.rb
+++ /dev/null
@@ -1,41 +0,0 @@
-require 'resolv'
-
-class BasicSocket
- alias original_resolv_send send
- def send(mesg, flags, *rest)
- rest[0] = Resolv.getaddress(rest[0]).to_s if 0 < rest.length
- original_resolv_send(mesg, flags, *rest)
- end
-end
-
-class << IPSocket
- alias original_resolv_getaddress getaddress
- def getaddress(host)
- return Resolv.getaddress(host).to_s
- end
-end
-
-class << TCPSocket
- alias original_resolv_new new
- def new(host, service)
- original_resolv_new(Resolv.getaddress(host).to_s, service)
- end
-
- alias original_resolv_open open
- def open(host, service)
- original_resolv_open(Resolv.getaddress(host).to_s, service)
- end
-end
-
-class UDPSocket
- alias original_resolv_connect connect
- def connect(host, port)
- original_resolv_connect(Resolv.getaddress(host).to_s, port)
- end
-
- alias original_resolv_send send
- def send(mesg, flags, *rest)
- rest[0] = Resolv.getaddress(rest[0]).to_s if 0 < rest.length
- original_resolv_send(mesg, flags, *rest)
- end
-end
diff --git a/lib/resolv.rb b/lib/resolv.rb
deleted file mode 100644
index 9bcc6eae19..0000000000
--- a/lib/resolv.rb
+++ /dev/null
@@ -1,1667 +0,0 @@
-=begin
-= resolv library
-resolv.rb is a resolver library written in Ruby.
-Since it is written in Ruby, it is thread-aware.
-I.e. it can resolv many hostnames concurrently.
-
-It is possible to lookup various resources of DNS using DNS module directly.
-
-== example
- Resolv.getaddress("www.ruby-lang.org")
- Resolv.getname("210.251.121.214")
- Resolv::DNS.new.getresources("www.ruby-lang.org", Resolv::DNS::Resource::IN::A).collect {|r| r.address}
- Resolv::DNS.new.getresources("ruby-lang.org", Resolv::DNS::Resource::IN::MX).collect {|r| [r.exchange.to_s, r.preference]}
-
-== Resolv class
-
-=== class methods
---- Resolv.getaddress(name)
---- Resolv.getaddresses(name)
---- Resolv.each_address(name) {|address| ...}
- They lookups IP addresses of ((|name|)) which represents a hostname
- as a string by default resolver.
-
- getaddress returns first entry of lookupped addresses.
- getaddresses returns lookupped addresses as an array.
- each_address iterates over lookupped addresses.
-
---- Resolv.getname(address)
---- Resolv.getnames(address)
---- Resolv.each_name(address) {|name| ...}
- lookups hostnames of ((|address|)) which represents IP address as a string.
-
- getname returns first entry of lookupped names.
- getnames returns lookupped names as an array.
- each_names iterates over lookupped names.
-
-== Resolv::Hosts class
-hostname resolver using /etc/hosts format.
-
-=== class methods
---- Resolv::Hosts.new(hosts='/etc/hosts')
-
-=== methods
---- Resolv::Hosts#getaddress(name)
---- Resolv::Hosts#getaddresses(name)
---- Resolv::Hosts#each_address(name) {|address| ...}
- address lookup methods.
-
---- Resolv::Hosts#getname(address)
---- Resolv::Hosts#getnames(address)
---- Resolv::Hosts#each_name(address) {|name| ...}
- hostnames lookup methods.
-
-== Resolv::DNS class
-DNS stub resolver.
-
-=== class methods
---- Resolv::DNS.new(resolv_conf='/etc/resolv.conf')
-
-=== methods
---- Resolv::DNS#getaddress(name)
---- Resolv::DNS#getaddresses(name)
---- Resolv::DNS#each_address(name) {|address| ...}
- address lookup methods.
-
- ((|name|)) must be a instance of Resolv::DNS::Name or String. Lookupped
- address is represented as an instance of Resolv::IPv4 or Resolv::IPv6.
-
---- Resolv::DNS#getname(address)
---- Resolv::DNS#getnames(address)
---- Resolv::DNS#each_name(address) {|name| ...}
- hostnames lookup methods.
-
- ((|address|)) must be a instance of Resolv::IPv4, Resolv::IPv6 or String.
- Lookupped name is represented as an instance of Resolv::DNS::Name.
-
---- Resolv::DNS#getresource(name, typeclass)
---- Resolv::DNS#getresources(name, typeclass)
---- Resolv::DNS#each_resource(name, typeclass) {|resource| ...}
- They lookup DNS resources of ((|name|)).
- ((|name|)) must be a instance of Resolv::Name or String.
-
- ((|typeclass|)) should be one of follows:
- * Resolv::DNS::Resource::IN::ANY
- * Resolv::DNS::Resource::IN::NS
- * Resolv::DNS::Resource::IN::CNAME
- * Resolv::DNS::Resource::IN::SOA
- * Resolv::DNS::Resource::IN::HINFO
- * Resolv::DNS::Resource::IN::MINFO
- * Resolv::DNS::Resource::IN::MX
- * Resolv::DNS::Resource::IN::TXT
- * Resolv::DNS::Resource::IN::ANY
- * Resolv::DNS::Resource::IN::A
- * Resolv::DNS::Resource::IN::WKS
- * Resolv::DNS::Resource::IN::PTR
- * Resolv::DNS::Resource::IN::AAAA
-
- Lookupped resource is represented as an instance of (a subclass of)
- Resolv::DNS::Resource.
- (Resolv::DNS::Resource::IN::A, etc.)
-
-== Resolv::DNS::Resource::IN::NS class
---- name
-== Resolv::DNS::Resource::IN::CNAME class
---- name
-== Resolv::DNS::Resource::IN::SOA class
---- mname
---- rname
---- serial
---- refresh
---- retry
---- expire
---- minimum
-== Resolv::DNS::Resource::IN::HINFO class
---- cpu
---- os
-== Resolv::DNS::Resource::IN::MINFO class
---- rmailbx
---- emailbx
-== Resolv::DNS::Resource::IN::MX class
---- preference
---- exchange
-== Resolv::DNS::Resource::IN::TXT class
---- data
-== Resolv::DNS::Resource::IN::A class
---- address
-== Resolv::DNS::Resource::IN::WKS class
---- address
---- protocol
---- bitmap
-== Resolv::DNS::Resource::IN::PTR class
---- name
-== Resolv::DNS::Resource::IN::AAAA class
---- address
-
-== Resolv::DNS::Name class
-
-=== class methods
---- Resolv::DNS::Name.create(name)
-
-=== methods
---- Resolv::DNS::Name#to_s
-
-== Resolv::DNS::Resource class
-
-== Resolv::IPv4 class
-=== class methods
---- Resolv::IPv4.create(address)
-
-=== methods
---- Resolv::IPv4#to_s
---- Resolv::IPv4#to_name
-
-=== constants
---- Resolv::IPv4::Regex
- regular expression for IPv4 address.
-
-== Resolv::IPv6 class
-=== class methods
---- Resolv::IPv6.create(address)
-
-=== methods
---- Resolv::IPv6#to_s
---- Resolv::IPv6#to_name
-
-=== constants
---- Resolv::IPv6::Regex
- regular expression for IPv6 address.
-
-== Bugs
-* NIS is not supported.
-* /etc/nsswitch.conf is not supported.
-* IPv6 is not supported.
-
-=end
-
-require 'socket'
-require 'fcntl'
-require 'timeout'
-require 'thread'
-
-class Resolv
- def self.getaddress(name)
- DefaultResolver.getaddress(name)
- end
-
- def self.getaddresses(name)
- DefaultResolver.getaddresses(name)
- end
-
- def self.each_address(name, &block)
- DefaultResolver.each_address(name, &block)
- end
-
- def self.getname(address)
- DefaultResolver.getname(address)
- end
-
- def self.getnames(address)
- DefaultResolver.getnames(address)
- end
-
- def self.each_name(address, &proc)
- DefaultResolver.each_name(address, &proc)
- end
-
- def initialize(resolvers=[Hosts.new, DNS.new])
- @resolvers = resolvers
- end
-
- def getaddress(name)
- each_address(name) {|address| return address}
- raise ResolvError.new("no address for #{name}")
- end
-
- def getaddresses(name)
- ret = []
- each_address(name) {|address| ret << address}
- return ret
- end
-
- def each_address(name)
- if AddressRegex =~ name
- yield name
- return
- end
- yielded = false
- @resolvers.each {|r|
- r.each_address(name) {|address|
- yield address.to_s
- yielded = true
- }
- return if yielded
- }
- end
-
- def getname(address)
- each_name(address) {|name| return name}
- raise ResolvError.new("no name for #{address}")
- end
-
- def getnames(address)
- ret = []
- each_name(address) {|name| ret << name}
- return ret
- end
-
- def each_name(address)
- yielded = false
- @resolvers.each {|r|
- r.each_name(address) {|name|
- yield name.to_s
- yielded = true
- }
- return if yielded
- }
- end
-
- class ResolvError < StandardError
- end
-
- class ResolvTimeout < TimeoutError
- end
-
- class Hosts
- DefaultFileName = '/etc/hosts'
-
- def initialize(filename = DefaultFileName)
- @filename = filename
- @mutex = Mutex.new
- @initialized = nil
- end
-
- def lazy_initialize
- @mutex.synchronize {
- unless @initialized
- @name2addr = {}
- @addr2name = {}
- open(@filename) {|f|
- f.each {|line|
- line.sub!(/#.*/, '')
- addr, hostname, *aliases = line.split(/\s+/)
- next unless addr
- @addr2name[addr] = [] unless @addr2name.include? addr
- @addr2name[addr] << hostname
- @addr2name[addr] += aliases
- @name2addr[hostname] = [] unless @name2addr.include? hostname
- @name2addr[hostname] << addr
- aliases.each {|n|
- @name2addr[n] = [] unless @name2addr.include? n
- @name2addr[n] << addr
- }
- }
- }
- @name2addr.each {|name, arr| arr.reverse!}
- @initialized = true
- end
- }
- end
-
- def getaddress(name)
- each_address(name) {|address| return address}
- raise ResolvError.new("#{@filename} has no name: #{name}")
- end
-
- def getaddresses(name)
- ret = []
- each_address(name) {|address| ret << address}
- return ret
- end
-
- def each_address(name, &proc)
- lazy_initialize
- if @name2addr.include?(name)
- @name2addr[name].each(&proc)
- end
- end
-
- def getname(address)
- each_name(address) {|name| return name}
- raise ResolvError.new("#{@filename} has no address: #{address}")
- end
-
- def getnames(address)
- ret = []
- each_name(address) {|name| ret << name}
- return ret
- end
-
- def each_name(address, &proc)
- lazy_initialize
- if @addr2name.include?(address)
- @addr2name[address].each(&proc)
- end
- end
- end
-
- class DNS
- # STD0013 (RFC 1035, etc.)
- # ftp://ftp.isi.edu/in-notes/iana/assignments/dns-parameters
-
- Port = 53
- UDPSize = 512
-
- DNSThreadGroup = ThreadGroup.new
-
- def initialize(config="/etc/resolv.conf")
- @mutex = Mutex.new
- @config = Config.new(config)
- @initialized = nil
- end
-
- def lazy_initialize
- @mutex.synchronize {
- unless @initialized
- @config.lazy_initialize
-
- if nameserver = @config.single?
- @requester = Requester::ConnectedUDP.new(nameserver)
- else
- @requester = Requester::UnconnectedUDP.new
- end
-
- @initialized = true
- end
- }
- end
-
- def getaddress(name)
- each_address(name) {|address| return address}
- raise ResolvError.new("DNS result has no information for #{name}")
- end
-
- def getaddresses(name)
- ret = []
- each_address(name) {|address| ret << address}
- return ret
- end
-
- def each_address(name)
- each_resource(name, Resource::IN::A) {|resource| yield resource.address}
- end
-
- def getname(address)
- each_name(address) {|name| return name}
- raise ResolvError.new("DNS result has no information for #{address}")
- end
-
- def getnames(address)
- ret = []
- each_name(address) {|name| ret << name}
- return ret
- end
-
- def each_name(address)
- case address
- when Name
- ptr = address
- when IPv4::Regex
- ptr = IPv4.create(address).to_name
- when IPv6::Regex
- ptr = IPv6.create(address).to_name
- else
- raise ResolvError.new("cannot interpret as address: #{address}")
- end
- each_resource(ptr, Resource::IN::PTR) {|resource| yield resource.name}
- end
-
- def getresource(name, typeclass)
- each_resource(name, typeclass) {|resource| return resource}
- raise ResolvError.new("DNS result has no information for #{name}")
- end
-
- def getresources(name, typeclass)
- ret = []
- each_resource(name, typeclass) {|resource| ret << resource}
- return ret
- end
-
- def each_resource(name, typeclass, &proc)
- lazy_initialize
- q = Queue.new
- senders = {}
- begin
- @config.resolv(name) {|candidate, tout, nameserver|
- msg = Message.new
- msg.rd = 1
- msg.add_question(candidate, typeclass)
- unless sender = senders[[candidate, nameserver]]
- sender = senders[[candidate, nameserver]] =
- @requester.sender(msg, candidate, q, nameserver)
- end
- sender.send
- reply = reply_name = nil
- timeout(tout, ResolvTimeout) { reply, reply_name = q.pop }
- case reply.rcode
- when RCode::NoError
- extract_resources(reply, reply_name, typeclass, &proc)
- return
- when RCode::NXDomain
- raise Config::NXDomain.new(reply_name)
- else
- raise Config::OtherResolvError.new(reply_name)
- end
- }
- ensure
- @requester.delete(q)
- end
- end
-
- def extract_resources(msg, name, typeclass)
- if typeclass < Resource::ANY
- n0 = Name.create(name)
- msg.each_answer {|n, ttl, data|
- yield data if n0 == n
- }
- end
- yielded = false
- n0 = Name.create(name)
- msg.each_answer {|n, ttl, data|
- if n0 == n
- case data
- when typeclass
- yield data
- yielded = true
- when Resource::CNAME
- n0 = data.name
- end
- end
- }
- return if yielded
- msg.each_answer {|n, ttl, data|
- if n0 == n
- case data
- when typeclass
- yield data
- end
- end
- }
- end
-
- class Requester
- def initialize
- @senders = {}
- end
-
- def delete(arg)
- case arg
- when Sender
- @senders.delete_if {|k, s| s == arg }
- when Queue
- @senders.delete_if {|k, s| s.queue == arg }
- else
- raise ArgumentError.new("neither Sender or Queue: #{arg}")
- end
- end
-
- class Sender
- def initialize(data, queue)
- @data = data
- @queue = queue
- end
- attr_reader :queue
-
- def recv(msg)
- @queue.push([msg, @data])
- end
- end
-
- class UnconnectedUDP < Requester
- def initialize
- super()
- @sock = UDPSocket.new
- @sock.fcntl(Fcntl::F_SETFD, 1)
- @id = {}
- @id.default = -1
- @thread = Thread.new {
- DNSThreadGroup.add Thread.current
- loop {
- reply, from = @sock.recvfrom(UDPSize)
- msg = begin
- Message.decode(reply)
- rescue DecodeError
- STDERR.print("DNS message decoding error: #{reply.inspect}\n")
- next
- end
- if s = @senders[[[from[3],from[1]],msg.id]]
- s.recv msg
- else
- #STDERR.print("non-handled DNS message: #{msg.inspect} from #{from.inspect}\n")
- end
- }
- }
- end
-
- def sender(msg, data, queue, host, port=Port)
- service = [host, port]
- id = Thread.exclusive {
- @id[service] = (@id[service] + 1) & 0xffff
- }
- request = msg.encode
- request[0,2] = [id].pack('n')
- return @senders[[service, id]] =
- Sender.new(request, data, @sock, host, port, queue)
- end
-
- class Sender < Requester::Sender
- def initialize(msg, data, sock, host, port, queue)
- super(data, queue)
- @msg = msg
- @sock = sock
- @host = host
- @port = port
- end
-
- def send
- @sock.send(@msg, 0, @host, @port)
- end
- end
- end
-
- class ConnectedUDP < Requester
- def initialize(host, port=Port)
- super()
- @host = host
- @port = port
- @sock = UDPSocket.new
- @sock.connect(host, port)
- @sock.fcntl(Fcntl::F_SETFD, 1)
- @id = -1
- @thread = Thread.new {
- DNSThreadGroup.add Thread.current
- loop {
- reply = @sock.recv(UDPSize)
- msg = begin
- Message.decode(reply)
- rescue DecodeError
- STDERR.print("DNS message decoding error: #{reply.inspect}")
- next
- end
- if s = @senders[msg.id]
- s.recv msg
- else
- #STDERR.print("non-handled DNS message: #{msg.inspect}")
- end
- }
- }
- end
-
- def sender(msg, data, queue, host=@host, port=@port)
- unless host == @host && port == @port
- raise RequestError.new("host/port don't match: #{host}:#{port}")
- end
- id = Thread.exclusive { @id = (@id + 1) & 0xffff }
- request = msg.encode
- request[0,2] = [id].pack('n')
- return @senders[id] = Sender.new(request, data, @sock, queue)
- end
-
- class Sender < Requester::Sender
- def initialize(msg, data, sock, queue)
- super(data, queue)
- @msg = msg
- @sock = sock
- end
-
- def send
- @sock.send(@msg, 0)
- end
- end
- end
-
- class TCP < Requester
- def initialize(host, port=Port)
- super()
- @host = host
- @port = port
- @sock = TCPSocket.new
- @sock.connect(host, port)
- @sock.fcntl(Fcntl::F_SETFD, 1)
- @id = -1
- @senders = {}
- @thread = Thread.new {
- DNSThreadGroup.add Thread.current
- loop {
- len = @sock.read(2).unpack('n')
- reply = @sock.read(len)
- msg = begin
- Message.decode(reply)
- rescue DecodeError
- STDERR.print("DNS message decoding error: #{reply.inspect}")
- next
- end
- if s = @senders[msg.id]
- s.push msg
- else
- #STDERR.print("non-handled DNS message: #{msg.inspect}")
- end
- }
- }
- end
-
- def sender(msg, data, queue, host=@host, port=@port)
- unless host == @host && port == @port
- raise RequestError.new("host/port don't match: #{host}:#{port}")
- end
- id = Thread.exclusive { @id = (@id + 1) & 0xffff }
- request = msg.encode
- request[0,2] = [request.length, id].pack('nn')
- return @senders[id] = Sender.new(request, data, @sock, queue)
- end
-
- class Sender < Requester::Sender
- def initialize(msg, data, sock, queue)
- super(data, queue)
- @msg = msg
- @sock = sock
- end
-
- def send
- @sock.print(@msg)
- @sock.flush
- end
- end
- end
-
- class RequestError < StandardError
- end
- end
-
- class Config
- def initialize(filename="/etc/resolv.conf")
- @mutex = Mutex.new
- @filename = filename
- @initialized = nil
- end
-
- def lazy_initialize
- @mutex.synchronize {
- unless @initialized
- @nameserver = []
- @search = nil
- @ndots = 1
- begin
- open(@filename) {|f|
- f.each {|line|
- line.sub!(/[#;].*/, '')
- keyword, *args = line.split(/\s+/)
- next unless keyword
- case keyword
- when 'nameserver'
- @nameserver += args
- when 'domain'
- @search = [Label.split(args[0])]
- when 'search'
- @search = args.map {|arg| Label.split(arg)}
- end
- }
- }
- rescue Errno::ENOENT
- end
-
- @nameserver = ['0.0.0.0'] if @nameserver.empty?
- unless @search
- hostname = Socket.gethostname
- if /\./ =~ hostname
- @search = [Label.split($')]
- else
- @search = [[]]
- end
- end
- @initialized = true
- end
- }
- end
-
- def single?
- lazy_initialize
- if @nameserver.length == 1
- return @nameserver[0]
- else
- return nil
- end
- end
-
- def generate_candidates(name)
- candidates = nil
- name = Name.create(name)
- if name.absolute?
- candidates = [name]
- else
- if @ndots <= name.length - 1
- candidates = [Name.new(name.to_a)]
- else
- candidates = []
- end
- candidates.concat(@search.map {|domain| Name.new(name.to_a + domain)})
- end
- return candidates
- end
-
- InitialTimeout = 5
-
- def generate_timeouts
- ts = [InitialTimeout]
- ts << ts[-1] * 2 / @nameserver.length
- ts << ts[-1] * 2
- ts << ts[-1] * 2
- return ts
- end
-
- def resolv(name)
- candidates = generate_candidates(name)
- timeouts = generate_timeouts
- begin
- candidates.each {|candidate|
- begin
- timeouts.each {|tout|
- @nameserver.each {|nameserver|
- begin
- yield candidate, tout, nameserver
- rescue ResolvTimeout
- end
- }
- }
- raise ResolvError.new("DNS resolv timeout: #{name}")
- rescue NXDomain
- end
- }
- rescue OtherResolvError
- raise ResolvError.new("DNS error: #{$!.message}")
- end
- raise ResolvError.new("DNS resolv error: #{name}")
- end
-
- class NXDomain < ResolvError
- end
-
- class OtherResolvError < ResolvError
- end
- end
-
- module OpCode
- Query = 0
- IQuery = 1
- Status = 2
- Notify = 4
- Update = 5
- end
-
- module RCode
- NoError = 0
- FormErr = 1
- ServFail = 2
- NXDomain = 3
- NotImp = 4
- Refused = 5
- YXDomain = 6
- YXRRSet = 7
- NXRRSet = 8
- NotAuth = 9
- NotZone = 10
- BADVERS = 16
- BADSIG = 16
- BADKEY = 17
- BADTIME = 18
- BADMODE = 19
- BADNAME = 20
- BADALG = 21
- end
-
- class DecodeError < StandardError
- end
-
- class EncodeError < StandardError
- end
-
- module Label
- def self.split(arg)
- labels = []
- arg.scan(/[^\.]+/) {labels << Str.new($&)}
- return labels
- end
-
- class Str
- def initialize(string)
- @string = string
- @downcase = string.downcase
- end
- attr_reader :string, :downcase
-
- def to_s
- return @string
- end
-
- def inspect
- return "#<#{self.class} #{self.to_s}>"
- end
-
- def ==(other)
- return @downcase == other.downcase
- end
-
- def eql?(other)
- return self == other
- end
-
- def hash
- return @downcase.hash
- end
- end
- end
-
- class Name
- def self.create(arg)
- case arg
- when Name
- return arg
- when String
- return Name.new(Label.split(arg), /\.\z/ =~ arg ? true : false)
- else
- raise ArgumentError.new("cannot interpret as DNS name: #{arg.inspect}")
- end
- end
-
- def initialize(labels, absolute=true)
- @labels = labels
- @absolute = absolute
- end
-
- def absolute?
- return @absolute
- end
-
- def ==(other)
- return @labels == other.to_a && @absolute == other.absolute?
- end
- alias eql? ==
-
- def hash
- return @labels.hash ^ @absolute.hash
- end
-
- def to_a
- return @labels
- end
-
- def length
- return @labels.length
- end
-
- def [](i)
- return @labels[i]
- end
-
- def to_s
- return @labels.join('.')
- end
- end
-
- class Message
- @@identifier = -1
-
- def initialize(id = (@@identifier += 1) & 0xffff)
- @id = id
- @qr = 0
- @opcode = 0
- @aa = 0
- @tc = 0
- @rd = 0 # recursion desired
- @ra = 0 # recursion available
- @rcode = 0
- @question = []
- @answer = []
- @authority = []
- @additional = []
- end
-
- attr_accessor :id, :qr, :opcode, :aa, :tc, :rd, :ra, :rcode
- attr_reader :question, :answer, :authority, :additional
-
- def ==(other)
- return @id == other.id &&
- @qr == other.qr &&
- @opcode == other.opcode &&
- @aa == other.aa &&
- @tc == other.tc &&
- @rd == other.rd &&
- @ra == other.ra &&
- @rcode == other.rcode &&
- @question == other.question &&
- @answer == other.answer &&
- @authority == other.authority &&
- @additional == other.additional
- end
-
- def add_question(name, typeclass)
- @question << [Name.create(name), typeclass]
- end
-
- def each_question
- @question.each {|name, typeclass|
- yield name, typeclass
- }
- end
-
- def add_answer(name, ttl, data)
- @answer << [Name.create(name), ttl, data]
- end
-
- def each_answer
- @answer.each {|name, ttl, data|
- yield name, ttl, data
- }
- end
-
- def add_authority(name, ttl, data)
- @authority << [Name.create(name), ttl, data]
- end
-
- def each_authority
- @authority.each {|name, ttl, data|
- yield name, ttl, data
- }
- end
-
- def add_additional(name, ttl, data)
- @additional << [Name.create(name), ttl, data]
- end
-
- def each_additional
- @additional.each {|name, ttl, data|
- yield name, ttl, data
- }
- end
-
- def each_resource
- each_answer {|name, ttl, data| yield name, ttl, data}
- each_authority {|name, ttl, data| yield name, ttl, data}
- each_additional {|name, ttl, data| yield name, ttl, data}
- end
-
- def encode
- return MessageEncoder.new {|msg|
- msg.put_pack('nnnnnn',
- @id,
- (@qr & 1) << 15 |
- (@opcode & 15) << 11 |
- (@aa & 1) << 10 |
- (@tc & 1) << 9 |
- (@rd & 1) << 8 |
- (@ra & 1) << 7 |
- (@rcode & 15),
- @question.length,
- @answer.length,
- @authority.length,
- @additional.length)
- @question.each {|q|
- name, typeclass = q
- msg.put_name(name)
- msg.put_pack('nn', typeclass::TypeValue, typeclass::ClassValue)
- }
- [@answer, @authority, @additional].each {|rr|
- rr.each {|r|
- name, ttl, data = r
- msg.put_name(name)
- msg.put_pack('nnN', data.class::TypeValue, data.class::ClassValue, ttl)
- msg.put_length16 {data.encode_rdata(msg)}
- }
- }
- }.to_s
- end
-
- class MessageEncoder
- def initialize
- @data = ''
- @names = {}
- yield self
- end
-
- def to_s
- return @data
- end
-
- def put_bytes(d)
- @data << d
- end
-
- def put_pack(template, *d)
- @data << d.pack(template)
- end
-
- def put_length16
- length_index = @data.length
- @data << "\0\0"
- data_start = @data.length
- yield
- data_end = @data.length
- @data[length_index, 2] = [data_end - data_start].pack("n")
- end
-
- def put_string(d)
- self.put_pack("C", d.length)
- @data << d
- end
-
- def put_name(d)
- put_labels(d.to_a)
- end
-
- def put_labels(d)
- d.each_index {|i|
- domain = d[i..-1]
- if idx = @names[domain]
- self.put_pack("n", 0xc000 | idx)
- return
- else
- @names[domain] = @data.length
- self.put_label(d[i])
- end
- }
- @data << "\0"
- end
-
- def put_label(d)
- self.put_string(d.string)
- end
- end
-
- def Message.decode(m)
- o = Message.new(0)
- MessageDecoder.new(m) {|msg|
- id, flag, qdcount, ancount, nscount, arcount =
- msg.get_unpack('nnnnnn')
- o.id = id
- o.qr = (flag >> 15) & 1
- o.opcode = (flag >> 11) & 15
- o.aa = (flag >> 10) & 1
- o.tc = (flag >> 9) & 1
- o.rd = (flag >> 8) & 1
- o.ra = (flag >> 7) & 1
- o.rcode = flag & 15
- (1..qdcount).each {
- name, typeclass = msg.get_question
- o.add_question(name, typeclass)
- }
- (1..ancount).each {
- name, ttl, data = msg.get_rr
- o.add_answer(name, ttl, data)
- }
- (1..nscount).each {
- name, ttl, data = msg.get_rr
- o.add_authority(name, ttl, data)
- }
- (1..arcount).each {
- name, ttl, data = msg.get_rr
- o.add_additional(name, ttl, data)
- }
- }
- return o
- end
-
- class MessageDecoder
- def initialize(data)
- @data = data
- @index = 0
- @limit = data.length
- yield self
- end
-
- def get_length16
- len, = self.get_unpack('n')
- save_limit = @limit
- @limit = @index + len
- d = yield len
- if @index < @limit
- raise DecodeError.new("junk exist")
- elsif @limit < @index
- raise DecodeError.new("limit exceed")
- end
- @limit = save_limit
- return d
- end
-
- def get_bytes(len = @limit - @index)
- d = @data[@index, len]
- @index += len
- return d
- end
-
- def get_unpack(template)
- len = 0
- template.each_byte {|byte|
- case byte
- when ?c, ?C
- len += 1
- when ?n
- len += 2
- when ?N
- len += 4
- else
- raise StandardError.new("unsupported template: '#{byte.chr}' in '#{template}'")
- end
- }
- raise DecodeError.new("limit exceed") if @limit < @index + len
- arr = @data.unpack("@#{@index}#{template}")
- @index += len
- return arr
- end
-
- def get_string
- len = @data[@index]
- raise DecodeError.new("limit exceed") if @limit < @index + 1 + len
- d = @data[@index + 1, len]
- @index += 1 + len
- return d
- end
-
- def get_name
- return Name.new(self.get_labels)
- end
-
- def get_labels(limit=nil)
- limit = @index if !limit || @index < limit
- d = []
- while true
- case @data[@index]
- when 0
- @index += 1
- return d
- when 192..255
- idx = self.get_unpack('n')[0] & 0x3fff
- if limit <= idx
- raise DecodeError.new("non-backward name pointer")
- end
- save_index = @index
- @index = idx
- d += self.get_labels(limit)
- @index = save_index
- return d
- else
- d << self.get_label
- end
- end
- return d
- end
-
- def get_label
- return Label::Str.new(self.get_string)
- end
-
- def get_question
- name = self.get_name
- type, klass = self.get_unpack("nn")
- return name, Resource.get_class(type, klass)
- end
-
- def get_rr
- name = self.get_name
- type, klass, ttl = self.get_unpack('nnN')
- typeclass = Resource.get_class(type, klass)
- return name, ttl, self.get_length16 {typeclass.decode_rdata(self)}
- end
- end
- end
-
- class Query
- def encode_rdata(msg)
- raise EncodeError.new("#{self.type} is query.")
- end
-
- def self.decode_rdata(msg)
- raise DecodeError.new("#{self.type} is query.")
- end
- end
-
- class Resource < Query
- ClassHash = {}
-
- def encode_rdata(msg)
- raise NotImplementedError.new
- end
-
- def self.decode_rdata(msg)
- raise NotImplementedError.new
- end
-
- def ==(other)
- return self.type == other.type &&
- self.instance_variables == other.instance_variables &&
- self.instance_variables.collect {|name| self.instance_eval name} ==
- other.instance_variables.collect {|name| other.instance_eval name}
- end
-
- def eql?(other)
- return self == other
- end
-
- def hash
- h = 0
- self.instance_variables.each {|name|
- h += self.instance_eval("#{name}.hash")
- }
- return h
- end
-
- def self.get_class(type_value, class_value)
- return ClassHash[[type_value, class_value]] ||
- Generic.create(type_value, class_value)
- end
-
- class Generic < Resource
- def initialize(data)
- @data = data
- end
- attr_reader :data
-
- def encode_rdata(msg)
- msg.put_bytes(data)
- end
-
- def self.decode_rdata(msg)
- return self.new(msg.get_bytes)
- end
-
- def self.create(type_value, class_value)
- c = Class.new(Generic)
- c.const_set(:TypeValue, type_value)
- c.const_set(:ClassValue, class_value)
- Generic.const_set("Type#{type_value}_Class#{class_value}", c)
- ClassHash[[type_value, class_value]] = c
- return c
- end
- end
-
- class DomainName < Resource
- def initialize(name)
- @name = name
- end
- attr_reader :name
-
- def encode_rdata(msg)
- msg.put_name(@name)
- end
-
- def self.decode_rdata(msg)
- return self.new(msg.get_name)
- end
- end
-
- # Standard (class generic) RRs
- ClassValue = nil
-
- class NS < DomainName
- TypeValue = 2
- end
-
- class CNAME < DomainName
- TypeValue = 5
- end
-
- class SOA < Resource
- TypeValue = 6
-
- def initialize(mname, rname, serial, refresh, retry_, expire, minimum)
- @mname = mname
- @rname = rname
- @serial = serial
- @refresh = refresh
- @retry = retry_
- @expire = expire
- @minimum = minimum
- end
- attr_reader :mname, :rname, :serial, :refresh, :retry, :expire, :minimum
-
- def encode_rdata(msg)
- msg.put_name(@mname)
- msg.put_name(@rname)
- msg.put_pack('NNNNN', @serial, @refresh, @retry, @expire, @minimum)
- end
-
- def self.decode_rdata(msg)
- mname = msg.get_name
- rname = msg.get_name
- serial, refresh, retry_, expire, minimum = msg.get_unpack('NNNNN')
- return self.new(
- mname, rname, serial, refresh, retry_, expire, minimum)
- end
- end
-
- class PTR < DomainName
- TypeValue = 12
- end
-
- class HINFO < Resource
- TypeValue = 13
-
- def initialize(cpu, os)
- @cpu = cpu
- @os = os
- end
- attr_reader :cpu, :os
-
- def encode_rdata(msg)
- msg.put_string(@cpu)
- msg.put_string(@os)
- end
-
- def self.decode_rdata(msg)
- cpu = msg.get_string
- os = msg.get_string
- return self.new(cpu, os)
- end
- end
-
- class MINFO < Resource
- TypeValue = 14
-
- def initialize(rmailbx, emailbx)
- @rmailbx = rmailbx
- @emailbx = emailbx
- end
- attr_reader :rmailbx, :emailbx
-
- def encode_rdata(msg)
- msg.put_name(@rmailbx)
- msg.put_name(@emailbx)
- end
-
- def self.decode_rdata(msg)
- rmailbx = msg.get_string
- emailbx = msg.get_string
- return self.new(rmailbx, emailbx)
- end
- end
-
- class MX < Resource
- TypeValue= 15
-
- def initialize(preference, exchange)
- @preference = preference
- @exchange = exchange
- end
- attr_reader :preference, :exchange
-
- def encode_rdata(msg)
- msg.put_pack('n', @preference)
- msg.put_name(@exchange)
- end
-
- def self.decode_rdata(msg)
- preference, = msg.get_unpack('n')
- exchange = msg.get_name
- return self.new(preference, exchange)
- end
- end
-
- class TXT < Resource
- TypeValue = 16
-
- def initialize(data)
- @data = data
- end
- attr_reader :data
-
- def encode_rdata(msg)
- msg.put_string(@data)
- end
-
- def self.decode_rdata(msg)
- data = msg.get_string
- return self.new(data)
- end
- end
-
- class ANY < Query
- TypeValue = 255
- end
-
- ClassInsensitiveTypes = [
- NS, CNAME, SOA, PTR, HINFO, MINFO, MX, TXT, ANY
- ]
-
- # ARPA Internet specific RRs
- module IN
- ClassValue = 1
-
- ClassInsensitiveTypes.each {|s|
- c = Class.new(s)
- c.const_set(:TypeValue, s::TypeValue)
- c.const_set(:ClassValue, ClassValue)
- ClassHash[[s::TypeValue, ClassValue]] = c
- self.const_set(s.name.sub(/.*::/, ''), c)
- }
-
- class A < Resource
- ClassHash[[TypeValue = 1, ClassValue = ClassValue]] = self
-
- def initialize(address)
- @address = IPv4.create(address)
- end
- attr_reader :address
-
- def encode_rdata(msg)
- msg.put_bytes(@address.address)
- end
-
- def self.decode_rdata(msg)
- return self.new(IPv4.new(msg.get_bytes(4)))
- end
- end
-
- class WKS < Resource
- ClassHash[[TypeValue = 11, ClassValue = ClassValue]] = self
-
- def initialize(address, protocol, bitmap)
- @address = IPv4.create(address)
- @protocol = protocol
- @bitmap = bitmap
- end
- attr_reader :address, :protocol, :bitmap
-
- def encode_rdata(msg)
- msg.put_bytes(@address.address)
- msg.put_pack("n", @protocol)
- msg.put_bytes(@bitmap)
- end
-
- def self.decode_rdata(msg)
- address = IPv4.new(msg.get_bytes(4))
- protocol, = msg.get_unpack("n")
- bitmap = msg.get_bytes
- return self.new(address, protocol, bitmap)
- end
- end
-
- class AAAA < Resource
- ClassHash[[TypeValue = 28, ClassValue = ClassValue]] = self
-
- def initialize(address)
- @address = IPv6.create(address)
- end
- attr_reader :address
-
- def encode_rdata(msg)
- msg.put_bytes(@address.address)
- end
-
- def self.decode_rdata(msg)
- return self.new(IPv6.new(msg.get_bytes(16)))
- end
- end
- end
- end
- end
-
- class IPv4
- Regex = /\A(\d+)\.(\d+)\.(\d+)\.(\d+)\z/
-
- def self.create(arg)
- case arg
- when IPv4
- return arg
- when Regex
- if (0..255) === (a = $1.to_i) &&
- (0..255) === (b = $2.to_i) &&
- (0..255) === (c = $3.to_i) &&
- (0..255) === (d = $4.to_i)
- return self.new([a, b, c, d].pack("CCCC"))
- else
- raise ArgumentError.new("IPv4 address with invalid value: " + arg)
- end
- else
- raise ArgumentError.new("cannot interprete as IPv4 address: #{arg.inspect}")
- end
- end
-
- def initialize(address)
- unless address.kind_of?(String) && address.length == 4
- raise ArgumentError.new('IPv4 address muse be 4 bytes')
- end
- @address = address
- end
- attr_reader :address
-
- def to_s
- return sprintf("%d.%d.%d.%d", *@address.unpack("CCCC"))
- end
-
- def inspect
- return "#<#{self.class} #{self.to_s}>"
- end
-
- def to_name
- return DNS::Name.create(
- '%d.%d.%d.%d.in-addr.arpa.' % @address.unpack('CCCC').reverse)
- end
-
- def ==(other)
- return @address == other.address
- end
-
- def eql?(other)
- return self == other
- end
-
- def hash
- return @address.hash
- end
- end
-
- class IPv6
- Regex_8Hex = /\A
- (?:[0-9A-Fa-f]{1,4}:){7}
- [0-9A-Fa-f]{1,4}
- \z/x
-
- Regex_CompressedHex = /\A
- ((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::
- ((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)
- \z/x
-
- Regex_6Hex4Dec = /\A
- ((?:[0-9A-Fa-f]{1,4}:){6,6})
- (\d+)\.(\d+)\.(\d+)\.(\d+)
- \z/x
-
- Regex_CompressedHex4Dec = /\A
- ((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::
- ((?:[0-9A-Fa-f]{1,4}:)*)
- (\d+)\.(\d+)\.(\d+)\.(\d+)
- \z/x
-
- Regex = /
- (?:#{Regex_8Hex.source}) |
- (?:#{Regex_CompressedHex.source}) |
- (?:#{Regex_6Hex4Dec.source}) |
- (?:#{Regex_CompressedHex4Dec.source})/x
-
- def self.create(arg)
- case arg
- when IPv6
- return arg
- when String
- address = ''
- if Regex_8Hex =~ arg
- arg.scan(/[0-9A-Fa-f]+/) {|hex| address << [hex.hex].pack('n')}
- elsif Regex_CompressedHex =~ arg
- prefix = $1
- suffix = $2
- a1 = ''
- a2 = ''
- prefix.scan(/[0-9A-Fa-f]+/) {|hex| a1 << [hex.hex].pack('n')}
- suffix.scan(/[0-9A-Fa-f]+/) {|hex| a2 << [hex.hex].pack('n')}
- omitlen = 16 - a1.length - a2.length
- address << a1 << "\0" * omitlen << a2
- elsif Regex_6Hex4Dec =~ arg
- prefix, a, b, c, d = $1, $2.to_i, $3.to_i, $4.to_i, $5.to_i
- if (0..255) === a && (0..255) === b && (0..255) === c && (0..255) === d
- prefix.scan(/[0-9A-Fa-f]+/) {|hex| address << [hex.hex].pack('n')}
- address << [a, b, c, d].pack('CCCC')
- else
- raise ArgumentError.new("not numeric IPv6 address: " + arg)
- end
- elsif Regex_CompressedHex4Dec =~ arg
- prefix, suffix, a, b, c, d = $1, $2, $3.to_i, $4.to_i, $5.to_i, $6.to_i
- if (0..255) === a && (0..255) === b && (0..255) === c && (0..255) === d
- a1 = ''
- a2 = ''
- prefix.scan(/[0-9A-Fa-f]+/) {|hex| a1 << [hex.hex].pack('n')}
- suffix.scan(/[0-9A-Fa-f]+/) {|hex| a2 << [hex.hex].pack('n')}
- omitlen = 12 - a1.length - a2.length
- address << a1 << "\0" * omitlen << a2 << [a, b, c, d].pack('CCCC')
- else
- raise ArgumentError.new("not numeric IPv6 address: " + arg)
- end
- else
- raise ArgumentError.new("not numeric IPv6 address: " + arg)
- end
- return IPv6.new(address)
- else
- raise ArgumentError.new("cannot interprete as IPv6 address: #{arg.inspect}")
- end
- end
-
- def initialize(address)
- unless address.kind_of?(String) && address.length == 16
- raise ArgumentError.new('IPv6 address muse be 16 bytes')
- end
- @address = address
- end
- attr_reader :address
-
- def to_s
- address = sprintf("%X:%X:%X:%X:%X:%X:%X:%X", *@address.unpack("nnnnnnnn"))
- unless address.sub!(/(^|:)0(:0)+(:|$)/, '::')
- address.sub!(/(^|:)0(:|$)/, '::')
- end
- return address
- end
-
- def inspect
- return "#<#{self.class} #{self.to_s}>"
- end
-
- def to_name
- # ip6.arpa should be searched too. [RFC3152]
- return DNS::Name.new(
- @address.unpack("H32")[0].split(//).reverse + ['ip6', 'int'])
- end
-
- def ==(other)
- return @address == other.address
- end
-
- def eql?(other)
- return self == other
- end
-
- def hash
- return @address.hash
- end
- end
-
- DefaultResolver = self.new
- AddressRegex = /(?:#{IPv4::Regex.source})|(?:#{IPv6::Regex.source})/
-end
diff --git a/lib/shell.rb b/lib/shell.rb
deleted file mode 100644
index acc4adec0b..0000000000
--- a/lib/shell.rb
+++ /dev/null
@@ -1,270 +0,0 @@
-#
-# shell.rb -
-# $Release Version: 0.6.0 $
-# $Revision: 1.8 $
-# $Date: 2001/03/19 09:01:11 $
-# by Keiju ISHITSUKA(Nippon Rational Inc.)
-#
-# --
-#
-#
-#
-
-require "e2mmap"
-require "thread"
-
-require "shell/error"
-require "shell/command-processor"
-require "shell/process-controller"
-
-class Shell
- @RCS_ID='-$Id: shell.rb,v 1.8 2001/03/19 09:01:11 keiju Exp keiju $-'
-
- include Error
- extend Exception2MessageMapper
-
-# @cascade = true
- # debug: true -> normal debug
- # debug: 1 -> eval definition debug
- # debug: 2 -> detail inspect debug
- @debug = false
- @verbose = true
-
- class << Shell
- attr :cascade, true
- attr :debug, true
- attr :verbose, true
-
-# alias cascade? cascade
- alias debug? debug
- alias verbose? verbose
- @verbose = true
-
- def debug=(val)
- @debug = val
- @verbose = val if val
- end
-
- def cd(path)
- sh = new
- sh.cd path
- sh
- end
-
- def default_system_path
- if @default_system_path
- @default_system_path
- else
- ENV["PATH"].split(":")
- end
- end
-
- def default_system_path=(path)
- @default_system_path = path
- end
-
- def default_record_separator
- if @default_record_separator
- @default_record_separator
- else
- $/
- end
- end
-
- def default_record_separator=(rs)
- @default_record_separator = rs
- end
- end
-
- def initialize
- @cwd = Dir.pwd
- @dir_stack = []
- @umask = nil
-
- @system_path = Shell.default_system_path
- @record_separator = Shell.default_record_separator
-
- @command_processor = CommandProcessor.new(self)
- @process_controller = ProcessController.new(self)
-
- @verbose = Shell.verbose
- @debug = Shell.debug
- end
-
- attr_reader :system_path
-
- def system_path=(path)
- @system_path = path
- rehash
- end
-
- attr :umask, true
- attr :record_separator, true
-
- attr :verbose, true
- attr :debug, true
-
- def debug=(val)
- @debug = val
- @verbose = val if val
- end
-
- alias verbose? verbose
- alias debug? debug
-
- attr_reader :command_processor
- attr_reader :process_controller
-
- def expand_path(path)
- File.expand_path(path, @cwd)
- end
-
- # Most Shell commands are defined via CommandProcessor
-
- #
- # Dir related methods
- #
- # Shell#cwd/dir/getwd/pwd
- # Shell#chdir/cd
- # Shell#pushdir/pushd
- # Shell#popdir/popd
- # Shell#mkdir
- # Shell#rmdir
-
- attr :cwd
- alias dir cwd
- alias getwd cwd
- alias pwd cwd
-
- attr :dir_stack
- alias dirs dir_stack
-
- # If called as iterator, it restores the current directory when the
- # block ends.
- def chdir(path = nil)
- if iterator?
- cwd_old = @cwd
- begin
- chdir(path)
- yield
- ensure
- chdir(cwd_old)
- end
- else
- path = "~" unless path
- @cwd = expand_path(path)
- notify "current dir: #{@cwd}"
- rehash
- self
- end
- end
- alias cd chdir
-
- def pushdir(path = nil)
- if iterator?
- pushdir(path)
- begin
- yield
- ensure
- popdir
- end
- elsif path
- @dir_stack.push @cwd
- chdir path
- notify "dir stack: [#{@dir_stack.join ', '}]"
- self
- else
- if pop = @dir_stack.pop
- @dir_stack.push @cwd
- chdir pop
- notify "dir stack: [#{@dir_stack.join ', '}]"
- self
- else
- Shell.Fail DirStackEmpty
- end
- end
- end
- alias pushd pushdir
-
- def popdir
- if pop = @dir_stack.pop
- chdir pop
- notify "dir stack: [#{@dir_stack.join ', '}]"
- self
- else
- Shell.Fail DirStackEmpty
- end
- end
- alias popd popdir
-
-
- #
- # process management
- #
- def jobs
- @process_controller.jobs
- end
-
- def kill(sig, command)
- @process_controller.kill_job(sig, command)
- end
-
- #
- # command definitions
- #
- def Shell.def_system_command(command, path = command)
- CommandProcessor.def_system_command(command, path)
- end
-
- def Shell.undef_system_command(command)
- CommandProcessor.undef_system_command(command)
- end
-
- def Shell.alias_command(ali, command, *opts, &block)
- CommandProcessor.alias_command(ali, command, *opts, &block)
- end
-
- def Shell.unalias_command(ali)
- CommandProcessor.unalias_command(ali)
- end
-
- def Shell.install_system_commands(pre = "sys_")
- CommandProcessor.install_system_commands(pre)
- end
-
- #
- def inspect
- if debug.kind_of?(Integer) && debug > 2
- super
- else
- to_s
- end
- end
-
- def self.notify(*opts, &block)
- Thread.exclusive do
- if opts[-1].kind_of?(String)
- yorn = verbose?
- else
- yorn = opts.pop
- end
- return unless yorn
-
- _head = true
- print opts.collect{|mes|
- mes = mes.dup
- yield mes if iterator?
- if _head
- _head = false
- "shell: " + mes
- else
- " " + mes
- end
- }.join("\n")+"\n"
- end
- end
-
- CommandProcessor.initialize
- CommandProcessor.run_config
-end
-
diff --git a/lib/shell/builtin-command.rb b/lib/shell/builtin-command.rb
deleted file mode 100644
index db1adfa48b..0000000000
--- a/lib/shell/builtin-command.rb
+++ /dev/null
@@ -1,154 +0,0 @@
-#
-# shell/builtin-command.rb -
-# $Release Version: 0.6.0 $
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)
-#
-# --
-#
-#
-#
-
-require "shell/filter"
-
-class Shell
- class BuiltInCommand<Filter
- def wait?
- false
- end
- def active?
- true
- end
- end
-
- class Echo < BuiltInCommand
- def initialize(sh, *strings)
- super sh
- @strings = strings
- end
-
- def each(rs = nil)
- rs = @shell.record_separator unless rs
- for str in @strings
- yield str + rs
- end
- end
- end
-
- class Cat < BuiltInCommand
- def initialize(sh, *filenames)
- super sh
- @cat_files = filenames
- end
-
- def each(rs = nil)
- if @cat_files.empty?
- super
- else
- for src in @cat_files
- @shell.foreach(src, rs){|l| yield l}
- end
- end
- end
- end
-
- class Glob < BuiltInCommand
- def initialize(sh, pattern)
- super sh
-
- @pattern = pattern
- Thread.critical = true
- back = Dir.pwd
- begin
- Dir.chdir @shell.cwd
- @files = Dir[pattern]
- ensure
- Dir.chdir back
- Thread.critical = false
- end
- end
-
- def each(rs = nil)
- rs = @shell.record_separator unless rs
- for f in @files
- yield f+rs
- end
- end
- end
-
-# class Sort < Cat
-# def initialize(sh, *filenames)
-# super
-# end
-#
-# def each(rs = nil)
-# ary = []
-# super{|l| ary.push l}
-# for l in ary.sort!
-# yield l
-# end
-# end
-# end
-
- class AppendIO < BuiltInCommand
- def initialize(sh, io, filter)
- super sh
- @input = filter
- @io = io
- end
-
- def input=(filter)
- @input.input=filter
- for l in @input
- @io << l
- end
- end
-
- end
-
- class AppendFile < AppendIO
- def initialize(sh, to_filename, filter)
- @file_name = to_filename
- io = sh.open(to_filename, "a")
- super(sh, io, filter)
- end
-
- def input=(filter)
- begin
- super
- ensure
- @io.close
- end
- end
- end
-
- class Tee < BuiltInCommand
- def initialize(sh, filename)
- super sh
- @to_filename = filename
- end
-
- def each(rs = nil)
- to = @shell.open(@to_filename, "w")
- begin
- super{|l| to << l; yield l}
- ensure
- to.close
- end
- end
- end
-
- class Concat < BuiltInCommand
- def initialize(sh, *jobs)
- super(sh)
- @jobs = jobs
- end
-
- def each(rs = nil)
- while job = @jobs.shift
- job.each{|l| yield l}
- end
- end
- end
-end
diff --git a/lib/shell/command-processor.rb b/lib/shell/command-processor.rb
deleted file mode 100644
index 459cf858d0..0000000000
--- a/lib/shell/command-processor.rb
+++ /dev/null
@@ -1,584 +0,0 @@
-#
-# shell/command-controller.rb -
-# $Release Version: 0.6.0 $
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(Nippon Rational Inc.)
-#
-# --
-#
-#
-#
-
-require "e2mmap"
-require "ftools"
-require "thread"
-
-require "shell/error"
-require "shell/filter"
-require "shell/system-command"
-require "shell/builtin-command"
-
-class Shell
- class CommandProcessor
-
- #
- # initialize of Shell and related classes.
- #
- NoDelegateMethods = ["initialize", "expand_path"]
- def self.initialize
-
- install_builtin_commands
-
- # define CommandProccessor#methods to Shell#methods and Filter#methods
- for m in CommandProcessor.instance_methods - NoDelegateMethods
- add_delegate_command_to_shell(m)
- end
-
- def self.method_added(id)
- add_delegate_command_to_shell(id)
- end
- end
-
- #
- # include run file.
- #
- def self.run_config
- begin
- load File.expand_path("~/.rb_shell") if ENV.key?("HOME")
- rescue LoadError, Errno::ENOENT
- rescue
- print "load error: #{rc}\n"
- print $!.type, ": ", $!, "\n"
- for err in $@[0, $@.size - 2]
- print "\t", err, "\n"
- end
- end
- end
-
- def initialize(shell)
- @shell = shell
- @system_commands = {}
- end
-
- #
- # CommandProcessor#expand_path(path)
- # path: String
- # return: String
- # returns the absolute path for <path>
- #
- def expand_path(path)
- @shell.expand_path(path)
- end
-
- #
- # File related commands
- # Shell#foreach
- # Shell#open
- # Shell#unlink
- # Shell#test
- #
- # -
- #
- # CommandProcessor#foreach(path, rs)
- # path: String
- # rs: String - record separator
- # iterator
- # Same as:
- # File#foreach (when path is file)
- # Dir#foreach (when path is directory)
- # path is relative to pwd
- #
- def foreach(path = nil, *rs)
- path = "." unless path
- path = expand_path(path)
-
- if File.directory?(path)
- Dir.foreach(path){|fn| yield fn}
- else
- IO.foreach(path, *rs){|l| yield l}
- end
- end
-
- #
- # CommandProcessor#open(path, mode)
- # path: String
- # mode: String
- # return: File or Dir
- # Same as:
- # File#open (when path is file)
- # Dir#open (when path is directory)
- # mode has an effect only when path is a file
- #
- def open(path, mode)
- path = expand_path(path)
- if File.directory?(path)
- Dir.open(path)
- else
- effect_umask do
- File.open(path, mode)
- end
- end
- end
- # public :open
-
- #
- # CommandProcessor#unlink(path)
- # same as:
- # Dir#unlink (when path is directory)
- # File#unlink (when path is file)
- #
- def unlink(path)
- path = expand_path(path)
- if File.directory?(path)
- Dir.unlink(path)
- else
- IO.unlink(path)
- end
- end
-
- #
- # CommandProcessor#test(command, file1, file2)
- # CommandProcessor#[command, file1, file2]
- # command: char or String or Symbol
- # file1: String
- # file2: String(optional)
- # return: Boolean
- # same as:
- # test() (when command is char or length 1 string or sumbol)
- # FileTest.command (others)
- # example:
- # sh[?e, "foo"]
- # sh[:e, "foo"]
- # sh["e", "foo"]
- # sh[:exists?, "foo"]
- # sh["exists?", "foo"]
- #
- def test(command, file1, file2=nil)
- file1 = expand_path(file1)
- file2 = expand_path(file2) if file2
- command = command.id2name if command.kind_of?(Symbol)
-
- case command
- when Integer
- top_level_test(command, file1, file2)
- when String
- if command.size == 1
- if file2
- top_level_test(command, file1, file2)
- else
- top_level_test(command, file1)
- end
- else
- if file2
- FileTest.send(command, file1, file2)
- else
- FileTest.send(command, file1)
- end
- end
- end
- end
- alias [] test
-
- #
- # Dir related methods
- #
- # Shell#mkdir
- # Shell#rmdir
- #
- #--
- #
- # CommandProcessor#mkdir(*path)
- # path: String
- # same as Dir.mkdir()
- #
- def mkdir(*path)
- for dir in path
- Dir.mkdir(expand_path(dir))
- end
- end
-
- #
- # CommandProcessor#rmdir(*path)
- # path: String
- # same as Dir.rmdir()
- #
- def rmdir(*path)
- for dir in path
- Dir.rmdir(expand_path(path))
- end
- end
-
- #
- # CommandProcessor#system(command, *opts)
- # command: String
- # opts: String
- # retuen: SystemCommand
- # Same as system() function
- # example:
- # print sh.system("ls", "-l")
- # sh.system("ls", "-l") | sh.head > STDOUT
- #
- def system(command, *opts)
- SystemCommand.new(@shell, find_system_command(command), *opts)
- end
-
- #
- # ProcessCommand#rehash
- # clear command hash table.
- #
- def rehash
- @system_commands = {}
- end
-
- #
- # ProcessCommand#transact
- #
- def check_point
- @shell.process_controller.wait_all_jobs_execution
- end
- alias finish_all_jobs check_point
-
- def transact(&block)
- begin
- @shell.instance_eval(&block)
- ensure
- check_point
- end
- end
-
- #
- # internal commands
- #
- def out(dev = STDOUT, &block)
- dev.print transact(&block)
- end
-
- def echo(*strings)
- Echo.new(@shell, *strings)
- end
-
- def cat(*filenames)
- Cat.new(@shell, *filenames)
- end
-
- # def sort(*filenames)
- # Sort.new(self, *filenames)
- # end
-
- def glob(pattern)
- Glob.new(@shell, pattern)
- end
-
- def append(to, filter)
- case to
- when String
- AppendFile.new(@shell, to, filter)
- when IO
- AppendIO.new(@shell, to, filter)
- else
- Shell.Fail CanNotMethodApply, "append", to.type
- end
- end
-
- def tee(file)
- Tee.new(@shell, file)
- end
-
- def concat(*jobs)
- Concat.new(@shell, *jobs)
- end
-
- # %pwd, %cwd -> @pwd
- def notify(*opts, &block)
- Thread.exclusive do
- Shell.notify(*opts) {|mes|
- yield mes if iterator?
-
- mes.gsub!("%pwd", "#{@cwd}")
- mes.gsub!("%cwd", "#{@cwd}")
- }
- end
- end
-
- #
- # private functions
- #
- def effect_umask
- if @shell.umask
- Thread.critical = true
- save = File.umask
- begin
- yield
- ensure
- File.umask save
- Thread.critical = false
- end
- else
- yield
- end
- end
- private :effect_umask
-
- def find_system_command(command)
- return command if /^\// =~ command
- case path = @system_commands[command]
- when String
- if exists?(path)
- return path
- else
- Shell.Fail CommandNotFound, command
- end
- when false
- Shell.Fail CommandNotFound, command
- end
-
- for p in @shell.system_path
- path = join(p, command)
- if FileTest.exists?(path)
- @system_commands[command] = path
- return path
- end
- end
- @system_commands[command] = false
- Shell.Fail CommandNotFound, command
- end
-
- #
- # CommandProcessor.def_system_command(command, path)
- # command: String
- # path: String
- # define 'command()' method as method.
- #
- def self.def_system_command(command, path = command)
- begin
- eval((d = %Q[def #{command}(*opts)
- SystemCommand.new(@shell, '#{path}', *opts)
- end]), nil, __FILE__, __LINE__ - 1)
- rescue SyntaxError
- Shell.notify "warn: Can't define #{command} path: #{path}."
- end
- Shell.notify "Define #{command} path: #{path}.", Shell.debug?
- Shell.notify("Definition of #{command}: ", d,
- Shell.debug.kind_of?(Integer) && Shell.debug > 1)
- end
-
- def self.undef_system_command(command)
- command = command.id2name if command.kind_of?(Symbol)
- remove_method(command)
- Shell.module_eval{remove_method(command)}
- Filter.module_eval{remove_method(command)}
- self
- end
-
- # define command alias
- # ex)
- # def_alias_command("ls_c", "ls", "-C", "-F")
- # def_alias_command("ls_c", "ls"){|*opts| ["-C", "-F", *opts]}
- #
- @alias_map = {}
- def self.alias_map
- @alias_map
- end
- def self.alias_command(ali, command, *opts, &block)
- ali = ali.id2name if ali.kind_of?(Symbol)
- command = command.id2name if command.kind_of?(Symbol)
- begin
- if iterator?
- @alias_map[ali.intern] = proc
-
- eval((d = %Q[def #{ali}(*opts)
- @shell.__send__(:#{command},
- *(CommandProcessor.alias_map[:#{ali}].call *opts))
- end]), nil, __FILE__, __LINE__ - 1)
-
- else
- args = opts.collect{|opt| '"' + opt + '"'}.join ","
- eval((d = %Q[def #{ali}(*opts)
- @shell.__send__(:#{command}, #{args}, *opts)
- end]), nil, __FILE__, __LINE__ - 1)
- end
- rescue SyntaxError
- Shell.notify "warn: Can't alias #{ali} command: #{command}."
- Shell.notify("Definition of #{ali}: ", d)
- raise
- end
- Shell.notify "Define #{ali} command: #{command}.", Shell.debug?
- Shell.notify("Definition of #{ali}: ", d,
- Shell.debug.kind_of?(Integer) && Shell.debug > 1)
- self
- end
-
- def self.unalias_command(ali)
- ali = ali.id2name if ali.kind_of?(Symbol)
- @alias_map.delete ali.intern
- undef_system_command(ali)
- end
-
- #
- # CommandProcessor.def_builtin_commands(delegation_class, command_specs)
- # delegation_class: Class or Module
- # command_specs: [[command_name, [argument,...]],...]
- # command_name: String
- # arguments: String
- # FILENAME?? -> expand_path(filename??)
- # *FILENAME?? -> filename??.collect{|f|expand_path(f)}.join(", ")
- # define command_name(argument,...) as
- # delegation_class.command_name(argument,...)
- #
- def self.def_builtin_commands(delegation_class, command_specs)
- for meth, args in command_specs
- arg_str = args.collect{|arg| arg.downcase}.join(", ")
- call_arg_str = args.collect{
- |arg|
- case arg
- when /^(FILENAME.*)$/
- format("expand_path(%s)", $1.downcase)
- when /^(\*FILENAME.*)$/
- # \*FILENAME* -> filenames.collect{|fn| expand_path(fn)}.join(", ")
- $1.downcase + '.collect{|fn| expand_path(fn)}'
- else
- arg
- end
- }.join(", ")
- d = %Q[def #{meth}(#{arg_str})
- #{delegation_class}.#{meth}(#{call_arg_str})
- end]
- Shell.notify "Define #{meth}(#{arg_str})", Shell.debug?
- Shell.notify("Definition of #{meth}: ", d,
- Shell.debug.kind_of?(Integer) && Shell.debug > 1)
- eval d
- end
- end
-
- #
- # CommandProcessor.install_system_commands(pre)
- # pre: String - command name prefix
- # defines every command which belongs in default_system_path via
- # CommandProcessor.command(). It doesn't define already defined
- # methods twice. By default, "pre_" is prefixes to each method
- # name. Characters that may not be used in a method name are
- # all converted to '_'. Definition errors are just ignored.
- #
- def self.install_system_commands(pre = "sys_")
- defined_meth = {}
- for m in Shell.methods
- defined_meth[m] = true
- end
- sh = Shell.new
- for path in Shell.default_system_path
- next unless sh.directory? path
- sh.cd path
- sh.foreach do
- |cn|
- if !defined_meth[pre + cn] && sh.file?(cn) && sh.executable?(cn)
- command = (pre + cn).gsub(/\W/, "_").sub(/^([0-9])/, '_\1')
- begin
- def_system_command(command, sh.expand_path(cn))
- rescue
- Shell.notify "warn: Can't define #{command} path: #{cn}"
- end
- defined_meth[command] = command
- end
- end
- end
- end
-
- #----------------------------------------------------------------------
- #
- # class initializing methods -
- #
- #----------------------------------------------------------------------
- def self.add_delegate_command_to_shell(id)
- id = id.intern if id.kind_of?(String)
- name = id.id2name
- if Shell.method_defined?(id)
- Shell.notify "warn: override definnition of Shell##{name}."
- Shell.notify "warn: alias Shell##{name} to Shell##{name}_org.\n"
- Shell.module_eval "alias #{name}_org #{name}"
- end
- Shell.notify "method added: Shell##{name}.", Shell.debug?
- Shell.module_eval(%Q[def #{name}(*args, &block)
- begin
- @command_processor.__send__(:#{name}, *args, &block)
- rescue Exception
- $@.delete_if{|s| /:in `__getobj__'$/ =~ s} #`
- $@.delete_if{|s| /^\\(eval\\):/ =~ s}
- raise
- end
- end], __FILE__, __LINE__)
-
- if Shell::Filter.method_defined?(id)
- Shell.notify "warn: override definnition of Shell::Filter##{name}."
- Shell.notify "warn: alias Shell##{name} to Shell::Filter##{name}_org."
- Filter.module_eval "alias #{name}_org #{name}"
- end
- Shell.notify "method added: Shell::Filter##{name}.", Shell.debug?
- Filter.module_eval(%Q[def #{name}(*args, &block)
- begin
- self | @shell.__send__(:#{name}, *args, &block)
- rescue Exception
- $@.delete_if{|s| /:in `__getobj__'$/ =~ s} #`
- $@.delete_if{|s| /^\\(eval\\):/ =~ s}
- raise
- end
- end], __FILE__, __LINE__)
- end
-
- #
- # define default builtin commands
- #
- def self.install_builtin_commands
- # method related File.
- # (exclude open/foreach/unlink)
- normal_delegation_file_methods = [
- ["atime", ["FILENAME"]],
- ["basename", ["fn", "*opts"]],
- ["chmod", ["mode", "*FILENAMES"]],
- ["chown", ["owner", "group", "*FILENAME"]],
- ["ctime", ["FILENAMES"]],
- ["delete", ["*FILENAMES"]],
- ["dirname", ["FILENAME"]],
- ["ftype", ["FILENAME"]],
- ["join", ["*items"]],
- ["link", ["FILENAME_O", "FILENAME_N"]],
- ["lstat", ["FILENAME"]],
- ["mtime", ["FILENAME"]],
- ["readlink", ["FILENAME"]],
- ["rename", ["FILENAME_FROM", "FILENAME_TO"]],
- # ["size", ["FILENAME"]],
- ["split", ["pathname"]],
- ["stat", ["FILENAME"]],
- ["symlink", ["FILENAME_O", "FILENAME_N"]],
- ["truncate", ["FILENAME", "length"]],
- ["utime", ["atime", "mtime", "*FILENAMES"]]]
-
- def_builtin_commands(File, normal_delegation_file_methods)
- alias_method :rm, :delete
-
- # method related FileTest
- def_builtin_commands(FileTest,
- FileTest.singleton_methods.collect{|m| [m, ["FILENAME"]]})
-
- # method related ftools
- normal_delegation_ftools_methods = [
- ["syscopy", ["FILENAME_FROM", "FILENAME_TO"]],
- ["copy", ["FILENAME_FROM", "FILENAME_TO"]],
- ["move", ["FILENAME_FROM", "FILENAME_TO"]],
- ["compare", ["FILENAME_FROM", "FILENAME_TO"]],
- ["safe_unlink", ["*FILENAMES"]],
- ["makedirs", ["*FILENAMES"]],
- # ["chmod", ["mode", "*FILENAMES"]],
- ["install", ["FILENAME_FROM", "FILENAME_TO", "mode"]],
- ]
- def_builtin_commands(File,
- normal_delegation_ftools_methods)
- alias_method :cmp, :compare
- alias_method :mv, :move
- alias_method :cp, :copy
- alias_method :rm_f, :safe_unlink
- alias_method :mkpath, :makedirs
- end
-
- end
-end
diff --git a/lib/shell/error.rb b/lib/shell/error.rb
deleted file mode 100644
index df5e669af6..0000000000
--- a/lib/shell/error.rb
+++ /dev/null
@@ -1,26 +0,0 @@
-#
-# shell/error.rb -
-# $Release Version: 0.6.0 $
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)
-#
-# --
-#
-#
-#
-
-require "e2mmap"
-
-class Shell
- module Error
- extend Exception2MessageMapper
- def_e2message TypeError, "wrong argument type %s (expected %s)"
-
- def_exception :DirStackEmpty, "Directory stack empty."
- def_exception :CanNotDefine, "Can't define method(%s, %s)."
- def_exception :CanNotMethodApply, "This method(%s) can't apply this type(%s)."
- def_exception :CommandNotFound, "Command not found(%s)."
- end
-end
-
diff --git a/lib/shell/filter.rb b/lib/shell/filter.rb
deleted file mode 100644
index 441cded221..0000000000
--- a/lib/shell/filter.rb
+++ /dev/null
@@ -1,111 +0,0 @@
-#
-# shell/filter.rb -
-# $Release Version: 0.6.0 $
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)
-#
-# --
-#
-#
-#
-
-class Shell
- #
- # Filter
- # A method to require
- # each()
- #
- class Filter
- include Enumerable
- include Error
-
- def initialize(sh)
- @shell = sh # parent shell
- @input = nil # input filter
- end
-
- attr_reader :input
-
- def input=(filter)
- @input = filter
- end
-
- def each(rs = nil)
- rs = @shell.record_separator unless rs
- if @input
- @input.each(rs){|l| yield l}
- end
- end
-
- def < (src)
- case src
- when String
- cat = Cat.new(@shell, src)
- cat | self
- when IO
- self.input = src
- self
- else
- Filter.Fail CanNotMethodApply, "<", to.type
- end
- end
-
- def > (to)
- case to
- when String
- dst = @shell.open(to, "w")
- begin
- each(){|l| dst << l}
- ensure
- dst.close
- end
- when IO
- each(){|l| to << l}
- else
- Filter.Fail CanNotMethodApply, ">", to.type
- end
- self
- end
-
- def >> (to)
- begin
- Shell.cd(@shell.pwd).append(to, self)
- rescue CanNotMethodApply
- Shell.Fail CanNotMethodApply, ">>", to.type
- end
- end
-
- def | (filter)
- filter.input = self
- if active?
- @shell.process_controller.start_job filter
- end
- filter
- end
-
- def + (filter)
- Join.new(@shell, self, filter)
- end
-
- def to_a
- ary = []
- each(){|l| ary.push l}
- ary
- end
-
- def to_s
- str = ""
- each(){|l| str.concat l}
- str
- end
-
- def inspect
- if @shell.debug.kind_of?(Integer) && @shell.debug > 2
- super
- else
- to_s
- end
- end
- end
-end
diff --git a/lib/shell/process-controller.rb b/lib/shell/process-controller.rb
deleted file mode 100644
index 26fb1d9f08..0000000000
--- a/lib/shell/process-controller.rb
+++ /dev/null
@@ -1,258 +0,0 @@
-#
-# shell/process-controller.rb -
-# $Release Version: 0.6.0 $
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)
-#
-# --
-#
-#
-#
-
-require "mutex_m"
-require "monitor"
-require "sync"
-
-class Shell
- class ProcessController
-
- @ProcessControllers = {}
- @ProcessControllers.extend Mutex_m
-
- class<<self
-
- def process_controllers_exclusive
- begin
- @ProcessControllers.lock unless Thread.critical
- yield
- ensure
- @ProcessControllers.unlock unless Thread.critical
- end
- end
-
- def activate(pc)
- process_controllers_exclusive do
- @ProcessControllers[pc] ||= 0
- @ProcessControllers[pc] += 1
- end
- end
-
- def inactivate(pc)
- process_controllers_exclusive do
- if @ProcessControllers[pc]
- if (@ProcessControllers[pc] -= 1) == 0
- @ProcessControllers.delete(pc)
- end
- end
- end
- end
-
- def each_active_object
- process_controllers_exclusive do
- for ref in @ProcessControllers.keys
- yield ref
- end
- end
- end
- end
-
- def initialize(shell)
- @shell = shell
- @waiting_jobs = []
- @active_jobs = []
- @jobs_sync = Sync.new
-
- @job_monitor = Mutex.new
- @job_condition = ConditionVariable.new
- end
-
- def jobs
- jobs = []
- @jobs_sync.synchronize(:SH) do
- jobs.concat @waiting_jobs
- jobs.concat @active_jobs
- end
- jobs
- end
-
- def active_jobs
- @active_jobs
- end
-
- def waiting_jobs
- @waiting_jobs
- end
-
- def jobs_exist?
- @jobs_sync.synchronize(:SH) do
- @active_jobs.empty? or @waiting_jobs.empty?
- end
- end
-
- def active_jobs_exist?
- @jobs_sync.synchronize(:SH) do
- @active_jobs.empty?
- end
- end
-
- def waiting_jobs_exist?
- @jobs_sync.synchronize(:SH) do
- @waiting_jobs.empty?
- end
- end
-
- # schedule a command
- def add_schedule(command)
- @jobs_sync.synchronize(:EX) do
- ProcessController.activate(self)
- if @active_jobs.empty?
- start_job command
- else
- @waiting_jobs.push(command)
- end
- end
- end
-
- # start a job
- def start_job(command = nil)
- @jobs_sync.synchronize(:EX) do
- if command
- return if command.active?
- @waiting_jobs.delete command
- else
- command = @waiting_jobs.shift
- return unless command
- end
- @active_jobs.push command
- command.start
-
- # start all jobs that input from the job
- for job in @waiting_jobs
- start_job(job) if job.input == command
- end
- end
- end
-
- def waiting_job?(job)
- @jobs_sync.synchronize(:SH) do
- @waiting_jobs.include?(job)
- end
- end
-
- def active_job?(job)
- @jobs_sync.synchronize(:SH) do
- @active_jobs.include?(job)
- end
- end
-
- # terminate a job
- def terminate_job(command)
- @jobs_sync.synchronize(:EX) do
- @active_jobs.delete command
- ProcessController.inactivate(self)
- if @active_jobs.empty?
- start_job
- end
- end
- end
-
- # kill a job
- def kill_job(sig, command)
- @jobs_sync.synchronize(:SH) do
- if @waiting_jobs.delete command
- ProcessController.inactivate(self)
- return
- elsif @active_jobs.include?(command)
- begin
- r = command.kill sig
- ProcessController.inactivate(self)
- rescue
- print "Shell: Warn: $!\n" if @shell.verbose?
- return nil
- end
- @active_jobs.delete command
- r
- end
- end
- end
-
- # wait for all jobs to terminate
- def wait_all_jobs_execution
- @job_monitor.synchronize do
- begin
- while !jobs.empty?
- @job_condition.wait(@job_monitor)
- end
- ensure
- redo unless jobs.empty?
- end
- end
- end
-
- # simple fork
- def sfork(command, &block)
- pipe_me_in, pipe_peer_out = IO.pipe
- pipe_peer_in, pipe_me_out = IO.pipe
- Thread.critical = true
-
- STDOUT.flush
- ProcessController.each_active_object do |pc|
- for jobs in pc.active_jobs
- jobs.flush
- end
- end
-
- pid = fork {
- Thread.critical = true
-
- Thread.list.each do |th|
- th.kill unless [Thread.main, Thread.current].include?(th)
- end
-
- STDIN.reopen(pipe_peer_in)
- STDOUT.reopen(pipe_peer_out)
-
- ObjectSpace.each_object(IO) do |io|
- if ![STDIN, STDOUT, STDERR].include?(io)
- io.close unless io.closed?
- end
- end
- yield
- }
-
- pipe_peer_in.close
- pipe_peer_out.close
- command.notify "job(%name:##{pid}) start", @shell.debug?
- Thread.critical = false
-
- th = Thread.start {
- Thread.critical = true
- begin
- _pid = nil
- command.notify("job(%id) start to waiting finish.", @shell.debug?)
- Thread.critical = false
- _pid = Process.waitpid(pid, nil)
- rescue Errno::ECHILD
- command.notify "warn: job(%id) was done already waitipd."
- _pid = true
- ensure
- # when the process ends, wait until the command termintes
- if _pid
- else
- command.notify("notice: Process finishing...",
- "wait for Job[%id] to finish.",
- "You can use Shell#transact or Shell#check_point for more safe execution.")
- redo
- end
- Thread.exclusive do
- terminate_job(command)
- @job_condition.signal
- command.notify "job(%id) finish.", @shell.debug?
- end
- end
- }
- return pid, pipe_me_in, pipe_me_out
- end
- end
-end
diff --git a/lib/shell/system-command.rb b/lib/shell/system-command.rb
deleted file mode 100644
index c22b9ac0a4..0000000000
--- a/lib/shell/system-command.rb
+++ /dev/null
@@ -1,168 +0,0 @@
-#
-# shell/system-command.rb -
-# $Release Version: 0.6.0 $
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)
-#
-# --
-#
-#
-#
-
-require "shell/filter"
-
-class Shell
- class SystemCommand < Filter
- def initialize(sh, command, *opts)
- if t = opts.find{|opt| !opt.kind_of?(String) && opt.type}
- Shell.Fail TypeError, t.type, "String"
- end
- super(sh)
- @command = command
- @opts = opts
-
- @input_queue = Queue.new
- @pid = nil
-
- sh.process_controller.add_schedule(self)
- end
-
- attr_reader :command
- alias name command
-
- def wait?
- @shell.process_controller.waiting_job?(self)
- end
-
- def active?
- @shell.process_controller.active_job?(self)
- end
-
- def input=(inp)
- super
- if active?
- start_export
- end
- end
-
- def start
- @pid, @pipe_in, @pipe_out = @shell.process_controller.sfork(self) {
- Dir.chdir @shell.pwd
- exec(@command, *@opts)
- }
- if @input
- start_export
- end
- start_import
- end
-
- def flush
- @pipe_out.flush if @pipe_out and !@pipe_out.closed?
- end
-
- def terminate
- begin
- @pipe_in.close
- rescue IOError
- end
- begin
- @pipe_out.close
- rescue IOError
- end
- end
-
- def kill(sig)
- if @pid
- Process.kill(sig, @pid)
- end
- end
-
-
- def start_import
-# Thread.critical = true
- notify "Job(%id) start imp-pipe.", @shell.debug?
- rs = @shell.record_separator unless rs
- _eop = true
-# Thread.critical = false
- th = Thread.start {
- Thread.critical = true
- begin
- Thread.critical = false
- while l = @pipe_in.gets
- @input_queue.push l
- end
- _eop = false
- rescue Errno::EPIPE
- _eop = false
- ensure
- if _eop
- notify("warn: Process finishing...",
- "wait for Job[%id] to finish pipe importing.",
- "You can use Shell#transact or Shell#check_point for more safe execution.")
-# Tracer.on
- Thread.current.run
- redo
- end
- Thread.exclusive do
- notify "job(%id}) close imp-pipe.", @shell.debug?
- @input_queue.push :EOF
- @pipe_in.close
- end
- end
- }
- end
-
- def start_export
- notify "job(%id) start exp-pipe.", @shell.debug?
- _eop = true
- th = Thread.start{
- Thread.critical = true
- begin
- Thread.critical = false
- @input.each{|l| @pipe_out.print l}
- _eop = false
- rescue Errno::EPIPE
- _eop = false
- ensure
- if _eop
- notify("shell: warn: Process finishing...",
- "wait for Job(%id) to finish pipe exporting.",
- "You can use Shell#transact or Shell#check_point for more safe execution.")
-# Tracer.on
- redo
- end
- Thread.exclusive do
- notify "job(%id) close exp-pipe.", @shell.debug?
- @pipe_out.close
- end
- end
- }
- end
-
- alias super_each each
- def each(rs = nil)
- while (l = @input_queue.pop) != :EOF
- yield l
- end
- end
-
- # ex)
- # if you wish to output:
- # "shell: job(#{@command}:#{@pid}) close pipe-out."
- # then
- # mes: "job(%id) close pipe-out."
- # yorn: Boolean(@shell.debug? or @shell.verbose?)
- def notify(*opts, &block)
- Thread.exclusive do
- @shell.notify(*opts) {|mes|
- yield mes if iterator?
-
- mes.gsub!("%id", "#{@command}:##{@pid}")
- mes.gsub!("%name", "#{@command}")
- mes.gsub!("%pid", "#{@pid}")
- }
- end
- end
- end
-end
diff --git a/lib/shell/version.rb b/lib/shell/version.rb
deleted file mode 100644
index 6694c804d8..0000000000
--- a/lib/shell/version.rb
+++ /dev/null
@@ -1,16 +0,0 @@
-#
-# version.rb - shell version definition file
-# $Release Version: 0.6.0$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)
-#
-# --
-#
-#
-#
-
-class Shell
- @RELEASE_VERSION = "0.6.0"
- @LAST_UPDATE_DATE = "01/03/19"
-end
diff --git a/lib/shellwords.rb b/lib/shellwords.rb
deleted file mode 100644
index 9fd7571172..0000000000
--- a/lib/shellwords.rb
+++ /dev/null
@@ -1,49 +0,0 @@
-# shellwords.rb
-# original is shellwords.pl
-#
-# Usage:
-# require 'shellwords'
-# words = Shellwords.shellwords(line)
-#
-# or
-#
-# require 'shellwords'
-# include Shellwords
-# words = shellwords(line)
-
-module Shellwords
- def shellwords(line)
- unless line.kind_of?(String)
- raise ArgumentError, "Argument must be String class object."
- end
- line = line.sub(/\A\s+/, '')
- words = []
- while line != ''
- field = ''
- while true
- if line.sub!(/\A"(([^"\\]|\\.)*)"/, '') then #"
- snippet = $1
- snippet.gsub!(/\\(.)/, '\1')
- elsif line =~ /\A"/ then #"
- raise ArgumentError, "Unmatched double quote: #{line}"
- elsif line.sub!(/\A'(([^'\\]|\\.)*)'/, '') then #'
- snippet = $1
- snippet.gsub!(/\\(.)/, '\1')
- elsif line =~ /\A'/ then #'
- raise ArgumentError, "Unmatched single quote: #{line}"
- elsif line.sub!(/\A\\(.)/, '') then
- snippet = $1
- elsif line.sub!(/\A([^\s\\'"]+)/, '') then #'
- snippet = $1
- else
- line.sub!(/\A\s+/, '')
- break
- end
- field.concat(snippet)
- end
- words.push(field)
- end
- words
- end
- module_function :shellwords
-end
diff --git a/lib/singleton.rb b/lib/singleton.rb
deleted file mode 100644
index 6ff6d190f2..0000000000
--- a/lib/singleton.rb
+++ /dev/null
@@ -1,336 +0,0 @@
-# The Singleton module implements the Singleton pattern.
-#
-# Usage:
-# class Klass
-# include Singleton
-# # ...
-# end
-#
-# * this ensures that only one instance of Klass lets call it
-# ``the instance'' can be created.
-#
-# a,b = Klass.instance, Klass.instance
-# a == b # => true
-# a.new # NoMethodError - new is private ...
-#
-# * ``The instance'' is created at instanciation time, in other words
-# the first call of Klass.instance(), thus
-#
-# class OtherKlass
-# include Singleton
-# # ...
-# end
-# ObjectSpace.each_object(OtherKlass){} # => 0.
-#
-# * This behavior is preserved under inheritance and cloning.
-#
-#
-# This is achieved by marking
-# * Klass.new and Klass.allocate - as private
-# * removing #clone and #dup and modifying
-# * Klass.inherited(sub_klass) and Klass.clone() -
-# to ensure that the Singleton pattern is properly
-# inherited and cloned.
-#
-# In addition Klass is providing the additional class methods
-# * Klass.instance() - returning ``the instance''. After a successful
-# self modifying instanciating first call the method body is a simple
-# def Klass.instance()
-# return @__instance__
-# end
-# * Klass._load(str) - calls instance()
-# * Klass._instanciate?() - returning ``the instance'' or nil
-# This hook method puts a second (or nth) thread calling
-# Klass.instance() on a waiting loop. The return value signifies
-# the successful completion or premature termination of the
-# first, or more generally, current instanciating thread.
-#
-# The sole instance method of Singleton is
-# * _dump(depth) - returning the empty string. Marshalling strips
-# by default all state information, e.g. instance variables and taint
-# state, from ``the instance''. Providing custom _load(str) and
-# _dump(depth) hooks allows the (partially) resurrections of a
-# previous state of ``the instance''.
-
-module Singleton
- private
- # default marshalling strategy
- def _dump(depth=-1) '' end
-
- class << self
- # extending an object with Singleton is a bad idea
- undef_method :extend_object
- private
- def append_features(mod)
- # This catches ill advisted inclusions of Singleton in
- # singletons types (sounds like an oxymoron) and
- # helps out people counting on transitive mixins
- unless mod.instance_of? (Class)
- raise TypeError, "Inclusion of the OO-Singleton module in module #{mod}"
- end
- unless (class << mod; self end) <= (class << Object; self end)
- raise TypeError, "Inclusion of the OO-Singleton module in singleton type"
- end
- super
- end
- def included (klass)
- # remove build in copying methods
- klass.class_eval do
- define_method(:clone) {raise TypeError, "can't clone singleton #{self.type}"}
- end
-
- # initialize the ``klass instance variable'' @__instance__ to nil
- klass.instance_eval do @__instance__ = nil end
- class << klass
- # a main point of the whole exercise - make
- # new and allocate private
- private :new, :allocate
-
- # declare the self modifying klass#instance method
- define_method (:instance, Singleton::FirstInstanceCall)
-
- # simple waiting loop hook - should do in most cases
- # note the pre/post-conditions of a thread-critical state
- private
- def _instanciate?()
- while false.equal?(@__instance__)
- Thread.critical = false
- sleep(0.08)
- Thread.critical = true
- end
- @__instance__
- end
-
- # default Marshalling strategy
- def _load(str) instance end
-
- # ensure that the Singleton pattern is properly inherited
- def inherited(sub_klass)
- super
- sub_klass.instance_eval do @__instance__ = nil end
- class << sub_klass
- define_method (:instance, Singleton::FirstInstanceCall)
- end
- end
-
- public
- # properly clone the Singleton pattern. Question - Did
- # you know that duping doesn't copy class methods?
- def clone
- res = super
- res.instance_eval do @__instance__ = nil end
- class << res
- define_method (:instance, Singleton::FirstInstanceCall)
- end
- res
- end
- end # of << klass
- end # of included
- end # of << Singleton
-
- FirstInstanceCall = proc do
- # @__instance__ takes on one of the following values
- # * nil - before and after a failed creation
- # * false - during creation
- # * sub_class instance - after a successful creation
- # the form makes up for the lack of returns in progs
- Thread.critical = true
- if @__instance__.nil?
- @__instance__ = false
- Thread.critical = false
- begin
- @__instance__ = new
- ensure
- if @__instance__
- def self.instance() @__instance__ end
- else
- @__instance__ = nil # failed instance creation
- end
- end
- elsif _instanciate?()
- Thread.critical = false
- else
- @__instance__ = false
- Thread.critical = false
- begin
- @__instance__ = new
- ensure
- if @__instance__
- def self.instance() @__instance__ end
- else
- @__instance__ = nil
- end
- end
- end
- @__instance__
- end
-end
-
-
-
-
-if __FILE__ == $0
-
-def num_of_instances(klass)
- "#{ObjectSpace.each_object(klass){}} #{klass} instance(s)"
-end
-
-# The basic and most important example. The latter examples demonstrate
-# advanced features that have no relevance for the general usage
-
-class SomeSingletonClass
- include Singleton
-end
-puts "There are #{num_of_instances(SomeSingletonClass)}"
-
-a = SomeSingletonClass.instance
-b = SomeSingletonClass.instance # a and b are same object
-puts "basic test is #{a == b}"
-
-begin
- SomeSingletonClass.new
-rescue NoMethodError => mes
- puts mes
-end
-
-
-
-puts "\nThreaded example with exception and customized #_instanciate?() hook"; p
-Thread.abort_on_exception = false
-
-class Ups < SomeSingletonClass
- def initialize
- type.__sleep
- puts "initialize called by thread ##{Thread.current[:i]}"
- end
- class << self
- def _instanciate?
- @enter.push Thread.current[:i]
- while false.equal?(@__instance__)
- Thread.critical = false
- sleep 0.04
- Thread.critical = true
- end
- @leave.push Thread.current[:i]
- @__instance__
- end
- def __sleep
- sleep (rand(0.08))
- end
- def allocate
- __sleep
- def self.allocate; __sleep; super() end
- raise "boom - allocation in thread ##{Thread.current[:i]} aborted"
- end
- def instanciate_all
- @enter = []
- @leave = []
- 1.upto(9) do |i|
- Thread.new do
- begin
- Thread.current[:i] = i
- __sleep
- instance
- rescue RuntimeError => mes
- puts mes
- end
- end
- end
- puts "Before there were #{num_of_instances(self)}"
- sleep 5
- puts "Now there is #{num_of_instances(self)}"
- puts "#{@enter.join "; "} was the order of threads entering the waiting loop"
- puts "#{@leave.join "; "} was the order of threads leaving the waiting loop"
- end
- end
-end
-
-Ups.instanciate_all
-# results in message like
-# Before there were 0 Ups instances
-# boom - allocation in thread #8 aborted
-# initialize called by thread #3
-# Now there is 1 Ups instance
-# 2; 3; 6; 1; 7; 5; 9; 4 was the order of threads entering the waiting loop
-# 3; 2; 1; 7; 6; 5; 4; 9 was the order of threads leaving the waiting loop
-
-puts "\nLets see if class level cloning really works"
-Yup = Ups.clone
-def Yup.allocate
- __sleep
- def self.allocate; __sleep; super() end
- raise "boom - allocation in thread ##{Thread.current[:i]} aborted"
-end
-Yup.instanciate_all
-
-
-puts "\n","Customized marshalling"
-class A
- include Singleton
- attr_accessor :persist, :die
- def _dump(depth)
- # this strips the @die information from the instance
- Marshal.dump(@persist,depth)
- end
-end
-def A._load(str)
- instance.persist = Marshal.load(str)
- instance
-end
-
-a = A.instance
-a.persist = ["persist"]
-a.die = "die"
-a.taint
-
-stored_state = Marshal.dump(a)
-# change state
-a.persist = nil
-a.die = nil
-b = Marshal.load(stored_state)
-p a == b # => true
-p a.persist # => ["persist"]
-p a.die # => nil
-
-puts "\n\nSingleton with overridden default #inherited() hook"
-class Up
- def Up.inherited(sub_klass)
- puts "#{sub_klass} subclasses #{self}"
- end
-end
-
-
-class Middle < Up
- undef_method :dup
- include Singleton
-end
-class Down < Middle; end
-
-puts "basic test is #{Down.instance == Down.instance}"
-
-
-puts "\n","Various exceptions"
-
-begin
- module AModule
- include Singleton
- end
-rescue TypeError => mes
- puts mes #=> Inclusion of the OO-Singleton module in module AModule
-end
-
-begin
- class << 'aString'
- include Singleton
- end
-rescue TypeError => mes
- puts mes # => Inclusion of the OO-Singleton module in singleton type
-end
-
-begin
- 'aString'.extend Singleton
-rescue NoMethodError => mes
- puts mes #=> undefined method `extend_object' for Singleton:Module
-end
-
-end
diff --git a/lib/sync.rb b/lib/sync.rb
deleted file mode 100644
index 79522ed885..0000000000
--- a/lib/sync.rb
+++ /dev/null
@@ -1,311 +0,0 @@
-#
-# sync.rb - 2 phase lock with counter
-# $Release Version: 1.0$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-#
-# --
-# Sync_m, Synchronizer_m
-# Usage:
-# obj.extend(Sync_m)
-# or
-# class Foo
-# include Sync_m
-# :
-# end
-#
-# Sync_m#sync_mode
-# Sync_m#sync_locked?, locked?
-# Sync_m#sync_shared?, shared?
-# Sync_m#sync_exclusive?, sync_exclusive?
-# Sync_m#sync_try_lock, try_lock
-# Sync_m#sync_lock, lock
-# Sync_m#sync_unlock, unlock
-#
-# Sync, Synchronicer:
-# include Sync_m
-# Usage:
-# sync = Sync.new
-#
-# Sync#mode
-# Sync#locked?
-# Sync#shared?
-# Sync#exclusive?
-# Sync#try_lock(mode) -- mode = :EX, :SH, :UN
-# Sync#lock(mode) -- mode = :EX, :SH, :UN
-# Sync#unlock
-# Sync#synchronize(mode) {...}
-#
-#
-
-unless defined? Thread
- fail "Thread not available for this ruby interpreter"
-end
-
-module Sync_m
- RCS_ID='-$Header$-'
-
- # lock mode
- UN = :UN
- SH = :SH
- EX = :EX
-
- # exceptions
- class Err < StandardError
- def Err.Fail(*opt)
- fail self, sprintf(self::Message, *opt)
- end
-
- class UnknownLocker < Err
- Message = "Thread(%s) not locked."
- def UnknownLocker.Fail(th)
- super(th.inspect)
- end
- end
-
- class LockModeFailer < Err
- Message = "Unknown lock mode(%s)"
- def LockModeFailer.Fail(mode)
- if mode.id2name
- mode = id2name
- end
- super(mode)
- end
- end
- end
-
- def Sync_m.define_aliases(cl)
- cl.module_eval %q{
- alias locked? sync_locked?
- alias shared? sync_shared?
- alias exclusive? sync_exclusive?
- alias lock sync_lock
- alias unlock sync_unlock
- alias try_lock sync_try_lock
- alias synchronize sync_synchronize
- }
- end
-
- def Sync_m.append_features(cl)
- super
- unless cl.instance_of?(Module)
- # do nothing for Modules
- # make aliases and include the proper module.
- define_aliases(cl)
- end
- end
-
- def Sync_m.extend_object(obj)
- super
- obj.sync_extended
- end
-
- def sync_extended
- unless (defined? locked? and
- defined? shared? and
- defined? exclusive? and
- defined? lock and
- defined? unlock and
- defined? try_lock and
- defined? synchronize)
- Sync_m.define_aliases(class<<self;self;end)
- end
- sync_initialize
- end
-
- # accessing
- def sync_locked?
- sync_mode != UN
- end
-
- def sync_shared?
- sync_mode == SH
- end
-
- def sync_exclusive?
- sync_mode == EX
- end
-
- # locking methods.
- def sync_try_lock(mode = EX)
- return unlock if sync_mode == UN
-
- Thread.critical = true
- ret = sync_try_lock_sub(sync_mode)
- Thread.critical = false
- ret
- end
-
- def sync_lock(m = EX)
- return unlock if m == UN
-
- until (Thread.critical = true; sync_try_lock_sub(m))
- if sync_sh_locker[Thread.current]
- sync_upgrade_waiting.push [Thread.current, sync_sh_locker[Thread.current]]
- sync_sh_locker.delete(Thread.current)
- else
- sync_waiting.push Thread.current
- end
- Thread.stop
- end
- Thread.critical = false
- self
- end
-
- def sync_unlock(m = EX)
- Thread.critical = true
- if sync_mode == UN
- Thread.critical = false
- Err::UnknownLocker.Fail(Thread.current)
- end
-
- m = sync_mode if m == EX and sync_mode == SH
-
- runnable = false
- case m
- when UN
- Thread.critical = false
- Err::UnknownLocker.Fail(Thread.current)
-
- when EX
- if sync_ex_locker == Thread.current
- if (self.sync_ex_count = sync_ex_count - 1) == 0
- self.sync_ex_locker = nil
- if sync_sh_locker.include?(Thread.current)
- self.sync_mode = SH
- else
- self.sync_mode = UN
- end
- runnable = true
- end
- else
- Err::UnknownLocker.Fail(Thread.current)
- end
-
- when SH
- if (count = sync_sh_locker[Thread.current]).nil?
- Err::UnknownLocker.Fail(Thread.current)
- else
- if (sync_sh_locker[Thread.current] = count - 1) == 0
- sync_sh_locker.delete(Thread.current)
- if sync_sh_locker.empty? and sync_ex_count == 0
- self.sync_mode = UN
- runnable = true
- end
- end
- end
- end
-
- if runnable
- if sync_upgrade_waiting.size > 0
- for k, v in sync_upgrade_waiting
- sync_sh_locker[k] = v
- end
- wait = sync_upgrade_waiting
- self.sync_upgrade_waiting = []
- Thread.critical = false
-
- for w, v in wait
- w.run
- end
- else
- wait = sync_waiting
- self.sync_waiting = []
- Thread.critical = false
- for w in wait
- w.run
- end
- end
- end
-
- Thread.critical = false
- self
- end
-
- def sync_synchronize(mode = EX)
- begin
- sync_lock(mode)
- yield
- ensure
- sync_unlock
- end
- end
-
- attr :sync_mode, true
-
- attr :sync_waiting, true
- attr :sync_upgrade_waiting, true
- attr :sync_sh_locker, true
- attr :sync_ex_locker, true
- attr :sync_ex_count, true
-
- private
-
- def sync_initialize
- @sync_mode = UN
- @sync_waiting = []
- @sync_upgrade_waiting = []
- @sync_sh_locker = Hash.new
- @sync_ex_locker = nil
- @sync_ex_count = 0
- end
-
- def initialize(*args)
- sync_initialize
- super
- end
-
- def sync_try_lock_sub(m)
- case m
- when SH
- case sync_mode
- when UN
- self.sync_mode = m
- sync_sh_locker[Thread.current] = 1
- ret = true
- when SH
- count = 0 unless count = sync_sh_locker[Thread.current]
- sync_sh_locker[Thread.current] = count + 1
- ret = true
- when EX
- # in EX mode, lock will upgrade to EX lock
- if sync_ex_locker == Thread.current
- self.sync_ex_count = sync_ex_count + 1
- ret = true
- else
- ret = false
- end
- end
- when EX
- if sync_mode == UN or
- sync_mode == SH && sync_sh_locker.size == 1 && sync_sh_locker.include?(Thread.current)
- self.sync_mode = m
- self.sync_ex_locker = Thread.current
- self.sync_ex_count = 1
- ret = true
- elsif sync_mode == EX && sync_ex_locker == Thread.current
- self.sync_ex_count = sync_ex_count + 1
- ret = true
- else
- ret = false
- end
- else
- Thread.critical = false
- Err::LockModeFailer.Fail mode
- end
- return ret
- end
-end
-Synchronizer_m = Sync_m
-
-class Sync
- #Sync_m.extend_class self
- include Sync_m
-
- def initialize
- super
- end
-
-end
-Synchronizer = Sync
diff --git a/lib/telnet.rb b/lib/telnet.rb
deleted file mode 100644
index b861ffa783..0000000000
--- a/lib/telnet.rb
+++ /dev/null
@@ -1,9 +0,0 @@
-#
-# telnet.rb
-#
-
-$stderr.puts 'Warning: telnet.rb is obsolete: use net/telnet'
-
-require 'net/telnet'
-
-Telnet = ::Net::Telnet
diff --git a/lib/tempfile.rb b/lib/tempfile.rb
deleted file mode 100644
index a0c7f4cf3f..0000000000
--- a/lib/tempfile.rb
+++ /dev/null
@@ -1,98 +0,0 @@
-#
-# $Id$
-#
-# The class for temporary files.
-# o creates a temporary file, which name is "basename.pid.n" with mode "w+".
-# o Tempfile objects can be used like IO object.
-# o with tempfile.close(true) created temporary files are removed.
-# o created files are also removed on script termination.
-# o with Tempfile#open, you can reopen the temporary file.
-# o file mode of the temporary files are 0600.
-
-require 'delegate'
-
-class Tempfile < SimpleDelegator
- Max_try = 10
-
- def Tempfile.callback(path, data)
- pid = $$
- lambda{
- if pid == $$
- print "removing ", path, "..." if $DEBUG
- data[0].close if data[0]
- if File.exist?(path)
- File.unlink(path)
- end
- if File.exist?(path + '.lock')
- Dir.rmdir(path + '.lock')
- end
- print "done\n" if $DEBUG
- end
- }
- end
-
- def initialize(basename, tmpdir=ENV['TMPDIR']||ENV['TMP']||ENV['TEMP']||'/tmp')
- if $SAFE > 0 and tmpdir.tainted?
- tmpdir = '/tmp'
- end
- n = 0
- while true
- begin
- tmpname = sprintf('%s/%s%d.%d', tmpdir, basename, $$, n)
- lock = tmpname + '.lock'
- unless File.exist?(tmpname) or File.exist?(lock)
- Dir.mkdir(lock)
- break
- end
- rescue
- raise "cannot generate tempfile `%s'" % tmpname if n >= Max_try
- #sleep(1)
- end
- n += 1
- end
-
- @protect = []
- @clean_files = Tempfile.callback(tmpname, @protect)
- ObjectSpace.define_finalizer(self, @clean_files)
-
- @tmpfile = File.open(tmpname, File::RDWR|File::CREAT|File::EXCL, 0600)
- @protect[0] = @tmpfile
- @tmpname = tmpname
- super(@tmpfile)
- Dir.rmdir(lock)
- end
-
- def Tempfile.open(*args)
- Tempfile.new(*args)
- end
-
- def open
- @tmpfile.close if @tmpfile
- @tmpfile = File.open(@tmpname, 'r+')
- @protect[0] = @tmpfile
- __setobj__(@tmpfile)
- end
-
- def close(real=false)
- @tmpfile.close if @tmpfile
- @protect[0] = @tmpfile = nil
- if real
- @clean_files.call
- ObjectSpace.undefine_finalizer(self)
- end
- end
-
- def path
- @tmpname
- end
-end
-
-if __FILE__ == $0
-# $DEBUG = true
- f = Tempfile.new("foo")
- f.print("foo\n")
- f.close
- f.open
- p f.gets # => "foo\n"
- f.close(true)
-end
diff --git a/lib/thread.rb b/lib/thread.rb
deleted file mode 100644
index 34db9c3d46..0000000000
--- a/lib/thread.rb
+++ /dev/null
@@ -1,283 +0,0 @@
-#
-# thread.rb - thread support classes
-# $Date$
-# by Yukihiro Matsumoto <matz@netlab.co.jp>
-#
-# Copyright (C) 2001 Yukihiro Matsumoto
-# Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
-# Copyright (C) 2000 Information-technology Promotion Agency, Japan
-#
-
-unless defined? Thread
- fail "Thread not available for this ruby interpreter"
-end
-
-unless defined? ThreadError
- class ThreadError<StandardError
- end
-end
-
-if $DEBUG
- Thread.abort_on_exception = true
-end
-
-def Thread.exclusive
- _old = Thread.critical
- begin
- Thread.critical = true
- return yield
- ensure
- Thread.critical = _old
- end
-end
-
-class Mutex
- def initialize
- @waiting = []
- @locked = false;
- @waiting.taint # enable tainted comunication
- self.taint
- end
-
- def locked?
- @locked
- end
-
- def try_lock
- result = false
- Thread.critical = true
- unless @locked
- @locked = true
- result = true
- end
- Thread.critical = false
- result
- end
-
- def lock
- while (Thread.critical = true; @locked)
- @waiting.push Thread.current
- Thread.stop
- end
- @locked = true
- Thread.critical = false
- self
- end
-
- def unlock
- return unless @locked
- Thread.critical = true
- @locked = false
- begin
- t = @waiting.shift
- t.wakeup if t
- rescue ThreadError
- retry
- end
- Thread.critical = false
- begin
- t.run if t
- rescue ThreadError
- end
- self
- end
-
- def synchronize
- lock
- begin
- yield
- ensure
- unlock
- end
- end
-
- def exclusive_unlock
- return unless @locked
- Thread.exclusive do
- @locked = false
- begin
- t = @waiting.shift
- t.wakeup if t
- rescue ThreadError
- retry
- end
- yield
- end
- self
- end
-end
-
-class ConditionVariable
- def initialize
- @waiters = []
- end
-
- def wait(mutex)
- mutex.exclusive_unlock do
- @waiters.push(Thread.current)
- Thread.stop
- end
- mutex.lock
- end
-
- def signal
- begin
- t = @waiters.shift
- t.run if t
- rescue ThreadError
- retry
- end
- end
-
- def broadcast
- waiters0 = nil
- Thread.exclusive do
- waiters0 = @waiters.dup
- @waiters.clear
- end
- for t in waiters0
- begin
- t.run
- rescue ThreadError
- end
- end
- end
-end
-
-class Queue
- def initialize
- @que = []
- @waiting = []
- @que.taint # enable tainted comunication
- @waiting.taint
- self.taint
- end
-
- def push(obj)
- Thread.critical = true
- @que.push obj
- begin
- t = @waiting.shift
- t.wakeup if t
- rescue ThreadError
- retry
- ensure
- Thread.critical = false
- end
- begin
- t.run if t
- rescue ThreadError
- end
- end
- alias << push
- alias enq push
-
- def pop(non_block=false)
- Thread.critical = true
- begin
- loop do
- if @que.empty?
- if non_block
- raise ThreadError, "queue empty"
- end
- @waiting.push Thread.current
- Thread.stop
- else
- return @que.shift
- end
- end
- ensure
- Thread.critical = false
- end
- end
- alias shift pop
- alias deq pop
-
- def empty?
- @que.empty?
- end
-
- def clear
- @que.clear
- end
-
- def length
- @que.length
- end
- def size
- length
- end
-
- def num_waiting
- @waiting.size
- end
-end
-
-class SizedQueue<Queue
- def initialize(max)
- @max = max
- @queue_wait = []
- @queue_wait.taint # enable tainted comunication
- super()
- end
-
- def max
- @max
- end
-
- def max=(max)
- Thread.critical = true
- if max <= @max
- @max = max
- Thread.critical = false
- else
- diff = max - @max
- @max = max
- Thread.critical = false
- diff.times do
- begin
- t = @queue_wait.shift
- t.run if t
- rescue ThreadError
- retry
- end
- end
- end
- max
- end
-
- def push(obj)
- Thread.critical = true
- while @que.length >= @max
- @queue_wait.push Thread.current
- Thread.stop
- Thread.critical = true
- end
- super
- end
- alias << push
-
- def pop(*args)
- retval = super
- Thread.critical = true
- if @que.length < @max
- begin
- t = @queue_wait.shift
- t.wakeup if t
- rescue ThreadError
- retry
- ensure
- Thread.critical = false
- end
- begin
- t.run if t
- rescue ThreadError
- end
- end
- retval
- end
-
- def num_waiting
- @waiting.size + @queue_wait.size
- end
-end
diff --git a/lib/thwait.rb b/lib/thwait.rb
deleted file mode 100644
index 00c8a8dd36..0000000000
--- a/lib/thwait.rb
+++ /dev/null
@@ -1,133 +0,0 @@
-#
-# thwait.rb - thread synchronization class
-# $Release Version: 0.9 $
-# $Revision: 1.3 $
-# $Date: 1998/06/26 03:19:34 $
-# by Keiju ISHITSUKA(Nihpon Rational Software Co.,Ltd.)
-#
-# --
-# feature:
-# provides synchronization for multiple threads.
-#
-# class methods:
-# * ThreadsWait.all_waits(thread1,...)
-# waits until all of specified threads are terminated.
-# if a block is supplied for the method, evaluates it for
-# each thread termination.
-# * th = ThreadsWait.new(thread1,...)
-# creates synchronization object, specifying thread(s) to wait.
-#
-# methods:
-# * th.threads
-# list threads to be synchronized
-# * th.empty?
-# is there any thread to be synchronized.
-# * th.finished?
-# is there already terminated thread.
-# * th.join(thread1,...)
-# wait for specified thread(s).
-# * th.join_nowait(threa1,...)
-# specifies thread(s) to wait. non-blocking.
-# * th.next_wait
-# waits until any of specified threads is terminated.
-# * th.all_waits
-# waits until all of specified threads are terminated.
-# if a block is supplied for the method, evaluates it for
-# each thread termination.
-#
-
-require "thread.rb"
-require "e2mmap.rb"
-
-class ThreadsWait
- RCS_ID='-$Id: thwait.rb,v 1.3 1998/06/26 03:19:34 keiju Exp keiju $-'
-
- Exception2MessageMapper.extend_to(binding)
- def_exception("ErrNoWaitingThread", "No threads for waiting.")
- def_exception("ErrNoFinishedThread", "No finished threads.")
-
- def ThreadsWait.all_waits(*threads)
- tw = ThreadsWait.new(*threads)
- if block_given?
- tw.all_waits do |th|
- yield th
- end
- else
- tw.all_waits
- end
- end
-
- def initialize(*threads)
- @threads = []
- @wait_queue = Queue.new
- join_nowait(*threads) unless threads.empty?
- end
-
- # accessing
- # threads - list threads to be synchronized
- attr :threads
-
- # testing
- # empty?
- # finished?
-
- # is there any thread to be synchronized.
- def empty?
- @threads.empty?
- end
-
- # is there already terminated thread.
- def finished?
- !@wait_queue.empty?
- end
-
- # main process:
- # join
- # join_nowait
- # next_wait
- # all_wait
-
- # adds thread(s) to join, waits for any of waiting threads to terminate.
- def join(*threads)
- join_nowait(*threads)
- next_wait
- end
-
- # adds thread(s) to join, no wait.
- def join_nowait(*threads)
- threads.flatten!
- @threads.concat threads
- for th in threads
- Thread.start(th) do |t|
- t.join
- @wait_queue.push t
- end
- end
- end
-
- # waits for any of waiting threads to terminate
- # if there is no thread to wait, raises ErrNoWaitingThread.
- # if `nonblock' is true, and there is no terminated thread,
- # raises ErrNoFinishedThread.
- def next_wait(nonblock = nil)
- ThreadsWait.fail ErrNoWaitingThread if @threads.empty?
- begin
- @threads.delete(th = @wait_queue.pop(nonblock))
- th
- rescue ThreadError
- ThreadsWait.fail ErrNoFinishedThread
- end
- end
-
- # waits until all of specified threads are terminated.
- # if a block is supplied for the method, evaluates it for
- # each thread termination.
- def all_waits
- until @threads.empty?
- th = next_wait
- yield th if block_given?
- end
- end
-end
-
-ThWait = ThreadsWait
diff --git a/lib/time.rb b/lib/time.rb
deleted file mode 100644
index aa8ee15de1..0000000000
--- a/lib/time.rb
+++ /dev/null
@@ -1,585 +0,0 @@
-# $Id$
-
-require 'parsedate'
-
-=begin
-= time
-
-This library extends Time class:
-* conversion between date string and time object.
- * date-time defined by RFC 2822
- * HTTP-date defined by RFC 2616
- * dateTime defined by XML Schema Part 2: Datatypes (ISO 8601)
- * various format handled by ParseDate. (string to time only)
-
-== Design Issue
-
-* specialized interface
-
- This library provides methods dedicated to special puposes:
- RFC 2822, RFC 2616 and XML Schema.
- They makes usual life easier.
-
-* doesn't depend on strftime
-
- This library doesn't use strftime.
- Especially Time#rfc2822 doesn't depend on strftime because:
-
- * %a and %b are locale sensitive
-
- Since they are locale sensitive, they may be replaced to
- invalid weekday/month name in some locales.
- Since ruby-1.6 doesn't invoke setlocale by default,
- the problem doesn't arise until some external library invokes setlocale.
- Ruby/GTK is the example of such library.
-
- * %z is not portable
-
- %z is required to generate zone in date-time of RFC 2822
- but it is not portable.
-=end
-
-class Time
- class << Time
-
- ZoneOffset = {
- 'UTC' => 0,
- # ISO 8601
- 'Z' => 0,
- # RFC 822
- 'UT' => 0, 'GMT' => 0,
- 'EST' => -5, 'EDT' => -4,
- 'CST' => -6, 'CDT' => -5,
- 'MST' => -7, 'MDT' => -6,
- 'PST' => -8, 'PDT' => -7,
- # Following definition of military zones is original one.
- # See RFC 1123 and RFC 2822 for the error of RFC 822.
- 'A' => +1, 'B' => +2, 'C' => +3, 'D' => +4, 'E' => +5, 'F' => +6,
- 'G' => +7, 'H' => +8, 'I' => +9, 'K' => +10, 'L' => +11, 'M' => +12,
- 'N' => -1, 'O' => -2, 'P' => -3, 'Q' => -4, 'R' => -5, 'S' => -6,
- 'T' => -7, 'U' => -8, 'V' => -9, 'W' => -10, 'X' => -11, 'Y' => -12,
- }
- def zone_offset(zone, year=Time.now.year)
- off = nil
- zone = zone.upcase
- if /\A([-+])(\d\d):?(\d\d)\z/ =~ zone
- off = ($1 == '-' ? -1 : 1) * ($2.to_i * 60 + $3.to_i) * 60
- elsif /\A[-+]\d\d\z/ =~ zone
- off = zone.to_i * 3600
- elsif ZoneOffset.include?(zone)
- off = ZoneOffset[zone] * 3600
- elsif ((t = Time.local(year, 1, 1)).zone.upcase == zone rescue false)
- off = t.utc_offset
- elsif ((t = Time.local(year, 7, 1)).zone.upcase == zone rescue false)
- off = t.utc_offset
- end
- off
- end
-
-=begin
-== class methods
-
---- Time.parse(date, now=Time.now)
---- Time.parse(date, now=Time.now) {|year| year}
- parses ((|date|)) using ParseDate.parsedate and converts it to a
- Time object.
-
- If a block is given, the year described in ((|date|)) is converted
- by the block. For example:
-
- Time.parse(...) {|y| y < 100 ? (y >= 69 ? y + 1900 : y + 2000) : y}
-
- If the upper components of the given time are broken or missing,
- they are supplied with those of ((|now|)). For the lower
- components, the minimum values (1 or 0) are assumed if broken or
- missing. For example:
-
- # Suppose it is "Thu Nov 29 14:33:20 GMT 2001" now and
- # your timezone is GMT:
- Time.parse("16:30") #=> Thu Nov 29 16:30:00 GMT 2001
- Time.parse("7/23") #=> Mon Jul 23 00:00:00 GMT 2001
- Time.parse("2002/1") #=> Tue Jan 01 00:00:00 GMT 2002
-
- Since there are numerous conflicts among locally defined timezone
- abbreviations all over the world, this method is not made to
- understand all of them. For example, the abbreviation "CST" is
- used variously as:
-
- -06:00 in America/Chicago,
- -05:00 in America/Havana,
- +08:00 in Asia/Harbin,
- +09:30 in Australia/Darwin,
- +10:30 in Australia/Adelaide,
- etc.
-
- Based on the fact, this method only understands the timezone
- abbreviations described in RFC 822 and the system timezone, in the
- order named. (i.e. a definition in RFC 822 overrides the system
- timezone definition) The system timezone is taken from
- (({Time.local(year, 1, 1).zone})) and
- (({Time.local(year, 7, 1).zone})).
- If the extracted timezone abbreviation does not match any of them,
- it is ignored and the given time is regarded as a local time.
-
- ArgumentError is raised if ParseDate cannot extract
- information from ((|date|))
- or Time class cannot represent specified date.
-
- This method can be used as fail-safe for other parsing methods as:
-
- Time.rfc2822(date) rescue Time.parse(date)
- Time.httpdate(date) rescue Time.parse(date)
- Time.xmlschema(date) rescue Time.parse(date)
-
- A failure for Time.parse should be checked, though.
-=end
- def parse(date, now=Time.now)
- year, mon, day, hour, min, sec, zone, _ = ParseDate.parsedate(date)
- year = yield year if year && block_given?
-
- if now
- begin
- break if year; year = now.year
- break if mon; mon = now.mon
- break if day; day = now.day
- break if hour; hour = now.hour
- break if min; min = now.min
- break if sec; sec = now.sec
- end until true
- end
-
- year ||= 1970
- mon ||= 1
- day ||= 1
- hour ||= 0
- min ||= 0
- sec ||= 0
-
- off = nil
- off = zone_offset(zone, year) if zone
-
- if off
- t = Time.utc(year, mon, day, hour, min, sec) - off
- t.localtime if off != 0
- t
- else
- Time.local(year, mon, day, hour, min, sec)
- end
- end
-
- MonthValue = {
- 'JAN' => 1, 'FEB' => 2, 'MAR' => 3, 'APR' => 4, 'MAY' => 5, 'JUN' => 6,
- 'JUL' => 7, 'AUG' => 8, 'SEP' => 9, 'OCT' =>10, 'NOV' =>11, 'DEC' =>12
- }
-
-=begin
---- Time.rfc2822(date)
---- Time.rfc822(date)
- parses ((|date|)) as date-time defined by RFC 2822 and converts it to a
- Time object.
- The format is identical to the date format defined by RFC 822 and
- updated by RFC 1123.
-
- ArgumentError is raised if ((|date|)) is not compliant with RFC 2822
- or Time class cannot represent specified date.
-=end
- def rfc2822(date)
- if /\A\s*
- (?:(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s*,\s*)?
- (\d{1,2})\s+
- (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+
- (\d{2,})\s+
- (\d{2})\s*
- :\s*(\d{2})\s*
- (?::\s*(\d{2}))?\s+
- ([+\-]\d{4}|
- UT|GMT|EST|EDT|CST|CDT|MST|MDT|PST|PDT|[A-IK-Z])/ix =~ date
- # Since RFC 2822 permit comments, the regexp has no right anchor.
- day = $1.to_i
- mon = MonthValue[$2.upcase]
- year = $3.to_i
- hour = $4.to_i
- min = $5.to_i
- sec = $6 ? $6.to_i : 0
- zone = $7
-
- # following year completion is compliant with RFC 2822.
- year = if year < 50
- 2000 + year
- elsif year < 1000
- 1900 + year
- else
- year
- end
-
- Time.utc(year, mon, day, hour, min, sec) - zone_offset(zone)
- else
- raise ArgumentError.new("not RFC 2822 compliant date: #{date.inspect}")
- end
- end
- alias rfc822 rfc2822
-
-=begin
---- Time.httpdate(date)
- parses ((|date|)) as HTTP-date defined by RFC 2616 and converts it to a
- Time object.
-
- ArgumentError is raised if ((|date|)) is not compliant with RFC 2616
- or Time class cannot represent specified date.
-=end
- def httpdate(date)
- if /\A\s*
- (?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),\x20
- (\d{2})\x20
- (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\x20
- (\d{4})\x20
- (\d{2}):(\d{2}):(\d{2})\x20
- GMT
- \s*\z/ix =~ date
- Time.rfc2822(date)
- elsif /\A\s*
- (?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday),\x20
- (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d)\x20
- (\d\d):(\d\d):(\d\d)\x20
- GMT
- \s*\z/ix =~ date
- Time.parse(date)
- elsif /\A\s*
- (?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\x20
- (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\x20
- (\d\d|\x20\d)\x20
- (\d\d):(\d\d):(\d\d)\x20
- (\d{4})
- \s*\z/ix =~ date
- Time.utc($6.to_i, MonthValue[$1.upcase], $2.to_i,
- $3.to_i, $4.to_i, $5.to_i)
- else
- raise ArgumentError.new("not RFC 2616 compliant date: #{date.inspect}")
- end
- end
-
-=begin
---- Time.xmlschema(date)
---- Time.iso8601(date)
- parses ((|date|)) as dateTime defined by XML Schema and
- converts it to a Time object.
- The format is restricted version of the format defined by ISO 8601.
-
- ArgumentError is raised if ((|date|)) is not compliant with the format
- or Time class cannot represent specified date.
-=end
- def xmlschema(date)
- if /\A\s*
- (-?\d+)-(\d\d)-(\d\d)
- T
- (\d\d):(\d\d):(\d\d)
- (\.\d*)?
- (Z|[+\-]\d\d:\d\d)?
- \s*\z/ix =~ date
- datetime = [$1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i]
- datetime << $7.to_f * 1000000 if $7
- if $8
- Time.utc(*datetime) - zone_offset($8)
- else
- Time.local(*datetime)
- end
- else
- raise ArgumentError.new("invalid date: #{date.inspect}")
- end
- end
- alias iso8601 xmlschema
- end
-
-=begin
-== methods
-=end
-
-=begin
---- Time#rfc2822
---- Time#rfc822
- returns a string which represents the time as date-time defined by RFC 2822:
-
- day-of-week, DD month-name CCYY hh:mm:ss zone
-
- where zone is [+-]hhmm.
-
- If self is a UTC time, +0000 is used as zone.
-=end
-
- RFC2822_DAY_NAME = [
- 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'
- ]
- RFC2822_MONTH_NAME = [
- 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
- 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
- ]
- def rfc2822
- sprintf('%s, %02d %s %d %02d:%02d:%02d ',
- RFC2822_DAY_NAME[wday],
- day, RFC2822_MONTH_NAME[mon-1], year,
- hour, min, sec) +
- if utc?
- '+0000'
- else
- off = utc_offset
- sign = off < 0 ? '-' : '+'
- sprintf('%s%02d%02d', sign, *(off.abs / 60).divmod(60))
- end
- end
- alias rfc822 rfc2822
-
-=begin
---- Time#httpdate
- returns a string which represents the time as rfc1123-date of HTTP-date
- defined by RFC 2616:
-
- day-of-week, DD month-name CCYY hh:mm:ss GMT
-
- Note that the result is always UTC (GMT).
-=end
- def httpdate
- t = dup.utc
- sprintf('%s, %02d %s %d %02d:%02d:%02d GMT',
- RFC2822_DAY_NAME[t.wday],
- t.day, RFC2822_MONTH_NAME[t.mon-1], t.year,
- t.hour, t.min, t.sec)
- end
-
-=begin
---- Time#xmlschema([fractional_seconds])
---- Time#iso8601([fractional_seconds])
- returns a string which represents the time as dateTime
- defined by XML Schema:
-
- CCYY-MM-DDThh:mm:ssTZD
- CCYY-MM-DDThh:mm:ss.sssTZD
-
- where TZD is Z or [+-]hh:mm.
-
- If self is a UTC time, Z is used as TZD.
- [+-]hh:mm is used otherwise.
-
- ((|fractional_seconds|)) specify a number of digits of
- fractional seconds.
- The default value of ((|fractional_seconds|)) is 0.
-=end
- def xmlschema(fraction_digits=0)
- sprintf('%d-%02d-%02dT%02d:%02d:%02d',
- year, mon, day, hour, min, sec) +
- if fraction_digits == 0
- ''
- elsif fraction_digits <= 6
- '.' + sprintf('%06d', usec)[0, fraction_digits]
- else
- '.' + sprintf('%06d', usec) + '0' * (fraction_digits - 6)
- end +
- if utc?
- 'Z'
- else
- off = utc_offset
- sign = off < 0 ? '-' : '+'
- sprintf('%s%02d:%02d', sign, *(off.abs / 60).divmod(60))
- end
- end
- alias iso8601 xmlschema
-end
-
-if __FILE__ == $0
- require 'runit/testcase'
- require 'runit/cui/testrunner'
-
- class TimeExtentionTest < RUNIT::TestCase
- def test_rfc822
- assert_equal(Time.utc(1976, 8, 26, 14, 30) + 4 * 3600,
- Time.rfc2822("26 Aug 76 14:30 EDT"))
- assert_equal(Time.utc(1976, 8, 27, 9, 32) + 7 * 3600,
- Time.rfc2822("27 Aug 76 09:32 PDT"))
- end
-
- def test_rfc2822
- assert_equal(Time.utc(1997, 11, 21, 9, 55, 6) + 6 * 3600,
- Time.rfc2822("Fri, 21 Nov 1997 09:55:06 -0600"))
- assert_equal(Time.utc(2003, 7, 1, 10, 52, 37) - 2 * 3600,
- Time.rfc2822("Tue, 1 Jul 2003 10:52:37 +0200"))
- assert_equal(Time.utc(1969, 2, 13, 23, 32, 54) + 3 * 3600 + 30 * 60,
- Time.rfc2822("Thu, 13 Feb 1969 23:32:54 -0330"))
- assert_equal(Time.utc(1997, 11, 21, 10, 1, 10) + 6 * 3600,
- Time.rfc2822("Fri, 21 Nov 1997 10:01:10 -0600"))
- assert_equal(Time.utc(1997, 11, 21, 11, 0, 0) + 6 * 3600,
- Time.rfc2822("Fri, 21 Nov 1997 11:00:00 -0600"))
- assert_equal(Time.utc(1997, 11, 24, 14, 22, 1) + 8 * 3600,
- Time.rfc2822("Mon, 24 Nov 1997 14:22:01 -0800"))
- assert_equal(Time.utc(1969, 2, 13, 23, 32, 0) + 3 * 3600 + 30 * 60,
- Time.rfc2822(" Thu,
- 13
- Feb
- 1969
- 23:32
- -0330 (Newfoundland Time)"))
- assert_equal(Time.utc(1997, 11, 21, 9, 55, 6),
- Time.rfc2822("21 Nov 97 09:55:06 GMT"))
- assert_equal(Time.utc(1997, 11, 21, 9, 55, 6) + 6 * 3600,
- Time.rfc2822("Fri, 21 Nov 1997 09 : 55 : 06 -0600"))
- assert_exception(ArgumentError) {
- # inner comment is not supported.
- Time.rfc2822("Fri, 21 Nov 1997 09(comment): 55 : 06 -0600")
- }
- end
-
- def test_rfc2616
- t = Time.utc(1994, 11, 6, 8, 49, 37)
- assert_equal(t, Time.httpdate("Sun, 06 Nov 1994 08:49:37 GMT"))
- assert_equal(t, Time.httpdate("Sunday, 06-Nov-94 08:49:37 GMT"))
- assert_equal(t, Time.httpdate("Sun Nov 6 08:49:37 1994"))
- assert_equal(Time.utc(1995, 11, 15, 6, 25, 24),
- Time.httpdate("Wed, 15 Nov 1995 06:25:24 GMT"))
- assert_equal(Time.utc(1995, 11, 15, 4, 58, 8),
- Time.httpdate("Wed, 15 Nov 1995 04:58:08 GMT"))
- assert_equal(Time.utc(1994, 11, 15, 8, 12, 31),
- Time.httpdate("Tue, 15 Nov 1994 08:12:31 GMT"))
- assert_equal(Time.utc(1994, 12, 1, 16, 0, 0),
- Time.httpdate("Thu, 01 Dec 1994 16:00:00 GMT"))
- assert_equal(Time.utc(1994, 10, 29, 19, 43, 31),
- Time.httpdate("Sat, 29 Oct 1994 19:43:31 GMT"))
- assert_equal(Time.utc(1994, 11, 15, 12, 45, 26),
- Time.httpdate("Tue, 15 Nov 1994 12:45:26 GMT"))
- assert_equal(Time.utc(1999, 12, 31, 23, 59, 59),
- Time.httpdate("Fri, 31 Dec 1999 23:59:59 GMT"))
- end
-
- # http://www.w3.org/TR/xmlschema-2/
- def test_xmlschema
- assert_equal(Time.utc(1999, 5, 31, 13, 20, 0) + 5 * 3600,
- Time.xmlschema("1999-05-31T13:20:00-05:00"))
- assert_equal(Time.local(2000, 1, 20, 12, 0, 0),
- Time.xmlschema("2000-01-20T12:00:00"))
- assert_equal(Time.utc(2000, 1, 20, 12, 0, 0),
- Time.xmlschema("2000-01-20T12:00:00Z"))
- assert_equal(Time.utc(2000, 1, 20, 12, 0, 0) - 12 * 3600,
- Time.xmlschema("2000-01-20T12:00:00+12:00"))
- assert_equal(Time.utc(2000, 1, 20, 12, 0, 0) + 13 * 3600,
- Time.xmlschema("2000-01-20T12:00:00-13:00"))
- assert_equal(Time.utc(2000, 3, 4, 23, 0, 0) - 3 * 3600,
- Time.xmlschema("2000-03-04T23:00:00+03:00"))
- assert_equal(Time.utc(2000, 3, 4, 20, 0, 0),
- Time.xmlschema("2000-03-04T20:00:00Z"))
- assert_equal(Time.local(2000, 1, 15, 0, 0, 0),
- Time.xmlschema("2000-01-15T00:00:00"))
- assert_equal(Time.local(2000, 2, 15, 0, 0, 0),
- Time.xmlschema("2000-02-15T00:00:00"))
- assert_equal(Time.local(2000, 1, 15, 12, 0, 0),
- Time.xmlschema("2000-01-15T12:00:00"))
- assert_equal(Time.utc(2000, 1, 16, 12, 0, 0),
- Time.xmlschema("2000-01-16T12:00:00Z"))
- assert_equal(Time.local(2000, 1, 1, 12, 0, 0),
- Time.xmlschema("2000-01-01T12:00:00"))
- assert_equal(Time.utc(1999, 12, 31, 23, 0, 0),
- Time.xmlschema("1999-12-31T23:00:00Z"))
- assert_equal(Time.local(2000, 1, 16, 12, 0, 0),
- Time.xmlschema("2000-01-16T12:00:00"))
- assert_equal(Time.local(2000, 1, 16, 0, 0, 0),
- Time.xmlschema("2000-01-16T00:00:00"))
- assert_equal(Time.utc(2000, 1, 12, 12, 13, 14),
- Time.xmlschema("2000-01-12T12:13:14Z"))
- assert_equal(Time.utc(2001, 4, 17, 19, 23, 17, 300000),
- Time.xmlschema("2001-04-17T19:23:17.3Z"))
- end
-
- def test_encode_xmlschema
- t = Time.utc(2001, 4, 17, 19, 23, 17, 300000)
- assert_equal("2001-04-17T19:23:17Z", t.xmlschema)
- assert_equal("2001-04-17T19:23:17.3Z", t.xmlschema(1))
- assert_equal("2001-04-17T19:23:17.300000Z", t.xmlschema(6))
- assert_equal("2001-04-17T19:23:17.3000000Z", t.xmlschema(7))
-
- t = Time.utc(2001, 4, 17, 19, 23, 17, 123456)
- assert_equal("2001-04-17T19:23:17.1234560Z", t.xmlschema(7))
- assert_equal("2001-04-17T19:23:17.123456Z", t.xmlschema(6))
- assert_equal("2001-04-17T19:23:17.12345Z", t.xmlschema(5))
- assert_equal("2001-04-17T19:23:17.1Z", t.xmlschema(1))
-
- t = Time.utc(1960, 12, 31, 23, 0, 0, 123456)
- assert_equal("1960-12-31T23:00:00.123456Z", t.xmlschema(6))
- end
-
- def test_completion
- now = Time.local(2001,11,29,21,26,35)
- assert_equal(Time.local( 2001,11,29,21,12),
- Time.parse("2001/11/29 21:12", now))
- assert_equal(Time.local( 2001,11,29),
- Time.parse("2001/11/29", now))
- assert_equal(Time.local( 2001,11),
- Time.parse("2001/11", now))
- assert_equal(Time.local( 2001,11,29),
- Time.parse( "11/29", now))
- #assert_equal(Time.local(2001,11,1), Time.parse("Nov", now))
- assert_equal(Time.local( 2001,11,29,10,22),
- Time.parse( "10:22", now))
- end
-
- def test_invalid
- # They were actually used in some web sites.
- assert_exception(ArgumentError) { Time.httpdate("1 Dec 2001 10:23:57 GMT") }
- assert_exception(ArgumentError) { Time.httpdate("Sat, 1 Dec 2001 10:25:42 GMT") }
- assert_exception(ArgumentError) { Time.httpdate("Sat, 1-Dec-2001 10:53:55 GMT") }
- assert_exception(ArgumentError) { Time.httpdate("Saturday, 01-Dec-2001 10:15:34 GMT") }
- assert_exception(ArgumentError) { Time.httpdate("Saturday, 01-Dec-101 11:10:07 GMT") }
- assert_exception(ArgumentError) { Time.httpdate("Fri, 30 Nov 2001 21:30:00 JST") }
-
- # They were actually used in some mails.
- assert_exception(ArgumentError) { Time.rfc2822("01-5-20") }
- assert_exception(ArgumentError) { Time.rfc2822("7/21/00") }
- assert_exception(ArgumentError) { Time.rfc2822("2001-8-28") }
- assert_exception(ArgumentError) { Time.rfc2822("00-5-6 1:13:06") }
- assert_exception(ArgumentError) { Time.rfc2822("2001-9-27 9:36:49") }
- assert_exception(ArgumentError) { Time.rfc2822("2000-12-13 11:01:11") }
- assert_exception(ArgumentError) { Time.rfc2822("2001/10/17 04:29:55") }
- assert_exception(ArgumentError) { Time.rfc2822("9/4/2001 9:23:19 PM") }
- assert_exception(ArgumentError) { Time.rfc2822("01 Nov 2001 09:04:31") }
- assert_exception(ArgumentError) { Time.rfc2822("13 Feb 2001 16:4 GMT") }
- assert_exception(ArgumentError) { Time.rfc2822("01 Oct 00 5:41:19 PM") }
- assert_exception(ArgumentError) { Time.rfc2822("2 Jul 00 00:51:37 JST") }
- assert_exception(ArgumentError) { Time.rfc2822("01 11 2001 06:55:57 -0500") }
- assert_exception(ArgumentError) { Time.rfc2822("18 \343\366\356\341\370 2000") }
- assert_exception(ArgumentError) { Time.rfc2822("Fri, Oct 2001 18:53:32") }
- assert_exception(ArgumentError) { Time.rfc2822("Fri, 2 Nov 2001 03:47:54") }
- assert_exception(ArgumentError) { Time.rfc2822("Fri, 27 Jul 2001 11.14.14 +0200") }
- assert_exception(ArgumentError) { Time.rfc2822("Thu, 2 Nov 2000 04:13:53 -600") }
- assert_exception(ArgumentError) { Time.rfc2822("Wed, 5 Apr 2000 22:57:09 JST") }
- assert_exception(ArgumentError) { Time.rfc2822("Mon, 11 Sep 2000 19:47:33 00000") }
- assert_exception(ArgumentError) { Time.rfc2822("Fri, 28 Apr 2000 20:40:47 +-900") }
- assert_exception(ArgumentError) { Time.rfc2822("Fri, 19 Jan 2001 8:15:36 AM -0500") }
- assert_exception(ArgumentError) { Time.rfc2822("Thursday, Sep 27 2001 7:42:35 AM EST") }
- assert_exception(ArgumentError) { Time.rfc2822("3/11/2001 1:31:57 PM Pacific Daylight Time") }
- assert_exception(ArgumentError) { Time.rfc2822("Mi, 28 Mrz 2001 11:51:36") }
- assert_exception(ArgumentError) { Time.rfc2822("P, 30 sept 2001 23:03:14") }
- assert_exception(ArgumentError) { Time.rfc2822("fr, 11 aug 2000 18:39:22") }
- assert_exception(ArgumentError) { Time.rfc2822("Fr, 21 Sep 2001 17:44:03 -1000") }
- assert_exception(ArgumentError) { Time.rfc2822("Mo, 18 Jun 2001 19:21:40 -1000") }
- assert_exception(ArgumentError) { Time.rfc2822("l\366, 12 aug 2000 18:53:20") }
- assert_exception(ArgumentError) { Time.rfc2822("l\366, 26 maj 2001 00:15:58") }
- assert_exception(ArgumentError) { Time.rfc2822("Dom, 30 Sep 2001 17:36:30") }
- assert_exception(ArgumentError) { Time.rfc2822("%&, 31 %2/ 2000 15:44:47 -0500") }
- assert_exception(ArgumentError) { Time.rfc2822("dom, 26 ago 2001 03:57:07 -0300") }
- assert_exception(ArgumentError) { Time.rfc2822("ter, 04 set 2001 16:27:58 -0300") }
- assert_exception(ArgumentError) { Time.rfc2822("Wen, 3 oct 2001 23:17:49 -0400") }
- assert_exception(ArgumentError) { Time.rfc2822("Wen, 3 oct 2001 23:17:49 -0400") }
- assert_exception(ArgumentError) { Time.rfc2822("ele, 11 h: 2000 12:42:15 -0500") }
- assert_exception(ArgumentError) { Time.rfc2822("Tue, 14 Aug 2001 3:55:3 +0200") }
- assert_exception(ArgumentError) { Time.rfc2822("Fri, 25 Aug 2000 9:3:48 +0800") }
- assert_exception(ArgumentError) { Time.rfc2822("Fri, 1 Dec 2000 0:57:50 EST") }
- assert_exception(ArgumentError) { Time.rfc2822("Mon, 7 May 2001 9:39:51 +0200") }
- assert_exception(ArgumentError) { Time.rfc2822("Wed, 1 Aug 2001 16:9:15 +0200") }
- assert_exception(ArgumentError) { Time.rfc2822("Wed, 23 Aug 2000 9:17:36 +0800") }
- assert_exception(ArgumentError) { Time.rfc2822("Fri, 11 Aug 2000 10:4:42 +0800") }
- assert_exception(ArgumentError) { Time.rfc2822("Sat, 15 Sep 2001 13:22:2 +0300") }
- assert_exception(ArgumentError) { Time.rfc2822("Wed,16 \276\305\324\302 2001 20:06:25 +0800") }
- assert_exception(ArgumentError) { Time.rfc2822("Wed,7 \312\256\322\273\324\302 2001 23:47:22 +0800") }
- assert_exception(ArgumentError) { Time.rfc2822("=?iso-8859-1?Q?(=C5=DA),?= 10 2 2001 23:32:26 +0900 (JST)") }
- assert_exception(ArgumentError) { Time.rfc2822("\307\341\314\343\332\311, 30 \344\346\335\343\310\321 2001 10:01:06") }
- assert_exception(ArgumentError) { Time.rfc2822("=?iso-8859-1?Q?(=BF=E5),?= 12 =?iso-8859-1?Q?9=B7=EE?= 2001 14:52:41\n+0900 (JST)") }
- end
- end
-
- RUNIT::CUI::TestRunner.run(TimeExtentionTest.suite)
-end
diff --git a/lib/timeout.rb b/lib/timeout.rb
deleted file mode 100644
index 8c6ccb7128..0000000000
--- a/lib/timeout.rb
+++ /dev/null
@@ -1,56 +0,0 @@
-#
-# timeout.rb -- execution timeout
-#
-# Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
-# Copyright (C) 2000 Information-technology Promotion Agency, Japan
-#
-#= SYNOPSIS
-#
-# require 'timeout'
-# status = timeout(5) {
-# # something may take time
-# }
-#
-#= DESCRIPTION
-#
-# timeout executes the block. If the block execution terminates successfully
-# before timeout, it returns true. If not, it terminates the execution and
-# raise TimeoutError exception.
-#
-#== Parameters
-#
-# : timout
-#
-# The time in seconds to wait for block teminatation.
-#
-#=end
-
-class TimeoutError<Interrupt
-end
-
-def timeout(sec, exception=TimeoutError)
- return yield if sec == nil
- begin
- x = Thread.current
- y = Thread.start {
- sleep sec
- x.raise exception, "execution expired" if x.alive?
- }
- yield sec
-# return true
- ensure
- y.kill if y and y.alive?
- end
-end
-
-if __FILE__ == $0
- p timeout(5) {
- 45
- }
- p timeout(5) {
- loop {
- p 10
- sleep 1
- }
- }
-end
diff --git a/lib/tracer.rb b/lib/tracer.rb
deleted file mode 100644
index 817f68484e..0000000000
--- a/lib/tracer.rb
+++ /dev/null
@@ -1,171 +0,0 @@
-#
-# tracer.rb -
-# $Release Version: 0.2$
-# $Revision: 1.8 $
-# $Date: 1998/05/19 03:42:49 $
-# by Keiju ISHITSUKA(Nippon Rational Inc.)
-#
-# --
-#
-#
-#
-
-#
-# tracer main class
-#
-class Tracer
- @RCS_ID='-$Id: tracer.rb,v 1.8 1998/05/19 03:42:49 keiju Exp keiju $-'
-
- @stdout = STDOUT
- @verbose = false
- class << self
- attr :verbose, true
- alias verbose? verbose
- attr :stdout, true
- end
-
- MY_FILE_NAME = caller(0)[0].scan(/^(.*):[0-9]+$/)[0][0]
-
- EVENT_SYMBOL = {
- "line" => "-",
- "call" => ">",
- "return" => "<",
- "class" => "C",
- "end" => "E",
- "c-call" => ">",
- "c-return" => "<",
- }
-
- def initialize
- @threads = Hash.new
- if defined? Thread.main
- @threads[Thread.main.id] = 0
- else
- @threads[Thread.current.id] = 0
- end
-
- @get_line_procs = {}
-
- @filters = []
- end
-
- def stdout
- Tracer.stdout
- end
-
- def on
- if block_given?
- on
- begin
- yield
- ensure
- off
- end
- else
- set_trace_func proc{|event, file, line, id, binding, klass, *rest|
- trace_func event, file, line, id, binding, klass
- }
- stdout.print "Trace on\n" if Tracer.verbose?
- end
- end
-
- def off
- set_trace_func nil
- stdout.print "Trace off\n" if Tracer.verbose?
- end
-
- def add_filter(p = proc)
- @filters.push p
- end
-
- def set_get_line_procs(file, p = proc)
- @get_line_procs[file] = p
- end
-
- def get_line(file, line)
- if p = @get_line_procs[file]
- return p.call line
- end
-
- unless list = SCRIPT_LINES__[file]
- begin
- f = open(file)
- begin
- SCRIPT_LINES__[file] = list = f.readlines
- ensure
- f.close
- end
- rescue
- SCRIPT_LINES__[file] = list = []
- end
- end
- if l = list[line - 1]
- l
- else
- "-\n"
- end
- end
-
- def get_thread_no
- if no = @threads[Thread.current.id]
- no
- else
- @threads[Thread.current.id] = @threads.size
- end
- end
-
- def trace_func(event, file, line, id, binding, klass)
- return if file == MY_FILE_NAME
-
- for p in @filters
- return unless p.call event, file, line, id, binding, klass
- end
-
- Thread.critical = true
- stdout.printf("#%d:%s:%d:%s:%s: %s",
- get_thread_no,
- file,
- line,
- klass || '',
- EVENT_SYMBOL[event],
- get_line(file, line))
- Thread.critical = false
- end
-
- Single = new
- def Tracer.on
- if block_given?
- Single.on{yield}
- else
- Single.on
- end
- end
-
- def Tracer.off
- Single.off
- end
-
- def Tracer.set_get_line_procs(file_name, p = proc)
- Single.set_get_line_procs(file_name, p)
- end
-
- def Tracer.add_filter(p = proc)
- Single.add_filter(p)
- end
-
-end
-
-SCRIPT_LINES__ = {} unless defined? SCRIPT_LINES__
-
-if caller(0).size == 1
- if $0 == Tracer::MY_FILE_NAME
- # direct call
-
- $0 = ARGV[0]
- ARGV.shift
- Tracer.on
- require $0
- else
- Tracer.on
- end
-end
diff --git a/lib/tsort.rb b/lib/tsort.rb
deleted file mode 100644
index 58e073dff4..0000000000
--- a/lib/tsort.rb
+++ /dev/null
@@ -1,289 +0,0 @@
-=begin
-= tsort.rb
-
-tsort.rb provides a module for topological sorting and
-strongly connected components.
-
-== Example
-
- require 'tsort'
-
- class Hash
- include TSort
- alias tsort_each_node each_key
- def tsort_each_child(node, &block)
- fetch(node).each(&block)
- end
- end
-
- {1=>[2, 3], 2=>[3], 3=>[], 4=>[]}.tsort
- #=> [3, 2, 1, 4]
-
- {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}.strongly_connected_components
- #=> [[4], [2, 3], [1]]
-
-== TSort module
-TSort implements topological sorting using Tarjan's algorithm for
-strongly connected components.
-
-TSort is designed to be able to use with any object which can be interpreted
-as a directed graph.
-TSort requires two methods to interpret a object as a graph:
-tsort_each_node and tsort_each_child.
-
-* tsort_each_node is used to iterate for all nodes over a graph.
-* tsort_each_child is used to iterate for child nodes of a given node.
-
-The equality of nodes are defined by eql? and hash since
-TSort uses Hash internally.
-
-=== methods
---- tsort
- returns a topologically sorted array of nodes.
- The array is sorted from children to parents:
- I.e. the first element has no child and the last node has no parent.
-
- If there is a cycle, (({TSort::Cyclic})) is raised.
-
---- tsort_each {|node| ...}
- is the iterator version of the (({tsort})) method.
- (({((|obj|)).tsort_each})) is similar to (({((|obj|)).tsort.each})) but
- modification of ((|obj|)) during the iteration may cause unexpected result.
-
- (({tsort_each})) returns (({nil})).
- If there is a cycle, (({TSort::Cyclic})) is raised.
-
---- strongly_connected_components
- returns strongly connected components as an array of array of nodes.
- The array is sorted as children to parents.
- Each elements of the array represents a strongly connected component.
-
---- each_strongly_connected_component {|nodes| ...}
- is the iterator version of the (({strongly_connected_components})) method.
- (({((|obj|)).each_strongly_connected_component})) is similar to
- (({((|obj|)).strongly_connected_components.each})) but
- modification of ((|obj|)) during the iteration may cause unexpected result.
-
- (({each_strongly_connected_component})) returns (({nil})).
-
---- each_strongly_connected_component_from(node) {|nodes| ...}
- iterates over strongly connected component in the subgraph reachable from
- ((|node|)).
-
- Return value is unspecified.
-
- (({each_strongly_connected_component_from})) doesn't call
- (({tsort_each_node})).
-
---- tsort_each_node {|node| ...}
- should be implemented by a extended class.
-
---- tsort_each_child(node) {|child| ...}
- should be implemented by a extended class.
-
-== More Realistic Example
-Very simple `make' like tool can be implemented as follows:
-
- require 'tsort'
-
- class Make
- def initialize
- @dep = {}
- @dep.default = []
- end
-
- def rule(outputs, inputs=[], &block)
- triple = [outputs, inputs, block]
- outputs.each {|f| @dep[f] = [triple]}
- @dep[triple] = inputs
- end
-
- def build(target)
- each_strongly_connected_component_from(target) {|ns|
- if ns.length != 1
- fs = ns.delete_if {|n| Array === n}
- raise TSort::Cyclic.new("cyclic dependencies: #{fs.join ', '}")
- end
- n = ns.first
- if Array === n
- outputs, inputs, block = n
- inputs_time = inputs.map {|f| File.mtime f}.max
- begin
- outputs_time = outputs.map {|f| File.mtime f}.min
- rescue Errno::ENOENT
- outputs_time = nil
- end
- if outputs_time == nil ||
- inputs_time != nil && outputs_time < inputs_time # `<=' is better?
- block.call
- end
- end
- }
- end
-
- def tsort_each_child(node, &block)
- @dep[node].each(&block)
- end
- include TSort
- end
-
- def command(arg)
- print arg, "\n"
- system arg
- end
-
- m = Make.new
- m.rule(%w[t1]) { command 'date > t1' }
- m.rule(%w[t2]) { command 'date > t2' }
- m.rule(%w[t3]) { command 'date > t3' }
- m.rule(%w[t4], %w[t1 t3]) { command 'cat t1 t3 > t4' }
- m.rule(%w[t5], %w[t4 t2]) { command 'cat t4 t2 > t5' }
- m.build('t5')
-
-== Bugs
-
-* (('tsort.rb')) is wrong name because this library uses
- Tarjan's algorithm for strongly connected components.
- Although (('strongly_connected_components.rb')) is correct but too long,
-
-== References
-R. E. Tarjan,
-Depth First Search and Linear Graph Algorithms,
-SIAM Journal on Computing, Vol. 1, No. 2, pp. 146-160, June 1972.
-
-#@Article{Tarjan:1972:DFS,
-# author = "R. E. Tarjan",
-# key = "Tarjan",
-# title = "Depth First Search and Linear Graph Algorithms",
-# journal = j-SIAM-J-COMPUT,
-# volume = "1",
-# number = "2",
-# pages = "146--160",
-# month = jun,
-# year = "1972",
-# CODEN = "SMJCAT",
-# ISSN = "0097-5397 (print), 1095-7111 (electronic)",
-# bibdate = "Thu Jan 23 09:56:44 1997",
-# bibsource = "Parallel/Multi.bib, Misc/Reverse.eng.bib",
-#}
-=end
-
-module TSort
- class Cyclic < StandardError
- end
-
- def tsort
- result = []
- tsort_each {|element| result << element}
- result
- end
-
- def tsort_each
- each_strongly_connected_component {|component|
- if component.size == 1
- yield component.first
- else
- raise Cyclic.new "topological sort failed: #{component.inspect}"
- end
- }
- end
-
- def strongly_connected_components
- result = []
- each_strongly_connected_component {|component| result << component}
- result
- end
-
- def each_strongly_connected_component(&block)
- id_map = {}
- stack = []
- tsort_each_node {|node|
- unless id_map.include? node
- each_strongly_connected_component_from(node, id_map, stack, &block)
- end
- }
- nil
- end
-
- def each_strongly_connected_component_from(node, id_map={}, stack=[], &block)
- minimum_id = node_id = id_map[node] = id_map.size
- stack_length = stack.length
- stack << node
-
- tsort_each_child(node) {|child|
- if id_map.include? child
- child_id = id_map[child]
- minimum_id = child_id if child_id && child_id < minimum_id
- else
- sub_minimum_id =
- each_strongly_connected_component_from(child, id_map, stack, &block)
- minimum_id = sub_minimum_id if sub_minimum_id < minimum_id
- end
- }
-
- if node_id == minimum_id
- component = stack.slice!(stack_length .. -1)
- component.each {|n| id_map[n] = nil}
- yield component
- end
-
- minimum_id
- end
-
- def tsort_each_node
- raise NotImplementedError.new
- end
-
- def tsort_each_child(node)
- raise NotImplementedError.new
- end
-end
-
-if __FILE__ == $0
- require 'runit/testcase'
- require 'runit/cui/testrunner'
-
- class Hash
- include TSort
- alias tsort_each_node each_key
- def tsort_each_child(node, &block)
- fetch(node).each(&block)
- end
- end
-
- class Array
- include TSort
- alias tsort_each_node each_index
- def tsort_each_child(node, &block)
- fetch(node).each(&block)
- end
- end
-
- class TSortTest < RUNIT::TestCase
- def test_dag
- h = {1=>[2, 3], 2=>[3], 3=>[]}
- assert_equal([3, 2, 1], h.tsort)
- assert_equal([[3], [2], [1]], h.strongly_connected_components)
- end
-
- def test_cycle
- h = {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}
- assert_equal([[4], [2, 3], [1]],
- h.strongly_connected_components.map {|nodes| nodes.sort})
- assert_exception(TSort::Cyclic) { h.tsort }
- end
-
- def test_array
- a = [[1], [0], [0], [2]]
- assert_equal([[0, 1], [2], [3]],
- a.strongly_connected_components.map {|nodes| nodes.sort})
-
- a = [[], [0]]
- assert_equal([[0], [1]],
- a.strongly_connected_components.map {|nodes| nodes.sort})
- end
- end
-
- RUNIT::CUI::TestRunner.run(TSortTest.suite)
-end
-
diff --git a/lib/uri.rb b/lib/uri.rb
deleted file mode 100644
index d33f0c827f..0000000000
--- a/lib/uri.rb
+++ /dev/null
@@ -1,41 +0,0 @@
-#
-# $Id$
-#
-# Copyright (c) 2001 akira yamada <akira@ruby-lang.org>
-# You can redistribute it and/or modify it under the same term as Ruby.
-#
-
-=begin
-
- Copyright (c) 2001 akira yamada <akira@ruby-lang.org>
- You can redistribute it and/or modify it under the same term as Ruby.
-
-= URI - URI support for Ruby
-
-=end
-
-module URI
- VERSION_CODE = '000906'.freeze
- VERSION = VERSION_CODE.scan(/../).collect{|n| n.to_i}.join('.').freeze
-end
-
-=begin
-
-== Components
-
- * ((<URI>)) Module
- * ((<URI::Generic>)) Class
- * ((<URI::FTP>)) Class
- * ((<URI::HTTP>)) Class
- * ((<URI::HTTPS>)) Class
- * ((<URI::LDAP>)) Class
- * ((<URI::MailTo>)) Class
-
-=end
-require 'uri/common'
-require 'uri/generic'
-require 'uri/ftp'
-require 'uri/http'
-require 'uri/https'
-require 'uri/ldap'
-require 'uri/mailto'
diff --git a/lib/uri/common.rb b/lib/uri/common.rb
deleted file mode 100644
index 6f2fa81ad2..0000000000
--- a/lib/uri/common.rb
+++ /dev/null
@@ -1,432 +0,0 @@
-#
-# $Id$
-#
-# Copyright (c) 2001 akira yamada <akira@ruby-lang.org>
-# You can redistribute it and/or modify it under the same term as Ruby.
-#
-
-=begin
-
-== URI
-
-=end
-
-module URI
- module REGEXP
- module PATTERN
- # RFC 2396 (URI Generic Syntax)
- # RFC 2732 (IPv6 Literal Addresses in URL's)
- # RFC 2373 (IPv6 Addressing Architecture)
-
- # alpha = lowalpha | upalpha
- ALPHA = "a-zA-Z"
- # alphanum = alpha | digit
- ALNUM = "#{ALPHA}\\d"
-
- # hex = digit | "A" | "B" | "C" | "D" | "E" | "F" |
- # "a" | "b" | "c" | "d" | "e" | "f"
- HEX = "a-fA-F\\d"
- # escaped = "%" hex hex
- ESCAPED = "%[#{HEX}]{2}"
- # mark = "-" | "_" | "." | "!" | "~" | "*" | "'" |
- # "(" | ")"
- # unreserved = alphanum | mark
- UNRESERVED = "-_.!~*'()#{ALNUM}"
- # reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
- # "$" | ","
- # reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
- # "$" | "," | "[" | "]" (RFC 2732)
- RESERVED = ";/?:@&=+$,\\[\\]"
-
- # uric = reserved | unreserved | escaped
- URIC = "(?:[#{UNRESERVED}#{RESERVED}]|#{ESCAPED})"
- # uric_no_slash = unreserved | escaped | ";" | "?" | ":" | "@" |
- # "&" | "=" | "+" | "$" | ","
- URIC_NO_SLASH = "(?:[#{UNRESERVED};?:@&=+$,]|#{ESCAPED})"
- # query = *uric
- QUERY = "#{URIC}*"
- # fragment = *uric
- FRAGMENT = "#{URIC}*"
-
- # domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum
- DOMLABEL = "(?:[#{ALNUM}](?:[-#{ALNUM}]*[#{ALNUM}])?)"
- # toplabel = alpha | alpha *( alphanum | "-" ) alphanum
- TOPLABEL = "(?:[#{ALPHA}](?:[-#{ALNUM}]*[#{ALNUM}])?)"
- # hostname = *( domainlabel "." ) toplabel [ "." ]
- HOSTNAME = "(?:#{DOMLABEL}\\.)*#{TOPLABEL}\\.?"
-
- # RFC 2373, APPENDIX B:
- # IPv6address = hexpart [ ":" IPv4address ]
- # IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT
- # hexpart = hexseq | hexseq "::" [ hexseq ] | "::" [ hexseq ]
- # hexseq = hex4 *( ":" hex4)
- # hex4 = 1*4HEXDIG
- #
- # XXX: This definition has a flaw. "::" + IPv4address must be
- # allowed too. Here is a replacement.
- #
- # IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT
- IPV4ADDR = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"
- # hex4 = 1*4HEXDIG
- HEX4 = "[#{HEX}]{1,4}"
- # lastpart = hex4 | IPv4address
- LASTPART = "(?:#{HEX4}|#{IPV4ADDR})"
- # hexseq1 = *( hex4 ":" ) hex4
- HEXSEQ1 = "(?:#{HEX4}:)*#{HEX4}"
- # hexseq2 = *( hex4 ":" ) lastpart
- HEXSEQ2 = "(?:#{HEX4}:)*#{LASTPART}"
- # IPv6address = hexseq2 | [ hexseq1 ] "::" [ hexseq2 ]
- IPV6ADDR = "(?:#{HEXSEQ2}|(?:#{HEXSEQ1})?::(?:#{HEXSEQ2})?)"
-
- # IPv6prefix = ( hexseq1 | [ hexseq1 ] "::" [ hexseq1 ] ) "/" 1*2DIGIT
- # unused
-
- # ipv6reference = "[" IPv6address "]" (RFC 2732)
- IPV6REF = "\\[#{IPV6ADDR}\\]"
-
- # host = hostname | IPv4address
- # host = hostname | IPv4address | IPv6reference (RFC 2732)
- HOST = "(?:#{HOSTNAME}|#{IPV4ADDR}|#{IPV6REF})"
- # port = *digit
- PORT = "\d*"
- # hostport = host [ ":" port ]
- HOSTPORT = "#{HOST}(?:#{PORT})?"
-
- # userinfo = *( unreserved | escaped |
- # ";" | ":" | "&" | "=" | "+" | "$" | "," )
- USERINFO = "(?:[#{UNRESERVED};:&=+$,]|#{ESCAPED})*"
-
- # pchar = unreserved | escaped |
- # ":" | "@" | "&" | "=" | "+" | "$" | ","
- PCHAR = "(?:[#{UNRESERVED}:@&=+$,]|#{ESCAPED})"
- # param = *pchar
- PARAM = "#{PCHAR}*"
- # segment = *pchar *( ";" param )
- SEGMENT = "#{PCHAR}*(?:;#{PARAM})*"
- # path_segments = segment *( "/" segment )
- PATH_SEGMENTS = "#{SEGMENT}(?:/#{SEGMENT})*"
-
- # server = [ [ userinfo "@" ] hostport ]
- SERVER = "(?:#{USERINFO}@)?#{HOSTPORT}"
- # reg_name = 1*( unreserved | escaped | "$" | "," |
- # ";" | ":" | "@" | "&" | "=" | "+" )
- REG_NAME = "(?:[#{UNRESERVED}$,;+@&=+]|#{ESCAPED})+"
- # authority = server | reg_name
- AUTHORITY = "(?:#{SERVER}|#{REG_NAME})"
-
- # rel_segment = 1*( unreserved | escaped |
- # ";" | "@" | "&" | "=" | "+" | "$" | "," )
- REL_SEGMENT = "(?:[#{UNRESERVED};@&=+$,]|#{ESCAPED})+"
-
- # scheme = alpha *( alpha | digit | "+" | "-" | "." )
- SCHEME = "[#{ALPHA}][-+.#{ALPHA}\\d]*"
-
- # abs_path = "/" path_segments
- ABS_PATH = "/#{PATH_SEGMENTS}"
- # rel_path = rel_segment [ abs_path ]
- REL_PATH = "#{REL_SEGMENT}(?:#{ABS_PATH})?"
- # net_path = "//" authority [ abs_path ]
- NET_PATH = "//#{AUTHORITY}(?:#{ABS_PATH})?"
-
- # hier_part = ( net_path | abs_path ) [ "?" query ]
- HIER_PART = "(?:#{NET_PATH}|#{ABS_PATH})(?:\\?(?:#{QUERY}))?"
- # opaque_part = uric_no_slash *uric
- OPAQUE_PART = "#{URIC_NO_SLASH}#{URIC}*"
-
- # absoluteURI = scheme ":" ( hier_part | opaque_part )
- ABS_URI = "#{SCHEME}:(?:#{HIER_PART}|#{OPAQUE_PART})"
- # relativeURI = ( net_path | abs_path | rel_path ) [ "?" query ]
- REL_URI = "(?:#{NET_PATH}|#{ABS_PATH}|#{REL_PATH})(?:\\?#{QUERY})?"
-
- # URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
- URI_REF = "(?:#{ABS_URI}|#{REL_URI})?(?:##{FRAGMENT})?"
-
- # XXX:
- X_ABS_URI = "
- (#{PATTERN::SCHEME}): (?# 1: scheme)
- (?:
- (?:
- //(?:
- (?:(?:(#{PATTERN::USERINFO})@)? (?# 2: userinfo)
- (?:(#{PATTERN::HOST})(?::(\\d*))?))?(?# 3: host, 4: port)
- |
- (#{PATTERN::REG_NAME}) (?# 5: registry)
- )
- (#{PATTERN::ABS_PATH})? (?# 6: path)
- )(?:\\?(#{PATTERN::QUERY}))? (?# 7: query)
- |
- (#{PATTERN::OPAQUE_PART}) (?# 8: opaque)
- )
- (?:\\#(#{PATTERN::FRAGMENT}))? (?# 9: fragment)
- "
- X_REL_URI = "
- (?:
- (?:
- //
- (?:
- (?:(#{PATTERN::USERINFO})@)? (?# 1: userinfo)
- (#{PATTERN::HOST})?(?::(\\d*))? (?# 2: host, 3: port)
- |
- (#{PATTERN::REG_NAME}) (?# 4: registry)
- )
- )
- |
- (#{PATTERN::REL_SEGMENT}) (?# 5: rel_segment)
- )?
- (#{PATTERN::ABS_PATH})? (?# 6: abs_path)
- (?:\\?(#{PATTERN::QUERY}))? (?# 7: query)
- (?:\\#(#{PATTERN::FRAGMENT}))? (?# 8: fragment)
- "
- end # PATTERN
-
- # for URI::split
- ABS_URI = Regexp.new('^' + PATTERN::X_ABS_URI + '$', #'
- Regexp::EXTENDED, 'N').freeze
- REL_URI = Regexp.new('^' + PATTERN::X_REL_URI + '$', #'
- Regexp::EXTENDED, 'N').freeze
-
- # for URI::extract
- URI_REF = Regexp.new(PATTERN::URI_REF, false, 'N').freeze
- ABS_URI_REF = Regexp.new(PATTERN::X_ABS_URI, Regexp::EXTENDED, 'N').freeze
- REL_URI_REF = Regexp.new(PATTERN::X_REL_URI, Regexp::EXTENDED, 'N').freeze
-
- # for URI::escape/unescape
- ESCAPED = Regexp.new(PATTERN::ESCAPED, false, 'N').freeze
- UNSAFE = Regexp.new("[^#{PATTERN::UNRESERVED}#{PATTERN::RESERVED}]",
- false, 'N').freeze
-
- # for Generic#initialize
- SCHEME = Regexp.new("^#{PATTERN::SCHEME}$", false, 'N').freeze #"
- USERINFO = Regexp.new("^#{PATTERN::USERINFO}$", false, 'N').freeze #"
- HOST = Regexp.new("^#{PATTERN::HOST}$", false, 'N').freeze #"
- PORT = Regexp.new("^#{PATTERN::PORT}$", false, 'N').freeze #"
- OPAQUE = Regexp.new("^#{PATTERN::OPAQUE_PART}$", false, 'N').freeze #"
- REGISTRY = Regexp.new("^#{PATTERN::REG_NAME}$", false, 'N').freeze #"
- ABS_PATH = Regexp.new("^#{PATTERN::ABS_PATH}$", false, 'N').freeze #"
- REL_PATH = Regexp.new("^#{PATTERN::REL_PATH}$", false, 'N').freeze #"
- QUERY = Regexp.new("^#{PATTERN::QUERY}$", false, 'N').freeze #"
- FRAGMENT = Regexp.new("^#{PATTERN::FRAGMENT}$", false, 'N').freeze #"
- end # REGEXP
-
- module Util
- def make_components_hash(klass, array_hash)
- tmp = {}
- if array_hash.kind_of?(Array) &&
- array_hash.size == klass.component.size - 1
- klass.component[1..-1].each_index do |i|
- begin
- tmp[klass.component[i + 1]] = array_hash[i].clone
- rescue TypeError
- tmp[klass.component[i + 1]] = array_hash[i]
- end
- end
-
- elsif array_hash.kind_of?(Hash)
- array_hash.each do |key, value|
- begin
- tmp[key] = value.clone
- rescue TypeError
- tmp[key] = value
- end
- end
- else
- raise ArgumentError,
- "expected Array of or Hash of compornents of #{klass.to_s} (#{klass.component[1..-1].join(', ')})"
- end
- tmp[:scheme] = klass.to_s.sub(/\A.*::/, '').downcase
-
- return tmp
- end
- module_function :make_components_hash
- end
-
- module Escape
- include REGEXP
-
- def escape(str, unsafe = UNSAFE)
- unless unsafe.kind_of?(Regexp)
- # perhaps unsafe is String object
- unsafe = Regexp.new(Regexp.quote(unsafe), false, 'N')
- end
- str.gsub(unsafe) do |us|
- tmp = ''
- us.each_byte do |uc|
- tmp << sprintf('%%%02X', uc)
- end
- tmp
- end
- end
- alias encode escape
-
- def unescape(str)
- str.gsub(ESCAPED) do
- $&[1,2].hex.chr
- end
- end
- alias decode unescape
- end
-
- include REGEXP
- extend Escape
-
- @@schemes = {}
-
- class Error < StandardError; end
- class InvalidURIError < Error; end # it is not URI.
- class InvalidComponentError < Error; end # it is not component of URI.
- class BadURIError < Error; end # the URI is valid but it is bad for the position.
-
-=begin
-
-=== Methods
-
---- URI::split(uri)
-
-=end
-
- def self.split(uri)
- case uri
- when ''
- # null uri
-
- when ABS_URI
- scheme, userinfo, host, port,
- registry, path, query, opaque, fragment = $~[1..-1]
-
- # URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
-
- # absoluteURI = scheme ":" ( hier_part | opaque_part )
- # hier_part = ( net_path | abs_path ) [ "?" query ]
- # opaque_part = uric_no_slash *uric
-
- # abs_path = "/" path_segments
- # net_path = "//" authority [ abs_path ]
-
- # authority = server | reg_name
- # server = [ [ userinfo "@" ] hostport ]
-
- if !scheme
- raise InvalidURIError,
- "bad URI(absolute but no scheme): #{uri}"
- end
- if !opaque && (!path && (!host && !registry))
- raise InvalidURIError,
- "bad URI(absolute but no path): #{uri}"
- end
-
- when REL_URI
- scheme = nil
- opaque = nil
-
- userinfo, host, port, registry,
- rel_segment, abs_path, query, fragment = $~[1..-1]
- if rel_segment && abs_path
- path = rel_segment + abs_path
- elsif rel_segment
- path = rel_segment
- elsif abs_path
- path = abs_path
- end
-
- # URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
-
- # relativeURI = ( net_path | abs_path | rel_path ) [ "?" query ]
-
- # net_path = "//" authority [ abs_path ]
- # abs_path = "/" path_segments
- # rel_path = rel_segment [ abs_path ]
-
- # authority = server | reg_name
- # server = [ [ userinfo "@" ] hostport ]
-
- else
- raise InvalidURIError, "bad URI(is not URI?): #{uri}"
- end
-
- path = '' if !path && !opaque # (see RFC2396 Section 5.2)
- ret = [
- scheme,
- userinfo, host, port, # X
- registry, # X
- path, # Y
- opaque, # Y
- query,
- fragment
- ]
- return ret
- end
-
-=begin
-
---- URI::parse(uri_str)
-
-=end
- def self.parse(uri)
- scheme, userinfo, host, port,
- registry, path, opaque, query, fragment = self.split(uri)
-
- if scheme && @@schemes.include?(scheme.upcase)
- @@schemes[scheme.upcase].new(scheme, userinfo, host, port,
- registry, path, opaque, query,
- fragment)
- else
- Generic.new(scheme, userinfo, host, port,
- registry, path, opaque, query,
- fragment)
- end
- end
-
-=begin
-
---- URI::join(str[, str, ...])
-
-=end
- def self.join(*str)
- u = self.parse(str[0])
- str[1 .. -1].each do |x|
- u = u.merge(x)
- end
- u
- end
-
-=begin
-
---- URI::extract(str[, schemes])
-
-=end
- def self.extract(str, schemes = [])
- urls = []
- if schemes.size > 0
- tmp = Regexp.new('(?:' + schemes.collect{|s|
- Regexp.quote(s + ':')
- }.join('|') + ')',
- Regexp::IGNORECASE, 'N')
- str.scan(tmp) {
- tmp_str = $& + $'
- if ABS_URI_REF =~ tmp_str
- if block_given?
- yield($&)
- else
- urls << $&
- end
- end
- }
-
- else
- str.scan(ABS_URI_REF) {
- if block_given?
- yield($&)
- else
- urls << $&
- end
- }
- end
-
- if block_given?
- return nil
- else
- return urls
- end
- end
-
-end # URI
diff --git a/lib/uri/ftp.rb b/lib/uri/ftp.rb
deleted file mode 100644
index 391cd550e9..0000000000
--- a/lib/uri/ftp.rb
+++ /dev/null
@@ -1,149 +0,0 @@
-#
-# $Id$
-#
-# Copyright (c) 2001 akira yamada <akira@ruby-lang.org>
-# You can redistribute it and/or modify it under the same term as Ruby.
-#
-
-require 'uri/generic'
-
-module URI
-
-=begin
-
-== URI::FTP
-
-=== Super Class
-
-((<URI::Generic>))
-
-=end
-
- # RFC1738 section 3.2.
- class FTP < Generic
- DEFAULT_PORT = 21
-
- COMPONENT = [
- :scheme,
- :userinfo, :host, :port,
- :path, :typecode
- ].freeze
-
- TYPECODE = ['a', 'i', 'd'].freeze
- TYPECODE_PREFIX = ';type='.freeze
-
-=begin
-
-=== Class Methods
-
---- URI::FTP::build
- Create a new URI::FTP object from components of URI::FTP with
- check. It is scheme, userinfo, host, port, path and typecode. It
- provided by an Array or a Hash. typecode is "a", "i" or "d".
-
---- URI::FTP::new
- Create a new URI::FTP object from ``generic'' components with no
- check.
-
-=end
-
- def self.new2(user, password, host, port, path,
- typecode = nil, arg_check = true)
- typecode = nil if typecode.size == 0
- if typecode && !TYPECODE.include?(typecode)
- raise ArgumentError,
- "bad typecode is specified: #{typecode}"
- end
-
- # do escape
-
- self.new('ftp',
- [user, password],
- host, port, nil,
- typecode ? path + TYPECODE_PREFIX + typecode : path,
- nil, nil, nil, arg_check)
- end
-
- def self.build(args)
- tmp = Util::make_components_hash(self, args)
-
- if tmp[:typecode]
- if tmp[:typecode].size == 1
- tmp[:typecode] = TYPECODE_PREFIX + tmp[:typecode]
- end
- tmp[:path] << tmp[:typecode]
- end
-
- return super(tmp)
- end
-
- def initialize(*arg)
- super(*arg)
- @typecode = nil
- tmp = @path.index(TYPECODE_PREFIX)
- if tmp
- typecode = @path[tmp + TYPECODE_PREFIX.size..-1]
- self.set_path(@path[0..tmp - 1])
-
- if arg[-1]
- self.typecode = typecode
- else
- self.set_typecode(typecode)
- end
- end
- end
- attr_reader :typecode
-
- #
- # methods for typecode
- #
-
- def check_typecode(v)
- if TYPECODE.include?(v)
- return true
- else
- raise InvalidComponentError,
- "bad typecode(expected #{TYPECODE.join(', ')}): #{v}"
- end
- end
- private :check_typecode
-
- def set_typecode(v)
- @typecode = v
- end
- protected :set_typecode
-
- def typecode=(typecode)
- check_typecode(typecode)
- set_typecode(typecode)
- end
-
-=begin
-=end
- def merge(oth)
- tmp = super(oth)
- if self != tmp
- tmp.set_typecode(oth.typecode)
- end
-
- return tmp
- end
-
-=begin
-=end
- def to_str
- save_path = nil
- if @typecode
- save_path = @path
- @path = @path + TYPECODE_PREFIX + @typecode
- end
- str = super
- if @typecode
- @path = save_path
- end
-
- return str
- end
- end # FTP
- @@schemes['FTP'] = FTP
-end # URI
diff --git a/lib/uri/generic.rb b/lib/uri/generic.rb
deleted file mode 100644
index e80c6f752b..0000000000
--- a/lib/uri/generic.rb
+++ /dev/null
@@ -1,1099 +0,0 @@
-#
-# $Id$
-#
-# Copyright (c) 2001 akira yamada <akira@ruby-lang.org>
-# You can redistribute it and/or modify it under the same term as Ruby.
-#
-
-require 'uri/common'
-
-module URI
-
-=begin
-
-== URI::Generic
-
-=== Super Class
-
-Object
-
-=end
-
- class Generic
- include REGEXP
-
-=begin
-
-=== Class Methods
-
---- URI::Generic::default_port
-
-=end
- DEFAULT_PORT = nil
-
- def self.default_port
- self::DEFAULT_PORT
- end
-
- def default_port
- self.type.default_port
- end
-
-=begin
---- URI::Generic::component
-=end
- COMPONENT = [
- :scheme,
- :userinfo, :host, :port, :registry,
- :path, :opaque,
- :query,
- :fragment
- ].freeze
-
- def self.component
- self::COMPONENT
- end
-
-=begin
---- URI::Generic::use_registry
-=end
- USE_REGISTRY = false
-
- def self.use_registry
- self::USE_REGISTRY
- end
-
-=begin
-
---- URI::Generic::build2
- At first, try to create a new URI::Generic object using
- URI::Generic::build. But, if you get a exception
- URI::InvalidComponentError, then re-try to create an object with
- escaped components.
-
---- URI::Generic::build
- Create a new URI::Generic object from components of URI::Generic
- with check. It is scheme, userinfo, host, port, registry, path,
- opaque, query and fragment. It provided by an Array of a Hash.
-
---- URI::Generic::new
- Create new URI::Generic object from ``generic'' components with no
- check.
-
-=end
- def self.build2(args)
- begin
- return self.build(args)
- rescue InvalidComponentError
- if args.kind_of?(Array)
- return self.build(args.collect{|x|
- if x
- URI.escape(x)
- else
- x
- end
- })
- elsif args.kind_of?(Hash)
- tmp = {}
- args.each do |key, value|
- tmp[key] = if value
- URI.escape(value)
- else
- value
- end
- end
- return self.build(tmp)
- end
- end
- end
-
- def self.build(args)
- if args.kind_of?(Array) &&
- args.size == ::URI::Generic::COMPONENT.size
- tmp = args
- elsif args.kind_of?(Hash)
- tmp = ::URI::Generic::COMPONENT.collect do |c|
- if args.include?(c)
- args[c]
- else
- nil
- end
- end
- else
- raise ArgumentError,
- "expected Array of or Hash of compornents of #{self.type} (#{self.type.component.join(', ')})"
- end
-
- tmp << true
- return self.new(*tmp)
- end
-
- def initialize(scheme,
- userinfo, host, port, registry,
- path, opaque,
- query,
- fragment,
- arg_check = false)
- @scheme = nil
- @user = nil
- @password = nil
- @host = nil
- @port = nil
- @path = nil
- @query = nil
- @opaque = nil
- @registry = nil
- @fragment = nil
-
- if arg_check
- self.scheme = scheme
- self.userinfo = userinfo
- self.host = host
- self.port = port
- self.path = path
- self.query = query
- self.opaque = opaque
- self.registry = registry
- self.fragment = fragment
- else
- self.set_scheme(scheme)
- self.set_userinfo(userinfo)
- self.set_host(host)
- self.set_port(port)
- self.set_path(path)
- self.set_query(query)
- self.set_opaque(opaque)
- self.set_registry(registry)
- self.set_fragment(fragment)
- end
- if @registry && !self.class.use_registry
- raise InvalidURIError, "the scheme #{@scheme} does not accept registry part: #{@registry} (or bad hostname?)"
- end
-
- @scheme.freeze if @scheme
- self.set_path('') if !@path && !@opaque # (see RFC2396 Section 5.2)
- self.set_port(self.default_port) if self.default_port && !@port
- end
- attr_reader :scheme
- attr_reader :host
- attr_reader :port
- attr_reader :registry
- attr_reader :path
- attr_reader :query
- attr_reader :opaque
- attr_reader :fragment
-
-=begin
-
-=== Instance Methods
-
-=end
-
-=begin
-
---- URI::Generic#component
-
-=end
- def component
- self.type.component
- end
-
- # set_XXX method sets value to @XXX instance variable with no check,
- # so be careful if you use these methods. or, you use these method
- # with check_XXX method, or you use XXX= methods.
-
-=begin
-
---- URI::Generic#scheme
-
---- URI::Generic#scheme=(v)
-
-=end
- #
- # methods for scheme
- #
- def check_scheme(v)
- if v && SCHEME !~ v
- raise InvalidComponentError,
- "bad component(expected scheme component): #{v}"
- end
-
- return true
- end
- private :check_scheme
-
- def set_scheme(v)
- @scheme = v
- end
- protected :set_scheme
-
- def scheme=(v)
- check_scheme(v)
- set_scheme(v)
- end
-
-=begin
-
---- URI::Generic#userinfo
-
---- URI::Generic#userinfo=(v)
-
---- URI::Generic#user
-
---- URI::Generic#user=(v)
-
---- URI::Generic#password
-
---- URI::Generic#password=(v)
-
-=end
- #
- # methods for userinfo
- #
- def check_userinfo(user, password = nil)
- if (user || password) &&
- (@registry || @opaque)
- raise InvalidURIError,
- "can not set userinfo with registry or opaque"
- end
-
- if !password
- user, password = split_userinfo(user)
- end
- check_user(user)
- check_password(password)
-
- return true
- end
- private :check_userinfo
-
- def check_user(v)
- return v unless v
-
- if USERINFO !~ v
- raise InvalidComponentError,
- "bad component(expected userinfo component or user component): #{v}"
- end
-
- return true
- end
- private :check_user
-
- def check_password(v)
- return v unless v
-
- if !@password
- raise InvalidURIError,
- "password component depends user component"
- end
-
- if USERINFO !~ v
- raise InvalidComponentError,
- "bad component(expected user component): #{v}"
- end
-
- return true
- end
- private :check_password
-
- def userinfo=(user, password = nil)
- check_userinfo(user, password)
- set_userinfo(user, password)
- end
-
- def user=(user)
- check_user(user)
- set_user(user)
- end
-
- def password=(password)
- check_password(password)
- set_password(password)
- end
-
- def set_userinfo(user, password = nil)
- if !password
- user, password = split_userinfo(user)
- end
- @user = user
- @password = password
- end
- protected :set_userinfo
-
- def set_user(v)
- set_userinfo(v, @password)
- end
- protected :set_user
-
- def set_password(v)
- set_userinfo(@user, v)
- end
- protected :set_password
-
- def split_userinfo(ui)
- return nil, nil unless ui
- tmp = ui.index(':')
- if tmp
- user = ui[0..tmp - 1]
- password = ui[tmp + 1..-1]
- else
- user = ui
- password = nil
- end
-
- return user, password
- end
- private :split_userinfo
-
- def escape_userpass(v)
- v = URI.escape(v, /[@:\/]/o) # RFC 1738 section 3.1 #/
- end
- private :escape_userpass
-
- def userinfo
- if !@password
- @user
- else
- @user + ':' + @password
- end
- end
-
- def user
- @user
- end
-
- def password
- @password
- end
-
-=begin
-
---- URI::Generic#host
-
---- URI::Generic#host=(v)
-
-=end
- #
- # methods for host
- #
-
- def check_host(v)
- return v unless v
-
- if @registry || @opaque
- raise InvalidURIError,
- "can not set host with registry or opaque"
- elsif HOST !~ v
- raise InvalidComponentError,
- "bad component(expected host component): #{v}"
- end
-
- return true
- end
- private :check_host
-
- def set_host(v)
- @host = v
- end
- protected :set_host
-
- def host=(v)
- check_host(v)
- set_host(v)
- end
-
-=begin
-
---- URI::Generic#port
-
---- URI::Generic#port=(v)
-
-=end
- #
- # methods for port
- #
-
- def check_port(v)
- return v unless v
-
- if @registry || @opaque
- raise InvalidURIError,
- "can not set port with registry or opaque"
- elsif !v.kind_of?(Fixnum) && PORT !~ v
- raise InvalidComponentError,
- "bad component(expected port component): #{v}"
- end
-
- return true
- end
- private :check_port
-
- def set_port(v)
- v = v.to_i if v && !v.kind_of?(Fixnum)
- @port = v
- end
- protected :set_port
-
- def port=(v)
- check_port(v)
- set_port(v)
- end
-
-=begin
-
---- URI::Generic#registry
-
---- URI::Generic#registry=(v)
-
-=end
- #
- # methods for registry
- #
-
- def check_registry(v)
- return v unless v
-
- # raise if both server and registry are not nil, because:
- # authority = server | reg_name
- # server = [ [ userinfo "@" ] hostport ]
- if @host || @port || @user # userinfo = @user + ':' + @password
- raise InvalidURIError,
- "can not set registry with host, port, or userinfo"
- elsif v && REGISTRY !~ v
- raise InvalidComponentError,
- "bad component(expected registry component): #{v}"
- end
-
- return true
- end
- private :check_registry
-
- def set_registry(v)
- @registry = v
- end
- protected :set_registry
-
- def registry=(v)
- check_registry(v)
- set_registry(v)
- end
-
-=begin
-
---- URI::Generic#path
-
---- URI::Generic#path=(v)
-
-=end
- #
- # methods for path
- #
-
- def check_path(v)
- # raise if both hier and opaque are not nil, because:
- # absoluteURI = scheme ":" ( hier_part | opaque_part )
- # hier_part = ( net_path | abs_path ) [ "?" query ]
- if v && @opaque
- raise InvalidURIError,
- "path conflicts with opaque"
- end
-
- if @scheme
- if v && v != '' && ABS_PATH !~ v
- raise InvalidComponentError,
- "bad component(expected absolute path component): #{v}"
- end
- else
- if v && v != '' && ABS_PATH !~ v && REL_PATH !~ v
- raise InvalidComponentError,
- "bad component(expected relative path component): #{v}"
- end
- end
-
- return true
- end
- private :check_path
-
- def set_path(v)
- @path = v
- end
- protected :set_path
-
- def path=(v)
- check_path(v)
- set_path(v)
- end
-
-=begin
-
---- URI::Generic#query
-
---- URI::Generic#query=(v)
-
-=end
- #
- # methods for query
- #
-
- def check_query(v)
- return v unless v
-
- # raise if both hier and opaque are not nil, because:
- # absoluteURI = scheme ":" ( hier_part | opaque_part )
- # hier_part = ( net_path | abs_path ) [ "?" query ]
- if @opaque
- raise InvalidURIError,
- "query conflicts with opaque"
- end
-
- if v && v != '' && QUERY !~ v
- raise InvalidComponentError,
- "bad component(expected query component): #{v}"
- end
-
- return true
- end
- private :check_query
-
- def set_query(v)
- @query = v
- end
- protected :set_query
-
- def query=(v)
- check_query(v)
- set_query(v)
- end
-
-=begin
-
---- URI::Generic#opaque
-
---- URI::Generic#opaque=(v)
-
-=end
- #
- # methods for opaque
- #
-
- def check_opaque(v)
- return v unless v
-
- # raise if both hier and opaque are not nil, because:
- # absoluteURI = scheme ":" ( hier_part | opaque_part )
- # hier_part = ( net_path | abs_path ) [ "?" query ]
- if @host || @port || @usr || @path # userinfo = @user + ':' + @password
- raise InvalidURIError,
- "can not set opaque with host, port, userinfo or path"
- elsif v && OPAQUE !~ v
- raise InvalidComponentError,
- "bad component(expected opaque component): #{v}"
- end
-
- return true
- end
- private :check_opaque
-
- def set_opaque(v)
- @opaque = v
- end
- protected :set_opaque
-
- def opaque=(v)
- check_opaque(v)
- set_opaque(v)
- end
-
-=begin
-
---- URI::Generic#fragment
-
---- URI::Generic#fragment=(v)
-
-=end
- #
- # methods for fragment
- #
-
- def check_fragment(v)
- return v unless v
-
- if v && v != '' && FRAGMENT !~ v
- raise InvalidComponentError,
- "bad component(expected fragment component): #{v}"
- end
-
- return true
- end
- private :check_fragment
-
- def set_fragment(v)
- @fragment = v
- end
- protected :set_fragment
-
- def fragment=(v)
- check_fragment(v)
- set_fragment(v)
- end
-
-=begin
-
---- URI::Generic#hierarchical?
-
-=end
- def hierarchical?
- if @path
- true
- else
- false
- end
- end
-
-=begin
-
---- URI::Generic#absolute?
-
-=end
- def absolute?
- if @scheme
- true
- else
- false
- end
- end
- alias absolute absolute?
-
-=begin
-
---- URI::Generic#relative?
-
-=end
- def relative?
- !absolute?
- end
-
-=begin
-
---- URI::Generic#merge(rel)
---- URI::Generic#+(rel)
-
-=end
- def split_path(path)
- path.split(%r{/+}, -1)
- end
- private :split_path
-
- def merge_path(base, rel)
- # RFC2396, Section 5.2, 5)
- if rel[0] == ?/ #/
- # RFC2396, Section 5.2, 5)
- return rel
-
- else
- # RFC2396, Section 5.2, 6)
- base_path = split_path(base)
- rel_path = split_path(rel)
-
- if base_path.empty?
- base_path = [''] # XXX
- end
-
- # RFC2396, Section 5.2, 6), a)
- base_path.pop unless base_path.size == 1
-
- # RFC2396, Section 5.2, 6), c)
- # RFC2396, Section 5.2, 6), d)
- rel_path.push('') if rel_path.last == '.'
- rel_path.delete('.')
-
- # RFC2396, Section 5.2, 6), e)
- tmp = []
- rel_path.each do |x|
- if x == '..' &&
- !(tmp.empty? || tmp.last == '..')
- tmp.pop
- else
- tmp << x
- end
- end
-
- add_trailer_slash = true
- while x = tmp.shift
- if x == '..' && base_path.size > 1
- # RFC2396, Section 4
- # a .. or . in an absolute path has no special meaning
- base_path.pop
- else
- # if x == '..'
- # valid absolute (but abnormal) path "/../..."
- # else
- # valid absolute path
- # end
- base_path << x
- tmp.each {|t| base_path << t}
- add_trailer_slash = false
- break
- end
- end
- base_path.push('') if add_trailer_slash
-
- return base_path.join('/')
- end
- end
- private :merge_path
-
- # abs(self) + rel(oth) => abs(new)
- def merge(oth)
- base, rel = merge0(oth)
- if base == rel
- return base
- end
-
- authority = rel.userinfo || rel.host || rel.port
-
- # RFC2396, Section 5.2, 2)
- if rel.path.empty? && !authority && !rel.query
- base.set_fragment(rel.fragment) if rel.fragment
- return base
- end
-
- base.set_query(nil)
- base.set_fragment(nil)
-
- # RFC2396, Section 5.2, 4)
- if !authority
- base.set_path(merge_path(base.path, rel.path))
- else
- # RFC2396, Section 5.2, 4)
- base.set_path(rel.path)
- end
-
- # RFC2396, Section 5.2, 7)
- base.set_userinfo(rel.userinfo) if rel.userinfo
- base.set_host(rel.host) if rel.host
- base.set_port(rel.port) if rel.port
- base.set_query(rel.query) if rel.query
- base.set_fragment(rel.fragment) if rel.fragment
-
- return base
- end # merge
- alias + merge
-
- # return base and rel.
- # you can modify `base', but can not `rel'.
- def merge0(oth)
- case oth
- when Generic
- when String
- oth = URI.parse(oth)
- else
- raise ArgumentError,
- "bad argument(expected URI object or URI string)"
- end
-
- if self.relative? && oth.relative?
- raise BadURIError,
- "both URI are relative"
- end
-
- if self.absolute? && oth.absolute?
- #raise BadURIError,
- # "both URI are absolute"
- # hmm... should return oth for usability?
- return oth, oth
- end
-
- if !self.hierarchical?
- raise BadURIError,
- "not hierarchical URI: #{self}"
- elsif !oth.hierarchical?
- raise BadURIError,
- "not hierarchical URI: #{oth}"
- end
-
- if self.absolute?
- return self.dup, oth
- else
- return oth, oth
- end
- end
- private :merge0
-
-=begin
-
---- URI::Generic#route_from(src)
---- URI::Generic#-(src)
-
-=end
- def route_from_path(src, dst)
- # RFC2396, Section 4.2
- return '' if src == dst
-
- src_path = split_path(src)
- dst_path = split_path(dst)
-
- # hmm... dst has abnormal absolute path,
- # like "/./", "/../", "/x/../", ...
- if dst_path.include?('..') ||
- dst_path.include?('.')
- return dst.dup
- end
-
- src_path.pop
-
- # discard same parts
- while dst_path.first == src_path.first
- break if dst_path.empty?
-
- src_path.shift
- dst_path.shift
- end
-
- tmp = dst_path.join('/')
-
- # calculate
- if src_path.empty?
- if tmp.empty?
- return './'
- elsif dst_path.first.include?(':') # (see RFC2396 Section 5)
- return './' + tmp
- else
- return tmp
- end
- end
-
- return '../' * src_path.size + tmp
- end
- private :route_from_path
-
- def route_from0(oth)
- case oth
- when Generic
- when String
- oth = URI.parse(oth)
- else
- raise ArgumentError,
- "bad argument(expected URI object or URI string)"
- end
-
- if self.relative?
- raise BadURIError,
- "relative URI: #{self}"
- end
- if oth.relative?
- raise BadURIError,
- "relative URI: #{oth}"
- end
-
- if !self.hierarchical? || !oth.hierarchical?
- return self, self.dup
- end
-
- if self.scheme != oth.scheme
- return oth, oth.dup
- end
- rel = URI::Generic.new(nil, # it is relative URI
- self.userinfo, self.host, self.port,
- self.registry, self.path, self.opaque,
- self.query, self.fragment)
-
- if rel.userinfo != oth.userinfo ||
- rel.host != oth.host ||
- rel.port != oth.port
- rel.set_port(nil) if rel.port == oth.default_port
- return rel, rel
- end
- rel.set_userinfo(nil)
- rel.set_host(nil)
- rel.set_port(nil)
-
- if rel.path == oth.path
- rel.set_path('')
- rel.set_query(nil) if rel.query == oth.query
- return rel, rel
- end
-
- # you can modify `rel', but can not `oth'.
- return oth, rel
- end
- private :route_from0
-
- # calculate relative path from oth to self
- def route_from(oth)
- # you can modify `rel', but can not `oth'.
- oth, rel = route_from0(oth)
- if oth == rel
- return rel
- end
-
- rel.set_path(route_from_path(oth.path, self.path))
- if rel.path == './' && self.query
- # "./?foo" -> "?foo"
- rel.set_path('')
- end
-
- return rel
- end
- # abs1 - abs2 => relative_path_to_abs1_from_abs2
- # (see http://www.nikonet.or.jp/spring/what_v/what_v_4.htm :-)
- alias - route_from
-
-=begin
-
---- URI::Generic#route_to(dst)
-
-=end
- # calculate relative path to oth from self
- def route_to(oth)
- case oth
- when Generic
- when String
- oth = URI.parse(oth)
- else
- raise ArgumentError,
- "bad argument(expected URI object or URI string)"
- end
-
- oth.route_from(self)
- end
-
-=begin
-
---- URI::Generic#normalize
---- URI::Generic#normalize!
-
-=end
- def normalize
- uri = dup
- uri.normalize!
- uri
- end
-
- def normalize!
- if path && path == ''
- set_path('/')
- end
- if host && host != host.downcase
- set_host(self.host.downcase)
- end
- end
-
-=begin
-
---- URI::Generic#to_s
-
-=end
- def path_query
- str = @path
- if @query
- str += '?' + @query
- end
- str
- end
- private :path_query
-
- def to_str
- str = ''
- if @scheme
- str << @scheme
- str << ':'
- end
-
- if @opaque
- str << @opaque
-
- else
- if @registry
- str << @registry
- else
- if @host
- str << '//'
- end
- if self.userinfo
- str << self.userinfo
- str << '@'
- end
- if @host
- str << @host
- end
- if @port && @port != self.default_port
- str << ':'
- str << @port.to_s
- end
- end
-
- str << path_query
- end
-
- if @fragment
- str << '#'
- str << @fragment
- end
-
- str
- end
-
- def to_s
- to_str
- end
-
-=begin
-
---- URI::Generic#==(oth)
-
-=end
- def ==(oth)
- if oth.kind_of?(String)
- oth = URI.parse(oth)
- end
-
- if self.class == oth.class
- self.normalize.to_ary == oth.normalize.to_ary
- else
- false
- end
- end
-
-=begin
-
---- URI::Generic#===(oth)
-
-=end
-# def ===(oth)
-# raise NotImplementedError
-# end
-
-=begin
---- URI::Generic#to_a
-=end
- def to_ary
- component.collect do |x|
- self.send(x)
- end
- end
-
- def to_a
- to_ary
- end
-
-=begin
-=end
- def inspect
- sprintf("#<%s:0x%x URL:%s>", self.type.to_s, self.id, self.to_s)
- end
-
-=begin
-=end
- def coerce(oth)
- case oth
- when String
- oth = URI.parse(oth)
- else
- super
- end
-
- return oth, self
- end
- end # Generic
-end # URI
diff --git a/lib/uri/http.rb b/lib/uri/http.rb
deleted file mode 100644
index 3e5b209d49..0000000000
--- a/lib/uri/http.rb
+++ /dev/null
@@ -1,76 +0,0 @@
-#
-# $Id$
-#
-# Copyright (c) 2001 akira yamada <akira@ruby-lang.org>
-# You can redistribute it and/or modify it under the same term as Ruby.
-#
-
-require 'uri/generic'
-
-module URI
-
-=begin
-
-== URI::HTTP
-
-=== Super Class
-
-((<URI::Generic>))
-
-=end
-
- # RFC1738 section 3.3.
- class HTTP < Generic
- DEFAULT_PORT = 80
-
- COMPONENT = [
- :scheme,
- :userinfo, :host, :port,
- :path,
- :query,
- :fragment
- ].freeze
-
-=begin
-
-=== Class Methods
-
---- URI::HTTP::build
- Create a new URI::HTTP object from components of URI::HTTP with
- check. It is scheme, userinfo, host, port, path, query and
- fragment. It provided by an Array of a Hash.
-
---- URI::HTTP::new
- Create a new URI::HTTP object from ``generic'' components with no
- check.
-
-=end
-
- def self.build(args)
- tmp = Util::make_components_hash(self, args)
- return super(tmp)
- end
-
- def initialize(*arg)
- super(*arg)
- end
-
-=begin
-
-=== Instance Methods
-
---- URI::HTTP#request_uri
-
-=end
- def request_uri
- r = path_query
- if r[0] != ?/
- r = '/' + r
- end
-
- r
- end
- end # HTTP
-
- @@schemes['HTTP'] = HTTP
-end # URI
diff --git a/lib/uri/https.rb b/lib/uri/https.rb
deleted file mode 100644
index 691198fafa..0000000000
--- a/lib/uri/https.rb
+++ /dev/null
@@ -1,26 +0,0 @@
-#
-# $Id$
-#
-# Copyright (c) 2001 akira yamada <akira@ruby-lang.org>
-# You can redistribute it and/or modify it under the same term as Ruby.
-#
-
-require 'uri/http'
-
-module URI
-
-=begin
-
-== URI::HTTPS
-
-=== Super Class
-
-((<URI::HTTP>))
-
-=end
-
- class HTTPS < HTTP
- DEFAULT_PORT = 443
- end
- @@schemes['HTTPS'] = HTTPS
-end # URI
diff --git a/lib/uri/ldap.rb b/lib/uri/ldap.rb
deleted file mode 100644
index 441ee69b86..0000000000
--- a/lib/uri/ldap.rb
+++ /dev/null
@@ -1,238 +0,0 @@
-#
-# $Id$
-#
-
-require 'uri/generic'
-
-module URI
-
-=begin
-
-== URI::LDAP
-
-URI::LDAP is copyrighted free software by Takaaki Tateishi and akira yamada.
-
- Copyright (c) 2001 Takaaki Tateishi <ttate@jaist.ac.jp> and
- akira yamada <akira@ruby-lang.org>.
- You can redistribute it and/or modify it under the same term as Ruby.
-
-=== Super Class
-
-((<URI::Generic>))
-
-=end
-
- # LDAP URI SCHEMA (described in RFC2255)
- # ldap://<host>/<dn>[?<attrs>[?<scope>[?<filter>[?<extensions>]]]]
- class LDAP < Generic
-
- DEFAULT_PORT = 389
-
- COMPONENT = [
- :scheme,
- :host, :port,
- :dn,
- :attributes,
- :scope,
- :filter,
- :extensions,
- ].freeze
-
- SCOPE = [
- SCOPE_ONE = 'one',
- SCOPE_SUB = 'sub',
- SCOPE_BASE = 'base',
- ].freeze
-
-=begin
-
-=== Class Methods
-
---- URI::LDAP::build
-
---- URI::LDAP::new
-
-=end
-
- def self.build(args)
- tmp = Util::make_components_hash(self, args)
-
- if tmp[:dn]
- tmp[:path] = tmp[:dn]
- end
-
- query = []
- [:extensions, :filter, :scope, :attributes].collect do |x|
- next if !tmp[x] && query.size == 0
- query.unshift(tmp[x])
- end
-
- tmp[:query] = query.join('?')
-
- return super(tmp)
- end
-
- def initialize(*arg)
- super(*arg)
-
- if @fragment
- raise InvalidURIError, 'bad LDAP URL'
- end
-
- parse_dn
- parse_query
- end
-
- def parse_dn
- @dn = @path[1..-1]
- end
- private :parse_dn
-
- def parse_query
- @attributes = nil
- @scope = nil
- @filter = nil
- @extensions = nil
-
- if @query
- attrs, scope, filter, extensions = @query.split('?')
-
- @attributes = attrs if attrs && attrs.size > 0
- @scope = scope if scope && scope.size > 0
- @filter = filter if filter && filter.size > 0
- @extensions = extensions if extensions && extensions.size > 0
- end
- end
- private :parse_query
-
- def build_path_query
- @path = '/' + @dn
-
- query = []
- [@extensions, @filter, @scope, @attributes].each do |x|
- next if !x && query.size == 0
- query.unshift(x)
- end
- @query = query.join('?')
- end
- private :build_path_query
-
-=begin
-
-=== Instance Methods
-
---- URI::LDAP#dn
-
---- URI::LDAP#dn=(v)
-
-=end
-
- def dn
- @dn
- end
-
- def set_dn(val)
- @dn = val
- build_path_query
- end
- protected :set_dn
-
- def dn=(val)
- set_dn(val)
- end
-
-=begin
-
---- URI::LDAP#attributes
-
---- URI::LDAP#attributes=(v)
-
-=end
-
- def attributes
- @attributes
- end
-
- def set_attributes(val)
- @attributes = val
- build_path_query
- end
- protected :set_attributes
-
- def attributes=(val)
- set_attributes(val)
- end
-
-=begin
-
---- URI::LDAP#scope
-
---- URI::LDAP#scope=(v)
-
-=end
-
- def scope
- @scope
- end
-
- def set_scope(val)
- @scope = val
- build_path_query
- end
- protected :set_scope
-
- def scope=(val)
- set_scope(val)
- end
-
-=begin
-
---- URI::LDAP#filter
-
---- URI::LDAP#filter=(v)
-
-=end
-
- def filter
- @filter
- end
-
- def set_filter(val)
- @filter = val
- build_path_query
- end
- protected :set_filter
-
- def filter=(val)
- set_filter(val)
- end
-
-=begin
-
---- URI::LDAP#extensions
-
---- URI::LDAP#extensions=(v)
-
-=end
-
- def extensions
- @extensions
- end
-
- def set_extensions(val)
- @extensions = val
- build_path_query
- end
- protected :set_extensions
-
- def extensions=(val)
- set_extensions(val)
- end
- end
-
- def hierarchical?
- false
- end
-
- @@schemes['LDAP'] = LDAP
-end
diff --git a/lib/uri/mailto.rb b/lib/uri/mailto.rb
deleted file mode 100644
index bf6b954903..0000000000
--- a/lib/uri/mailto.rb
+++ /dev/null
@@ -1,260 +0,0 @@
-#
-# $Id$
-#
-# Copyright (c) 2001 akira yamada <akira@ruby-lang.org>
-# You can redistribute it and/or modify it under the same term as Ruby.
-#
-
-require 'uri/generic'
-
-module URI
-
-=begin
-
-== URI::MailTo
-
-=== Super Class
-
-((<URI::Generic>))
-
-=end
-
- # RFC2368, The mailto URL scheme
- class MailTo < Generic
- include REGEXP
-
- DEFAULT_PORT = nil
-
- COMPONENT = [
- :scheme,
- :to, :headers
- ].freeze
-
- # "hname" and "hvalue" are encodings of an RFC 822 header name and
- # value, respectively. As with "to", all URL reserved characters must
- # be encoded.
- #
- # "#mailbox" is as specified in RFC 822 [RFC822]. This means that it
- # consists of zero or more comma-separated mail addresses, possibly
- # including "phrase" and "comment" components. Note that all URL
- # reserved characters in "to" must be encoded: in particular,
- # parentheses, commas, and the percent sign ("%"), which commonly occur
- # in the "mailbox" syntax.
- #
- # Within mailto URLs, the characters "?", "=", "&" are reserved.
-
- # hname = *urlc
- # hvalue = *urlc
- # header = hname "=" hvalue
- HEADER_REGEXP = "(?:[^?=&]*=[^?=&]*)".freeze
- # headers = "?" header *( "&" header )
- # to = #mailbox
- # mailtoURL = "mailto:" [ to ] [ headers ]
- MAILBOX_REGEXP = "(?:[^(),%?=&]|#{PATTERN::ESCAPED})".freeze
- MAILTO_REGEXP = Regexp.new("
- \\A
- (#{MAILBOX_REGEXP}*?) (?# 1: to)
- (?:
- \\?
- (#{HEADER_REGEXP}(?:\\&#{HEADER_REGEXP})*) (?# 2: headers)
- )?
- \\z
- ", Regexp::EXTENDED, 'N').freeze
-
-=begin
-
-=== Class Methods
-
---- URI::MailTo::build
- Create a new URI::MailTo object from components of URI::MailTo
- with check. It is to and headers. It provided by an Array of a
- Hash. You can provide headers as an String like
- "subject=subscribe&cc=addr" or an Array like [["subject",
- "subscribe"], ["cc", "addr"]]
-
---- URI::MailTo::new
- Create a new URI::MailTo object from ``generic'' components with
- no check. Because, this method is usually called from URI::parse
- and the method checks validity of each components.
-
-=end
-
- def self.build(args)
- tmp = Util::make_components_hash(self, args)
-
- if tmp[:to]
- tmp[:opaque] = tmp[:to]
- else
- tmp[:opaque] = ''
- end
-
- if tmp[:headers]
- tmp[:opaque] << '?'
-
- if tmp[:headers].kind_of?(Array)
- tmp[:opaque] << tmp[:headers].collect { |x|
- if x.kind_of?(Array)
- x[0] + '=' + x[1..-1].to_s
- else
- x.to_s
- end
- }.join('&')
-
- elsif tmp[:headers].kind_of?(Hash)
- tmp[:opaque] << tmp[:headers].collect { |h,v|
- h + '=' + v
- }.join('&')
-
- else
- tmp[:opaque] << tmp[:headers].to_s
- end
- end
-
- return super(tmp)
- end
-
- def initialize(*arg)
- super(*arg)
-
- @to = nil
- @headers = []
-
- if MAILTO_REGEXP =~ @opaque
- if arg[-1]
- self.to = $1
- self.headers = $2
- else
- set_to($1)
- set_headers($2)
- end
- elsif arg[-1]
- raise InvalidComponentError,
- "unrecognised opaque part for mailtoURL: #{@opaque}"
- end
- end
- attr_reader :to
- attr_reader :headers
-
-=begin
-
-=== Instance Methods
-
---- URI::MailTo#to
-
---- URI::MailTo#to=(v)
-
-=end
-
- #
- # methods for to
- #
-
- def check_to(v)
- return true unless v
- return true if v.size == 0
-
- if OPAQUE !~ v || /\A#{MAILBOX_REGEXP}*\z/o !~ v
- raise InvalidComponentError,
- "bad component(expected opaque component): #{v}"
- end
-
- return true
- end
- private :check_to
-
- def set_to(v)
- @to = v
- end
- protected :set_to
-
- def to=(v)
- check_to(v)
- set_to(v)
- end
-
-=begin
-
---- URI::MailTo#headers
-
---- URI::MailTo#headers=(v)
-
-=end
-
- #
- # methods for headers
- #
-
- def check_headers(v)
- return true unless v
- return true if v.size == 0
-
- if OPAQUE !~ v ||
- /\A(#{HEADER_REGEXP}(?:\&#{HEADER_REGEXP})*)\z/o !~ v
- raise InvalidComponentError,
- "bad component(expected opaque component): #{v}"
- end
-
- return true
- end
- private :check_headers
-
- def set_headers(v)
- @headers = []
- if v
- v.scan(HEADER_REGEXP) do |x|
- @headers << x.split(/=/o, 2)
- end
- end
- end
- protected :set_headers
-
- def headers=(v)
- check_headers(v)
- set_headers(v)
- end
-
- def to_str
- @scheme + ':' +
- if @to
- @to
- else
- ''
- end +
- if @headers.size > 0
- '?' + @headers.collect{|x| x.join('=')}.join('&')
- else
- ''
- end
- end
-
-=begin
-
---- URI::MailTo#to_mailtext
-
-=end
- def to_mailtext
- to = URI::unescape(@to)
- head = ''
- body = ''
- @headers.each do |x|
- case x[0]
- when 'body'
- body = URI::unescape(x[1])
- when 'to'
- to << ', ' + URI::unescape(x[1])
- else
- head << URI::unescape(x[0]).capitalize + ': ' +
- URI::unescape(x[1]) + "\n"
- end
- end
-
- return "To: #{to}
-#{head}
-#{body}
-"
- end
- alias to_rfc822text to_mailtext
- end # MailTo
-
- @@schemes['MAILTO'] = MailTo
-end # URI
diff --git a/lib/weakref.rb b/lib/weakref.rb
deleted file mode 100644
index 6861fde5f5..0000000000
--- a/lib/weakref.rb
+++ /dev/null
@@ -1,87 +0,0 @@
-# Weak Reference class that does not bother GCing.
-#
-# Usage:
-# foo = Object.new
-# foo = Object.new
-# p foo.to_s # original's class
-# foo = WeakRef.new(foo)
-# p foo.to_s # should be same class
-# ObjectSpace.garbage_collect
-# p foo.to_s # should raise exception (recycled)
-
-require "delegate"
-
-class WeakRef<Delegator
-
- class RefError<StandardError
- end
-
- ID_MAP = {} # obj -> [ref,...]
- ID_REV_MAP = {} # ref -> obj
- @@final = lambda{|id|
- __old_status = Thread.critical
- Thread.critical = true
- begin
- rids = ID_MAP[id]
- if rids
- for rid in rids
- ID_REV_MAP[rid] = nil
- end
- ID_MAP[id] = nil
- end
- rid = ID_REV_MAP[id]
- if rid
- ID_REV_MAP[id] = nil
- ID_MAP[rid].delete(id)
- ID_MAP[rid] = nil if ID_MAP[rid].empty?
- end
- ensure
- Thread.critical = __old_status
- end
- }
-
- def initialize(orig)
- super
- @__id = orig.__id__
- ObjectSpace.define_finalizer orig, @@final
- ObjectSpace.define_finalizer self, @@final
- __old_status = Thread.critical
- begin
- Thread.critical = true
- ID_MAP[@__id] = [] unless ID_MAP[@__id]
- ensure
- Thread.critical = __old_status
- end
- ID_MAP[@__id].push self.__id__
- ID_REV_MAP[self.id] = @__id
- end
-
- def __getobj__
- unless ID_MAP[@__id]
- raise RefError, "Illegal Reference - probably recycled", caller(2)
- end
- begin
- ObjectSpace._id2ref(@__id)
- rescue RangeError
- raise RefError, "Illegal Reference - probably recycled", caller(2)
- end
- end
-
- def weakref_alive?
- if ID_MAP[@__id]
- true
- else
- false
- end
- end
-end
-
-if __FILE__ == $0
- require 'thread'
- foo = Object.new
- p foo.to_s # original's class
- foo = WeakRef.new(foo)
- p foo.to_s # should be same class
- ObjectSpace.garbage_collect
- p foo.to_s # should raise exception (recycled)
-end
diff --git a/main.c b/main.c
deleted file mode 100644
index ef1b495d9c..0000000000
--- a/main.c
+++ /dev/null
@@ -1,52 +0,0 @@
-/**********************************************************************
-
- main.c -
-
- $Author$
- $Date$
- created at: Fri Aug 19 13:19:58 JST 1994
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
-
-**********************************************************************/
-
-#include "ruby.h"
-
-#ifdef DJGPP
-unsigned int _stklen = 0x180000;
-#endif
-
-#ifdef __human68k__
-int _stacksize = 262144;
-#endif
-
-#if defined __MINGW32__
-int _CRT_glob = 0;
-#endif
-
-#if defined(__MACOS__) && defined(__MWERKS__)
-#include <console.h>
-#endif
-
-/* to link startup code with ObjC support */
-#if defined(__APPLE__) && defined(__MACH__)
-static void objcdummyfunction( void ) { objc_msgSend(); }
-#endif
-
-int
-main(argc, argv, envp)
- int argc;
- char **argv, **envp;
-{
-#if defined(NT)
- NtInitialize(&argc, &argv);
-#endif
-#if defined(__MACOS__) && defined(__MWERKS__)
- argc = ccommand(&argv);
-#endif
-
- ruby_init();
- ruby_options(argc, argv);
- ruby_run();
- return 0;
-}
diff --git a/marshal.c b/marshal.c
deleted file mode 100644
index 4bd7a35ecb..0000000000
--- a/marshal.c
+++ /dev/null
@@ -1,1171 +0,0 @@
-/**********************************************************************
-
- marshal.c -
-
- $Author$
- $Date$
- created at: Thu Apr 27 16:30:01 JST 1995
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
-
-**********************************************************************/
-
-#include <math.h>
-
-#include "ruby.h"
-#include "rubyio.h"
-#include "st.h"
-
-#if !defined(atof) && !defined(HAVE_STDLIB_H)
-double strtod();
-#endif
-
-#if SIZEOF_INT*2 <= SIZEOF_LONG_LONG || SIZEOF_INT*2 <= SIZEOF_LONG
-typedef unsigned int BDIGIT;
-#define SIZEOF_BDIGITS SIZEOF_INT
-#else
-typedef unsigned short BDIGIT;
-#define SIZEOF_BDIGITS SIZEOF_SHORT
-#endif
-
-#define BITSPERSHORT (2*CHAR_BIT)
-#define SHORTMASK ((1<<BITSPERSHORT)-1)
-#define SHORTDN(x) RSHIFT(x,BITSPERSHORT)
-
-#if SIZEOF_SHORT == SIZEOF_BDIGITS
-#define SHORTLEN(x) (x)
-#else
-static int
-shortlen(len, ds)
- long len;
- BDIGIT *ds;
-{
- BDIGIT num;
- int offset = 0;
-
- num = ds[len-1];
- while (num) {
- num = SHORTDN(num);
- offset++;
- }
- return (len - 1)*sizeof(BDIGIT)/2 + offset;
-}
-#define SHORTLEN(x) shortlen((x),d)
-#endif
-
-#define MARSHAL_MAJOR 4
-#define MARSHAL_MINOR 7
-
-#define TYPE_NIL '0'
-#define TYPE_TRUE 'T'
-#define TYPE_FALSE 'F'
-#define TYPE_FIXNUM 'i'
-
-#define TYPE_UCLASS 'C'
-#define TYPE_OBJECT 'o'
-#define TYPE_USERDEF 'u'
-#define TYPE_USRMARHAL 'U'
-#define TYPE_FLOAT 'f'
-#define TYPE_BIGNUM 'l'
-#define TYPE_STRING '"'
-#define TYPE_REGEXP '/'
-#define TYPE_ARRAY '['
-#define TYPE_HASH '{'
-#define TYPE_HASH_DEF '}'
-#define TYPE_STRUCT 'S'
-#define TYPE_MODULE_OLD 'M'
-#define TYPE_CLASS 'c'
-#define TYPE_MODULE 'm'
-
-#define TYPE_SYMBOL ':'
-#define TYPE_SYMLINK ';'
-
-#define TYPE_IVAR 'I'
-#define TYPE_LINK '@'
-
-static ID s_dump, s_load;
-
-struct dump_arg {
- VALUE obj;
- FILE *fp;
- VALUE str;
- st_table *symbol;
- st_table *data;
- int taint;
-};
-
-struct dump_call_arg {
- VALUE obj;
- struct dump_arg *arg;
- int limit;
-};
-
-static void w_long _((long, struct dump_arg*));
-
-static void
-w_byte(c, arg)
- char c;
- struct dump_arg *arg;
-{
- if (arg->fp) putc(c, arg->fp);
- else rb_str_buf_cat(arg->str, &c, 1);
-}
-
-static void
-w_bytes(s, n, arg)
- char *s;
- int n;
- struct dump_arg *arg;
-{
- w_long(n, arg);
- if (arg->fp) {
- fwrite(s, 1, n, arg->fp);
- }
- else {
- rb_str_cat(arg->str, s, n);
- }
-}
-
-static void
-w_short(x, arg)
- int x;
- struct dump_arg *arg;
-{
- w_byte((x >> 0) & 0xff, arg);
- w_byte((x >> 8) & 0xff, arg);
-}
-
-static void
-w_long(x, arg)
- long x;
- struct dump_arg *arg;
-{
- char buf[sizeof(long)+1];
- int i, len = 0;
-
-#if SIZEOF_LONG > 4
- if (!(RSHIFT(x, 31) == 0 || RSHIFT(x, 31) == -1)) {
- /* big long does not fit in 4 bytes */
- rb_raise(rb_eTypeError, "long too big to dump");
- }
-#endif
-
- if (x == 0) {
- w_byte(0, arg);
- return;
- }
- if (0 < x && x < 123) {
- w_byte(x + 5, arg);
- return;
- }
- if (-124 < x && x < 0) {
- w_byte((x - 5)&0xff, arg);
- return;
- }
- for (i=1;i<sizeof(long)+1;i++) {
- buf[i] = x & 0xff;
- x = RSHIFT(x,8);
- if (x == 0) {
- buf[0] = i;
- break;
- }
- if (x == -1) {
- buf[0] = -i;
- break;
- }
- }
- len = i;
- for (i=0;i<=len;i++) {
- w_byte(buf[i], arg);
- }
-}
-
-static void
-w_float(d, arg)
- double d;
- struct dump_arg *arg;
-{
- char buf[100];
-
- if (isinf(d)) {
- if (d < 0) strcpy(buf, "-inf");
- else strcpy(buf, "inf");
- }
- else if (isnan(d)) {
- strcpy(buf, "nan");
- }
- else if (d == 0.0) {
- if (1.0/d < 0) strcpy(buf, "-0");
- else strcpy(buf, "0");
- }
- else {
- /* xxx: should not use system's sprintf(3) */
- sprintf(buf, "%.16g", d);
- }
- w_bytes(buf, strlen(buf), arg);
-}
-
-static void
-w_symbol(id, arg)
- ID id;
- struct dump_arg *arg;
-{
- char *sym = rb_id2name(id);
- long num;
-
- if (st_lookup(arg->symbol, id, &num)) {
- w_byte(TYPE_SYMLINK, arg);
- w_long(num, arg);
- }
- else {
- w_byte(TYPE_SYMBOL, arg);
- w_bytes(sym, strlen(sym), arg);
- st_add_direct(arg->symbol, id, arg->symbol->num_entries);
- }
-}
-
-static void
-w_unique(s, arg)
- char *s;
- struct dump_arg *arg;
-{
- if (s[0] == '#') {
- rb_raise(rb_eArgError, "can't dump anonymous class %s", s);
- }
- w_symbol(rb_intern(s), arg);
-}
-
-static void w_object _((VALUE,struct dump_arg*,int));
-
-static int
-hash_each(key, value, arg)
- VALUE key, value;
- struct dump_call_arg *arg;
-{
- w_object(key, arg->arg, arg->limit);
- w_object(value, arg->arg, arg->limit);
- return ST_CONTINUE;
-}
-
-static int
-obj_each(id, value, arg)
- ID id;
- VALUE value;
- struct dump_call_arg *arg;
-{
- w_symbol(id, arg->arg);
- w_object(value, arg->arg, arg->limit);
- return ST_CONTINUE;
-}
-
-static void
-w_uclass(obj, klass, arg)
- VALUE obj, klass;
- struct dump_arg *arg;
-{
- if (rb_obj_class(obj) != klass) {
- w_byte(TYPE_UCLASS, arg);
- w_unique(rb_class2name(CLASS_OF(obj)), arg);
- }
-}
-
-static void
-w_ivar(tbl, arg)
- st_table *tbl;
- struct dump_call_arg *arg;
-{
- if (tbl) {
- w_long(tbl->num_entries, arg->arg);
- st_foreach(tbl, obj_each, arg);
- }
- else {
- w_long(0, arg->arg);
- }
-}
-
-static void
-w_object(obj, arg, limit)
- VALUE obj;
- struct dump_arg *arg;
- int limit;
-{
- struct dump_call_arg c_arg;
- st_table *ivtbl = 0;
-
- if (limit == 0) {
- rb_raise(rb_eArgError, "exceed depth limit");
- }
- if (obj == Qnil) {
- w_byte(TYPE_NIL, arg);
- }
- else if (obj == Qtrue) {
- w_byte(TYPE_TRUE, arg);
- }
- else if (obj == Qfalse) {
- w_byte(TYPE_FALSE, arg);
- }
- else if (FIXNUM_P(obj)) {
-#if SIZEOF_LONG <= 4
- w_byte(TYPE_FIXNUM, arg);
- w_long(FIX2INT(obj), arg);
-#else
- if (RSHIFT((long)obj, 31) == 0 || RSHIFT((long)obj, 31) == -1) {
- w_byte(TYPE_FIXNUM, arg);
- w_long(FIX2LONG(obj), arg);
- }
- else {
- w_object(rb_int2big(FIX2LONG(obj)), arg, limit);
- return;
- }
-#endif
- }
- else if (SYMBOL_P(obj)) {
- w_symbol(SYM2ID(obj), arg);
- return;
- }
- else {
- long num;
-
- limit--;
- c_arg.limit = limit;
- c_arg.arg = arg;
-
- if (st_lookup(arg->data, obj, &num)) {
- w_byte(TYPE_LINK, arg);
- w_long(num, arg);
- return;
- }
-
- if (OBJ_TAINTED(obj)) arg->taint = Qtrue;
-
- st_add_direct(arg->data, obj, arg->data->num_entries);
- if (rb_respond_to(obj, s_dump)) {
- VALUE v;
-
- w_byte(TYPE_USERDEF, arg);
- w_unique(rb_class2name(CLASS_OF(obj)), arg);
- v = rb_funcall(obj, s_dump, 1, INT2NUM(limit));
- if (TYPE(v) != T_STRING) {
- rb_raise(rb_eTypeError, "_dump() must return String");
- }
- w_bytes(RSTRING(v)->ptr, RSTRING(v)->len, arg);
- return;
- }
-
- if (ivtbl = rb_generic_ivar_table(obj)) {
- w_byte(TYPE_IVAR, arg);
- }
-
- switch (BUILTIN_TYPE(obj)) {
- case T_CLASS:
- if (FL_TEST(obj, FL_SINGLETON)) {
- rb_raise(rb_eTypeError, "singleton class can't be dumped");
- }
- w_byte(TYPE_CLASS, arg);
- {
- VALUE path = rb_class_path(obj);
- if (RSTRING(path)->ptr[0] == '#') {
- rb_raise(rb_eArgError, "can't dump anonymous class %s",
- RSTRING(path)->ptr);
- }
- w_bytes(RSTRING(path)->ptr, RSTRING(path)->len, arg);
- }
- break;
-
- case T_MODULE:
- w_byte(TYPE_MODULE, arg);
- {
- VALUE path = rb_class_path(obj);
- if (RSTRING(path)->ptr[0] == '#') {
- rb_raise(rb_eArgError, "can't dump anonymous module %s",
- RSTRING(path)->ptr);
- }
- w_bytes(RSTRING(path)->ptr, RSTRING(path)->len, arg);
- }
- break;
-
- case T_FLOAT:
- w_byte(TYPE_FLOAT, arg);
- w_float(RFLOAT(obj)->value, arg);
- break;
-
- case T_BIGNUM:
- w_byte(TYPE_BIGNUM, arg);
- {
- char sign = RBIGNUM(obj)->sign ? '+' : '-';
- long len = RBIGNUM(obj)->len;
- BDIGIT *d = RBIGNUM(obj)->digits;
-
- w_byte(sign, arg);
- w_long(SHORTLEN(len), arg); /* w_short? */
- while (len--) {
-#if SIZEOF_BDIGITS > SIZEOF_SHORT
- BDIGIT num = *d;
- int i;
-
- for (i=0; i<SIZEOF_BDIGITS; i+=SIZEOF_SHORT) {
- w_short(num & SHORTMASK, arg);
- num = SHORTDN(num);
- if (len == 0 && num == 0) break;
- }
-#else
- w_short(*d, arg);
-#endif
- d++;
- }
- }
- break;
-
- case T_STRING:
- w_uclass(obj, rb_cString, arg);
- w_byte(TYPE_STRING, arg);
- w_bytes(RSTRING(obj)->ptr, RSTRING(obj)->len, arg);
- break;
-
- case T_REGEXP:
- w_uclass(obj, rb_cRegexp, arg);
- w_byte(TYPE_REGEXP, arg);
- w_bytes(RREGEXP(obj)->str, RREGEXP(obj)->len, arg);
- w_byte(rb_reg_options(obj), arg);
- break;
-
- case T_ARRAY:
- w_uclass(obj, rb_cArray, arg);
- w_byte(TYPE_ARRAY, arg);
- {
- long len = RARRAY(obj)->len;
- VALUE *ptr = RARRAY(obj)->ptr;
-
- w_long(len, arg);
- while (len--) {
- w_object(*ptr, arg, limit);
- ptr++;
- }
- }
- break;
-
- case T_HASH:
- w_uclass(obj, rb_cHash, arg);
- if (!NIL_P(RHASH(obj)->ifnone)) {
- w_byte(TYPE_HASH_DEF, arg);
- }
- else {
- w_byte(TYPE_HASH, arg);
- }
- w_long(RHASH(obj)->tbl->num_entries, arg);
- st_foreach(RHASH(obj)->tbl, hash_each, &c_arg);
- if (!NIL_P(RHASH(obj)->ifnone)) {
- w_object(RHASH(obj)->ifnone, arg, limit);
- }
- break;
-
- case T_STRUCT:
- w_byte(TYPE_STRUCT, arg);
- {
- long len = RSTRUCT(obj)->len;
- VALUE mem;
- long i;
-
- w_unique(rb_class2name(CLASS_OF(obj)), arg);
- w_long(len, arg);
- mem = rb_struct_iv_get(rb_obj_class(obj), "__member__");
- if (mem == Qnil) {
- rb_raise(rb_eTypeError, "uninitialized struct");
- }
- for (i=0; i<len; i++) {
- w_symbol(SYM2ID(RARRAY(mem)->ptr[i]), arg);
- w_object(RSTRUCT(obj)->ptr[i], arg, limit);
- }
- }
- break;
-
- case T_OBJECT:
- w_byte(TYPE_OBJECT, arg);
- {
- VALUE klass = CLASS_OF(obj);
- char *path;
-
- while (FL_TEST(klass, FL_SINGLETON) || BUILTIN_TYPE(klass) == T_ICLASS) {
- if (RCLASS(klass)->m_tbl->num_entries > 0 ||
- RCLASS(klass)->iv_tbl->num_entries > 1) {
- rb_raise(rb_eTypeError, "singleton can't be dumped");
- }
- klass = RCLASS(klass)->super;
- }
- path = rb_class2name(klass);
- w_unique(path, arg);
- w_ivar(ROBJECT(obj)->iv_tbl, &c_arg);
- }
- break;
-
- default:
- rb_raise(rb_eTypeError, "can't dump %s",
- rb_class2name(CLASS_OF(obj)));
- break;
- }
- }
- if (ivtbl) {
- w_ivar(ivtbl, &c_arg);
- }
-}
-
-static VALUE
-dump(arg)
- struct dump_call_arg *arg;
-{
- w_object(arg->obj, arg->arg, arg->limit);
- return 0;
-}
-
-static VALUE
-dump_ensure(arg)
- struct dump_arg *arg;
-{
- st_free_table(arg->symbol);
- st_free_table(arg->data);
- if (!arg->fp && arg->taint) {
- OBJ_TAINT(arg->str);
- }
- return 0;
-}
-
-static VALUE
-marshal_dump(argc, argv)
- int argc;
- VALUE* argv;
-{
- VALUE obj, port, a1, a2;
- int limit = -1;
- struct dump_arg arg;
- struct dump_call_arg c_arg;
-
- port = 0;
- rb_scan_args(argc, argv, "12", &obj, &a1, &a2);
- if (argc == 3) {
- if (!NIL_P(a2)) limit = NUM2INT(a2);
- port = a1;
- }
- else if (argc == 2) {
- if (FIXNUM_P(a1)) limit = FIX2INT(a1);
- else port = a1;
- }
- if (port) {
- if (rb_obj_is_kind_of(port, rb_cIO)) {
- OpenFile *fptr;
-
- rb_io_binmode(port);
- GetOpenFile(port, fptr);
- rb_io_check_writable(fptr);
- arg.fp = (fptr->f2) ? fptr->f2 : fptr->f;
- }
- else {
- rb_raise(rb_eTypeError, "instance of IO needed");
- }
- }
- else {
- arg.fp = 0;
- port = rb_str_buf_new(0);
- arg.str = port;
- }
-
- arg.symbol = st_init_numtable();
- arg.data = st_init_numtable();
- arg.taint = Qfalse;
- c_arg.obj = obj;
- c_arg.arg = &arg;
- c_arg.limit = limit;
-
- w_byte(MARSHAL_MAJOR, &arg);
- w_byte(MARSHAL_MINOR, &arg);
-
- rb_ensure(dump, (VALUE)&c_arg, dump_ensure, (VALUE)&arg);
-
- return port;
-}
-
-struct load_arg {
- FILE *fp;
- char *ptr, *end;
- st_table *symbol;
- VALUE data;
- VALUE proc;
- int taint;
-};
-
-static VALUE r_object _((struct load_arg *arg));
-
-static int
-r_byte(arg)
- struct load_arg *arg;
-{
- int c;
-
- if (arg->fp) {
- c = rb_getc(arg->fp);
- if (c == EOF) rb_eof_error();
- }
- else if (arg->ptr < arg->end) {
- c = *(unsigned char*)arg->ptr++;
- }
- else {
- rb_raise(rb_eArgError, "marshal data too short");
- }
- return c;
-}
-
-static unsigned short
-r_short(arg)
- struct load_arg *arg;
-{
- unsigned short x;
-
- x = r_byte(arg);
- x |= r_byte(arg)<<8;
-
- return x;
-}
-
-static void
-long_toobig(size)
- int size;
-{
- rb_raise(rb_eTypeError, "long too big for this architecture (size %d, given %d)",
- sizeof(long), size);
-}
-
-#undef SIGN_EXTEND_CHAR
-#if __STDC__
-# define SIGN_EXTEND_CHAR(c) ((signed char)(c))
-#else /* not __STDC__ */
-/* As in Harbison and Steele. */
-# define SIGN_EXTEND_CHAR(c) ((((unsigned char)(c)) ^ 128) - 128)
-#endif
-
-static long
-r_long(arg)
- struct load_arg *arg;
-{
- register long x;
- int c = SIGN_EXTEND_CHAR(r_byte(arg));
- long i;
-
- if (c == 0) return 0;
- if (c > 0) {
- if (4 < c && c < 128) {
- return c - 5;
- }
- if (c > sizeof(long)) long_toobig(c);
- x = 0;
- for (i=0;i<c;i++) {
- x |= (long)r_byte(arg) << (8*i);
- }
- }
- else {
- if (-129 < c && c < -4) {
- return c + 5;
- }
- c = -c;
- if (c > sizeof(long)) long_toobig(c);
- x = -1;
- for (i=0;i<c;i++) {
- x &= ~((long)0xff << (8*i));
- x |= (long)r_byte(arg) << (8*i);
- }
- }
- return x;
-}
-
-#define r_bytes2(s, len, arg) do { \
- (len) = r_long(arg); \
- (s) = ALLOCA_N(char,(len)+1); \
- r_bytes0((s),(len),(arg)); \
-} while (0)
-
-#define r_bytes(s, arg) do { \
- long r_bytes_len; \
- r_bytes2((s), r_bytes_len, (arg)); \
-} while (0)
-
-static void
-r_bytes0(s, len, arg)
- char *s;
- long len;
- struct load_arg *arg;
-{
- if (arg->fp) {
- len = fread(s, 1, len, arg->fp);
- }
- else {
- if (arg->ptr + len > arg->end) {
- len = arg->end - arg->ptr;
- }
- memcpy(s, arg->ptr, len);
- arg->ptr += len;
- }
- s[len] = '\0';
-}
-
-static ID
-r_symlink(arg)
- struct load_arg *arg;
-{
- ID id;
- long num = r_long(arg);
-
- if (st_lookup(arg->symbol, num, &id)) {
- return id;
- }
- rb_raise(rb_eTypeError, "bad symbol");
-}
-
-static ID
-r_symreal(arg)
- struct load_arg *arg;
-{
- char *buf;
- ID id;
-
- r_bytes(buf, arg);
- id = rb_intern(buf);
- st_insert(arg->symbol, arg->symbol->num_entries, id);
-
- return id;
-}
-
-static ID
-r_symbol(arg)
- struct load_arg *arg;
-{
- if (r_byte(arg) == TYPE_SYMLINK) {
- return r_symlink(arg);
- }
- return r_symreal(arg);
-}
-
-static char*
-r_unique(arg)
- struct load_arg *arg;
-{
- return rb_id2name(r_symbol(arg));
-}
-
-static VALUE
-r_string(arg)
- struct load_arg *arg;
-{
- char *buf;
- long len;
-
- r_bytes2(buf, len, arg);
- return rb_str_new(buf, len);
-}
-
-static VALUE
-r_regist(v, arg)
- VALUE v;
- struct load_arg *arg;
-{
- rb_hash_aset(arg->data, INT2FIX(RHASH(arg->data)->tbl->num_entries), v);
- if (arg->taint) OBJ_TAINT(v);
- return v;
-}
-
-static void
-r_ivar(obj, arg)
- VALUE obj;
- struct load_arg *arg;
-{
- long len;
-
- len = r_long(arg);
- if (len > 0) {
- while (len--) {
- ID id = r_symbol(arg);
- VALUE val = r_object(arg);
- rb_ivar_set(obj, id, val);
- }
- }
-}
-
-static VALUE
-r_object(arg)
- struct load_arg *arg;
-{
- VALUE v = Qnil;
- int type = r_byte(arg);
- long id;
-
- switch (type) {
- case TYPE_LINK:
- id = r_long(arg);
- v = rb_hash_aref(arg->data, INT2FIX(id));
- if (NIL_P(v)) {
- rb_raise(rb_eArgError, "dump format error (unlinked)");
- }
- return v;
-
- case TYPE_IVAR:
- v = r_object(arg);
- r_ivar(v, arg);
- return v;
-
- case TYPE_UCLASS:
- {
- VALUE c = rb_path2class(r_unique(arg));
-
- v = r_object(arg);
- if (rb_special_const_p(v) || TYPE(v) == T_OBJECT || TYPE(v) == T_CLASS) {
- format_error:
- rb_raise(rb_eArgError, "dump format error (user class)");
- }
- if (TYPE(v) == T_MODULE || !RTEST(rb_funcall(c, '<', 1, RBASIC(v)->klass))) {
- VALUE tmp = rb_obj_alloc(c);
-
- if (TYPE(v) != TYPE(tmp)) goto format_error;
- }
- RBASIC(v)->klass = c;
- return v;
- }
-
- case TYPE_NIL:
- v = Qnil;
- break;
-
- case TYPE_TRUE:
- v = Qtrue;
- break;
-
- case TYPE_FALSE:
- v = Qfalse;
- break;
-
- case TYPE_FIXNUM:
- {
- long i = r_long(arg);
- v = INT2FIX(i);
- }
- break;
-
- case TYPE_FLOAT:
- {
- char *buf;
- double d, t = 0.0;
-
- r_bytes(buf, arg);
- if (strcmp(buf, "nan") == 0) {
- d = t / t;
- }
- else if (strcmp(buf, "inf") == 0) {
- d = 1.0 / t;
- }
- else if (strcmp(buf, "-inf") == 0) {
- d = -1.0 / t;
- }
- else {
- /* xxx: should not use system's strtod(3) */
- d = strtod(buf, 0);
- }
- v = rb_float_new(d);
- r_regist(v, arg);
- }
- break;
-
- case TYPE_BIGNUM:
- {
- long len;
- BDIGIT *digits;
-
- NEWOBJ(big, struct RBignum);
- OBJSETUP(big, rb_cBignum, T_BIGNUM);
- big->sign = (r_byte(arg) == '+');
- len = r_long(arg);
-#if SIZEOF_BDIGITS == SIZEOF_SHORT
- big->len = len;
-#else
- big->len = (len + 1) * 2 / sizeof(BDIGIT);
-#endif
- big->digits = digits = ALLOC_N(BDIGIT, big->len);
- while (len > 0) {
-#if SIZEOF_BDIGITS > SIZEOF_SHORT
- BDIGIT num = 0;
- int shift = 0;
- int i;
-
- for (i=0; i<SIZEOF_BDIGITS; i+=2) {
- int j = r_short(arg);
- num |= j << shift;
- shift += BITSPERSHORT;
- if (--len == 0) break;
- }
- *digits++ = num;
-#else
- *digits++ = r_short(arg);
- len--;
-#endif
- }
- v = rb_big_norm((VALUE)big);
- if (TYPE(v) == T_BIGNUM) {
- r_regist(v, arg);
- }
- }
- break;
-
- case TYPE_STRING:
- v = r_regist(r_string(arg), arg);
- break;
-
- case TYPE_REGEXP:
- {
- char *buf;
- long len;
- int options;
-
- r_bytes2(buf, len, arg);
- options = r_byte(arg);
- v = r_regist(rb_reg_new(buf, len, options), arg);
- }
- break;
-
- case TYPE_ARRAY:
- {
- volatile long len = r_long(arg); /* gcc 2.7.2.3 -O2 bug?? */
-
- v = rb_ary_new2(len);
- r_regist(v, arg);
- while (len--) {
- rb_ary_push(v, r_object(arg));
- }
- }
- break;
-
- case TYPE_HASH:
- case TYPE_HASH_DEF:
- {
- long len = r_long(arg);
-
- v = rb_hash_new();
- r_regist(v, arg);
- while (len--) {
- VALUE key = r_object(arg);
- VALUE value = r_object(arg);
- rb_hash_aset(v, key, value);
- }
- if (type == TYPE_HASH_DEF) {
- RHASH(v)->ifnone = r_object(arg);
- }
- }
- break;
-
- case TYPE_STRUCT:
- {
- VALUE klass, mem, values;
- volatile long i; /* gcc 2.7.2.3 -O2 bug?? */
- long len;
- ID slot;
-
- klass = rb_path2class(r_unique(arg));
- mem = rb_struct_iv_get(klass, "__member__");
- if (mem == Qnil) {
- rb_raise(rb_eTypeError, "uninitialized struct");
- }
- len = r_long(arg);
-
- values = rb_ary_new2(len);
- for (i=0; i<len; i++) {
- rb_ary_push(values, Qnil);
- }
- v = rb_struct_alloc(klass, values);
- r_regist(v, arg);
- for (i=0; i<len; i++) {
- slot = r_symbol(arg);
-
- if (RARRAY(mem)->ptr[i] != ID2SYM(slot)) {
- rb_raise(rb_eTypeError, "struct %s not compatible (:%s for :%s)",
- rb_class2name(klass),
- rb_id2name(slot),
- rb_id2name(SYM2ID(RARRAY(mem)->ptr[i])));
- }
- rb_struct_aset(v, INT2FIX(i), r_object(arg));
- }
- }
- break;
-
- case TYPE_USERDEF:
- {
- VALUE klass;
-
- klass = rb_path2class(r_unique(arg));
- if (!rb_respond_to(klass, s_load)) {
- rb_raise(rb_eTypeError, "class %s needs to have method `_load'",
- rb_class2name(klass));
- }
- v = rb_funcall(klass, s_load, 1, r_string(arg));
- r_regist(v, arg);
- }
- break;
-
- case TYPE_OBJECT:
- {
- VALUE klass;
-
- klass = rb_path2class(r_unique(arg));
- v = rb_obj_alloc(klass);
- if (TYPE(v) != T_OBJECT) {
- rb_raise(rb_eArgError, "dump format error");
- }
- r_regist(v, arg);
- r_ivar(v, arg);
- }
- break;
-
- case TYPE_MODULE_OLD:
- {
- char *buf;
- r_bytes(buf, arg);
- v = r_regist(rb_path2class(buf), arg);
- }
- break;
-
- case TYPE_CLASS:
- {
- char *buf;
- r_bytes(buf, arg);
- v = rb_path2class(buf);
- if (TYPE(v) != T_CLASS) {
- rb_raise(rb_eTypeError, "%s is not a class", buf);
- }
- r_regist(v, arg);
- }
- break;
-
- case TYPE_MODULE:
- {
- char *buf;
- r_bytes(buf, arg);
- v = rb_path2class(buf);
- if (TYPE(v) != T_MODULE) {
- rb_raise(rb_eTypeError, "%s is not a module", buf);
- }
- r_regist(v, arg);
- }
- break;
-
- case TYPE_SYMBOL:
- v = ID2SYM(r_symreal(arg));
- break;
-
- case TYPE_SYMLINK:
- return ID2SYM(r_symlink(arg));
-
- default:
- rb_raise(rb_eArgError, "dump format error(0x%x)", type);
- break;
- }
- if (arg->proc) {
- rb_funcall(arg->proc, rb_intern("yield"), 1, v);
- }
- return v;
-}
-
-static VALUE
-load(arg)
- struct load_arg *arg;
-{
- return r_object(arg);
-}
-
-static VALUE
-load_ensure(arg)
- struct load_arg *arg;
-{
- st_free_table(arg->symbol);
- return 0;
-}
-
-static VALUE
-marshal_load(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE port, proc;
- int major, minor;
- VALUE v;
- OpenFile *fptr;
- struct load_arg arg;
- volatile VALUE hash; /* protect from GC */
-
- rb_scan_args(argc, argv, "11", &port, &proc);
- if (rb_obj_is_kind_of(port, rb_cIO)) {
- rb_io_binmode(port);
- GetOpenFile(port, fptr);
- rb_io_check_readable(fptr);
- arg.fp = fptr->f;
- arg.taint = Qtrue;
- }
- else if (rb_respond_to(port, rb_intern("to_str"))) {
- arg.taint = OBJ_TAINTED(port); /* original taintedness */
- StringValue(port); /* possible conversion */
- arg.fp = 0;
- arg.ptr = RSTRING(port)->ptr;
- arg.end = arg.ptr + RSTRING(port)->len;
- }
- else {
- rb_raise(rb_eTypeError, "instance of IO needed");
- }
-
- major = r_byte(&arg);
- minor = r_byte(&arg);
- if (major != MARSHAL_MAJOR || minor > MARSHAL_MINOR) {
- rb_raise(rb_eTypeError, "incompatible marshal file format (can't be read)\n\
-\tformat version %d.%d required; %d.%d given",
- MARSHAL_MAJOR, MARSHAL_MINOR, major, minor);
- }
- if (RTEST(ruby_verbose) && minor != MARSHAL_MINOR) {
- rb_warn("incompatible marshal file format (can be read)\n\
-\tformat version %d.%d required; %d.%d given",
- MARSHAL_MAJOR, MARSHAL_MINOR, major, minor);
- }
-
- arg.symbol = st_init_numtable();
- arg.data = hash = rb_hash_new();
- if (NIL_P(proc)) arg.proc = 0;
- else arg.proc = proc;
- v = rb_ensure(load, (VALUE)&arg, load_ensure, (VALUE)&arg);
-
- return v;
-}
-
-void
-Init_marshal()
-{
- VALUE rb_mMarshal = rb_define_module("Marshal");
-
- s_dump = rb_intern("_dump");
- s_load = rb_intern("_load");
- rb_define_module_function(rb_mMarshal, "dump", marshal_dump, -1);
- rb_define_module_function(rb_mMarshal, "load", marshal_load, -1);
- rb_define_module_function(rb_mMarshal, "restore", marshal_load, -1);
-
- rb_define_const(rb_mMarshal, "MAJOR_VERSION", INT2FIX(MARSHAL_MAJOR));
- rb_define_const(rb_mMarshal, "MINOR_VERSION", INT2FIX(MARSHAL_MINOR));
-}
-
-VALUE
-rb_marshal_dump(obj, port)
- VALUE obj, port;
-{
- int argc = 1;
- VALUE argv[2];
-
- argv[0] = obj;
- argv[1] = port;
- if (!NIL_P(port)) argc = 2;
- return marshal_dump(argc, argv);
-}
-
-VALUE
-rb_marshal_load(port)
- VALUE port;
-{
- return marshal_load(1, &port);
-}
diff --git a/math.c b/math.c
deleted file mode 100644
index 4af3cef96e..0000000000
--- a/math.c
+++ /dev/null
@@ -1,224 +0,0 @@
-/**********************************************************************
-
- math.c -
-
- $Author$
- $Date$
- created at: Tue Jan 25 14:12:56 JST 1994
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
-
-**********************************************************************/
-
-#include "ruby.h"
-#include <math.h>
-
-VALUE rb_mMath;
-
-#define Need_Float(x) (x) = rb_Float(x)
-#define Need_Float2(x,y) {\
- Need_Float(x);\
- Need_Float(y);\
-}
-
-static VALUE
-math_atan2(obj, y, x)
- VALUE obj, x, y;
-{
- Need_Float2(y, x);
- return rb_float_new(atan2(RFLOAT(y)->value, RFLOAT(x)->value));
-}
-
-static VALUE
-math_cos(obj, x)
- VALUE obj, x;
-{
- Need_Float(x);
-
- return rb_float_new(cos(RFLOAT(x)->value));
-}
-
-static VALUE
-math_sin(obj, x)
- VALUE obj, x;
-{
- Need_Float(x);
-
- return rb_float_new(sin(RFLOAT(x)->value));
-}
-
-static VALUE
-math_tan(obj, x)
- VALUE obj, x;
-{
- Need_Float(x);
-
- return rb_float_new(tan(RFLOAT(x)->value));
-}
-
-static VALUE
-math_acos(obj, x)
- VALUE obj, x;
-{
- Need_Float(x);
- /*
- if (RFLOAT(x)->value < -1.0 || RFLOAT(x)->value > 1.0)
- rb_raise(rb_eArgError, "Out of range (-1..1)");
- */
- return rb_float_new(acos(RFLOAT(x)->value));
-}
-
-static VALUE
-math_asin(obj, x)
- VALUE obj, x;
-{
- Need_Float(x);
- /*
- if (RFLOAT(x)->value < -1.0 || RFLOAT(x)->value > 1.0)
- rb_raise(rb_eArgError, "Out of range (-1..1)");
- */
- return rb_float_new(asin(RFLOAT(x)->value));
-}
-
-static VALUE
-math_atan(obj, x)
- VALUE obj, x;
-{
- Need_Float(x);
- return rb_float_new(atan(RFLOAT(x)->value));
-}
-
-static VALUE
-math_cosh(obj, x)
- VALUE obj, x;
-{
- Need_Float(x);
- return rb_float_new(cosh(RFLOAT(x)->value));
-}
-
-static VALUE
-math_sinh(obj, x)
- VALUE obj, x;
-{
- Need_Float(x);
- return rb_float_new(sinh(RFLOAT(x)->value));
-}
-
-static VALUE
-math_tanh(obj, x)
- VALUE obj, x;
-{
- Need_Float(x);
- return rb_float_new(tanh(RFLOAT(x)->value));
-}
-
-static VALUE
-math_exp(obj, x)
- VALUE obj, x;
-{
- Need_Float(x);
- return rb_float_new(exp(RFLOAT(x)->value));
-}
-
-#if defined __CYGWIN__
-#define log(x) ((x) < 0.0 ? nan() : log(x))
-#define log10(x) ((x) < 0.0 ? nan() : log10(x))
-#endif
-
-static VALUE
-math_log(obj, x)
- VALUE obj, x;
-{
- Need_Float(x);
- return rb_float_new(log(RFLOAT(x)->value));
-}
-
-static VALUE
-math_log10(obj, x)
- VALUE obj, x;
-{
- Need_Float(x);
- return rb_float_new(log10(RFLOAT(x)->value));
-}
-
-static VALUE
-math_sqrt(obj, x)
- VALUE obj, x;
-{
- Need_Float(x);
-
- if (RFLOAT(x)->value < 0.0) rb_raise(rb_eArgError, "square root for negative number");
- return rb_float_new(sqrt(RFLOAT(x)->value));
-}
-
-static VALUE
-math_frexp(obj, x)
- VALUE obj, x;
-{
- double d;
- int exp;
-
- Need_Float(x);
- d = frexp(RFLOAT(x)->value, &exp);
-
- return rb_assoc_new(rb_float_new(d), INT2NUM(exp));
-}
-
-static VALUE
-math_ldexp(obj, x, n)
- VALUE obj, x, n;
-{
- double d;
-
- Need_Float(x);
- return rb_float_new(d = ldexp(RFLOAT(x)->value, NUM2INT(n)));
-}
-
-static VALUE
-math_hypot(obj, x, y)
- VALUE obj, x, y;
-{
- Need_Float2(x, y);
- return rb_float_new(hypot(RFLOAT(x)->value, RFLOAT(y)->value));
-}
-
-void
-Init_Math()
-{
- rb_mMath = rb_define_module("Math");
-
-#ifdef M_PI
- rb_define_const(rb_mMath, "PI", rb_float_new(M_PI));
-#else
- rb_define_const(rb_mMath, "PI", rb_float_new(atan(1.0)*4.0));
-#endif
-
-#ifdef M_E
- rb_define_const(rb_mMath, "E", rb_float_new(M_E));
-#else
- rb_define_const(rb_mMath, "E", rb_float_new(exp(1.0)));
-#endif
-
- rb_define_module_function(rb_mMath, "atan2", math_atan2, 2);
- rb_define_module_function(rb_mMath, "cos", math_cos, 1);
- rb_define_module_function(rb_mMath, "sin", math_sin, 1);
- rb_define_module_function(rb_mMath, "tan", math_tan, 1);
-
- rb_define_module_function(rb_mMath, "acos", math_acos, 1);
- rb_define_module_function(rb_mMath, "asin", math_asin, 1);
- rb_define_module_function(rb_mMath, "atan", math_atan, 1);
-
- rb_define_module_function(rb_mMath, "cosh", math_cosh, 1);
- rb_define_module_function(rb_mMath, "sinh", math_sinh, 1);
- rb_define_module_function(rb_mMath, "tanh", math_tanh, 1);
-
- rb_define_module_function(rb_mMath, "exp", math_exp, 1);
- rb_define_module_function(rb_mMath, "log", math_log, 1);
- rb_define_module_function(rb_mMath, "log10", math_log10, 1);
- rb_define_module_function(rb_mMath, "sqrt", math_sqrt, 1);
-
- rb_define_module_function(rb_mMath, "frexp", math_frexp, 1);
- rb_define_module_function(rb_mMath, "ldexp", math_ldexp, 2);
-
- rb_define_module_function(rb_mMath, "hypot", math_hypot, 2);
-}
diff --git a/misc/README b/misc/README
deleted file mode 100644
index adc119d02e..0000000000
--- a/misc/README
+++ /dev/null
@@ -1,5 +0,0 @@
-README this file
-inf-ruby.el program to run ruby under emacs
-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
diff --git a/misc/inf-ruby.el b/misc/inf-ruby.el
deleted file mode 100644
index 7679ff91d7..0000000000
--- a/misc/inf-ruby.el
+++ /dev/null
@@ -1,332 +0,0 @@
-;;; -*-Emacs-Lisp-*-
-;;;
-;;; $Id$
-;;; $Author$
-;;; $Date$
-;;;
-;;; Inferior Ruby Mode - ruby process in a buffer.
-;;; adapted from cmuscheme.el
-;;;
-;;; Usage:
-;;;
-;;; (0) check ruby-program-name variable that can run your environment.
-;;;
-;;; (1) modify .emacs to use ruby-mode
-;;; for example :
-;;;
-;;; (autoload 'ruby-mode "ruby-mode"
-;;; "Mode for editing ruby source files" t)
-;;; (setq auto-mode-alist
-;;; (append '(("\\.rb$" . ruby-mode)) auto-mode-alist))
-;;; (setq interpreter-mode-alist (append '(("ruby" . ruby-mode))
-;;; interpreter-mode-alist))
-;;;
-;;; (2) set to road inf-ruby and set inf-ruby key definition in ruby-mode.
-;;;
-;;; (autoload 'run-ruby "inf-ruby"
-;;; "Run an inferior Ruby process")
-;;; (autoload 'inf-ruby-keys "inf-ruby"
-;;; "Set local key defs for inf-ruby in ruby-mode")
-;;; (add-hook 'ruby-mode-hook
-;;; '(lambda ()
-;;; (inf-ruby-keys)
-;;; ))
-;;;
-;;; HISTORY
-;;; senda - 8 Apr 1998: Created.
-;;; $Log$
-;;; Revision 1.4 2002/01/29 07:16:09 matz
-;;; * file.c (rb_stat_rdev_major): added. [new]
-;;;
-;;; * file.c (rb_stat_rdev_minor): added. [new]
-;;;
-;;; * file.c (rb_stat_inspect): print mode in octal.
-;;;
-;;; Revision 1.3 1999/12/01 09:24:18 matz
-;;; 19991201
-;;;
-;;; Revision 1.2 1999/08/13 05:45:18 matz
-;;; 1.4.0
-;;;
-;;; Revision 1.1.1.1.2.1 1999/07/15 07:59:59 matz
-;;; 990715
-;;;
-;;; Revision 1.1.1.1 1999/01/20 04:59:36 matz
-;;; ruby 1.3 cycle
-;;;
-;;; Revision 1.1.2.1 1998/12/16 07:30:36 matz
-;;; first public release of 1.1d (pre1.2) series
-;;;
-;;; Revision 1.4 1998/05/20 02:45:58 senda
-;;; default program to irb
-;;;
-;;; Revision 1.3 1998/04/10 04:11:30 senda
-;;; modification by Matsumoto san (1.1b9_09)
-;;; remove-in-string defined
-;;; global variable :
-;;; inferior-ruby-first-prompt-pattern
-;;; inferior-ruby-prompt-pattern
-;;; defined
-;;;
-;;; Revision 1.2 1998/04/09 07:53:42 senda
-;;; remove M-C-x in inferior-ruby-mode
-;;;
-;;; Revision 1.1 1998/04/09 07:28:36 senda
-;;; Initial revision
-;;;
-;;;
-
-(require 'comint)
-(require 'ruby-mode)
-
-;;
-;; you may change these variables
-;;
-;(defvar ruby-program-name "rbc --noreadline"
-; "*Program invoked by the run-ruby command")
-;
-;(defvar inferior-ruby-first-prompt-pattern "^rbc0> *"
-; "first prompt regex pattern of ruby interpreter.")
-;
-;(defvar inferior-ruby-prompt-pattern "^\\(rbc.[>*\"'] *\\)+"
-; "prompt regex pattern of ruby interpreter.")
-
-;;;; for irb
-(defvar ruby-program-name "irb --inf-ruby-mode"
- "*Program invoked by the run-ruby command")
-
-(defvar inferior-ruby-first-prompt-pattern "^irb(.*)[0-9:]+0> *"
- "first prompt regex pattern of ruby interpreter.")
-
-(defvar inferior-ruby-prompt-pattern "^\\(irb(.*)[0-9:]+[>*\"'] *\\)+"
- "prompt regex pattern of ruby interpreter.")
-
-;;
-;; mode variables
-;;
-(defvar inferior-ruby-mode-hook nil
- "*Hook for customising inferior-ruby mode.")
-(defvar inferior-ruby-mode-map nil
- "*Mode map for inferior-ruby-mode")
-
-(cond ((not inferior-ruby-mode-map)
- (setq inferior-ruby-mode-map
- (copy-keymap comint-mode-map))
-; (define-key inferior-ruby-mode-map "\M-\C-x" ;gnu convention
-; 'ruby-send-definition)
-; (define-key inferior-ruby-mode-map "\C-x\C-e" 'ruby-send-last-sexp)
- (define-key inferior-ruby-mode-map "\C-c\C-l" 'ruby-load-file)
-))
-
-(defun inf-ruby-keys ()
- "Set local key defs for inf-ruby in ruby-mode"
- (define-key ruby-mode-map "\M-\C-x" 'ruby-send-definition)
-; (define-key ruby-mode-map "\C-x\C-e" 'ruby-send-last-sexp)
- (define-key ruby-mode-map "\C-c\C-e" 'ruby-send-definition)
- (define-key ruby-mode-map "\C-c\M-e" 'ruby-send-definition-and-go)
- (define-key ruby-mode-map "\C-c\C-r" 'ruby-send-region)
- (define-key ruby-mode-map "\C-c\M-r" 'ruby-send-region-and-go)
- (define-key ruby-mode-map "\C-c\C-z" 'switch-to-ruby)
- (define-key ruby-mode-map "\C-c\C-l" 'ruby-load-file)
- (define-key ruby-mode-map "\C-c\C-s" 'run-ruby)
-)
-
-(defvar ruby-buffer nil "current ruby (actually irb) process buffer.")
-
-(defun inferior-ruby-mode ()
- "Major mode for interacting with an inferior ruby (irb) process.
-
-The following commands are available:
-\\{inferior-ruby-mode-map}
-
-A ruby process can be fired up with M-x run-ruby.
-
-Customisation: Entry to this mode runs the hooks on comint-mode-hook and
-inferior-ruby-mode-hook (in that order).
-
-You can send text to the inferior ruby process from other buffers containing
-Ruby source.
- switch-to-ruby switches the current buffer to the ruby process buffer.
- ruby-send-definition sends the current definition to the ruby process.
- ruby-send-region sends the current region to the ruby process.
-
- ruby-send-definition-and-go, ruby-send-region-and-go,
- switch to the ruby process buffer after sending their text.
-For information on running multiple processes in multiple buffers, see
-documentation for variable ruby-buffer.
-
-Commands:
-Return after the end of the process' output sends the text from the
- end of process to point.
-Return before the end of the process' output copies the sexp ending at point
- to the end of the process' output, and sends it.
-Delete converts tabs to spaces as it moves back.
-Tab indents for ruby; with argument, shifts rest
- of expression rigidly with the current line.
-C-M-q does Tab on each line starting within following expression.
-Paragraphs are separated only by blank lines. # start comments.
-If you accidentally suspend your process, use \\[comint-continue-subjob]
-to continue it."
- (interactive)
- (comint-mode)
- ;; Customise in inferior-ruby-mode-hook
- ;(setq comint-prompt-regexp "^[^>\n]*>+ *")
- (setq comint-prompt-regexp inferior-ruby-prompt-pattern)
- ;;(scheme-mode-variables)
- (ruby-mode-variables)
- (setq major-mode 'inferior-ruby-mode)
- (setq mode-name "Inferior Ruby")
- (setq mode-line-process '(":%s"))
- (use-local-map inferior-ruby-mode-map)
- (setq comint-input-filter (function ruby-input-filter))
- (setq comint-get-old-input (function ruby-get-old-input))
- (run-hooks 'inferior-ruby-mode-hook))
-
-(defvar inferior-ruby-filter-regexp "\\`\\s *\\S ?\\S ?\\s *\\'"
- "*Input matching this regexp are not saved on the history list.
-Defaults to a regexp ignoring all inputs of 0, 1, or 2 letters.")
-
-(defun ruby-input-filter (str)
- "Don't save anything matching inferior-ruby-filter-regexp"
- (not (string-match inferior-ruby-filter-regexp str)))
-
-;; adapted from replace-in-string in XEmacs (subr.el)
-(defun remove-in-string (str regexp)
- "Remove all matches in STR for REGEXP and returns the new string."
- (let ((rtn-str "") (start 0) match prev-start)
- (while (setq match (string-match regexp str start))
- (setq prev-start start
- start (match-end 0)
- rtn-str (concat rtn-str (substring str prev-start match))))
- (concat rtn-str (substring str start))))
-
-(defun ruby-get-old-input ()
- "Snarf the sexp ending at point"
- (save-excursion
- (let ((end (point)))
- (re-search-backward inferior-ruby-first-prompt-pattern)
- (remove-in-string (buffer-substring (point) end)
- inferior-ruby-prompt-pattern)
- )))
-
-(defun ruby-args-to-list (string)
- (let ((where (string-match "[ \t]" string)))
- (cond ((null where) (list string))
- ((not (= where 0))
- (cons (substring string 0 where)
- (ruby-args-to-list (substring string (+ 1 where)
- (length string)))))
- (t (let ((pos (string-match "[^ \t]" string)))
- (if (null pos)
- nil
- (ruby-args-to-list (substring string pos
- (length string)))))))))
-
-(defun run-ruby (cmd)
- "Run an inferior Ruby process, input and output via buffer *ruby*.
-If there is a process already running in `*ruby*', switch to that buffer.
-With argument, allows you to edit the command line (default is value
-of `ruby-program-name'). Runs the hooks `inferior-ruby-mode-hook'
-\(after the `comint-mode-hook' is run).
-\(Type \\[describe-mode] in the process buffer for a list of commands.)"
-
- (interactive (list (if current-prefix-arg
- (read-string "Run Ruby: " ruby-program-name)
- ruby-program-name)))
- (if (not (comint-check-proc "*ruby*"))
- (let ((cmdlist (ruby-args-to-list cmd)))
- (set-buffer (apply 'make-comint "ruby" (car cmdlist)
- nil (cdr cmdlist)))
- (inferior-ruby-mode)))
- (setq ruby-program-name cmd)
- (setq ruby-buffer "*ruby*")
- (pop-to-buffer "*ruby*"))
-
-(defun ruby-send-region (start end)
- "Send the current region to the inferior Ruby process."
- (interactive "r")
- (comint-send-region (ruby-proc) start end)
- (comint-send-string (ruby-proc) "\n"))
-
-(defun ruby-send-definition ()
- "Send the current definition to the inferior Ruby process."
- (interactive)
- (save-excursion
- (ruby-end-of-defun)
- (let ((end (point)))
- (ruby-beginning-of-defun)
- (ruby-send-region (point) end))))
-
-;(defun ruby-send-last-sexp ()
-; "Send the previous sexp to the inferior Ruby process."
-; (interactive)
-; (ruby-send-region (save-excursion (backward-sexp) (point)) (point)))
-
-(defun switch-to-ruby (eob-p)
- "Switch to the ruby process buffer.
-With argument, positions cursor at end of buffer."
- (interactive "P")
- (if (get-buffer ruby-buffer)
- (pop-to-buffer ruby-buffer)
- (error "No current process buffer. See variable ruby-buffer."))
- (cond (eob-p
- (push-mark)
- (goto-char (point-max)))))
-
-(defun ruby-send-region-and-go (start end)
- "Send the current region to the inferior Ruby process.
-Then switch to the process buffer."
- (interactive "r")
- (ruby-send-region start end)
- (switch-to-ruby t))
-
-(defun ruby-send-definition-and-go ()
- "Send the current definition to the inferior Ruby.
-Then switch to the process buffer."
- (interactive)
- (ruby-send-definition)
- (switch-to-ruby t))
-
-(defvar ruby-source-modes '(ruby-mode)
- "*Used to determine if a buffer contains Ruby source code.
-If it's loaded into a buffer that is in one of these major modes, it's
-considered a ruby source file by ruby-load-file.
-Used by these commands to determine defaults.")
-
-(defvar ruby-prev-l/c-dir/file nil
- "Caches the last (directory . file) pair.
-Caches the last pair used in the last ruby-load-file command.
-Used for determining the default in the
-next one.")
-
-(defun ruby-load-file (file-name)
- "Load a Ruby file into the inferior Ruby process."
- (interactive (comint-get-source "Load Ruby file: " ruby-prev-l/c-dir/file
- ruby-source-modes t)) ; T because LOAD
- ; needs an exact name
- (comint-check-source file-name) ; Check to see if buffer needs saved.
- (setq ruby-prev-l/c-dir/file (cons (file-name-directory file-name)
- (file-name-nondirectory file-name)))
- (comint-send-string (ruby-proc) (concat "(load \""
- file-name
- "\"\)\n")))
-
-(defun ruby-proc ()
- "Returns the current ruby process. See variable ruby-buffer."
- (let ((proc (get-buffer-process (if (eq major-mode 'inferior-ruby-mode)
- (current-buffer)
- ruby-buffer))))
- (or proc
- (error "No current process. See variable ruby-buffer"))))
-
-;;; Do the user's customisation...
-
-(defvar inf-ruby-load-hook nil
- "This hook is run when inf-ruby is loaded in.
-This is a good place to put keybindings.")
-
-(run-hooks 'inf-ruby-load-hook)
-
-(provide 'inf-ruby)
-
-;;; inf-ruby.el ends here
diff --git a/misc/ruby-mode.el b/misc/ruby-mode.el
deleted file mode 100644
index ec70feedd5..0000000000
--- a/misc/ruby-mode.el
+++ /dev/null
@@ -1,904 +0,0 @@
-;;;
-;;; ruby-mode.el -
-;;;
-;;; $Author$
-;;; $Date$
-;;; created at: Fri Feb 4 14:49:13 JST 1994
-;;;
-
-(defconst ruby-mode-revision "$Revision$")
-
-(defconst ruby-mode-version
- (progn
- (string-match "[0-9.]+" ruby-mode-revision)
- (substring ruby-mode-revision (match-beginning 0) (match-end 0))))
-
-(defconst ruby-block-beg-re
- "class\\|module\\|def\\|if\\|unless\\|case\\|while\\|until\\|for\\|begin\\|do"
- )
-
-(defconst ruby-non-block-do-re
- "\\(while\\|until\\|for\\|rescue\\)\\>"
- )
-
-(defconst ruby-indent-beg-re
- "\\(\\s *\\(class\\|module\\|def\\)\\)\\|if\\|unless\\|case\\|while\\|until\\|for\\|begin"
- )
-
-(defconst ruby-modifier-beg-re
- "if\\|unless\\|while\\|until"
- )
-
-(defconst ruby-modifier-re
- (concat ruby-modifier-beg-re "\\|rescue")
- )
-
-(defconst ruby-block-mid-re
- "then\\|else\\|elsif\\|when\\|rescue\\|ensure"
- )
-
-(defconst ruby-block-op-re
- "and\\|or\\|not"
- )
-
-(defconst ruby-block-hanging-re
- (concat ruby-modifier-beg-re "\\|" ruby-block-op-re)
- )
-
-(defconst ruby-block-end-re "end")
-
-(defconst ruby-delimiter
- (concat "[?$/%(){}#\"'`.:]\\|\\[\\|\\]\\|\\<\\("
- ruby-block-beg-re
- "\\|" ruby-block-end-re
- "\\)\\>\\|^=begin")
- )
-
-(defconst ruby-negative
- (concat "^[ \t]*\\(\\(" ruby-block-mid-re "\\)\\>\\|\\("
- ruby-block-end-re "\\)\\>\\|}\\|\\]\\)")
- )
-
-(defconst ruby-operator-chars "-,.+*/%&|^~=<>:")
-(defconst ruby-operator-re (concat "[" ruby-operator-chars "]"))
-
-(defconst ruby-symbol-chars "a-zA-Z0-9_")
-(defconst ruby-symbol-re (concat "[" ruby-symbol-chars "]"))
-
-(defvar ruby-mode-abbrev-table nil
- "Abbrev table in use in ruby-mode buffers.")
-
-(define-abbrev-table 'ruby-mode-abbrev-table ())
-
-(defvar ruby-mode-map nil "Keymap used in ruby mode.")
-
-(if ruby-mode-map
- nil
- (setq ruby-mode-map (make-sparse-keymap))
- (define-key ruby-mode-map "{" 'ruby-electric-brace)
- (define-key ruby-mode-map "}" 'ruby-electric-brace)
- (define-key ruby-mode-map "\e\C-a" 'ruby-beginning-of-defun)
- (define-key ruby-mode-map "\e\C-e" 'ruby-end-of-defun)
- (define-key ruby-mode-map "\e\C-b" 'ruby-beginning-of-block)
- (define-key ruby-mode-map "\e\C-f" 'ruby-end-of-block)
- (define-key ruby-mode-map "\e\C-p" 'ruby-beginning-of-block)
- (define-key ruby-mode-map "\e\C-n" 'ruby-end-of-block)
- (define-key ruby-mode-map "\e\C-h" 'ruby-mark-defun)
- (define-key ruby-mode-map "\t" 'ruby-indent-command)
- (define-key ruby-mode-map "\C-c\C-e" 'ruby-insert-end)
- (define-key ruby-mode-map "\C-j" 'ruby-reindent-then-newline-and-indent)
- (define-key ruby-mode-map "\C-m" 'newline))
-
-(defvar ruby-mode-syntax-table nil
- "Syntax table in use in ruby-mode buffers.")
-
-(if ruby-mode-syntax-table
- ()
- (setq ruby-mode-syntax-table (make-syntax-table))
- (modify-syntax-entry ?\' "\"" ruby-mode-syntax-table)
- (modify-syntax-entry ?\" "\"" ruby-mode-syntax-table)
- (modify-syntax-entry ?\` "\"" ruby-mode-syntax-table)
- (modify-syntax-entry ?# "<" ruby-mode-syntax-table)
- (modify-syntax-entry ?\n ">" ruby-mode-syntax-table)
- (modify-syntax-entry ?\\ "\\" ruby-mode-syntax-table)
- (modify-syntax-entry ?$ "." ruby-mode-syntax-table)
- (modify-syntax-entry ?? "_" ruby-mode-syntax-table)
- (modify-syntax-entry ?_ "_" ruby-mode-syntax-table)
- (modify-syntax-entry ?< "." ruby-mode-syntax-table)
- (modify-syntax-entry ?> "." ruby-mode-syntax-table)
- (modify-syntax-entry ?& "." ruby-mode-syntax-table)
- (modify-syntax-entry ?| "." ruby-mode-syntax-table)
- (modify-syntax-entry ?% "." ruby-mode-syntax-table)
- (modify-syntax-entry ?= "." ruby-mode-syntax-table)
- (modify-syntax-entry ?/ "." ruby-mode-syntax-table)
- (modify-syntax-entry ?+ "." ruby-mode-syntax-table)
- (modify-syntax-entry ?* "." ruby-mode-syntax-table)
- (modify-syntax-entry ?- "." ruby-mode-syntax-table)
- (modify-syntax-entry ?\; "." ruby-mode-syntax-table)
- (modify-syntax-entry ?\( "()" ruby-mode-syntax-table)
- (modify-syntax-entry ?\) ")(" ruby-mode-syntax-table)
- (modify-syntax-entry ?\{ "(}" ruby-mode-syntax-table)
- (modify-syntax-entry ?\} "){" ruby-mode-syntax-table)
- (modify-syntax-entry ?\[ "(]" ruby-mode-syntax-table)
- (modify-syntax-entry ?\] ")[" ruby-mode-syntax-table)
- )
-
-(defvar ruby-indent-level 2
- "*Indentation of ruby statements.")
-
-(eval-when-compile (require 'cl))
-(defun ruby-imenu-create-index ()
- (let ((index-alist '())
- class-name class-begin method-name method-begin decl)
- (goto-char (point-min))
- (while (re-search-forward "^\\s *\\(class\\|def\\)\\s *\\([^(\n ]+\\)" nil t)
- (setq decl (buffer-substring (match-beginning 1) (match-end 1)))
- (cond
- ((string= "class" decl)
- (setq class-begin (match-beginning 2))
- (setq class-name (buffer-substring class-begin (match-end 2)))
- (push (cons class-name (match-beginning 0)) index-alist)
- (ruby-mark-defun)
- (save-restriction
- (narrow-to-region (region-beginning) (region-end))
- (while (re-search-forward "^\\s *def\\s *\\([^(\n ]+\\)" nil 'move)
- (setq method-begin (match-beginning 1))
- (setq method-name (buffer-substring method-begin (match-end 1)))
- (push (cons (concat class-name "#" method-name) (match-beginning 0)) index-alist))))
- ((string= "def" decl)
- (setq method-begin (match-beginning 2))
- (setq method-name (buffer-substring method-begin (match-end 2)))
- (push (cons method-name (match-beginning 0)) index-alist))))
- index-alist))
-
-(defun ruby-mode-variables ()
- (set-syntax-table ruby-mode-syntax-table)
- (setq local-abbrev-table ruby-mode-abbrev-table)
- (make-local-variable 'indent-line-function)
- (setq indent-line-function 'ruby-indent-line)
- (make-local-variable 'require-final-newline)
- (setq require-final-newline t)
- (make-variable-buffer-local 'comment-start)
- (setq comment-start "# ")
- (make-variable-buffer-local 'comment-end)
- (setq comment-end "")
- (make-variable-buffer-local 'comment-column)
- (setq comment-column 32)
- (make-variable-buffer-local 'comment-start-skip)
- (setq comment-start-skip "\\(^\\|\\s-\\);?#+ *")
- (make-local-variable 'parse-sexp-ignore-comments)
- (setq parse-sexp-ignore-comments t)
- (make-local-variable 'paragraph-start)
- (setq paragraph-start (concat "$\\|" page-delimiter))
- (make-local-variable 'paragraph-separate)
- (setq paragraph-separate paragraph-start)
- (make-local-variable 'paragraph-ignore-fill-prefix)
- (setq paragraph-ignore-fill-prefix t))
-
-(defun ruby-mode ()
- "Major mode for editing ruby scripts.
-\\[ruby-indent-command] properly indents subexpressions of multi-line
-class, module, def, if, while, for, do, and case statements, taking
-nesting into account.
-
-The variable ruby-indent-level controls the amount of indentation.
-\\{ruby-mode-map}"
- (interactive)
- (kill-all-local-variables)
- (use-local-map ruby-mode-map)
- (setq mode-name "Ruby")
- (setq major-mode 'ruby-mode)
- (ruby-mode-variables)
-
- (make-local-variable 'imenu-create-index-function)
- (setq imenu-create-index-function 'ruby-imenu-create-index)
-
- (make-local-variable 'add-log-current-defun-function)
- (setq add-log-current-defun-function 'ruby-add-log-current-method)
-
- (run-hooks 'ruby-mode-hook))
-
-(defun ruby-current-indentation ()
- (save-excursion
- (beginning-of-line)
- (back-to-indentation)
- (current-column)))
-
-(defun ruby-indent-line (&optional flag)
- "Correct indentation of the current ruby line."
- (ruby-indent-to (ruby-calculate-indent)))
-
-(defun ruby-indent-command ()
- (interactive)
- (ruby-indent-line t))
-
-(defun ruby-indent-to (x)
- (if x
- (let (shift top beg)
- (and (< x 0) (error "invalid nest"))
- (setq shift (current-column))
- (beginning-of-line)
- (setq beg (point))
- (back-to-indentation)
- (setq top (current-column))
- (skip-chars-backward " \t")
- (if (>= shift top) (setq shift (- shift top))
- (setq shift 0))
- (if (and (bolp)
- (= x top))
- (move-to-column (+ x shift))
- (move-to-column top)
- (delete-region beg (point))
- (beginning-of-line)
- (indent-to x)
- (move-to-column (+ x shift))))))
-
-(defun ruby-expr-beg (&optional option)
- (save-excursion
- (store-match-data nil)
- (skip-chars-backward " \t")
- (cond
- ((bolp) t)
- ((looking-at "\\?")
- (or (bolp) (forward-char -1))
- (not (looking-at "\\sw")))
- (t
- (forward-char -1)
- (or (looking-at ruby-operator-re)
- (looking-at "[\\[({,;]")
- (and (not (eq option 'modifier))
- (looking-at "[!?]"))
- (and (looking-at ruby-symbol-re)
- (skip-chars-backward ruby-symbol-chars)
- (cond
- ((or (looking-at ruby-block-beg-re)
- (looking-at ruby-block-op-re)
- (looking-at ruby-block-mid-re))
- (goto-char (match-end 0))
- (looking-at "\\>"))
- ((eq option 'expr-qstr)
- (looking-at "[a-zA-Z][a-zA-z0-9_]* +%[^ \t]"))
- ((eq option 'expr-re)
- (looking-at "[a-zA-Z][a-zA-z0-9_]* +/[^ \t]"))
- (t nil))))))))
-
-(defun ruby-forward-string (term &optional end no-error expand)
- (let ((n 1) (c (string-to-char term))
- (re (if expand
- (concat "[^\\]\\(\\\\\\\\\\)*\\([" term "]\\|\\(#{\\)\\)")
- (concat "[^\\]\\(\\\\\\\\\\)*[" term "]"))))
- (while (and (re-search-forward re end no-error)
- (if (match-beginning 3)
- (ruby-forward-string "}{" end no-error nil)
- (> (setq n (if (eq (char-before (point)) c)
- (1- n) (1+ n))) 0)))
- (forward-char -1))
- (cond ((zerop n))
- (no-error nil)
- (error "unterminated string"))))
-
-(defun ruby-parse-region (start end)
- (let ((indent-point end)
- (indent 0)
- (in-string nil)
- (in-paren nil)
- (depth 0)
- (nest nil)
- (pcol nil))
- (save-excursion
- (if start
- (goto-char start)
- (ruby-beginning-of-indent))
- (save-restriction
- (narrow-to-region (point) end)
- (while (and (> indent-point (point))
- (re-search-forward ruby-delimiter indent-point t))
- (or depth (setq depth 0))
- (let ((pnt (point)) w re expand)
- (goto-char (match-beginning 0))
- (cond
- ((or (looking-at "\"") ;skip string
- (looking-at "`"))
- (cond
- ((and (not (eobp))
- (ruby-forward-string (buffer-substring (point) (1+ (point))) indent-point t t))
- nil)
- (t
- (setq in-string (point))
- (goto-char indent-point))))
- ((looking-at "'")
- (cond
- ((and (not (eobp))
- (re-search-forward "[^\\]\\(\\\\\\\\\\)*'" indent-point t))
- nil)
- (t
- (setq in-string (point))
- (goto-char indent-point))))
- ((looking-at "/")
- (cond
- ((and (not (eobp)) (ruby-expr-beg 'expr-re))
- (if (ruby-forward-string "/" indent-point t t)
- nil
- (setq in-string (point))
- (goto-char indent-point)))
- (t
- (goto-char pnt))))
- ((looking-at "%")
- (cond
- ((and (not (eobp))
- (ruby-expr-beg 'expr-qstr)
- (not (looking-at "%="))
- (looking-at "%[Qqrxw]?\\(.\\)"))
- (goto-char (match-beginning 1))
- (setq expand (not (eq (char-before) ?q)))
- (setq w (buffer-substring (match-beginning 1)
- (match-end 1)))
- (cond
- ((string= w "[") (setq re "]["))
- ((string= w "{") (setq re "}{"))
- ((string= w "(") (setq re ")("))
- ((string= w "<") (setq re "><"))
- ((or (and expand (string= w "\\"))
- (member w '("*" "." "+" "?" "^" "$")))
- (setq w (concat "\\" w))))
- (unless (cond (re (ruby-forward-string re indent-point t expand))
- (expand (ruby-forward-string w indent-point t t))
- (t (re-search-forward
- (if (string= w "\\")
- "\\\\[^\\]*\\\\"
- (concat "[^\\]\\(\\\\\\\\\\)*" w))
- indent-point t)))
- (setq in-string (point))
- (goto-char indent-point)))
- (t
- (goto-char pnt))))
- ((looking-at "\\?") ;skip ?char
- (cond
- ((ruby-expr-beg)
- (looking-at "?\\(\\\\C-\\|\\\\M-\\)*.")
- (goto-char (match-end 0)))
- (t
- (goto-char pnt))))
- ((looking-at "\\$") ;skip $char
- (goto-char pnt)
- (forward-char 1))
- ((looking-at "#") ;skip comment
- (forward-line 1)
- (goto-char (point))
- )
- ((looking-at "(")
- (setq nest (cons (cons (char-after (point)) pnt) nest))
- (setq pcol (cons (cons pnt depth) pcol))
- (setq depth 0)
- (goto-char pnt)
- )
- ((looking-at "[\\[{]")
- (setq nest (cons (cons (char-after (point)) pnt) nest))
- (setq depth (1+ depth))
- (goto-char pnt)
- )
- ((looking-at ")")
- (setq nest (cdr nest))
- (setq depth (cdr (car pcol)))
- (setq pcol (cdr pcol))
- (goto-char pnt))
- ((looking-at "[])}]")
- (setq nest (cdr nest))
- (setq depth (1- depth))
- (goto-char pnt))
- ((looking-at ruby-block-end-re)
- (if (or (and (not (bolp))
- (progn
- (forward-char -1)
- (setq w (char-after (point)))
- (or (eq ?_ w)
- (eq ?. w))))
- (progn
- (goto-char pnt)
- (setq w (char-after (point)))
- (or (eq ?_ w)
- (eq ?! w)
- (eq ?? w))))
- nil
- (setq nest (cdr nest))
- (setq depth (1- depth)))
- (goto-char pnt))
- ((looking-at "def\\s +[^(\n;]*")
- (if (or (bolp)
- (progn
- (forward-char -1)
- (not (eq ?_ (char-after (point))))))
- (progn
- (setq nest (cons (cons nil pnt) nest))
- (setq depth (1+ depth))))
- (goto-char (match-end 0)))
- ((looking-at ruby-block-beg-re)
- (and
- (save-match-data
- (or (not (looking-at "do\\>[^_]"))
- (save-excursion
- (back-to-indentation)
- (not (looking-at ruby-non-block-do-re)))))
- (or (bolp)
- (progn
- (forward-char -1)
- (setq w (char-after (point)))
- (not (or (eq ?_ w)
- (eq ?. w)))))
- (goto-char pnt)
- (setq w (char-after (point)))
- (not (eq ?_ w))
- (not (eq ?! w))
- (not (eq ?? w))
- (skip-chars-forward " \t")
- (goto-char (match-beginning 0))
- (or (not (looking-at ruby-modifier-re))
- (ruby-expr-beg 'modifier))
- (goto-char pnt)
- (setq nest (cons (cons nil pnt) nest))
- (setq depth (1+ depth)))
- (goto-char pnt))
- ((looking-at ":\\([a-zA-Z_][a-zA-Z_0-9]*\\)?")
- (goto-char (match-end 0)))
- ((or (looking-at "\\.")
- (looking-at "\\.\\.\\.?")
- (looking-at "\\.[0-9]+")
- (looking-at "\\.[a-zA-Z_0-9]+"))
- (goto-char (match-end 0)))
- ((looking-at "^=begin")
- (if (re-search-forward "^=end" indent-point t)
- (forward-line 1)
- (setq in-string (match-end 0))
- (goto-char indent-point)))
- (t
- (error (format "bad string %s"
- (buffer-substring (point) pnt)
- )))))))
- (list in-string (car nest) depth (car (car pcol))))))
-
-(defun ruby-indent-size (pos nest)
- (+ pos (* (if nest nest 1) ruby-indent-level)))
-
-(defun ruby-calculate-indent (&optional parse-start)
- (save-excursion
- (beginning-of-line)
- (let ((indent-point (point))
- (case-fold-search nil)
- state bol eol
- (indent 0))
- (if parse-start
- (goto-char parse-start)
- (ruby-beginning-of-indent)
- (setq parse-start (point)))
- (back-to-indentation)
- (setq indent (current-column))
- (setq state (ruby-parse-region parse-start indent-point))
- (cond
- ((nth 0 state) ; within string
- (setq indent nil)) ; do nothing
- ((car (nth 1 state)) ; in paren
- (goto-char (cdr (nth 1 state)))
- (if (eq (car (nth 1 state)) ?\( )
- (let ((column (current-column))
- (s (ruby-parse-region (point) indent-point)))
- (cond
- ((and (nth 2 s) (> (nth 2 s) 0))
- (goto-char (cdr (nth 1 s)))
- (forward-word -1)
- (setq indent (ruby-indent-size (current-column) (nth 2 state))))
- (t
- (setq indent (current-column)))))
- (cond
- ((nth 3 state)
- (goto-char (nth 3 state))
- (setq indent (ruby-indent-size (current-column) (nth 2 state))))
- (t
- (goto-char parse-start)
- (back-to-indentation)
- (setq indent (ruby-indent-size (current-column) (nth 2 state)))))
- ))
- ((and (nth 2 state)(> (nth 2 state) 0)) ; in nest
- (if (null (cdr (nth 1 state)))
- (error "invalid nest"))
- (goto-char (cdr (nth 1 state)))
- (forward-word -1) ; skip back a keyword
- (cond
- ((looking-at "do\\>[^_]") ; iter block is a special case
- (cond
- ((nth 3 state)
- (goto-char (nth 3 state))
- (setq indent (ruby-indent-size (current-column) (nth 2 state))))
- (t
- (goto-char parse-start)
- (back-to-indentation)
- (setq indent (ruby-indent-size (current-column) (nth 2 state))))))
- (t
- (setq indent (+ (current-column) ruby-indent-level)))))
-
- ((and (nth 2 state) (< (nth 2 state) 0)) ; in negative nest
- (setq indent (ruby-indent-size (current-column) (nth 2 state)))))
-
- (cond
- (indent
- (goto-char indent-point)
- (end-of-line)
- (setq eol (point))
- (beginning-of-line)
- (cond
- ((re-search-forward ruby-negative eol t)
- (and (not (eq ?_ (char-after (match-end 0))))
- (setq indent (- indent ruby-indent-level))))
- ;;operator terminated lines
- ((and
- (save-excursion
- (beginning-of-line)
- (not (bobp)))
- (or (null (car (nth 1 state))) ;not in parens
- (and (eq (car (nth 1 state)) ?\{)
- (save-excursion ;except non-block braces
- (goto-char (cdr (nth 1 state)))
- (or (bobp) (forward-char -1))
- (not (ruby-expr-beg))))))
- ;; goto beginning of non-empty no-comment line
- (let (end done)
- (while (not done)
- (skip-chars-backward " \t\n")
- (setq end (point))
- (beginning-of-line)
- (if (re-search-forward "^\\s *#" end t)
- (beginning-of-line)
- (setq done t))))
- (setq bol (point))
- (end-of-line)
- (skip-chars-backward " \t")
- (let ((pos (point)))
- (while (and (re-search-backward "#" bol t)
- (eq (char-before) ??))
- (forward-char -1))
- (skip-chars-backward " \t")
- (and
- (setq state (ruby-parse-region parse-start (point)))
- (nth 0 state)
- (goto-char pos)))
- (or (bobp) (forward-char -1))
- (and
- (or (and (looking-at ruby-symbol-re)
- (skip-chars-backward ruby-symbol-chars)
- (looking-at ruby-block-hanging-re)
- (not (eq (point) (nth 3 state)))
- (save-excursion
- (goto-char (match-end 0))
- (not (looking-at "[a-z_]"))))
- (and (looking-at ruby-operator-re)
- (not (eq (char-after (1- (point))) ??))
- (not (eq (char-after (1- (point))) ?$))
- (or (not (eq ?/ (char-after (point))))
- (null (nth 0 (ruby-parse-region parse-start (point)))))
- (or (not (eq ?| (char-after (point))))
- (save-excursion
- (or (eolp) (forward-char -1))
- (cond
- ((search-backward "|" nil t)
- (skip-chars-backward " \t\n")
- (and (not (eolp))
- (progn
- (forward-char -1)
- (not (looking-at "{")))
- (progn
- (forward-word -1)
- (not (looking-at "do\\>[^_]")))))
- (t t))))))
- (setq indent (+ indent ruby-indent-level)))))))
- indent)))
-
-(defun ruby-electric-brace (arg)
- (interactive "P")
- (self-insert-command (prefix-numeric-value arg))
- (ruby-indent-line t))
-
-(defun ruby-beginning-of-defun (&optional arg)
- "Move backward to next beginning-of-defun.
-With argument, do this that many times.
-Returns t unless search stops due to end of buffer."
- (interactive "p")
- (and (re-search-backward (concat "^\\(" ruby-block-beg-re "\\)\\b")
- nil 'move (or arg 1))
- (progn (beginning-of-line) t)))
-
-(defun ruby-beginning-of-indent ()
- (and (re-search-backward (concat "^\\(" ruby-indent-beg-re "\\)\\b")
- nil 'move)
- (progn
- (beginning-of-line)
- t)))
-
-(defun ruby-end-of-defun (&optional arg)
- "Move forward to next end of defun.
-An end of a defun is found by moving forward from the beginning of one."
- (interactive "p")
- (and (re-search-forward (concat "^\\(" ruby-block-end-re "\\)\\($\\|\\b[^_]\\)")
- nil 'move (or arg 1))
- (progn (beginning-of-line) t))
- (forward-line 1))
-
-(defun ruby-move-to-block (n)
- (let (start pos done down)
- (setq start (ruby-calculate-indent))
- (if (eobp)
- nil
- (while (and (not (bobp)) (not (eobp)) (not done))
- (forward-line n)
- (cond
- ((looking-at "^$"))
- ((looking-at "^\\s *#"))
- (t
- (setq pos (current-indentation))
- (cond
- ((< start pos)
- (setq down t))
- ((and down (= pos start))
- (setq done t))
- ((> start pos)
- (setq done t)))))
- (if done
- (progn
- (back-to-indentation)
- (if (looking-at ruby-block-mid-re)
- (setq done nil)))))))
- (back-to-indentation))
-
-(defun ruby-beginning-of-block ()
- "Move backward to next beginning-of-block"
- (interactive)
- (ruby-move-to-block -1))
-
-(defun ruby-end-of-block ()
- "Move forward to next beginning-of-block"
- (interactive)
- (ruby-move-to-block 1))
-
-(defun ruby-reindent-then-newline-and-indent ()
- (interactive "*")
- (newline)
- (save-excursion
- (end-of-line 0)
- (indent-according-to-mode)
- (delete-region (point) (progn (skip-chars-backward " \t") (point))))
- (indent-according-to-mode))
-
-(fset 'ruby-encomment-region (symbol-function 'comment-region))
-
-(defun ruby-decomment-region (beg end)
- (interactive "r")
- (save-excursion
- (goto-char beg)
- (while (re-search-forward "^\\([ \t]*\\)#" end t)
- (replace-match "\\1" nil nil)
- (save-excursion
- (ruby-indent-line)))))
-
-(defun ruby-insert-end ()
- (interactive)
- (insert "end")
- (ruby-indent-line t)
- (end-of-line))
-
-(defun ruby-mark-defun ()
- "Put mark at end of this Ruby function, point at beginning."
- (interactive)
- (push-mark (point))
- (ruby-end-of-defun)
- (push-mark (point) nil t)
- (ruby-beginning-of-defun)
- (re-search-backward "^\n" (- (point) 1) t))
-
-(defun ruby-add-log-current-method ()
- "Return current method string."
- (condition-case nil
- (save-excursion
- (let ((mlist nil) (indent 0))
- ;; get current method (or class/module)
- (if (re-search-backward
- (concat "^[ \t]*\\(def\\|class\\|module\\)[ \t]+"
- "\\(" ruby-symbol-re "+\\)")
- nil t)
- (progn
- (setq mlist (list (buffer-substring
- (match-beginning 2) (match-end 2))))
- (goto-char (match-beginning 1))
- (setq indent (current-column))
- (beginning-of-line)))
- ;; nest class/module
- (while (and (> indent 0)
- (re-search-backward
- (concat
- "^[ \t]*\\(class\\|module\\)[ \t]+"
- "\\([A-Z]" ruby-symbol-re "+\\)")
- nil t))
- (goto-char (match-beginning 1))
- (if (< (current-column) indent)
- (progn
- (setq mlist
- (cons (buffer-substring
- (match-beginning 2) (match-end 2)) mlist))
- (setq indent (current-column))
- (beginning-of-line))))
- ;; generate string
- (if (consp mlist)
- (mapconcat (function identity) mlist "::")
- nil)))))
-
-(cond
- ((featurep 'font-lock)
- (or (boundp 'font-lock-variable-name-face)
- (setq font-lock-variable-name-face font-lock-type-face))
-
- (setq ruby-font-lock-syntactic-keywords
- '(
- ;; #{ }, #$hoge, #@foo are not comments
- ("\\(#\\)[{$@]" 1 (1 . nil))
- ;; the last $' in the string ,'...$' is not variable
- ;; the last ?' in the string ,'...?' is not ascii code
- ("\\(^\\|[[\\s <+(,=]\\)\\('\\)[^'\n\\\\]*\\(\\\\.[^'\n\\\\]*\\)*[?$]\\('\\)"
- (2 (7 . nil))
- (4 (7 . nil)))
- ;; the last $` in the string ,`...$` is not variable
- ;; the last ?` in the string ,`...?` is not ascii code
- ("\\(^\\|[[\\s <+(,=]\\)\\(`\\)[^`\n\\\\]*\\(\\\\.[^`\n\\\\]*\\)*[?$]\\(`\\)"
- (2 (7 . nil))
- (4 (7 . nil)))
- ;; the last $" in the string ,"...$" is not variable
- ;; the last ?" in the string ,"...?" is not ascii code
- ("\\(^\\|[[\\s <+(,=]\\)\\(\"\\)[^\"\n\\\\]*\\(\\\\.[^\"\n\\\\]*\\)*[?$]\\(\"\\)"
- (2 (7 . nil))
- (4 (7 . nil)))
- ;; $' $" $` .... are variables
- ;; ?' ?" ?` are ascii codes
- ("[?$][#\"'`]" 0 (1 . nil))
- ;; regexps
- ("\\(^\\|[=(,~?:;]\\|\\(^\\|\\s \\)\\(if\\|elsif\\|unless\\|while\\|until\\|when\\|and\\|or\\|&&\\|||\\)\\|g?sub!?\\|scan\\|split!?\\)\\s *\\(/\\)[^/\n\\\\]*\\(\\\\.[^/\n\\\\]*\\)*\\(/\\)"
- (4 (7 . ?/))
- (6 (7 . ?/)))
- ;; %Q!...!
- ("\\(^\\|[[\\s <+(,=]\\)%[xrqQ]?\\([^a-zA-Z0-9 \n]\\)[^\n\\\\]*\\(\\\\.[^\n\\\\]*\\)*\\(\\2\\)"
- (2 (7 . nil))
- (4 (7 . nil)))
- ("^\\(=\\)begin\\(\\s \\|$\\)" 1 (7 . nil))
- ("^\\(=\\)end\\(\\s \\|$\\)" 1 (7 . nil))))
-
- (cond ((featurep 'xemacs)
- (put 'ruby-mode 'font-lock-defaults
- '((ruby-font-lock-keywords)
- nil nil nil
- beginning-of-line
- (font-lock-syntactic-keywords
- . ruby-font-lock-syntactic-keywords))))
- (t
- (add-hook 'ruby-mode-hook
- '(lambda ()
- (make-local-variable 'font-lock-defaults)
- (make-local-variable 'font-lock-keywords)
- (make-local-variable 'font-lock-syntactic-keywords)
- (setq font-lock-defaults '((ruby-font-lock-keywords) nil nil))
- (setq font-lock-keywords ruby-font-lock-keywords)
- (setq font-lock-syntactic-keywords ruby-font-lock-syntactic-keywords)))))
-
- (defun ruby-font-lock-docs (limit)
- (if (re-search-forward "^=begin\\(\\s \\|$\\)" limit t)
- (let (beg)
- (beginning-of-line)
- (setq beg (point))
- (forward-line 1)
- (if (re-search-forward "^=end\\(\\s \\|$\\)" limit t)
- (progn
- (set-match-data (list beg (point)))
- t)))))
-
- (defun ruby-font-lock-maybe-docs (limit)
- (let (beg)
- (save-excursion
- (if (and (re-search-backward "^=\\(begin\\|end\\)\\(\\s \\|$\\)" nil t)
- (string= (match-string 1) "begin"))
- (progn
- (beginning-of-line)
- (setq beg (point)))))
- (if (and beg (and (re-search-forward "^=\\(begin\\|end\\)\\(\\s \\|$\\)" nil t)
- (string= (match-string 1) "end")))
- (progn
- (set-match-data (list beg (point)))
- t)
- nil)))
-
- (defvar ruby-font-lock-keywords
- (list
- (cons (concat
- "\\(^\\|[^_:.@$]\\|\\.\\.\\)\\b\\("
- (mapconcat
- 'identity
- '("alias"
- "and"
- "begin"
- "break"
- "case"
- "catch"
- "class"
- "def"
- "do"
- "elsif"
- "else"
- "fail"
- "ensure"
- "for"
- "end"
- "if"
- "in"
- "module"
- "next"
- "not"
- "or"
- "raise"
- "redo"
- "rescue"
- "retry"
- "return"
- "then"
- "throw"
- "super"
- "unless"
- "undef"
- "until"
- "when"
- "while"
- "yield"
- )
- "\\|")
- "\\)\\>\\([^_]\\|$\\)")
- 2)
- ;; variables
- '("\\(^\\|[^_:.@$]\\|\\.\\.\\)\\b\\(nil\\|self\\|true\\|false\\)\\b\\([^_]\\|$\\)"
- 2 font-lock-variable-name-face)
- ;; variables
- '("\\(\\$\\([^a-zA-Z0-9 \n]\\|[0-9]\\)\\)\\W"
- 1 font-lock-variable-name-face)
- '("\\(\\$\\|@\\|@@\\)\\(\\w\\|_\\)+"
- 0 font-lock-variable-name-face)
- ;; embedded document
- '(ruby-font-lock-docs
- 0 font-lock-comment-face t)
- '(ruby-font-lock-maybe-docs
- 0 font-lock-comment-face t)
- ;; constants
- '("\\(^\\|[^_]\\)\\b\\([A-Z]+\\(\\w\\|_\\)*\\)"
- 2 font-lock-type-face)
- ;; functions
- '("^\\s *def\\s +\\([^( ]+\\)"
- 1 font-lock-function-name-face)
- ;; symbols
- '("\\(^\\|[^:]\\)\\(:\\([-+/%&|^~`]\\|\\*\\*?\\|<\\(<\\|=>?\\)?\\|>[>=]?\\|===?\\|=~\\|\\[\\]\\|\\(\\w\\|_\\)+\\([!?=]\\|\\b\\)\\|#{[^}\n\\\\]*\\(\\\\.[^}\n\\\\]*\\)*}\\)\\)"
- 2 font-lock-reference-face)
- ;; expression expansion
- '("#\\({[^}\n\\\\]*\\(\\\\.[^}\n\\\\]*\\)*}\\|\\(\\$\\|@\\|@@\\)\\(\\w\\|_\\)+\\)"
- 0 font-lock-variable-name-face t))
- "*Additional expressions to highlight in ruby mode."))
-
- ((featurep 'hilit19)
- (hilit-set-mode-patterns
- 'ruby-mode
- '(("[^$\\?]\\(\"[^\\\"]*\\(\\\\\\(.\\|\n\\)[^\\\"]*\\)*\"\\)" 1 string)
- ("[^$\\?]\\('[^\\']*\\(\\\\\\(.\\|\n\\)[^\\']*\\)*'\\)" 1 string)
- ("[^$\\?]\\(`[^\\`]*\\(\\\\\\(.\\|\n\\)[^\\`]*\\)*`\\)" 1 string)
- ("^\\s *#.*$" nil comment)
- ("[^$@?\\]\\(#[^$@{\n].*$\\)" 1 comment)
- ("[^a-zA-Z_]\\(\\?\\(\\\\[CM]-\\)*.\\)" 1 string)
- ("^\\s *\\(require\\|load\\).*$" nil include)
- ("^\\s *\\(include\\|alias\\|undef\\).*$" nil decl)
- ("^\\s *\\<\\(class\\|def\\|module\\)\\>" "[)\n;]" defun)
- ("[^_]\\<\\(begin\\|case\\|else\\|elsif\\|end\\|ensure\\|for\\|if\\|unless\\|rescue\\|then\\|when\\|while\\|until\\|do\\|yield\\)\\>\\([^_]\\|$\\)" 1 defun)
- ("[^_]\\<\\(and\\|break\\|next\\|raise\\|fail\\|in\\|not\\|or\\|redo\\|retry\\|return\\|super\\|yield\\|catch\\|throw\\|self\\|nil\\)\\>\\([^_]\\|$\\)" 1 keyword)
- ("\\$\\(.\\|\\sw+\\)" nil type)
- ("[$@].[a-zA-Z_0-9]*" nil struct)
- ("^__END__" nil label))))
- )
-
-
-(provide 'ruby-mode)
diff --git a/misc/rubydb2x.el b/misc/rubydb2x.el
deleted file mode 100644
index a74265fb0e..0000000000
--- a/misc/rubydb2x.el
+++ /dev/null
@@ -1,104 +0,0 @@
-(require 'gud)
-(provide 'rubydb)
-
-;; ======================================================================
-;; rubydb functions
-
-;;; History of argument lists passed to rubydb.
-(defvar gud-rubydb-history nil)
-
-(defun gud-rubydb-massage-args (file args)
- (cons "-I" (cons "." (cons "-r" (cons "debug" (cons file args))))))
-
-;; There's no guarantee that Emacs will hand the filter the entire
-;; marker at once; it could be broken up across several strings. We
-;; might even receive a big chunk with several markers in it. If we
-;; receive a chunk of text which looks like it might contain the
-;; beginning of a marker, we save it here between calls to the
-;; filter.
-(defvar gud-rubydb-marker-acc "")
-
-(defun gud-rubydb-marker-filter (string)
- (save-match-data
- (setq gud-marker-acc (concat gud-marker-acc string))
- (let ((output ""))
-
- ;; Process all the complete markers in this chunk.
- (while (string-match "\032\032\\([^:\n]*\\):\\([0-9]*\\):.*\n"
- gud-marker-acc)
- (setq
-
- ;; Extract the frame position from the marker.
- gud-last-frame
- (cons (substring gud-marker-acc (match-beginning 1) (match-end 1))
- (string-to-int (substring gud-marker-acc
- (match-beginning 2)
- (match-end 2))))
-
- ;; Append any text before the marker to the output we're going
- ;; to return - we don't include the marker in this text.
- output (concat output
- (substring gud-marker-acc 0 (match-beginning 0)))
-
- ;; Set the accumulator to the remaining text.
- gud-marker-acc (substring gud-marker-acc (match-end 0))))
-
- ;; Does the remaining text look like it might end with the
- ;; beginning of another marker? If it does, then keep it in
- ;; gud-marker-acc until we receive the rest of it. Since we
- ;; know the full marker regexp above failed, it's pretty simple to
- ;; test for marker starts.
- (if (string-match "\032.*\\'" gud-marker-acc)
- (progn
- ;; Everything before the potential marker start can be output.
- (setq output (concat output (substring gud-marker-acc
- 0 (match-beginning 0))))
-
- ;; Everything after, we save, to combine with later input.
- (setq gud-marker-acc
- (substring gud-marker-acc (match-beginning 0))))
-
- (setq output (concat output gud-marker-acc)
- gud-marker-acc ""))
-
- output)))
-
-(defun gud-rubydb-find-file (f)
- (find-file-noselect f))
-
-(defvar rubydb-command-name "ruby"
- "File name for executing ruby.")
-
-;;;###autoload
-(defun rubydb (command-line)
- "Run rubydb on program FILE in buffer *gud-FILE*.
-The directory containing FILE becomes the initial working directory
-and source-file directory for your debugger."
- (interactive
- (list (read-from-minibuffer "Run rubydb (like this): "
- (if (consp gud-rubydb-history)
- (car gud-rubydb-history)
- (concat rubydb-command-name " "))
- nil nil
- '(gud-rubydb-history . 1))))
-
- (gud-overload-functions '((gud-massage-args . gud-rubydb-massage-args)
- (gud-marker-filter . gud-rubydb-marker-filter)
- (gud-find-file . gud-rubydb-find-file)
- ))
- (gud-common-init command-line)
-
- (gud-def gud-break "b %l" "\C-b" "Set breakpoint at current line.")
-; (gud-def gud-remove "clear %l" "\C-d" "Remove breakpoint at current line")
- (gud-def gud-step "s" "\C-s" "Step one source line with display.")
- (gud-def gud-next "n" "\C-n" "Step one line (skip functions).")
- (gud-def gud-cont "c" "\C-r" "Continue with display.")
- (gud-def gud-finish "finish" "\C-f" "Finish executing current function.")
- (gud-def gud-up "up %p" "<" "Up N stack frames (numeric arg).")
- (gud-def gud-down "down %p" ">" "Down N stack frames (numeric arg).")
- (gud-def gud-print "p %e" "\C-p" "Evaluate ruby expression at point.")
-
- (setq comint-prompt-regexp "^(rdb:-) ")
- (setq paragraph-start comint-prompt-regexp)
- (run-hooks 'rubydb-mode-hook)
- )
diff --git a/misc/rubydb3x.el b/misc/rubydb3x.el
deleted file mode 100644
index 98ce1a1978..0000000000
--- a/misc/rubydb3x.el
+++ /dev/null
@@ -1,115 +0,0 @@
-(require 'gud)
-(provide 'rubydb)
-
-;; ======================================================================
-;; rubydb functions
-
-;;; History of argument lists passed to rubydb.
-(defvar gud-rubydb-history nil)
-
-(if (fboundp 'gud-overload-functions)
- (defun gud-rubydb-massage-args (file args)
- (cons "-r" (cons "debug" (cons file args))))
- (defun gud-rubydb-massage-args (file args)
- (cons "-r" (cons "debug" args))))
-
-;; There's no guarantee that Emacs will hand the filter the entire
-;; marker at once; it could be broken up across several strings. We
-;; might even receive a big chunk with several markers in it. If we
-;; receive a chunk of text which looks like it might contain the
-;; beginning of a marker, we save it here between calls to the
-;; filter.
-(defvar gud-rubydb-marker-acc "")
-(make-variable-buffer-local 'gud-rubydb-marker-acc)
-
-(defun gud-rubydb-marker-filter (string)
- (setq gud-rubydb-marker-acc (concat gud-rubydb-marker-acc string))
- (let ((output ""))
-
- ;; Process all the complete markers in this chunk.
- (while (string-match "\032\032\\([^:\n]*\\):\\([0-9]*\\):.*\n"
- gud-rubydb-marker-acc)
- (setq
-
- ;; Extract the frame position from the marker.
- gud-last-frame
- (cons (substring gud-rubydb-marker-acc (match-beginning 1) (match-end 1))
- (string-to-int (substring gud-rubydb-marker-acc
- (match-beginning 2)
- (match-end 2))))
-
- ;; Append any text before the marker to the output we're going
- ;; to return - we don't include the marker in this text.
- output (concat output
- (substring gud-rubydb-marker-acc 0 (match-beginning 0)))
-
- ;; Set the accumulator to the remaining text.
- gud-rubydb-marker-acc (substring gud-rubydb-marker-acc (match-end 0))))
-
- ;; Does the remaining text look like it might end with the
- ;; beginning of another marker? If it does, then keep it in
- ;; gud-rubydb-marker-acc until we receive the rest of it. Since we
- ;; know the full marker regexp above failed, it's pretty simple to
- ;; test for marker starts.
- (if (string-match "\032.*\\'" gud-rubydb-marker-acc)
- (progn
- ;; Everything before the potential marker start can be output.
- (setq output (concat output (substring gud-rubydb-marker-acc
- 0 (match-beginning 0))))
-
- ;; Everything after, we save, to combine with later input.
- (setq gud-rubydb-marker-acc
- (substring gud-rubydb-marker-acc (match-beginning 0))))
-
- (setq output (concat output gud-rubydb-marker-acc)
- gud-rubydb-marker-acc ""))
-
- output))
-
-(defun gud-rubydb-find-file (f)
- (save-excursion
- (let ((buf (find-file-noselect f)))
- (set-buffer buf)
-;; (gud-make-debug-menu)
- buf)))
-
-(defvar rubydb-command-name "ruby"
- "File name for executing ruby.")
-
-;;;###autoload
-(defun rubydb (command-line)
- "Run rubydb on program FILE in buffer *gud-FILE*.
-The directory containing FILE becomes the initial working directory
-and source-file directory for your debugger."
- (interactive
- (list (read-from-minibuffer "Run rubydb (like this): "
- (if (consp gud-rubydb-history)
- (car gud-rubydb-history)
- (concat rubydb-command-name " "))
- nil nil
- '(gud-rubydb-history . 1))))
-
- (if (not (fboundp 'gud-overload-functions))
- (gud-common-init command-line 'gud-rubydb-massage-args
- 'gud-rubydb-marker-filter 'gud-rubydb-find-file)
- (gud-overload-functions '((gud-massage-args . gud-rubydb-massage-args)
- (gud-marker-filter . gud-rubydb-marker-filter)
- (gud-find-file . gud-rubydb-find-file)))
- (gud-common-init command-line rubydb-command-name))
-
- (gud-def gud-break "b %l" "\C-b" "Set breakpoint at current line.")
-; (gud-def gud-remove "clear %l" "\C-d" "Remove breakpoint at current line")
- (gud-def gud-step "s" "\C-s" "Step one source line with display.")
- (gud-def gud-next "n" "\C-n" "Step one line (skip functions).")
- (gud-def gud-cont "c" "\C-r" "Continue with display.")
- (gud-def gud-finish "finish" "\C-f" "Finish executing current function.")
- (gud-def gud-up "up %p" "<" "Up N stack frames (numeric arg).")
- (gud-def gud-down "down %p" ">" "Down N stack frames (numeric arg).")
- (gud-def gud-print "p %e" "\C-p" "Evaluate ruby expression at point.")
-
- (setq comint-prompt-regexp "^(rdb:-) ")
- (if (boundp 'comint-last-output-start)
- (set-marker comint-last-output-start (point)))
- (set (make-local-variable 'paragraph-start) comint-prompt-regexp)
- (run-hooks 'rubydb-mode-hook)
- )
diff --git a/missing/alloca.c b/missing/alloca.c
deleted file mode 100644
index 39697f114a..0000000000
--- a/missing/alloca.c
+++ /dev/null
@@ -1,194 +0,0 @@
-/* alloca -- (mostly) portable public-domain implementation -- D A Gwyn
-
- last edit: 86/05/30 rms
- include config.h, since on VMS it renames some symbols.
- Use xmalloc instead of malloc.
-
- This implementation of the PWB library alloca() function,
- which is used to allocate space off the run-time stack so
- that it is automatically reclaimed upon procedure exit,
- was inspired by discussions with J. Q. Johnson of Cornell.
-
- It should work under any C implementation that uses an
- actual procedure stack (as opposed to a linked list of
- frames). There are some preprocessor constants that can
- be defined when compiling for your specific system, for
- improved efficiency; however, the defaults should be okay.
-
- The general concept of this implementation is to keep
- track of all alloca()-allocated blocks, and reclaim any
- that are found to be deeper in the stack than the current
- invocation. This heuristic does not reclaim storage as
- soon as it becomes invalid, but it will do so eventually.
-
- As a special case, alloca(0) reclaims storage without
- allocating any. It is a good idea to use alloca(0) in
- your main control loop, etc. to force garbage collection.
-*/
-#ifndef lint
-static char SCCSid[] = "@(#)alloca.c 1.1"; /* for the "what" utility */
-#endif
-
-#include "config.h"
-#ifdef emacs
-#ifdef static
-/* actually, only want this if static is defined as ""
- -- this is for usg, in which emacs must undefine static
- in order to make unexec workable
- */
-#ifndef STACK_DIRECTION
-you
-lose
--- must know STACK_DIRECTION at compile-time
-#endif /* STACK_DIRECTION undefined */
-#endif /* static */
-#endif /* emacs */
-
-#ifdef X3J11
-typedef void *pointer; /* generic pointer type */
-#else
-typedef char *pointer; /* generic pointer type */
-#endif /* X3J11 */
-
-#define NULL 0 /* null pointer constant */
-
-#ifdef RUBY_LIB
-#define xmalloc ruby_xmalloc
-#define xfree ruby_xfree
-#endif
-
-extern void xfree();
-extern pointer xmalloc();
-
-/*
- Define STACK_DIRECTION if you know the direction of stack
- growth for your system; otherwise it will be automatically
- deduced at run-time.
-
- STACK_DIRECTION > 0 => grows toward higher addresses
- STACK_DIRECTION < 0 => grows toward lower addresses
- STACK_DIRECTION = 0 => direction of growth unknown
-*/
-
-#ifndef STACK_DIRECTION
-#define STACK_DIRECTION 0 /* direction unknown */
-#endif
-
-#if STACK_DIRECTION != 0
-
-#define STACK_DIR STACK_DIRECTION /* known at compile-time */
-
-#else /* STACK_DIRECTION == 0; need run-time code */
-
-static int stack_dir; /* 1 or -1 once known */
-#define STACK_DIR stack_dir
-
-static void
-find_stack_direction (/* void */)
-{
- static char *addr = NULL; /* address of first
- `dummy', once known */
- auto char dummy; /* to get stack address */
-
- if (addr == NULL)
- { /* initial entry */
- addr = &dummy;
-
- find_stack_direction (); /* recurse once */
- }
- else /* second entry */
- if (&dummy > addr)
- stack_dir = 1; /* stack grew upward */
- else
- stack_dir = -1; /* stack grew downward */
-}
-
-#endif /* STACK_DIRECTION == 0 */
-
-/*
- An "alloca header" is used to:
- (a) chain together all alloca()ed blocks;
- (b) keep track of stack depth.
-
- It is very important that sizeof(header) agree with malloc()
- alignment chunk size. The following default should work okay.
-*/
-
-#ifndef ALIGN_SIZE
-#define ALIGN_SIZE sizeof(double)
-#endif
-
-typedef union hdr
-{
- char align[ALIGN_SIZE]; /* to force sizeof(header) */
- struct
- {
- union hdr *next; /* for chaining headers */
- char *deep; /* for stack depth measure */
- } h;
-} header;
-
-/*
- alloca( size ) returns a pointer to at least `size' bytes of
- storage which will be automatically reclaimed upon exit from
- the procedure that called alloca(). Originally, this space
- was supposed to be taken from the current stack frame of the
- caller, but that method cannot be made to work for some
- implementations of C, for example under Gould's UTX/32.
-*/
-
-static header *last_alloca_header = NULL; /* -> last alloca header */
-
-pointer
-alloca (size) /* returns pointer to storage */
- unsigned size; /* # bytes to allocate */
-{
- auto char probe; /* probes stack depth: */
- register char *depth = &probe;
-
-#if STACK_DIRECTION == 0
- if (STACK_DIR == 0) /* unknown growth direction */
- find_stack_direction ();
-#endif
-
- /* Reclaim garbage, defined as all alloca()ed storage that
- was allocated from deeper in the stack than currently. */
- {
- register header *hp; /* traverses linked list */
-
- for (hp = last_alloca_header; hp != NULL;)
- if (STACK_DIR > 0 && hp->h.deep > depth
- || STACK_DIR < 0 && hp->h.deep < depth)
- {
- register header *np = hp->h.next;
-
- xfree ((pointer) hp); /* collect garbage */
-
- hp = np; /* -> next header */
- }
- else
- break; /* rest are not deeper */
-
- last_alloca_header = hp; /* -> last valid storage */
- }
-
- if (size == 0)
- return NULL; /* no allocation required */
-
- /* Allocate combined header + user data storage. */
-
- {
- register pointer new = xmalloc (sizeof (header) + size);
- /* address of header */
-
- ((header *)new)->h.next = last_alloca_header;
- ((header *)new)->h.deep = depth;
-
- last_alloca_header = (header *)new;
-
- /* User storage begins just after header. */
-
- return (pointer)((char *)new + sizeof(header));
- }
-}
-
diff --git a/missing/crypt.c b/missing/crypt.c
deleted file mode 100644
index 9f9b562c36..0000000000
--- a/missing/crypt.c
+++ /dev/null
@@ -1,276 +0,0 @@
-/* From Andy Tanenbaum's book "Computer Networks",
- rewritten in C
-*/
-
-struct block {
- unsigned char b_data[64];
-};
-
-struct ordering {
- unsigned char o_data[64];
-};
-
-static struct block key;
-
-static struct ordering InitialTr = {
- 58,50,42,34,26,18,10, 2,60,52,44,36,28,20,12, 4,
- 62,54,46,38,30,22,14, 6,64,56,48,40,32,24,16, 8,
- 57,49,41,33,25,17, 9, 1,59,51,43,35,27,19,11, 3,
- 61,53,45,37,29,21,13, 5,63,55,47,39,31,23,15, 7,
-};
-
-static struct ordering FinalTr = {
- 40, 8,48,16,56,24,64,32,39, 7,47,15,55,23,63,31,
- 38, 6,46,14,54,22,62,30,37, 5,45,13,53,21,61,29,
- 36, 4,44,12,52,20,60,28,35, 3,43,11,51,19,59,27,
- 34, 2,42,10,50,18,58,26,33, 1,41, 9,49,17,57,25,
-};
-
-static struct ordering swap = {
- 33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,
- 49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,
- 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,
- 17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,
-};
-
-static struct ordering KeyTr1 = {
- 57,49,41,33,25,17, 9, 1,58,50,42,34,26,18,
- 10, 2,59,51,43,35,27,19,11, 3,60,52,44,36,
- 63,55,47,39,31,23,15, 7,62,54,46,38,30,22,
- 14, 6,61,53,45,37,29,21,13, 5,28,20,12, 4,
-};
-
-static struct ordering KeyTr2 = {
- 14,17,11,24, 1, 5, 3,28,15, 6,21,10,
- 23,19,12, 4,26, 8,16, 7,27,20,13, 2,
- 41,52,31,37,47,55,30,40,51,45,33,48,
- 44,49,39,56,34,53,46,42,50,36,29,32,
-};
-
-static struct ordering etr = {
- 32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9,
- 8, 9,10,11,12,13,12,13,14,15,16,17,
- 16,17,18,19,20,21,20,21,22,23,24,25,
- 24,25,26,27,28,29,28,29,30,31,32, 1,
-};
-
-static struct ordering ptr = {
- 16, 7,20,21,29,12,28,17, 1,15,23,26, 5,18,31,10,
- 2, 8,24,14,32,27, 3, 9,19,13,30, 6,22,11, 4,25,
-};
-
-static unsigned char s_boxes[8][64] = {
-{ 14, 4,13, 1, 2,15,11, 8, 3,10, 6,12, 5, 9, 0, 7,
- 0,15, 7, 4,14, 2,13, 1,10, 6,12,11, 9, 5, 3, 8,
- 4, 1,14, 8,13, 6, 2,11,15,12, 9, 7, 3,10, 5, 0,
- 15,12, 8, 2, 4, 9, 1, 7, 5,11, 3,14,10, 0, 6,13,
-},
-
-{ 15, 1, 8,14, 6,11, 3, 4, 9, 7, 2,13,12, 0, 5,10,
- 3,13, 4, 7,15, 2, 8,14,12, 0, 1,10, 6, 9,11, 5,
- 0,14, 7,11,10, 4,13, 1, 5, 8,12, 6, 9, 3, 2,15,
- 13, 8,10, 1, 3,15, 4, 2,11, 6, 7,12, 0, 5,14, 9,
-},
-
-{ 10, 0, 9,14, 6, 3,15, 5, 1,13,12, 7,11, 4, 2, 8,
- 13, 7, 0, 9, 3, 4, 6,10, 2, 8, 5,14,12,11,15, 1,
- 13, 6, 4, 9, 8,15, 3, 0,11, 1, 2,12, 5,10,14, 7,
- 1,10,13, 0, 6, 9, 8, 7, 4,15,14, 3,11, 5, 2,12,
-},
-
-{ 7,13,14, 3, 0, 6, 9,10, 1, 2, 8, 5,11,12, 4,15,
- 13, 8,11, 5, 6,15, 0, 3, 4, 7, 2,12, 1,10,14, 9,
- 10, 6, 9, 0,12,11, 7,13,15, 1, 3,14, 5, 2, 8, 4,
- 3,15, 0, 6,10, 1,13, 8, 9, 4, 5,11,12, 7, 2,14,
-},
-
-{ 2,12, 4, 1, 7,10,11, 6, 8, 5, 3,15,13, 0,14, 9,
- 14,11, 2,12, 4, 7,13, 1, 5, 0,15,10, 3, 9, 8, 6,
- 4, 2, 1,11,10,13, 7, 8,15, 9,12, 5, 6, 3, 0,14,
- 11, 8,12, 7, 1,14, 2,13, 6,15, 0, 9,10, 4, 5, 3,
-},
-
-{ 12, 1,10,15, 9, 2, 6, 8, 0,13, 3, 4,14, 7, 5,11,
- 10,15, 4, 2, 7,12, 9, 5, 6, 1,13,14, 0,11, 3, 8,
- 9,14,15, 5, 2, 8,12, 3, 7, 0, 4,10, 1,13,11, 6,
- 4, 3, 2,12, 9, 5,15,10,11,14, 1, 7, 6, 0, 8,13,
-},
-
-{ 4,11, 2,14,15, 0, 8,13, 3,12, 9, 7, 5,10, 6, 1,
- 13, 0,11, 7, 4, 9, 1,10,14, 3, 5,12, 2,15, 8, 6,
- 1, 4,11,13,12, 3, 7,14,10,15, 6, 8, 0, 5, 9, 2,
- 6,11,13, 8, 1, 4,10, 7, 9, 5, 0,15,14, 2, 3,12,
-},
-
-{ 13, 2, 8, 4, 6,15,11, 1,10, 9, 3,14, 5, 0,12, 7,
- 1,15,13, 8,10, 3, 7, 4,12, 5, 6,11, 0,14, 9, 2,
- 7,11, 4, 1, 9,12,14, 2, 0, 6,10,13,15, 3, 5, 8,
- 2, 1,14, 7, 4,10, 8,13,15,12, 9, 0, 3, 5, 6,11,
-},
-};
-
-static int rots[] = {
- 1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1,
-};
-
-static void transpose(struct block *data, struct ordering *t, int n)
-{
- struct block x;
-
- x = *data;
-
- while (n-- > 0) {
- data->b_data[n] = x.b_data[t->o_data[n] - 1];
- }
-}
-
-static void rotate(struct block *key)
-{
- register unsigned char *p = key->b_data;
- register unsigned char *ep = &(key->b_data[55]);
- int data0 = key->b_data[0], data28 = key->b_data[28];
-
- while (p++ < ep) *(p-1) = *p;
- key->b_data[27] = (char) data0;
- key->b_data[55] = (char) data28;
-}
-
-static struct ordering *EP = &etr;
-
-static void f(int i, struct block *key, struct block *a, struct block *x)
-{
- struct block e, ikey, y;
- int k;
- register unsigned char *p, *q, *r;
-
- e = *a;
- transpose(&e, EP, 48);
- for (k = rots[i]; k; k--) rotate(key);
- ikey = *key;
- transpose(&ikey, &KeyTr2, 48);
- p = &(y.b_data[48]);
- q = &(e.b_data[48]);
- r = &(ikey.b_data[48]);
- while (p > y.b_data) {
- *--p = *--q ^ *--r;
- }
- q = x->b_data;
- for (k = 0; k < 8; k++) {
- register int xb, r;
-
- r = *p++ << 5;
- r += *p++ << 3;
- r += *p++ << 2;
- r += *p++ << 1;
- r += *p++;
- r += *p++ << 4;
-
- xb = s_boxes[k][r];
-
- *q++ = (char) (xb >> 3) & 1;
- *q++ = (char) (xb>>2) & 1;
- *q++ = (char) (xb>>1) & 1;
- *q++ = (char) (xb & 1);
- }
- transpose(x, &ptr, 32);
-}
-
-void definekey(char *k)
-{
-
- key = *((struct block *) k);
- transpose(&key, &KeyTr1, 56);
-}
-
-void encrypt(char *blck, int edflag)
-{
- register struct block *p = (struct block *) blck;
- register int i;
-
- transpose(p, &InitialTr, 64);
- for (i = 15; i>= 0; i--) {
- int j = edflag ? i : 15 - i;
- register int k;
- struct block b, x;
-
- b = *p;
- for (k = 31; k >= 0; k--) {
- p->b_data[k] = b.b_data[k + 32];
- }
- f(j, &key, p, &x);
- for (k = 31; k >= 0; k--) {
- p->b_data[k+32] = b.b_data[k] ^ x.b_data[k];
- }
- }
- transpose(p, &swap, 64);
- transpose(p, &FinalTr, 64);
-}
-
-char *crypt(char *pw, char *salt)
-{
-
- char pwb[66];
- static char result[16];
- register char *p = pwb;
- struct ordering new_etr;
- register int i;
-
- while (*pw && p < &pwb[64]) {
- register int j = 7;
-
- while (j--) {
- *p++ = (*pw >> j) & 01;
- }
- pw++;
- *p++ = 0;
- }
- while (p < &pwb[64]) *p++ = 0;
-
- definekey(p = pwb);
-
- while (p < &pwb[66]) *p++ = 0;
-
- new_etr = etr;
- EP = &new_etr;
- for (i = 0; i < 2; i++) {
- register char c = *salt++;
- register int j;
-
- result[i] = c;
- if ( c > 'Z') c -= 6 + 7 + '.'; /* c was a lower case letter */
- else if ( c > '9') c -= 7 + '.';/* c was upper case letter */
- else c -= '.'; /* c was digit, '.' or '/'. */
- /* now, 0 <= c <= 63 */
- for (j = 0; j < 6; j++) {
- if ((c >> j) & 01) {
- int t = 6*i + j;
- int temp = new_etr.o_data[t];
- new_etr.o_data[t] = new_etr.o_data[t+24];
- new_etr.o_data[t+24] = (char) temp;
- }
- }
- }
-
- if (result[1] == 0) result[1] = result[0];
-
- for (i = 0; i < 25; i++) encrypt(pwb,0);
- EP = &etr;
-
- p = pwb;
- pw = result+2;
- while (p < &pwb[66]) {
- register int c = 0;
- register int j = 6;
-
- while (j--) {
- c <<= 1;
- c |= *p++;
- }
- c += '.'; /* becomes >= '.' */
- if (c > '9') c += 7; /* not in [./0-9], becomes upper */
- if (c > 'Z') c += 6; /* not in [A-Z], becomes lower */
- *pw++ = (char) c;
- }
- *pw = 0;
- return result;
-}
diff --git a/missing/dup2.c b/missing/dup2.c
deleted file mode 100644
index e7cc46f4c1..0000000000
--- a/missing/dup2.c
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Public domain dup2() lookalike
- * by Curtis Jackson @ AT&T Technologies, Burlington, NC
- * electronic address: burl!rcj
- *
- * dup2 performs the following functions:
- *
- * Check to make sure that fd1 is a valid open file descriptor.
- * Check to see if fd2 is already open; if so, close it.
- * Duplicate fd1 onto fd2; checking to make sure fd2 is a valid fd.
- * Return fd2 if all went well; return BADEXIT otherwise.
- */
-
-#include "config.h"
-
-#if defined(HAVE_FCNTL)
-# include <fcntl.h>
-#endif
-
-#if !defined(HAVE_FCNTL) || !defined(F_DUPFD)
-# include <errno.h>
-#endif
-
-#define BADEXIT -1
-
-int
-dup2(fd1, fd2)
-int fd1, fd2;
-{
-#if defined(HAVE_FCNTL) && defined(F_DUPFD)
- if (fd1 != fd2) {
-#ifdef F_GETFL
- if (fcntl(fd1, F_GETFL) < 0)
- return BADEXIT;
- if (fcntl(fd2, F_GETFL) >= 0)
- close(fd2);
-#else
- close(fd2);
-#endif
- if (fcntl(fd1, F_DUPFD, fd2) < 0)
- return BADEXIT;
- }
- return fd2;
-#else
- extern int errno;
- int i, fd, fds[256];
-
- if (fd1 == fd2) return 0;
- close(fd2);
- for (i=0; i<256; i++) {
- fd = fds[i] = dup(fd1);
- if (fd == fd2) break;
- }
- while (i) {
- close(fds[i--]);
- }
- if (fd == fd2) return 0;
- errno = EMFILE;
- return BADEXIT;
-#endif
-}
diff --git a/missing/file.h b/missing/file.h
deleted file mode 100644
index 2d491d0fc1..0000000000
--- a/missing/file.h
+++ /dev/null
@@ -1,22 +0,0 @@
-/* This is file FILE.H */
-
-#ifndef _FILE_H_
-#define _FILE_H_
-
-#include <fcntl.h>
-
-#ifndef L_SET
-# define L_SET 0 /* seek from beginning. */
-# define L_CURR 1 /* seek from current position. */
-# define L_INCR 1 /* ditto. */
-# define L_XTND 2 /* seek from end. */
-#endif
-
-#ifndef R_OK
-# define R_OK 4 /* test whether readable. */
-# define W_OK 2 /* test whether writable. */
-# define X_OK 1 /* test whether execubale. */
-# define F_OK 0 /* test whether exist. */
-#endif
-
-#endif
diff --git a/missing/fileblocks.c b/missing/fileblocks.c
deleted file mode 100644
index ccb8d667b4..0000000000
--- a/missing/fileblocks.c
+++ /dev/null
@@ -1 +0,0 @@
-/* dummy for autoconf */
diff --git a/missing/finite.c b/missing/finite.c
deleted file mode 100644
index f91035a8cd..0000000000
--- a/missing/finite.c
+++ /dev/null
@@ -1,8 +0,0 @@
-/* public domain rewrite of finite(3) */
-
-int
-finite(n)
- double n;
-{
- return !isnan(n) && !isinf(n);
-}
diff --git a/missing/flock.c b/missing/flock.c
deleted file mode 100644
index c828fcc7ad..0000000000
--- a/missing/flock.c
+++ /dev/null
@@ -1,134 +0,0 @@
-#include "config.h"
-
-#if defined HAVE_FCNTL && defined HAVE_FCNTL_H
-
-/* These are the flock() constants. Since this sytems doesn't have
- flock(), the values of the constants are probably not available.
-*/
-# ifndef LOCK_SH
-# define LOCK_SH 1
-# endif
-# ifndef LOCK_EX
-# define LOCK_EX 2
-# endif
-# ifndef LOCK_NB
-# define LOCK_NB 4
-# endif
-# ifndef LOCK_UN
-# define LOCK_UN 8
-# endif
-
-#include <fcntl.h>
-#include <unistd.h>
-#include <errno.h>
-
-int
-flock(fd, operation)
- int fd;
- int operation;
-{
- struct flock lock;
-
- switch (operation & ~LOCK_NB) {
- case LOCK_SH:
- lock.l_type = F_RDLCK;
- break;
- case LOCK_EX:
- lock.l_type = F_WRLCK;
- break;
- case LOCK_UN:
- lock.l_type = F_UNLCK;
- break;
- default:
- errno = EINVAL;
- return -1;
- }
- lock.l_whence = SEEK_SET;
- lock.l_start = lock.l_len = 0L;
-
- return fcntl(fd, (operation & LOCK_NB) ? F_SETLK : F_SETLKW, &lock);
-}
-
-#elif defined(HAVE_LOCKF)
-
-#include <unistd.h>
-#include <errno.h>
-
-/* Emulate flock() with lockf() or fcntl(). This is just to increase
- portability of scripts. The calls might not be completely
- interchangeable. What's really needed is a good file
- locking module.
-*/
-
-# ifndef F_ULOCK
-# define F_ULOCK 0 /* Unlock a previously locked region */
-# endif
-# ifndef F_LOCK
-# define F_LOCK 1 /* Lock a region for exclusive use */
-# endif
-# ifndef F_TLOCK
-# define F_TLOCK 2 /* Test and lock a region for exclusive use */
-# endif
-# ifndef F_TEST
-# define F_TEST 3 /* Test a region for other processes locks */
-# endif
-
-/* These are the flock() constants. Since this sytems doesn't have
- flock(), the values of the constants are probably not available.
-*/
-# ifndef LOCK_SH
-# define LOCK_SH 1
-# endif
-# ifndef LOCK_EX
-# define LOCK_EX 2
-# endif
-# ifndef LOCK_NB
-# define LOCK_NB 4
-# endif
-# ifndef LOCK_UN
-# define LOCK_UN 8
-# endif
-
-int
-flock(fd, operation)
- int fd;
- int operation;
-{
- switch (operation) {
-
- /* LOCK_SH - get a shared lock */
- case LOCK_SH:
- rb_notimplement();
- return -1;
- /* LOCK_EX - get an exclusive lock */
- case LOCK_EX:
- return lockf (fd, F_LOCK, 0);
-
- /* LOCK_SH|LOCK_NB - get a non-blocking shared lock */
- case LOCK_SH|LOCK_NB:
- rb_notimplement();
- return -1;
- /* LOCK_EX|LOCK_NB - get a non-blocking exclusive lock */
- case LOCK_EX|LOCK_NB:
- return lockf (fd, F_TLOCK, 0);
-
- /* LOCK_UN - unlock */
- case LOCK_UN:
- return lockf (fd, F_ULOCK, 0);
-
- /* Default - can't decipher operation */
- default:
- errno = EINVAL;
- return -1;
- }
-}
-#elif !defined NT
-int
-flock(fd, operation)
- int fd;
- int operation;
-{
- rb_notimplement();
- return -1;
-}
-#endif
diff --git a/missing/hypot.c b/missing/hypot.c
deleted file mode 100644
index aad5259e92..0000000000
--- a/missing/hypot.c
+++ /dev/null
@@ -1,17 +0,0 @@
-/* public domain rewrite of hypot */
-
-#include <math.h>
-
-double hypot(x,y)
- double x, y;
-{
- if (x < 0) x = -x;
- if (y < 0) y = -y;
- if (x < y) {
- double tmp = x;
- x = y; y = tmp;
- }
- if (y == 0.0) return x;
- y /= x;
- return x * sqrt(1.0+y*y);
-}
diff --git a/missing/isinf.c b/missing/isinf.c
deleted file mode 100644
index 38772ba4f1..0000000000
--- a/missing/isinf.c
+++ /dev/null
@@ -1,46 +0,0 @@
-/* public domain rewrite of isinf(3) */
-
-#ifdef __osf__
-
-#define _IEEE 1
-#include <nan.h>
-
-int
-isinf(n)
- double n;
-{
- if (IsNANorINF(n) && IsINF(n)) {
- return 1;
- } else {
- return 0;
- }
-}
-
-#else
-
-#include "config.h"
-#ifdef HAVE_STRING_H
-# include <string.h>
-#else
-# include <strings.h>
-#endif
-
-static double zero() { return 0.0; }
-static double one() { return 1.0; }
-static double inf() { return one() / zero(); }
-
-int
-isinf(n)
- double n;
-{
- static double pinf = 0.0;
- static double ninf = 0.0;
-
- if (pinf == 0.0) {
- pinf = inf();
- ninf = -pinf;
- }
- return memcmp(&n, &pinf, sizeof n) == 0
- || memcmp(&n, &ninf, sizeof n) == 0;
-}
-#endif
diff --git a/missing/isnan.c b/missing/isnan.c
deleted file mode 100644
index df424c2e61..0000000000
--- a/missing/isnan.c
+++ /dev/null
@@ -1,31 +0,0 @@
-/* public domain rewrite of isnan(3) */
-
-#ifdef _MSC_VER
-
-#include <float.h>
-int
-isnan(n)
- double n;
-{
- return _isnan(n);
-}
-
-#else
-
-static int double_ne();
-
-int
-isnan(n)
- double n;
-{
- return double_ne(n, n);
-}
-
-static
-int
-double_ne(n1, n2)
- double n1, n2;
-{
- return n1 != n2;
-}
-#endif
diff --git a/missing/memcmp.c b/missing/memcmp.c
deleted file mode 100644
index 9edc9c13b9..0000000000
--- a/missing/memcmp.c
+++ /dev/null
@@ -1,18 +0,0 @@
-/* public domain rewrite of memcmp(3) */
-
-int
-memcmp(s1,s2,len)
- char *s1;
- char *s2;
- register int len;
-{
- register unsigned char *a = (unsigned char*)s1;
- register unsigned char *b = (unsigned char*)s2;
- register int tmp;
-
- while (len--) {
- if (tmp = *a++ - *b++)
- return tmp;
- }
- return 0;
-}
diff --git a/missing/memmove.c b/missing/memmove.c
deleted file mode 100644
index 7961c5c0e6..0000000000
--- a/missing/memmove.c
+++ /dev/null
@@ -1,20 +0,0 @@
-/* public domain rewrite of memcmp(3) */
-
-char *
-memmove (dst, src, n)
- char *dst, *src;
- int n;
-{
- char *ret = dst;
-
- if (src < dst) {
- src += n;
- dst += n;
- while (n--)
- *--dst = *--src;
- }
- else if (dst < src)
- while (n--)
- *dst++ = *src++;
- return ret;
-}
diff --git a/missing/mkdir.c b/missing/mkdir.c
deleted file mode 100644
index ed1476db9a..0000000000
--- a/missing/mkdir.c
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Written by Robert Rother, Mariah Corporation, August 1985.
- *
- * If you want it, it's yours. All I ask in return is that if you
- * figure out how to do this in a Bourne Shell script you send me
- * a copy.
- * sdcsvax!rmr or rmr@uscd
- *
- * Severely hacked over by John Gilmore to make a 4.2BSD compatible
- * subroutine. 11Mar86; hoptoad!gnu
- *
- * Modified by rmtodd@uokmax 6-28-87 -- when making an already existing dir,
- * subroutine didn't return EEXIST. It does now.
- */
-
-#include <sys/stat.h>
-#include <errno.h>
-/*
- * Make a directory.
- */
-int
-mkdir (dpath, dmode)
- char *dpath;
- int dmode;
-{
- int cpid, status;
- struct stat statbuf;
-
- if (stat (dpath, &statbuf) == 0)
- {
- errno = EEXIST; /* Stat worked, so it already exists */
- return -1;
- }
-
- /* If stat fails for a reason other than non-existence, return error */
- if (errno != ENOENT)
- return -1;
-
- switch (cpid = fork ())
- {
-
- case -1: /* Error in fork() */
- return (-1); /* Errno is set already */
-
- case 0: /* Child process */
- /*
- * Cheap hack to set mode of new directory. Since this
- * child process is going away anyway, we zap its umask.
- * FIXME, this won't suffice to set SUID, SGID, etc. on this
- * directory. Does anybody care?
- */
- status = umask (0); /* Get current umask */
- status = umask (status | (0777 & ~dmode)); /* Set for mkdir */
- execl ("/bin/mkdir", "mkdir", dpath, (char *) 0);
- _exit (-1); /* Can't exec /bin/mkdir */
-
- default: /* Parent process */
- while (cpid != wait (&status)); /* Wait for kid to finish */
- }
-
- if (WIFSIGNALED (status) || WEXITSTATUS (status) != 0)
- {
- errno = EIO; /* We don't know why, but */
- return -1; /* /bin/mkdir failed */
- }
-
- return 0;
-}
-
-int
-rmdir (dpath)
- char *dpath;
-{
- int cpid, status;
- struct stat statbuf;
-
- if (stat (dpath, &statbuf) != 0)
- {
- /* Stat just set errno. We don't have to */
- return -1;
- }
-
- switch (cpid = fork ())
- {
-
- case -1: /* Error in fork() */
- return (-1); /* Errno is set already */
-
- case 0: /* Child process */
- execl ("/bin/rmdir", "rmdir", dpath, (char *) 0);
- _exit (-1); /* Can't exec /bin/mkdir */
-
- default: /* Parent process */
- while (cpid != wait (&status)); /* Wait for kid to finish */
- }
-
- if (WIFSIGNALED (status) || WEXITSTATUS (status) != 0)
- {
- errno = EIO; /* We don't know why, but */
- return -1; /* /bin/rmdir failed */
- }
-
- return 0;
-}
diff --git a/missing/os2.c b/missing/os2.c
deleted file mode 100644
index 57798ab54c..0000000000
--- a/missing/os2.c
+++ /dev/null
@@ -1,113 +0,0 @@
-/* os/2 compatibility functions -- follows Ruby's lisence */
-
-#include "ruby.h"
-#include <stdio.h>
-#include <stdlib.h>
-#include <fcntl.h>
-#include <process.h>
-#include <limits.h>
-#include <errno.h>
-
-#define INCL_DOS
-#include <os2.h>
-
-int
-chown(char *path, int owner, int group)
-{
- return 0;
-}
-
-int
-link(char *from, char *to)
-{
- return -1;
-}
-
-typedef char* CHARP;
-
-int
-do_spawn(cmd)
-char *cmd;
-{
- register char **a;
- register char *s;
- char **argv;
- char *shell, *sw, *cmd2;
- int status;
-
- if ((shell = getenv("RUBYSHELL")) != NULL && *shell != '\0') {
- s = shell;
- do
- *s = isupper(*s) ? tolower(*s) : *s;
- while (*++s);
- if (strstr(shell, "cmd") || strstr(shell, "4os2"))
- sw = "/c";
- else
- sw = "-c";
- } else if ((shell = getenv("SHELL")) != NULL && *shell != '\0') {
- s = shell;
- do
- *s = isupper(*s) ? tolower(*s) : *s;
- while (*++s);
- if (strstr(shell, "cmd") || strstr(shell, "4os2"))
- sw = "/c";
- else
- sw = "-c";
- } else if ((shell = getenv("COMSPEC")) != NULL && *shell != '\0') {
- s = shell;
- do
- *s = isupper(*s) ? tolower(*s) : *s;
- while (*++s);
- if (strstr(shell, "cmd") || strstr(shell, "4os2"))
- sw = "/c";
- else
- sw = "-c";
- }
- /* see if there are shell metacharacters in it */
- /*SUPPRESS 530*/
- /* for (s = cmd; *s && isalpha(*s); s++) ;
- if (*s == '=')
- goto doshell; */
- for (s = cmd; *s; s++) {
- if (*sw == '-' && *s != ' ' &&
- !isalpha(*s) && index("$&*(){}[]'\";\\|?<>~`\n",*s)) {
- if (*s == '\n' && !s[1]) {
- *s = '\0';
- break;
- }
- goto doshell;
- } else if (*sw == '/' && *s != ' ' &&
- !isalpha(*s) && index("^()<>|&\n",*s)) {
- if (*s == '\n' && !s[1]) {
- *s = '\0';
- break;
- }
- doshell:
- status = spawnlp(P_WAIT,shell,shell,sw,cmd,(char*)NULL);
- return status;
- }
- }
- argv = ALLOC_N(CHARP,(strlen(cmd) / 2 + 2));
- cmd2 = ALLOC_N(char, (strlen(cmd) + 1));
- strcpy(cmd2, cmd);
- a = argv;
- for (s = cmd2; *s;) {
- while (*s && isspace(*s)) s++;
- if (*s)
- *(a++) = s;
- while (*s && !isspace(*s)) s++;
- if (*s)
- *s++ = '\0';
- }
- *a = NULL;
- if (argv[0]) {
- if ((status = spawnvp(P_WAIT, argv[0], argv)) == -1) {
- free(argv);
- free(cmd2);
- return -1;
- }
- }
- free(cmd2);
- free(argv);
- return status;
-}
diff --git a/missing/strcasecmp.c b/missing/strcasecmp.c
deleted file mode 100644
index fddb8385be..0000000000
--- a/missing/strcasecmp.c
+++ /dev/null
@@ -1,16 +0,0 @@
-/* public domain rewrite of strcasecmp(3) */
-
-#include <ctype.h>
-
-int
-strcasecmp(p1, p2)
- char *p1, *p2;
-{
- while (*p1 && *p2) {
- if (toupper(*p1) != toupper(*p2))
- return toupper(*p1) - toupper(*p2);
- p1++;
- p2++;
- }
- return strlen(p1) - strlen(p2);
-}
diff --git a/missing/strchr.c b/missing/strchr.c
deleted file mode 100644
index 82f3cc96b0..0000000000
--- a/missing/strchr.c
+++ /dev/null
@@ -1,30 +0,0 @@
-/* public domain rewrite of strchr(3) and strrchr(3) */
-
-char *
-strchr(s, c)
- char *s;
- int c;
-{
- if (c == 0) return s + strlen(s);
- while (*s) {
- if (*s == c)
- return s;
- s++;
- }
- return 0;
-}
-
-char *
-strrchr(s, c)
- char *s;
- int c;
-{
- char *save = 0;
-
- while (*s) {
- if (*s == c)
- save = s;
- s++;
- }
- return save;
-}
diff --git a/missing/strerror.c b/missing/strerror.c
deleted file mode 100644
index c1bf6feff8..0000000000
--- a/missing/strerror.c
+++ /dev/null
@@ -1,17 +0,0 @@
-/* public domain rewrite of strerror(3) */
-
-extern int sys_nerr;
-extern char *sys_errlist[];
-
-static char msg[50];
-
-char *
-strerror(error)
- int error;
-{
- if (error <= sys_nerr && error > 0) {
- return sys_errlist[error];
- }
- sprintf(msg, "Unknown error (%d)", error);
- return msg;
-}
diff --git a/missing/strftime.c b/missing/strftime.c
deleted file mode 100644
index a9e0bc0757..0000000000
--- a/missing/strftime.c
+++ /dev/null
@@ -1,889 +0,0 @@
-/*
- * strftime.c
- *
- * Public-domain implementation of ANSI C library routine.
- *
- * It's written in old-style C for maximal portability.
- * However, since I'm used to prototypes, I've included them too.
- *
- * If you want stuff in the System V ascftime routine, add the SYSV_EXT define.
- * For extensions from SunOS, add SUNOS_EXT.
- * For stuff needed to implement the P1003.2 date command, add POSIX2_DATE.
- * For VMS dates, add VMS_EXT.
- * For a an RFC822 time format, add MAILHEADER_EXT.
- * For ISO week years, add ISO_DATE_EXT.
- * For complete POSIX semantics, add POSIX_SEMANTICS.
- *
- * The code for %c, %x, and %X now follows the 1003.2 specification for
- * the POSIX locale.
- * This version ignores LOCALE information.
- * It also doesn't worry about multi-byte characters.
- * So there.
- *
- * This file is also shipped with GAWK (GNU Awk), gawk specific bits of
- * code are included if GAWK is defined.
- *
- * Arnold Robbins
- * January, February, March, 1991
- * Updated March, April 1992
- * Updated April, 1993
- * Updated February, 1994
- * Updated May, 1994
- * Updated January, 1995
- * Updated September, 1995
- * Updated January, 1996
- *
- * Fixes from ado@elsie.nci.nih.gov
- * February 1991, May 1992
- * Fixes from Tor Lillqvist tml@tik.vtt.fi
- * May, 1993
- * Further fixes from ado@elsie.nci.nih.gov
- * February 1994
- * %z code from chip@chinacat.unicom.com
- * Applied September 1995
- * %V code fixed (again) and %G, %g added,
- * January 1996
- */
-
-#include "config.h"
-
-#ifndef GAWK
-#include <stdio.h>
-#include <ctype.h>
-#include <string.h>
-#include <time.h>
-#endif
-#if defined(TM_IN_SYS_TIME) || ! defined(GAWK)
-#include <sys/types.h>
-#include <sys/time.h>
-#endif
-
-/* defaults: season to taste */
-#define SYSV_EXT 1 /* stuff in System V ascftime routine */
-#define SUNOS_EXT 1 /* stuff in SunOS strftime routine */
-#define POSIX2_DATE 1 /* stuff in Posix 1003.2 date command */
-#define VMS_EXT 1 /* include %v for VMS date format */
-#define MAILHEADER_EXT 1 /* add %z for HHMM format */
-#define ISO_DATE_EXT 1 /* %G and %g for year of ISO week */
-#ifndef GAWK
-#define POSIX_SEMANTICS 1 /* call tzset() if TZ changes */
-#endif
-
-#if defined(ISO_DATE_EXT)
-#if ! defined(POSIX2_DATE)
-#define POSIX2_DATE 1
-#endif
-#endif
-
-#if defined(POSIX2_DATE)
-#if ! defined(SYSV_EXT)
-#define SYSV_EXT 1
-#endif
-#if ! defined(SUNOS_EXT)
-#define SUNOS_EXT 1
-#endif
-#endif
-
-#if defined(POSIX2_DATE)
-#define adddecl(stuff) stuff
-#else
-#define adddecl(stuff)
-#endif
-
-#undef strchr /* avoid AIX weirdness */
-
-#ifndef __STDC__
-#define const /**/
-extern void tzset();
-static int weeknumber();
-adddecl(static int iso8601wknum();)
-#else
-extern void tzset(void);
-static int weeknumber(const struct tm *timeptr, int firstweekday);
-adddecl(static int iso8601wknum(const struct tm *timeptr);)
-#endif
-
-#ifdef STDC_HEADERS
-#include <stdlib.h>
-#include <string.h>
-#else
-extern void *malloc();
-extern void *realloc();
-extern char *getenv();
-extern char *strchr();
-#endif
-
-#define range(low, item, hi) max(low, min(item, hi))
-
-#if !defined(OS2) && !defined(MSDOS) && defined(HAVE_TZNAME)
-extern char *tzname[2];
-extern int daylight;
-#ifdef SOLARIS
-extern long timezone, altzone;
-#else
-extern int timezone, altzone;
-#endif
-#endif
-
-#undef min /* just in case */
-
-/* min --- return minimum of two numbers */
-
-#ifndef __STDC__
-static inline int
-min(a, b)
-int a, b;
-#else
-static inline int
-min(int a, int b)
-#endif
-{
- return (a < b ? a : b);
-}
-
-#undef max /* also, just in case */
-
-/* max --- return maximum of two numbers */
-
-#ifndef __STDC__
-static inline int
-max(a, b)
-int a, b;
-#else
-static inline int
-max(int a, int b)
-#endif
-{
- return (a > b ? a : b);
-}
-
-/* strftime --- produce formatted time */
-
-#ifndef __STDC__
-size_t
-strftime(s, maxsize, format, timeptr)
-char *s;
-size_t maxsize;
-const char *format;
-const struct tm *timeptr;
-#else
-size_t
-strftime(char *s, size_t maxsize, const char *format, const struct tm *timeptr)
-#endif
-{
- char *endp = s + maxsize;
- char *start = s;
- auto char tbuf[100];
- long off;
- int i, w;
- long y;
- static short first = 1;
-#ifdef POSIX_SEMANTICS
- static char *savetz = NULL;
- static int savetzlen = 0;
- char *tz;
-#endif /* POSIX_SEMANTICS */
-#ifndef HAVE_TM_ZONE
-#ifndef HAVE_TM_NAME
-#ifndef HAVE_TZNAME
- extern char *timezone();
- struct timeval tv;
- struct timezone zone;
-#endif /* HAVE_TZNAME */
-#endif /* HAVE_TM_NAME */
-#endif /* HAVE_TM_ZONE */
-
- /* various tables, useful in North America */
- static const char *days_a[] = {
- "Sun", "Mon", "Tue", "Wed",
- "Thu", "Fri", "Sat",
- };
- static const char *days_l[] = {
- "Sunday", "Monday", "Tuesday", "Wednesday",
- "Thursday", "Friday", "Saturday",
- };
- static const char *months_a[] = {
- "Jan", "Feb", "Mar", "Apr", "May", "Jun",
- "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
- };
- static const char *months_l[] = {
- "January", "February", "March", "April",
- "May", "June", "July", "August", "September",
- "October", "November", "December",
- };
- static const char *ampm[] = { "AM", "PM", };
-
- if (s == NULL || format == NULL || timeptr == NULL || maxsize == 0)
- return 0;
-
- /* quick check if we even need to bother */
- if (strchr(format, '%') == NULL && strlen(format) + 1 >= maxsize)
- return 0;
-
-#ifndef POSIX_SEMANTICS
- if (first) {
- tzset();
- first = 0;
- }
-#else /* POSIX_SEMANTICS */
- tz = getenv("TZ");
- if (first) {
- if (tz != NULL) {
- int tzlen = strlen(tz);
-
- savetz = (char *) malloc(tzlen + 1);
- if (savetz != NULL) {
- savetzlen = tzlen + 1;
- strcpy(savetz, tz);
- }
- }
- tzset();
- first = 0;
- }
- /* if we have a saved TZ, and it is different, recapture and reset */
- if (tz && savetz && (tz[0] != savetz[0] || strcmp(tz, savetz) != 0)) {
- i = strlen(tz) + 1;
- if (i > savetzlen) {
- savetz = (char *) realloc(savetz, i);
- if (savetz) {
- savetzlen = i;
- strcpy(savetz, tz);
- }
- } else
- strcpy(savetz, tz);
- tzset();
- }
-#endif /* POSIX_SEMANTICS */
-
- for (; *format && s < endp - 1; format++) {
- tbuf[0] = '\0';
- if (*format != '%') {
- *s++ = *format;
- continue;
- }
- again:
- switch (*++format) {
- case '\0':
- *s++ = '%';
- goto out;
-
- case '%':
- *s++ = '%';
- continue;
-
- case 'a': /* abbreviated weekday name */
- if (timeptr->tm_wday < 0 || timeptr->tm_wday > 6)
- strcpy(tbuf, "?");
- else
- strcpy(tbuf, days_a[timeptr->tm_wday]);
- break;
-
- case 'A': /* full weekday name */
- if (timeptr->tm_wday < 0 || timeptr->tm_wday > 6)
- strcpy(tbuf, "?");
- else
- strcpy(tbuf, days_l[timeptr->tm_wday]);
- break;
-
-#ifdef SYSV_EXT
- case 'h': /* abbreviated month name */
-#endif
- case 'b': /* abbreviated month name */
- if (timeptr->tm_mon < 0 || timeptr->tm_mon > 11)
- strcpy(tbuf, "?");
- else
- strcpy(tbuf, months_a[timeptr->tm_mon]);
- break;
-
- case 'B': /* full month name */
- if (timeptr->tm_mon < 0 || timeptr->tm_mon > 11)
- strcpy(tbuf, "?");
- else
- strcpy(tbuf, months_l[timeptr->tm_mon]);
- break;
-
- case 'c': /* appropriate date and time representation */
- strftime(tbuf, sizeof tbuf, "%a %b %e %H:%M:%S %Y", timeptr);
- break;
-
- case 'd': /* day of the month, 01 - 31 */
- i = range(1, timeptr->tm_mday, 31);
- sprintf(tbuf, "%02d", i);
- break;
-
- case 'H': /* hour, 24-hour clock, 00 - 23 */
- i = range(0, timeptr->tm_hour, 23);
- sprintf(tbuf, "%02d", i);
- break;
-
- case 'I': /* hour, 12-hour clock, 01 - 12 */
- i = range(0, timeptr->tm_hour, 23);
- if (i == 0)
- i = 12;
- else if (i > 12)
- i -= 12;
- sprintf(tbuf, "%02d", i);
- break;
-
- case 'j': /* day of the year, 001 - 366 */
- sprintf(tbuf, "%03d", timeptr->tm_yday + 1);
- break;
-
- case 'm': /* month, 01 - 12 */
- i = range(0, timeptr->tm_mon, 11);
- sprintf(tbuf, "%02d", i + 1);
- break;
-
- case 'M': /* minute, 00 - 59 */
- i = range(0, timeptr->tm_min, 59);
- sprintf(tbuf, "%02d", i);
- break;
-
- case 'p': /* am or pm based on 12-hour clock */
- i = range(0, timeptr->tm_hour, 23);
- if (i < 12)
- strcpy(tbuf, ampm[0]);
- else
- strcpy(tbuf, ampm[1]);
- break;
-
- case 'S': /* second, 00 - 60 */
- i = range(0, timeptr->tm_sec, 60);
- sprintf(tbuf, "%02d", i);
- break;
-
- case 'U': /* week of year, Sunday is first day of week */
- sprintf(tbuf, "%02d", weeknumber(timeptr, 0));
- break;
-
- case 'w': /* weekday, Sunday == 0, 0 - 6 */
- i = range(0, timeptr->tm_wday, 6);
- sprintf(tbuf, "%d", i);
- break;
-
- case 'W': /* week of year, Monday is first day of week */
- sprintf(tbuf, "%02d", weeknumber(timeptr, 1));
- break;
-
- case 'x': /* appropriate date representation */
- strftime(tbuf, sizeof tbuf, "%m/%d/%y", timeptr);
- break;
-
- case 'X': /* appropriate time representation */
- strftime(tbuf, sizeof tbuf, "%H:%M:%S", timeptr);
- break;
-
- case 'y': /* year without a century, 00 - 99 */
- i = timeptr->tm_year % 100;
- sprintf(tbuf, "%02d", i);
- break;
-
- case 'Y': /* year with century */
- sprintf(tbuf, "%ld", 1900L + timeptr->tm_year);
- break;
-
-#ifdef MAILHEADER_EXT
- /*
- * From: Chip Rosenthal <chip@chinacat.unicom.com>
- * Date: Sun, 19 Mar 1995 00:33:29 -0600 (CST)
- *
- * Warning: the %z [code] is implemented by inspecting the
- * timezone name conditional compile settings, and
- * inferring a method to get timezone offsets. I've tried
- * this code on a couple of machines, but I don't doubt
- * there is some system out there that won't like it.
- * Maybe the easiest thing to do would be to bracket this
- * with an #ifdef that can turn it off. The %z feature
- * would be an admittedly obscure one that most folks can
- * live without, but it would be a great help to those of
- * us that muck around with various message processors.
- */
- case 'z': /* time zone offset east of GMT e.g. -0600 */
-#ifdef HAVE_TM_NAME
- /*
- * Systems with tm_name probably have tm_tzadj as
- * secs west of GMT. Convert to mins east of GMT.
- */
- off = -timeptr->tm_tzadj / 60;
-#else /* !HAVE_TM_NAME */
-#ifdef HAVE_TM_ZONE
- /*
- * Systems with tm_zone probably have tm_gmtoff as
- * secs east of GMT. Convert to mins east of GMT.
- */
- off = timeptr->tm_gmtoff / 60;
-#else /* !HAVE_TM_ZONE */
-#if HAVE_TZNAME
- /*
- * Systems with tzname[] probably have timezone as
- * secs west of GMT. Convert to mins east of GMT.
- */
- off = -(daylight ? timezone : altzone) / 60;
-#else /* !HAVE_TZNAME */
- gettimeofday(&tv, &zone);
- off = -zone.tz_minuteswest;
-#endif /* !HAVE_TZNAME */
-#endif /* !HAVE_TM_ZONE */
-#endif /* !HAVE_TM_NAME */
- if (off < 0) {
- tbuf[0] = '-';
- off = -off;
- } else {
- tbuf[0] = '+';
- }
- sprintf(tbuf+1, "%02d%02d", off/60, off%60);
- break;
-#endif /* MAILHEADER_EXT */
-
- case 'Z': /* time zone name or abbrevation */
-#ifdef HAVE_TZNAME
- i = (daylight && timeptr->tm_isdst > 0); /* 0 or 1 */
- strcpy(tbuf, tzname[i]);
-#else
-#ifdef HAVE_TM_ZONE
- strcpy(tbuf, timeptr->tm_zone);
-#else
-#ifdef HAVE_TM_NAME
- strcpy(tbuf, timeptr->tm_name);
-#else
- gettimeofday(& tv, & zone);
- strcpy(tbuf, timezone(zone.tz_minuteswest,
- timeptr->tm_isdst > 0));
-#endif /* HAVE_TM_NAME */
-#endif /* HAVE_TM_ZONE */
-#endif /* HAVE_TZNAME */
- break;
-
-#ifdef SYSV_EXT
- case 'n': /* same as \n */
- tbuf[0] = '\n';
- tbuf[1] = '\0';
- break;
-
- case 't': /* same as \t */
- tbuf[0] = '\t';
- tbuf[1] = '\0';
- break;
-
- case 'D': /* date as %m/%d/%y */
- strftime(tbuf, sizeof tbuf, "%m/%d/%y", timeptr);
- break;
-
- case 'e': /* day of month, blank padded */
- sprintf(tbuf, "%2d", range(1, timeptr->tm_mday, 31));
- break;
-
- case 'r': /* time as %I:%M:%S %p */
- strftime(tbuf, sizeof tbuf, "%I:%M:%S %p", timeptr);
- break;
-
- case 'R': /* time as %H:%M */
- strftime(tbuf, sizeof tbuf, "%H:%M", timeptr);
- break;
-
- case 'T': /* time as %H:%M:%S */
- strftime(tbuf, sizeof tbuf, "%H:%M:%S", timeptr);
- break;
-#endif
-
-#ifdef SUNOS_EXT
- case 'k': /* hour, 24-hour clock, blank pad */
- sprintf(tbuf, "%2d", range(0, timeptr->tm_hour, 23));
- break;
-
- case 'l': /* hour, 12-hour clock, 1 - 12, blank pad */
- i = range(0, timeptr->tm_hour, 23);
- if (i == 0)
- i = 12;
- else if (i > 12)
- i -= 12;
- sprintf(tbuf, "%2d", i);
- break;
-#endif
-
-
-#ifdef VMS_EXT
- case 'v': /* date as dd-bbb-YYYY */
- sprintf(tbuf, "%2d-%3.3s-%4ld",
- range(1, timeptr->tm_mday, 31),
- months_a[range(0, timeptr->tm_mon, 11)],
- timeptr->tm_year + 1900L);
- for (i = 3; i < 6; i++)
- if (islower(tbuf[i]))
- tbuf[i] = toupper(tbuf[i]);
- break;
-#endif
-
-
-#ifdef POSIX2_DATE
- case 'C':
- sprintf(tbuf, "%02ld", (timeptr->tm_year + 1900L) / 100);
- break;
-
-
- case 'E':
- case 'O':
- /* POSIX locale extensions, ignored for now */
- goto again;
-
- case 'V': /* week of year according ISO 8601 */
- sprintf(tbuf, "%02d", iso8601wknum(timeptr));
- break;
-
- case 'u':
- /* ISO 8601: Weekday as a decimal number [1 (Monday) - 7] */
- sprintf(tbuf, "%d", timeptr->tm_wday == 0 ? 7 :
- timeptr->tm_wday);
- break;
-#endif /* POSIX2_DATE */
-
-#ifdef ISO_DATE_EXT
- case 'G':
- case 'g':
- /*
- * Year of ISO week.
- *
- * If it's December but the ISO week number is one,
- * that week is in next year.
- * If it's January but the ISO week number is 52 or
- * 53, that week is in last year.
- * Otherwise, it's this year.
- */
- w = iso8601wknum(timeptr);
- if (timeptr->tm_mon == 11 && w == 1)
- y = 1900L + timeptr->tm_year + 1;
- else if (timeptr->tm_mon == 0 && w >= 52)
- y = 1900L + timeptr->tm_year - 1;
- else
- y = 1900L + timeptr->tm_year;
-
- if (*format == 'G')
- sprintf(tbuf, "%ld", y);
- else
- sprintf(tbuf, "%02ld", y % 100);
- break;
-#endif /* ISO_DATE_EXT */
- default:
- tbuf[0] = '%';
- tbuf[1] = *format;
- tbuf[2] = '\0';
- break;
- }
- i = strlen(tbuf);
- if (i) {
- if (s + i < endp - 1) {
- strcpy(s, tbuf);
- s += i;
- } else
- return 0;
- }
- }
-out:
- if (s < endp && *format == '\0') {
- *s = '\0';
- return (s - start);
- } else
- return 0;
-}
-
-/* isleap --- is a year a leap year? */
-
-#ifndef __STDC__
-static int
-isleap(year)
-long year;
-#else
-static int
-isleap(long year)
-#endif
-{
- return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0);
-}
-
-
-#ifdef POSIX2_DATE
-/* iso8601wknum --- compute week number according to ISO 8601 */
-
-#ifndef __STDC__
-static int
-iso8601wknum(timeptr)
-const struct tm *timeptr;
-#else
-static int
-iso8601wknum(const struct tm *timeptr)
-#endif
-{
- /*
- * From 1003.2:
- * If the week (Monday to Sunday) containing January 1
- * has four or more days in the new year, then it is week 1;
- * otherwise it is the highest numbered week of the previous
- * year (52 or 53), and the next week is week 1.
- *
- * ADR: This means if Jan 1 was Monday through Thursday,
- * it was week 1, otherwise week 52 or 53.
- *
- * XPG4 erroneously included POSIX.2 rationale text in the
- * main body of the standard. Thus it requires week 53.
- */
-
- int weeknum, jan1day, diff;
-
- /* get week number, Monday as first day of the week */
- weeknum = weeknumber(timeptr, 1);
-
- /*
- * With thanks and tip of the hatlo to tml@tik.vtt.fi
- *
- * What day of the week does January 1 fall on?
- * We know that
- * (timeptr->tm_yday - jan1.tm_yday) MOD 7 ==
- * (timeptr->tm_wday - jan1.tm_wday) MOD 7
- * and that
- * jan1.tm_yday == 0
- * and that
- * timeptr->tm_wday MOD 7 == timeptr->tm_wday
- * from which it follows that. . .
- */
- jan1day = timeptr->tm_wday - (timeptr->tm_yday % 7);
- if (jan1day < 0)
- jan1day += 7;
-
- /*
- * If Jan 1 was a Monday through Thursday, it was in
- * week 1. Otherwise it was last year's highest week, which is
- * this year's week 0.
- *
- * What does that mean?
- * If Jan 1 was Monday, the week number is exactly right, it can
- * never be 0.
- * If it was Tuesday through Thursday, the weeknumber is one
- * less than it should be, so we add one.
- * Otherwise, Friday, Saturday or Sunday, the week number is
- * OK, but if it is 0, it needs to be 52 or 53.
- */
- switch (jan1day) {
- case 1: /* Monday */
- break;
- case 2: /* Tuesday */
- case 3: /* Wednesday */
- case 4: /* Thursday */
- weeknum++;
- break;
- case 5: /* Friday */
- case 6: /* Saturday */
- case 0: /* Sunday */
- if (weeknum == 0) {
-#ifdef USE_BROKEN_XPG4
- /* XPG4 (as of March 1994) says 53 unconditionally */
- weeknum = 53;
-#else
- /* get week number of last week of last year */
- struct tm dec31ly; /* 12/31 last year */
- dec31ly = *timeptr;
- dec31ly.tm_year--;
- dec31ly.tm_mon = 11;
- dec31ly.tm_mday = 31;
- dec31ly.tm_wday = (jan1day == 0) ? 6 : jan1day - 1;
- dec31ly.tm_yday = 364 + isleap(dec31ly.tm_year + 1900L);
- weeknum = iso8601wknum(& dec31ly);
-#endif
- }
- break;
- }
-
- if (timeptr->tm_mon == 11) {
- /*
- * The last week of the year
- * can be in week 1 of next year.
- * Sigh.
- *
- * This can only happen if
- * M T W
- * 29 30 31
- * 30 31
- * 31
- */
- int wday, mday;
-
- wday = timeptr->tm_wday;
- mday = timeptr->tm_mday;
- if ( (wday == 1 && (mday >= 29 && mday <= 31))
- || (wday == 2 && (mday == 30 || mday == 31))
- || (wday == 3 && mday == 31))
- weeknum = 1;
- }
-
- return weeknum;
-}
-#endif
-
-/* weeknumber --- figure how many weeks into the year */
-
-/* With thanks and tip of the hatlo to ado@elsie.nci.nih.gov */
-
-#ifndef __STDC__
-static int
-weeknumber(timeptr, firstweekday)
-const struct tm *timeptr;
-int firstweekday;
-#else
-static int
-weeknumber(const struct tm *timeptr, int firstweekday)
-#endif
-{
- int wday = timeptr->tm_wday;
- int ret;
-
- if (firstweekday == 1) {
- if (wday == 0) /* sunday */
- wday = 6;
- else
- wday--;
- }
- ret = ((timeptr->tm_yday + 7 - wday) / 7);
- if (ret < 0)
- ret = 0;
- return ret;
-}
-
-#if 0
-/* ADR --- I'm loathe to mess with ado's code ... */
-
-Date: Wed, 24 Apr 91 20:54:08 MDT
-From: Michal Jaegermann <audfax!emory!vm.ucs.UAlberta.CA!NTOMCZAK>
-To: arnold@audiofax.com
-
-Hi Arnold,
-in a process of fixing of strftime() in libraries on Atari ST I grabbed
-some pieces of code from your own strftime. When doing that it came
-to mind that your weeknumber() function compiles a little bit nicer
-in the following form:
-/*
- * firstweekday is 0 if starting in Sunday, non-zero if in Monday
- */
-{
- return (timeptr->tm_yday - timeptr->tm_wday +
- (firstweekday ? (timeptr->tm_wday ? 8 : 1) : 7)) / 7;
-}
-How nicer it depends on a compiler, of course, but always a tiny bit.
-
- Cheers,
- Michal
- ntomczak@vm.ucs.ualberta.ca
-#endif
-
-#ifdef TEST_STRFTIME
-
-/*
- * NAME:
- * tst
- *
- * SYNOPSIS:
- * tst
- *
- * DESCRIPTION:
- * "tst" is a test driver for the function "strftime".
- *
- * OPTIONS:
- * None.
- *
- * AUTHOR:
- * Karl Vogel
- * Control Data Systems, Inc.
- * vogelke@c-17igp.wpafb.af.mil
- *
- * BUGS:
- * None noticed yet.
- *
- * COMPILE:
- * cc -o tst -DTEST_STRFTIME strftime.c
- */
-
-/* ADR: I reformatted this to my liking, and deleted some unneeded code. */
-
-#ifndef NULL
-#include <stdio.h>
-#endif
-#include <sys/time.h>
-#include <string.h>
-
-#define MAXTIME 132
-
-/*
- * Array of time formats.
- */
-
-static char *array[] =
-{
- "(%%A) full weekday name, var length (Sunday..Saturday) %A",
- "(%%B) full month name, var length (January..December) %B",
- "(%%C) Century %C",
- "(%%D) date (%%m/%%d/%%y) %D",
- "(%%E) Locale extensions (ignored) %E",
- "(%%H) hour (24-hour clock, 00..23) %H",
- "(%%I) hour (12-hour clock, 01..12) %I",
- "(%%M) minute (00..59) %M",
- "(%%O) Locale extensions (ignored) %O",
- "(%%R) time, 24-hour (%%H:%%M) %R",
- "(%%S) second (00..60) %S",
- "(%%T) time, 24-hour (%%H:%%M:%%S) %T",
- "(%%U) week of year, Sunday as first day of week (00..53) %U",
- "(%%V) week of year according to ISO 8601 %V",
- "(%%W) week of year, Monday as first day of week (00..53) %W",
- "(%%X) appropriate locale time representation (%H:%M:%S) %X",
- "(%%Y) year with century (1970...) %Y",
- "(%%Z) timezone (EDT), or blank if timezone not determinable %Z",
- "(%%a) locale's abbreviated weekday name (Sun..Sat) %a",
- "(%%b) locale's abbreviated month name (Jan..Dec) %b",
- "(%%c) full date (Sat Nov 4 12:02:33 1989)%n%t%t%t %c",
- "(%%d) day of the month (01..31) %d",
- "(%%e) day of the month, blank-padded ( 1..31) %e",
- "(%%h) should be same as (%%b) %h",
- "(%%j) day of the year (001..366) %j",
- "(%%k) hour, 24-hour clock, blank pad ( 0..23) %k",
- "(%%l) hour, 12-hour clock, blank pad ( 0..12) %l",
- "(%%m) month (01..12) %m",
- "(%%p) locale's AM or PM based on 12-hour clock %p",
- "(%%r) time, 12-hour (same as %%I:%%M:%%S %%p) %r",
- "(%%u) ISO 8601: Weekday as decimal number [1 (Monday) - 7] %u",
- "(%%v) VMS date (dd-bbb-YYYY) %v",
- "(%%w) day of week (0..6, Sunday == 0) %w",
- "(%%x) appropriate locale date representation %x",
- "(%%y) last two digits of year (00..99) %y",
- "(%%z) timezone offset east of GMT as HHMM (e.g. -0500) %z",
- (char *) NULL
-};
-
-/* main routine. */
-
-int
-main(argc, argv)
-int argc;
-char **argv;
-{
- long time();
-
- char *next;
- char string[MAXTIME];
-
- int k;
- int length;
-
- struct tm *tm;
-
- long clock;
-
- /* Call the function. */
-
- clock = time((long *) 0);
- tm = localtime(&clock);
-
- for (k = 0; next = array[k]; k++) {
- length = strftime(string, MAXTIME, next, tm);
- printf("%s\n", string);
- }
-
- exit(0);
-}
-#endif /* TEST_STRFTIME */
diff --git a/missing/strncasecmp.c b/missing/strncasecmp.c
deleted file mode 100644
index a4cc5828b8..0000000000
--- a/missing/strncasecmp.c
+++ /dev/null
@@ -1,21 +0,0 @@
-/* public domain rewrite of strncasecmp(3) */
-
-#include <ctype.h>
-
-int
-strncasecmp(p1, p2, len)
- char *p1;
- char *p2;
- int len;
-{
- while (len != 0) {
- if (toupper(*p1) != toupper(*p2)) {
- return toupper(*p1) - toupper(*p2);
- }
- if (*p1 == '\0') {
- return 0;
- }
- len--; p1++; p2++;
- }
- return 0;
-}
diff --git a/missing/strstr.c b/missing/strstr.c
deleted file mode 100644
index 1673518f06..0000000000
--- a/missing/strstr.c
+++ /dev/null
@@ -1,26 +0,0 @@
-/* public domain rewrite of strstr(3) */
-
-char *
-strstr(haystack, needle)
- char *haystack, *needle;
-{
- char *hend;
- char *a, *b;
-
- if (*needle == 0) return haystack;
- hend = haystack + strlen(haystack) - strlen(needle) + 1;
- while (haystack < hend) {
- if (*haystack == *needle) {
- a = haystack;
- b = needle;
- for (;;) {
- if (*b == 0) return haystack;
- if (*a++ != *b++) {
- break;
- }
- }
- }
- haystack++;
- }
- return 0;
-}
diff --git a/missing/strtod.c b/missing/strtod.c
deleted file mode 100644
index fdccd48081..0000000000
--- a/missing/strtod.c
+++ /dev/null
@@ -1,271 +0,0 @@
-/*
- * strtod.c --
- *
- * Source code for the "strtod" library procedure.
- *
- * Copyright (c) 1988-1993 The Regents of the University of California.
- * Copyright (c) 1994 Sun Microsystems, Inc.
- *
- * Permission to use, copy, modify, and distribute this
- * software and its documentation for any purpose and without
- * fee is hereby granted, provided that the above copyright
- * notice appear in all copies. The University of California
- * makes no representations about the suitability of this
- * software for any purpose. It is provided "as is" without
- * express or implied warranty.
- *
- * RCS: @(#) $Id$
- */
-
-#include "config.h"
-#ifdef HAVE_STDLIB_H
-# include <stdlib.h>
-#endif
-#include <ctype.h>
-#include <errno.h>
-extern int errno;
-
-#ifndef __STDC__
-# ifdef __GNUC__
-# define const __const__
-# else
-# define const
-# endif
-#endif
-
-#ifndef TRUE
-#define TRUE 1
-#define FALSE 0
-#endif
-#ifndef NULL
-#define NULL 0
-#endif
-
-static int maxExponent = 511; /* Largest possible base 10 exponent. Any
- * exponent larger than this will already
- * produce underflow or overflow, so there's
- * no need to worry about additional digits.
- */
-static double powersOf10[] = { /* Table giving binary powers of 10. Entry */
- 10., /* is 10^2^i. Used to convert decimal */
- 100., /* exponents into floating-point numbers. */
- 1.0e4,
- 1.0e8,
- 1.0e16,
- 1.0e32,
- 1.0e64,
- 1.0e128,
- 1.0e256
-};
-
-/*
- *----------------------------------------------------------------------
- *
- * strtod --
- *
- * This procedure converts a floating-point number from an ASCII
- * decimal representation to internal double-precision format.
- *
- * Results:
- * The return value is the double-precision floating-point
- * representation of the characters in string. If endPtr isn't
- * NULL, then *endPtr is filled in with the address of the
- * next character after the last one that was part of the
- * floating-point number.
- *
- * Side effects:
- * None.
- *
- *----------------------------------------------------------------------
- */
-
-double
-strtod(string, endPtr)
- const char *string; /* A decimal ASCII floating-point number,
- * optionally preceded by white space.
- * Must have form "-I.FE-X", where I is the
- * integer part of the mantissa, F is the
- * fractional part of the mantissa, and X
- * is the exponent. Either of the signs
- * may be "+", "-", or omitted. Either I
- * or F may be omitted, or both. The decimal
- * point isn't necessary unless F is present.
- * The "E" may actually be an "e". E and X
- * may both be omitted (but not just one).
- */
- char **endPtr; /* If non-NULL, store terminating character's
- * address here. */
-{
- int sign, expSign = FALSE;
- double fraction, dblExp, *d;
- register const char *p;
- register int c;
- int exp = 0; /* Exponent read from "EX" field. */
- int fracExp = 0; /* Exponent that derives from the fractional
- * part. Under normal circumstatnces, it is
- * the negative of the number of digits in F.
- * However, if I is very long, the last digits
- * of I get dropped (otherwise a long I with a
- * large negative exponent could cause an
- * unnecessary overflow on I alone). In this
- * case, fracExp is incremented one for each
- * dropped digit. */
- int mantSize; /* Number of digits in mantissa. */
- int decPt; /* Number of mantissa digits BEFORE decimal
- * point. */
- const char *pExp; /* Temporarily holds location of exponent
- * in string. */
-
- /*
- * Strip off leading blanks and check for a sign.
- */
-
- p = string;
- while (isspace(*p)) {
- p += 1;
- }
- if (*p == '-') {
- sign = TRUE;
- p += 1;
- } else {
- if (*p == '+') {
- p += 1;
- }
- sign = FALSE;
- }
-
- /*
- * Count the number of digits in the mantissa (including the decimal
- * point), and also locate the decimal point.
- */
-
- decPt = -1;
- for (mantSize = 0; ; mantSize += 1)
- {
- c = *p;
- if (!isdigit(c)) {
- if ((c != '.') || (decPt >= 0)) {
- break;
- }
- decPt = mantSize;
- }
- p += 1;
- }
-
- /*
- * Now suck up the digits in the mantissa. Use two integers to
- * collect 9 digits each (this is faster than using floating-point).
- * If the mantissa has more than 18 digits, ignore the extras, since
- * they can't affect the value anyway.
- */
-
- pExp = p;
- p -= mantSize;
- if (decPt < 0) {
- decPt = mantSize;
- } else {
- mantSize -= 1; /* One of the digits was the point. */
- }
- if (mantSize > 18) {
- fracExp = decPt - 18;
- mantSize = 18;
- } else {
- fracExp = decPt - mantSize;
- }
- if (mantSize == 0) {
- fraction = 0.0;
- p = string;
- goto done;
- } else {
- int frac1, frac2;
- frac1 = 0;
- for ( ; mantSize > 9; mantSize -= 1)
- {
- c = *p;
- p += 1;
- if (c == '.') {
- c = *p;
- p += 1;
- }
- frac1 = 10*frac1 + (c - '0');
- }
- frac2 = 0;
- for (; mantSize > 0; mantSize -= 1)
- {
- c = *p;
- p += 1;
- if (c == '.') {
- c = *p;
- p += 1;
- }
- frac2 = 10*frac2 + (c - '0');
- }
- fraction = (1.0e9 * frac1) + frac2;
- }
-
- /*
- * Skim off the exponent.
- */
-
- p = pExp;
- if ((*p == 'E') || (*p == 'e')) {
- p += 1;
- if (*p == '-') {
- expSign = TRUE;
- p += 1;
- } else {
- if (*p == '+') {
- p += 1;
- }
- expSign = FALSE;
- }
- while (isdigit(*p)) {
- exp = exp * 10 + (*p - '0');
- p += 1;
- }
- }
- if (expSign) {
- exp = fracExp - exp;
- } else {
- exp = fracExp + exp;
- }
-
- /*
- * Generate a floating-point number that represents the exponent.
- * Do this by processing the exponent one bit at a time to combine
- * many powers of 2 of 10. Then combine the exponent with the
- * fraction.
- */
-
- if (exp < 0) {
- expSign = TRUE;
- exp = -exp;
- } else {
- expSign = FALSE;
- }
- if (exp > maxExponent) {
- exp = maxExponent;
- errno = ERANGE;
- }
- dblExp = 1.0;
- for (d = powersOf10; exp != 0; exp >>= 1, d += 1) {
- if (exp & 01) {
- dblExp *= *d;
- }
- }
- if (expSign) {
- fraction /= dblExp;
- } else {
- fraction *= dblExp;
- }
-
-done:
- if (endPtr != NULL) {
- *endPtr = (char *) p;
- }
-
- if (sign) {
- return -fraction;
- }
- return fraction;
-}
diff --git a/missing/strtol.c b/missing/strtol.c
deleted file mode 100644
index e94aa54ca0..0000000000
--- a/missing/strtol.c
+++ /dev/null
@@ -1,29 +0,0 @@
-/* public domain rewrite of strtol(3) */
-
-#include <ctype.h>
-
-long
-strtol(nptr, endptr, base)
- char *nptr;
- char **endptr;
- int base;
-{
- long result;
- char *p = nptr;
-
- while (isspace(*p)) {
- p++;
- }
- if (*p == '-') {
- p++;
- result = -strtoul(p, endptr, base);
- }
- else {
- if (*p == '+') p++;
- result = strtoul(p, endptr, base);
- }
- if (endptr != 0 && *endptr == p) {
- *endptr = nptr;
- }
- return result;
-}
diff --git a/missing/strtoul.c b/missing/strtoul.c
deleted file mode 100644
index f16f2ad9cf..0000000000
--- a/missing/strtoul.c
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
- * strtoul.c --
- *
- * Source code for the "strtoul" library procedure.
- *
- * Copyright 1988 Regents of the University of California
- * Permission to use, copy, modify, and distribute this
- * software and its documentation for any purpose and without
- * fee is hereby granted, provided that the above copyright
- * notice appear in all copies. The University of California
- * makes no representations about the suitability of this
- * software for any purpose. It is provided "as is" without
- * express or implied warranty.
- */
-
-#include <ctype.h>
-
-/*
- * The table below is used to convert from ASCII digits to a
- * numerical equivalent. It maps from '0' through 'z' to integers
- * (100 for non-digit characters).
- */
-
-static char cvtIn[] = {
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* '0' - '9' */
- 100, 100, 100, 100, 100, 100, 100, /* punctuation */
- 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, /* 'A' - 'Z' */
- 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
- 30, 31, 32, 33, 34, 35,
- 100, 100, 100, 100, 100, 100, /* punctuation */
- 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, /* 'a' - 'z' */
- 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
- 30, 31, 32, 33, 34, 35};
-
-/*
- *----------------------------------------------------------------------
- *
- * strtoul --
- *
- * Convert an ASCII string into an integer.
- *
- * Results:
- * The return value is the integer equivalent of string. If endPtr
- * is non-NULL, then *endPtr is filled in with the character
- * after the last one that was part of the integer. If string
- * doesn't contain a valid integer value, then zero is returned
- * and *endPtr is set to string.
- *
- * Side effects:
- * None.
- *
- *----------------------------------------------------------------------
- */
-
-unsigned long int
-strtoul(string, endPtr, base)
- char *string; /* String of ASCII digits, possibly
- * preceded by white space. For bases
- * greater than 10, either lower- or
- * upper-case digits may be used.
- */
- char **endPtr; /* Where to store address of terminating
- * character, or NULL. */
- int base; /* Base for conversion. Must be less
- * than 37. If 0, then the base is chosen
- * from the leading characters of string:
- * "0x" means hex, "0" means octal, anything
- * else means decimal.
- */
-{
- register char *p;
- register unsigned long int result = 0;
- register unsigned digit;
- int anyDigits = 0;
-
- /*
- * Skip any leading blanks.
- */
-
- p = string;
- while (isspace(*p)) {
- p += 1;
- }
-
- /*
- * If no base was provided, pick one from the leading characters
- * of the string.
- */
-
- if (base == 0)
- {
- if (*p == '0') {
- p += 1;
- if (*p == 'x') {
- p += 1;
- base = 16;
- } else {
-
- /*
- * Must set anyDigits here, otherwise "0" produces a
- * "no digits" error.
- */
-
- anyDigits = 1;
- base = 8;
- }
- }
- else base = 10;
- } else if (base == 16) {
-
- /*
- * Skip a leading "0x" from hex numbers.
- */
-
- if ((p[0] == '0') && (p[1] == 'x')) {
- p += 2;
- }
- }
-
- /*
- * Sorry this code is so messy, but speed seems important. Do
- * different things for base 8, 10, 16, and other.
- */
-
- if (base == 8) {
- for ( ; ; p += 1) {
- digit = *p - '0';
- if (digit > 7) {
- break;
- }
- result = (result << 3) + digit;
- anyDigits = 1;
- }
- } else if (base == 10) {
- for ( ; ; p += 1) {
- digit = *p - '0';
- if (digit > 9) {
- break;
- }
- result = (10*result) + digit;
- anyDigits = 1;
- }
- } else if (base == 16) {
- for ( ; ; p += 1) {
- digit = *p - '0';
- if (digit > ('z' - '0')) {
- break;
- }
- digit = cvtIn[digit];
- if (digit > 15) {
- break;
- }
- result = (result << 4) + digit;
- anyDigits = 1;
- }
- } else {
- for ( ; ; p += 1) {
- digit = *p - '0';
- if (digit > ('z' - '0')) {
- break;
- }
- digit = cvtIn[digit];
- if (digit >= base) {
- break;
- }
- result = result*base + digit;
- anyDigits = 1;
- }
- }
-
- /*
- * See if there were any digits at all.
- */
-
- if (!anyDigits) {
- p = string;
- }
-
- if (endPtr != 0) {
- *endPtr = p;
- }
-
- return result;
-}
diff --git a/missing/vsnprintf.c b/missing/vsnprintf.c
deleted file mode 100644
index 489bf58361..0000000000
--- a/missing/vsnprintf.c
+++ /dev/null
@@ -1,1131 +0,0 @@
-/*-
- * Copyright (c) 1990, 1993
- * The Regents of the University of California. All rights reserved.
- *
- * This code is derived from software contributed to Berkeley by
- * Chris Torek.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- * must display the following acknowledgement:
- * This product includes software developed by the University of
- * California, Berkeley and its contributors.
- * 4. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-/*
- * IMPORTANT NOTE:
- * --------------
- * From ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change
- * paragraph 3 above is now null and void.
- */
-
-/* SNPRINTF.C
- * fjc 7-31-97 Modified by Mib Software to be a standalone snprintf.c module.
- * http://www.mibsoftware.com
- * Mib Software does not warrant this software any differently than the
- * University of California, Berkeley as described above. All warranties
- * are disclaimed. Use this software at your own risk.
- *
- * All code referencing FILE * functions was eliminated, since it could
- * never be called. All header files and necessary files are collapsed
- * into one file, internal functions are declared static. This should
- * allow inclusion into libraries with less chance of namespace collisions.
- *
- * snprintf should be the only externally visible item.
- *
- * As of 7-31-97 FLOATING_POINT is NOT provided. The code is somewhat
- * non-portable, so it is disabled.
- */
-
-/* Define FLOATING_POINT to get floating point. */
-/*
-#define FLOATING_POINT
-*/
-
-#include <sys/types.h>
-#define u_long unsigned long
-#define u_short unsigned short
-#define u_int unsigned int
-
-#undef __P
-#if defined(__STDC__)
-# include <stdarg.h>
-# if !defined(__P)
-# define __P(x) x
-# endif
-#else
-# define __P(x) ()
-# if !defined(const)
-# define const
-# endif
-# include <varargs.h>
-#endif
-#ifndef _BSD_VA_LIST_
-#define _BSD_VA_LIST_ va_list
-#endif
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# ifndef LONG_MAX
-# ifdef HAVE_LIMITS_H
-# include <limits.h>
-# else
- /* assuming 32bit(2's compliment) long */
-# define LONG_MAX 2147483647
-# endif
-# endif
-#endif
-
-#if defined(__hpux) && !defined(__GNUC__)
-#define const
-#endif
-
-#if defined(sgi)
-#undef __const
-#define __const
-#endif /* People who don't like const sys_error */
-
-#include <stddef.h>
-
-#ifndef NULL
-#define NULL 0
-#endif
-
-/*
- * NB: to fit things in six character monocase externals, the stdio
- * code uses the prefix `__s' for stdio objects, typically followed
- * by a three-character attempt at a mnemonic.
- */
-
-/* stdio buffers */
-struct __sbuf {
- unsigned char *_base;
- int _size;
-};
-
-
-/*
- * stdio state variables.
- *
- * The following always hold:
- *
- * if (_flags&(__SLBF|__SWR)) == (__SLBF|__SWR),
- * _lbfsize is -_bf._size, else _lbfsize is 0
- * if _flags&__SRD, _w is 0
- * if _flags&__SWR, _r is 0
- *
- * This ensures that the getc and putc macros (or inline functions) never
- * try to write or read from a file that is in `read' or `write' mode.
- * (Moreover, they can, and do, automatically switch from read mode to
- * write mode, and back, on "r+" and "w+" files.)
- *
- * _lbfsize is used only to make the inline line-buffered output stream
- * code as compact as possible.
- *
- * _ub, _up, and _ur are used when ungetc() pushes back more characters
- * than fit in the current _bf, or when ungetc() pushes back a character
- * that does not match the previous one in _bf. When this happens,
- * _ub._base becomes non-nil (i.e., a stream has ungetc() data iff
- * _ub._base!=NULL) and _up and _ur save the current values of _p and _r.
- *
- * NB: see WARNING above before changing the layout of this structure!
- */
-typedef struct __sFILE {
- unsigned char *_p; /* current position in (some) buffer */
- int _r; /* read space left for getc() */
- int _w; /* write space left for putc() */
- short _flags; /* flags, below; this FILE is free if 0 */
- short _file; /* fileno, if Unix descriptor, else -1 */
- struct __sbuf _bf; /* the buffer (at least 1 byte, if !NULL) */
- int _lbfsize; /* 0 or -_bf._size, for inline putc */
-} FILE;
-
-
-#define __SLBF 0x0001 /* line buffered */
-#define __SNBF 0x0002 /* unbuffered */
-#define __SRD 0x0004 /* OK to read */
-#define __SWR 0x0008 /* OK to write */
- /* RD and WR are never simultaneously asserted */
-#define __SRW 0x0010 /* open for reading & writing */
-#define __SEOF 0x0020 /* found EOF */
-#define __SERR 0x0040 /* found error */
-#define __SMBF 0x0080 /* _buf is from malloc */
-#define __SAPP 0x0100 /* fdopen()ed in append mode */
-#define __SSTR 0x0200 /* this is an sprintf/snprintf string */
-#define __SOPT 0x0400 /* do fseek() optimisation */
-#define __SNPT 0x0800 /* do not do fseek() optimisation */
-#define __SOFF 0x1000 /* set iff _offset is in fact correct */
-#define __SMOD 0x2000 /* true => fgetln modified _p text */
-
-
-#define EOF (-1)
-
-
-#define __sfeof(p) (((p)->_flags & __SEOF) != 0)
-#define __sferror(p) (((p)->_flags & __SERR) != 0)
-#define __sclearerr(p) ((void)((p)->_flags &= ~(__SERR|__SEOF)))
-#define __sfileno(p) ((p)->_file)
-
-#define feof(p) __sfeof(p)
-#define ferror(p) __sferror(p)
-#define clearerr(p) __sclearerr(p)
-
-#ifndef _ANSI_SOURCE
-#define fileno(p) __sfileno(p)
-#endif
-
-
-#if defined(__hpux) && !defined(__GNUC__)
-#include <string.h>
-#endif
-
-/*
- * I/O descriptors for __sfvwrite().
- */
-struct __siov {
- void *iov_base;
- size_t iov_len;
-};
-struct __suio {
- struct __siov *uio_iov;
- int uio_iovcnt;
- int uio_resid;
-};
-
-/*
- * Write some memory regions. Return zero on success, EOF on error.
- *
- * This routine is large and unsightly, but most of the ugliness due
- * to the three different kinds of output buffering is handled here.
- */
-static BSD__sfvwrite(fp, uio)
- register FILE *fp;
- register struct __suio *uio;
-{
- register size_t len;
- register char *p;
- register struct __siov *iov;
- register int w;
-
- if ((len = uio->uio_resid) == 0)
- return (0);
-#ifndef __hpux
-#define MIN(a, b) ((a) < (b) ? (a) : (b))
-#endif
-#define COPY(n) (void)memcpy((void *)fp->_p, (void *)p, (size_t)(n))
-
- iov = uio->uio_iov;
- p = iov->iov_base;
- len = iov->iov_len;
- iov++;
-#define GETIOV(extra_work) \
- while (len == 0) { \
- extra_work; \
- p = iov->iov_base; \
- len = iov->iov_len; \
- iov++; \
- }
- if (fp->_flags & __SNBF) {
- /* fjc 7-31-97 Will never happen. We are working with
- strings only
- */
- } else if ((fp->_flags & __SLBF) == 0) {
- /*
- * Fully buffered: fill partially full buffer, if any,
- * and then flush. If there is no partial buffer, write
- * one _bf._size byte chunk directly (without copying).
- *
- * String output is a special case: write as many bytes
- * as fit, but pretend we wrote everything. This makes
- * snprintf() return the number of bytes needed, rather
- * than the number used, and avoids its write function
- * (so that the write function can be invalid).
- */
- do {
- GETIOV(;);
- w = fp->_w;
- if (fp->_flags & __SSTR) {
- if (len < w)
- w = len;
- COPY(w); /* copy MIN(fp->_w,len), */
- fp->_w -= w;
- fp->_p += w;
- w = len; /* but pretend copied all */
- } else {
- /* fjc 7-31-97 Will never happen. We are working with
- strings only
- */
- }
- p += w;
- len -= w;
- } while ((uio->uio_resid -= w) != 0);
- } else {
- /* fjc 7-31-97 Will never happen. We are working with
- strings only
- */
- }
- return (0);
-
-err:
- fp->_flags |= __SERR;
- return (EOF);
-}
-
-/*
- * Actual printf innards.
- *
- * This code is large and complicated...
- */
-
-#if !defined(__CYGWIN32__) && defined(__hpux) && !defined(__GNUC__)
-#include <stdlib.h>
-#endif
-
-/*
- * Flush out all the vectors defined by the given uio,
- * then reset it so that it can be reused.
- */
-static int
-BSD__sprint(fp, uio)
- FILE *fp;
- register struct __suio *uio;
-{
- register int err;
-
- if (uio->uio_resid == 0) {
- uio->uio_iovcnt = 0;
- return (0);
- }
- err = BSD__sfvwrite(fp, uio);
- uio->uio_resid = 0;
- uio->uio_iovcnt = 0;
- return (err);
-}
-
-
-/*
- * Helper function for `fprintf to unbuffered unix file': creates a
- * temporary buffer. We only work on write-only files; this avoids
- * worries about ungetc buffers and so forth.
- */
-static int
-BSD__sbprintf(fp, fmt, ap)
- register FILE *fp;
- const char *fmt;
- va_list ap;
-{
-/* We don't support files. */
- return 0;
-}
-
-
-/*
- * Macros for converting digits to letters and vice versa
- */
-#define to_digit(c) ((c) - '0')
-#define is_digit(c) ((unsigned)to_digit(c) <= 9)
-#define to_char(n) ((n) + '0')
-
-/*
- * Convert an unsigned long to ASCII for printf purposes, returning
- * a pointer to the first character of the string representation.
- * Octal numbers can be forced to have a leading zero; hex numbers
- * use the given digits.
- */
-static char *
-BSD__ultoa(val, endp, base, octzero, xdigs)
- register u_long val;
- char *endp;
- int base, octzero;
- char *xdigs;
-{
- register char *cp = endp;
- register long sval;
-
- /*
- * Handle the three cases separately, in the hope of getting
- * better/faster code.
- */
- switch (base) {
- case 10:
- if (val < 10) { /* many numbers are 1 digit */
- *--cp = to_char(val);
- return (cp);
- }
- /*
- * On many machines, unsigned arithmetic is harder than
- * signed arithmetic, so we do at most one unsigned mod and
- * divide; this is sufficient to reduce the range of
- * the incoming value to where signed arithmetic works.
- */
- if (val > LONG_MAX) {
- *--cp = to_char(val % 10);
- sval = val / 10;
- } else
- sval = val;
- do {
- *--cp = to_char(sval % 10);
- sval /= 10;
- } while (sval != 0);
- break;
-
- case 8:
- do {
- *--cp = to_char(val & 7);
- val >>= 3;
- } while (val);
- if (octzero && *cp != '0')
- *--cp = '0';
- break;
-
- case 16:
- do {
- *--cp = xdigs[val & 15];
- val >>= 4;
- } while (val);
- break;
-
- default: /* oops */
- /*
- abort();
- */
- break; /* fjc 7-31-97. Don't reference abort() here */
- }
- return (cp);
-}
-
-#ifdef FLOATING_POINT
-#include <math.h>
-/* #include "floatio.h" */
-
-#ifndef MAXEXP
-# define MAXEXP 1024
-#endif
-
-#ifndef MAXFRACT
-# define MAXFRACT 64
-#endif
-
-#define BUF (MAXEXP+MAXFRACT+1) /* + decimal point */
-#define DEFPREC 6
-
-static char *cvt __P((double, int, int, char *, int *, int, int *));
-static int exponent __P((char *, int, int));
-
-#else /* no FLOATING_POINT */
-
-#define BUF 68
-
-#endif /* FLOATING_POINT */
-
-
-/*
- * Flags used during conversion.
- */
-#define ALT 0x001 /* alternate form */
-#define HEXPREFIX 0x002 /* add 0x or 0X prefix */
-#define LADJUST 0x004 /* left adjustment */
-#define LONGDBL 0x008 /* long double; unimplemented */
-#define LONGINT 0x010 /* long integer */
-
-#ifdef _HAVE_SANE_QUAD_
-#define QUADINT 0x020 /* quad integer */
-#endif /* _HAVE_SANE_QUAD_ */
-
-#define SHORTINT 0x040 /* short integer */
-#define ZEROPAD 0x080 /* zero (as opposed to blank) pad */
-#define FPT 0x100 /* Floating point number */
-static int
-BSD_vfprintf(fp, fmt0, ap)
- FILE *fp;
- const char *fmt0;
- va_list ap;
-{
- register char *fmt; /* format string */
- register int ch; /* character from fmt */
- register int n; /* handy integer (short term usage) */
- register char *cp; /* handy char pointer (short term usage) */
- register struct __siov *iovp;/* for PRINT macro */
- register int flags; /* flags as above */
- int ret; /* return value accumulator */
- int width; /* width from format (%8d), or 0 */
- int prec; /* precision from format (%.3d), or -1 */
- char sign; /* sign prefix (' ', '+', '-', or \0) */
-#ifdef FLOATING_POINT
- char softsign; /* temporary negative sign for floats */
- double _double; /* double precision arguments %[eEfgG] */
- int expt; /* integer value of exponent */
- int expsize; /* character count for expstr */
- int ndig; /* actual number of digits returned by cvt */
- char expstr[7]; /* buffer for exponent string */
-#endif
- u_long ulval; /* integer arguments %[diouxX] */
-#ifdef _HAVE_SANE_QUAD_
- u_quad_t uqval; /* %q integers */
-#endif /* _HAVE_SANE_QUAD_ */
- int base; /* base for [diouxX] conversion */
- int dprec; /* a copy of prec if [diouxX], 0 otherwise */
- int fieldsz; /* field size expanded by sign, etc */
- int realsz; /* field size expanded by dprec */
- int size; /* size of converted field or string */
- char *xdigs; /* digits for [xX] conversion */
-#define NIOV 8
- struct __suio uio; /* output information: summary */
- struct __siov iov[NIOV];/* ... and individual io vectors */
- char buf[BUF]; /* space for %c, %[diouxX], %[eEfgG] */
- char ox[2]; /* space for 0x hex-prefix */
-
- /*
- * Choose PADSIZE to trade efficiency vs. size. If larger printf
- * fields occur frequently, increase PADSIZE and make the initialisers
- * below longer.
- */
-#define PADSIZE 16 /* pad chunk size */
- static char blanks[PADSIZE] =
- {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
- static char zeroes[PADSIZE] =
- {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
-
- /*
- * BEWARE, these `goto error' on error, and PAD uses `n'.
- */
-#define PRINT(ptr, len) { \
- iovp->iov_base = (ptr); \
- iovp->iov_len = (len); \
- uio.uio_resid += (len); \
- iovp++; \
- if (++uio.uio_iovcnt >= NIOV) { \
- if (BSD__sprint(fp, &uio)) \
- goto error; \
- iovp = iov; \
- } \
-}
-#define PAD(howmany, with) { \
- if ((n = (howmany)) > 0) { \
- while (n > PADSIZE) { \
- PRINT(with, PADSIZE); \
- n -= PADSIZE; \
- } \
- PRINT(with, n); \
- } \
-}
-#define FLUSH() { \
- if (uio.uio_resid && BSD__sprint(fp, &uio)) \
- goto error; \
- uio.uio_iovcnt = 0; \
- iovp = iov; \
-}
-
- /*
- * To extend shorts properly, we need both signed and unsigned
- * argument extraction methods.
- */
-#define SARG() \
- (flags&LONGINT ? va_arg(ap, long) : \
- flags&SHORTINT ? (long)(short)va_arg(ap, int) : \
- (long)va_arg(ap, int))
-#define UARG() \
- (flags&LONGINT ? va_arg(ap, u_long) : \
- flags&SHORTINT ? (u_long)(u_short)va_arg(ap, int) : \
- (u_long)va_arg(ap, u_int))
-
- /* optimise fprintf(stderr) (and other unbuffered Unix files) */
- if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
- fp->_file >= 0)
- return (BSD__sbprintf(fp, fmt0, ap));
-
- fmt = (char *)fmt0;
- uio.uio_iov = iovp = iov;
- uio.uio_resid = 0;
- uio.uio_iovcnt = 0;
- ret = 0;
-
- /*
- * Scan the format for conversions (`%' character).
- */
- for (;;) {
- for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
- /* void */;
- if ((n = fmt - cp) != 0) {
- PRINT(cp, n);
- ret += n;
- }
- if (ch == '\0')
- goto done;
- fmt++; /* skip over '%' */
-
- flags = 0;
- dprec = 0;
- width = 0;
- prec = -1;
- sign = '\0';
-
-rflag: ch = *fmt++;
-reswitch: switch (ch) {
- case ' ':
- /*
- * ``If the space and + flags both appear, the space
- * flag will be ignored.''
- * -- ANSI X3J11
- */
- if (!sign)
- sign = ' ';
- goto rflag;
- case '#':
- flags |= ALT;
- goto rflag;
- case '*':
- /*
- * ``A negative field width argument is taken as a
- * - flag followed by a positive field width.''
- * -- ANSI X3J11
- * They don't exclude field widths read from args.
- */
- if ((width = va_arg(ap, int)) >= 0)
- goto rflag;
- width = -width;
- /* FALLTHROUGH */
- case '-':
- flags |= LADJUST;
- goto rflag;
- case '+':
- sign = '+';
- goto rflag;
- case '.':
- if ((ch = *fmt++) == '*') {
- n = va_arg(ap, int);
- prec = n < 0 ? -1 : n;
- goto rflag;
- }
- n = 0;
- while (is_digit(ch)) {
- n = 10 * n + to_digit(ch);
- ch = *fmt++;
- }
- prec = n < 0 ? -1 : n;
- goto reswitch;
- case '0':
- /*
- * ``Note that 0 is taken as a flag, not as the
- * beginning of a field width.''
- * -- ANSI X3J11
- */
- flags |= ZEROPAD;
- goto rflag;
- case '1': case '2': case '3': case '4':
- case '5': case '6': case '7': case '8': case '9':
- n = 0;
- do {
- n = 10 * n + to_digit(ch);
- ch = *fmt++;
- } while (is_digit(ch));
- width = n;
- goto reswitch;
-#ifdef FLOATING_POINT
- case 'L':
- flags |= LONGDBL;
- goto rflag;
-#endif
- case 'h':
- flags |= SHORTINT;
- goto rflag;
- case 'l':
- flags |= LONGINT;
- goto rflag;
-#ifdef _HAVE_SANE_QUAD_
- case 'q':
- flags |= QUADINT;
- goto rflag;
-#endif /* _HAVE_SANE_QUAD_ */
- case 'c':
- *(cp = buf) = va_arg(ap, int);
- size = 1;
- sign = '\0';
- break;
- case 'D':
- flags |= LONGINT;
- /*FALLTHROUGH*/
- case 'd':
- case 'i':
-#ifdef _HAVE_SANE_QUAD_
- if (flags & QUADINT) {
- uqval = va_arg(ap, quad_t);
- if ((quad_t)uqval < 0) {
- uqval = -uqval;
- sign = '-';
- }
- } else {
-#else /* _HAVE_SANE_QUAD_ */
- {
-#endif /* _HAVE_SANE_QUAD_ */
- ulval = SARG();
- if ((long)ulval < 0) {
- ulval = -ulval;
- sign = '-';
- }
- }
- base = 10;
- goto number;
-#ifdef FLOATING_POINT
- case 'e': /* anomalous precision */
- case 'E':
- prec = (prec == -1) ?
- DEFPREC + 1 : prec + 1;
- /* FALLTHROUGH */
- goto fp_begin;
- case 'f': /* always print trailing zeroes */
- if (prec != 0)
- flags |= ALT;
- case 'g':
- case 'G':
- if (prec == -1)
- prec = DEFPREC;
-fp_begin: _double = va_arg(ap, double);
- /* do this before tricky precision changes */
- if (isinf(_double)) {
- if (_double < 0)
- sign = '-';
- cp = "Inf";
- size = 3;
- break;
- }
- if (isnan(_double)) {
- cp = "NaN";
- size = 3;
- break;
- }
- flags |= FPT;
- cp = cvt(_double, prec, flags, &softsign,
- &expt, ch, &ndig);
- if (ch == 'g' || ch == 'G') {
- if (expt <= -4 || expt > prec)
- ch = (ch == 'g') ? 'e' : 'E';
- else
- ch = 'g';
- }
- if (ch <= 'e') { /* 'e' or 'E' fmt */
- --expt;
- expsize = exponent(expstr, expt, ch);
- size = expsize + ndig;
- if (ndig > 1 || flags & ALT)
- ++size;
- } else if (ch == 'f') { /* f fmt */
- if (expt > 0) {
- size = expt;
- if (prec || flags & ALT)
- size += prec + 1;
- } else /* "0.X" */
- size = prec + 2;
- } else if (expt >= ndig) { /* fixed g fmt */
- size = expt;
- if (flags & ALT)
- ++size;
- } else
- size = ndig + (expt > 0 ?
- 1 : 2 - expt);
-
- if (softsign)
- sign = '-';
- break;
-#endif /* FLOATING_POINT */
- case 'n':
-#ifdef _HAVE_SANE_QUAD_
- if (flags & QUADINT)
- *va_arg(ap, quad_t *) = ret;
- else if (flags & LONGINT)
-#else /* _HAVE_SANE_QUAD_ */
- if (flags & LONGINT)
-#endif /* _HAVE_SANE_QUAD_ */
- *va_arg(ap, long *) = ret;
- else if (flags & SHORTINT)
- *va_arg(ap, short *) = ret;
- else
- *va_arg(ap, int *) = ret;
- continue; /* no output */
- case 'O':
- flags |= LONGINT;
- /*FALLTHROUGH*/
- case 'o':
-#ifdef _HAVE_SANE_QUAD_
- if (flags & QUADINT)
- uqval = va_arg(ap, u_quad_t);
- else
-#endif /* _HAVE_SANE_QUAD_ */
- ulval = UARG();
- base = 8;
- goto nosign;
- case 'p':
- /*
- * ``The argument shall be a pointer to void. The
- * value of the pointer is converted to a sequence
- * of printable characters, in an implementation-
- * defined manner.''
- * -- ANSI X3J11
- */
- ulval = (u_long)va_arg(ap, void *);
- base = 16;
- xdigs = "0123456789abcdef";
-#ifdef _HAVE_SANE_QUAD_
- flags = (flags & ~QUADINT) | HEXPREFIX;
-#else /* _HAVE_SANE_QUAD_ */
- flags = (flags) | HEXPREFIX;
-#endif /* _HAVE_SANE_QUAD_ */
- ch = 'x';
- goto nosign;
- case 's':
- if ((cp = va_arg(ap, char *)) == NULL)
- cp = "(null)";
- if (prec >= 0) {
- /*
- * can't use strlen; can only look for the
- * NUL in the first `prec' characters, and
- * strlen() will go further.
- */
- char *p = (char *)memchr(cp, 0, prec);
-
- if (p != NULL) {
- size = p - cp;
- if (size > prec)
- size = prec;
- } else
- size = prec;
- } else
- size = strlen(cp);
- sign = '\0';
- break;
- case 'U':
- flags |= LONGINT;
- /*FALLTHROUGH*/
- case 'u':
-#ifdef _HAVE_SANE_QUAD_
- if (flags & QUADINT)
- uqval = va_arg(ap, u_quad_t);
- else
-#endif /* _HAVE_SANE_QUAD_ */
- ulval = UARG();
- base = 10;
- goto nosign;
- case 'X':
- xdigs = "0123456789ABCDEF";
- goto hex;
- case 'x':
- xdigs = "0123456789abcdef";
-hex:
-#ifdef _HAVE_SANE_QUAD_
- if (flags & QUADINT)
- uqval = va_arg(ap, u_quad_t);
- else
-#endif /* _HAVE_SANE_QUAD_ */
- ulval = UARG();
- base = 16;
- /* leading 0x/X only if non-zero */
- if (flags & ALT &&
-#ifdef _HAVE_SANE_QUAD_
- (flags & QUADINT ? uqval != 0 : ulval != 0))
-#else /* _HAVE_SANE_QUAD_ */
- ulval != 0)
-#endif /* _HAVE_SANE_QUAD_ */
- flags |= HEXPREFIX;
-
- /* unsigned conversions */
-nosign: sign = '\0';
- /*
- * ``... diouXx conversions ... if a precision is
- * specified, the 0 flag will be ignored.''
- * -- ANSI X3J11
- */
-number: if ((dprec = prec) >= 0)
- flags &= ~ZEROPAD;
-
- /*
- * ``The result of converting a zero value with an
- * explicit precision of zero is no characters.''
- * -- ANSI X3J11
- */
- cp = buf + BUF;
-#ifdef _HAVE_SANE_QUAD_
- if (flags & QUADINT) {
- if (uqval != 0 || prec != 0)
- cp = __uqtoa(uqval, cp, base,
- flags & ALT, xdigs);
- } else {
-#else /* _HAVE_SANE_QUAD_ */
- {
-#endif /* _HAVE_SANE_QUAD_ */
- if (ulval != 0 || prec != 0)
- cp = BSD__ultoa(ulval, cp, base,
- flags & ALT, xdigs);
- }
- size = buf + BUF - cp;
- break;
- default: /* "%?" prints ?, unless ? is NUL */
- if (ch == '\0')
- goto done;
- /* pretend it was %c with argument ch */
- cp = buf;
- *cp = ch;
- size = 1;
- sign = '\0';
- break;
- }
-
- /*
- * All reasonable formats wind up here. At this point, `cp'
- * points to a string which (if not flags&LADJUST) should be
- * padded out to `width' places. If flags&ZEROPAD, it should
- * first be prefixed by any sign or other prefix; otherwise,
- * it should be blank padded before the prefix is emitted.
- * After any left-hand padding and prefixing, emit zeroes
- * required by a decimal [diouxX] precision, then print the
- * string proper, then emit zeroes required by any leftover
- * floating precision; finally, if LADJUST, pad with blanks.
- *
- * Compute actual size, so we know how much to pad.
- * fieldsz excludes decimal prec; realsz includes it.
- */
- fieldsz = size;
- if (sign)
- fieldsz++;
- else if (flags & HEXPREFIX)
- fieldsz += 2;
- realsz = dprec > fieldsz ? dprec : fieldsz;
-
- /* right-adjusting blank padding */
- if ((flags & (LADJUST|ZEROPAD)) == 0)
- PAD(width - realsz, blanks);
-
- /* prefix */
- if (sign) {
- PRINT(&sign, 1);
- } else if (flags & HEXPREFIX) {
- ox[0] = '0';
- ox[1] = ch;
- PRINT(ox, 2);
- }
-
- /* right-adjusting zero padding */
- if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
- PAD(width - realsz, zeroes);
-
- /* leading zeroes from decimal precision */
- PAD(dprec - fieldsz, zeroes);
-
- /* the string or number proper */
-#ifdef FLOATING_POINT
- if ((flags & FPT) == 0) {
- PRINT(cp, size);
- } else { /* glue together f_p fragments */
- if (ch >= 'f') { /* 'f' or 'g' */
- if (_double == 0) {
- /* kludge for __dtoa irregularity */
- if (prec == 0 ||
- (flags & ALT) == 0) {
- PRINT("0", 1);
- } else {
- PRINT("0.", 2);
- PAD(ndig - 1, zeroes);
- }
- } else if (expt <= 0) {
- PRINT("0.", 2);
- PAD(-expt, zeroes);
- PRINT(cp, ndig);
- } else if (expt >= ndig) {
- PRINT(cp, ndig);
- PAD(expt - ndig, zeroes);
- if (flags & ALT)
- PRINT(".", 1);
- } else {
- PRINT(cp, expt);
- cp += expt;
- PRINT(".", 1);
- PRINT(cp, ndig-expt);
- }
- } else { /* 'e' or 'E' */
- if (ndig > 1 || flags & ALT) {
- ox[0] = *cp++;
- ox[1] = '.';
- PRINT(ox, 2);
- if (_double || flags & ALT == 0) {
- PRINT(cp, ndig-1);
- } else /* 0.[0..] */
- /* __dtoa irregularity */
- PAD(ndig - 1, zeroes);
- } else /* XeYYY */
- PRINT(cp, 1);
- PRINT(expstr, expsize);
- }
- }
-#else
- PRINT(cp, size);
-#endif
- /* left-adjusting padding (always blank) */
- if (flags & LADJUST)
- PAD(width - realsz, blanks);
-
- /* finally, adjust ret */
- ret += width > realsz ? width : realsz;
-
- FLUSH(); /* copy out the I/O vectors */
- }
-done:
- FLUSH();
-error:
- return (__sferror(fp) ? EOF : ret);
- /* NOTREACHED */
-}
-
-#ifdef FLOATING_POINT
-
-extern char *BSD__dtoa __P((double, int, int, int *, int *, char **));
-
-static char *
-cvt(value, ndigits, flags, sign, decpt, ch, length)
- double value;
- int ndigits, flags, *decpt, ch, *length;
- char *sign;
-{
- int mode, dsgn;
- char *digits, *bp, *rve;
-
- if (ch == 'f')
- mode = 3;
- else {
- mode = 2;
- }
- if (value < 0) {
- value = -value;
- *sign = '-';
- } else
- *sign = '\000';
- digits = BSD__dtoa(value, mode, ndigits, decpt, &dsgn, &rve);
- if (flags & ALT) { /* Print trailing zeros */
- bp = digits + ndigits;
- if (ch == 'f') {
- if (*digits == '0' && value)
- *decpt = -ndigits + 1;
- bp += *decpt;
- }
- if (value == 0) /* kludge for __dtoa irregularity */
- rve = bp;
- while (rve < bp)
- *rve++ = '0';
- }
- *length = rve - digits;
- return (digits);
-}
-
-static int
-exponent(p0, exp, fmtch)
- char *p0;
- int exp, fmtch;
-{
- register char *p, *t;
- char expbuf[MAXEXP];
-
- p = p0;
- *p++ = fmtch;
- if (exp < 0) {
- exp = -exp;
- *p++ = '-';
- }
- else
- *p++ = '+';
- t = expbuf + MAXEXP;
- if (exp > 9) {
- do {
- *--t = to_char(exp % 10);
- } while ((exp /= 10) > 9);
- *--t = to_char(exp);
- for (; t < expbuf + MAXEXP; *p++ = *t++);
- }
- else {
- *p++ = '0';
- *p++ = to_char(exp);
- }
- return (p - p0);
-}
-#endif /* FLOATING_POINT */
-
-int
-vsnprintf(str, n, fmt, ap)
- char *str;
- size_t n;
- const char *fmt;
- _BSD_VA_LIST_ ap;
-{
- int ret;
- FILE f;
-
- if ((int)n < 1)
- return (EOF);
- f._flags = __SWR | __SSTR;
- f._bf._base = f._p = (unsigned char *)str;
- f._bf._size = f._w = n - 1;
- ret = BSD_vfprintf(&f, fmt, ap);
- *f._p = 0;
- return (ret);
-}
-
-#if defined(LIBC_SCCS) && !defined(lint)
-static char sccsid[] = "@(#)snprintf.c 8.1 (Berkeley) 6/4/93";
-#endif /* LIBC_SCCS and not lint */
-
-#if defined(__STDC__)
-# include <stdarg.h>
-#else
-# include <varargs.h>
-#endif
-
-int
-#if defined(__STDC__)
-snprintf(char *str, size_t n, char const *fmt, ...)
-#else
-snprintf(str, n, fmt, va_alist)
-char *str, *fmt;
-size_t n;
-va_dcl
-#endif
-{
- int ret;
- va_list ap;
- FILE f;
-
- if ((int)n < 1)
- return (EOF);
-
-#if defined(__STDC__)
- va_start(ap, fmt);
-#else
- va_start(ap);
-#endif
- f._flags = __SWR | __SSTR;
- f._bf._base = f._p = (unsigned char *)str;
- f._bf._size = f._w = n - 1;
- ret = BSD_vfprintf(&f, fmt, ap);
- *f._p = 0;
- va_end(ap);
- return (ret);
-}
diff --git a/missing/x68.c b/missing/x68.c
deleted file mode 100644
index 08bce8778c..0000000000
--- a/missing/x68.c
+++ /dev/null
@@ -1,40 +0,0 @@
-/* x68 compatibility functions -- follows Ruby's lisence */
-
-#include "config.h"
-
-#if !HAVE_SELECT
-#include "x68/select.c"
-#endif
-#if MISSING__DTOS18
-#include "x68/_dtos18.c"
-#endif
-#if MISSING_FCONVERT
-#include "x68/_round.c"
-#include "x68/fconvert.c"
-#endif
-
-/* missing some basic syscalls */
-int
-link(const char *src, const char *dst)
-{
- return symlink(src, dst);
-}
-
-#ifndef HAVE_GETTIMEOFDAY
-#include <time.h>
-#include <sys/time.h>
-
-struct timezone {
- int tz_minueswest;
- int tz_dsttime;
-};
-
-int
-gettimeofday(struct timeval *tv, struct timezone *tz)
-{
- tv->tv_sec = (long)time((time_t*)0);
- tv->tv_usec = 0;
-
- return 0;
-}
-#endif
diff --git a/mkconfig.rb b/mkconfig.rb
deleted file mode 100644
index a2db2d21bc..0000000000
--- a/mkconfig.rb
+++ /dev/null
@@ -1,120 +0,0 @@
-#!./miniruby -s
-
-require File.dirname($0)+"/lib/ftools"
-
-rbconfig_rb = ARGV[0] || 'rbconfig.rb'
-srcdir = $srcdir if $srcdir
-File.makedirs(File.dirname(rbconfig_rb), true)
-
-version = RUBY_VERSION
-rbconfig_rb_tmp = rbconfig_rb + '.tmp'
-config = open(rbconfig_rb_tmp, "w")
-$orgout = $stdout.dup
-$stdout.reopen(config)
-
-fast = {'prefix'=>TRUE, 'ruby_install_name'=>TRUE, 'INSTALL'=>TRUE, 'EXEEXT'=>TRUE}
-print %[
-module Config
-
- RUBY_VERSION == "#{version}" or
- raise "ruby lib version (#{version}) doesn't match executable version (\#{RUBY_VERSION})"
-
-# This file was created by configrb when ruby was built. Any changes
-# made to this file will be lost the next time ruby is built.
-]
-
-print " DESTDIR = '' if not defined? DESTDIR\n CONFIG = {}\n"
-v_fast = []
-v_others = []
-has_srcdir = false
-has_version = false
-File.foreach "config.status" do |line|
- next if /^#/ =~ line
- if /^s[%,]@program_transform_name@[%,]s,(.*)/ =~ line
- next if $install_name
- ptn = $1.sub(/\$\$/, '$').split(/,/) #'
- v_fast << " CONFIG[\"ruby_install_name\"] = \"" + "ruby".sub(ptn[0],ptn[1]) + "\"\n"
- elsif /^s[%,]@(\w+)@[%,](.*)[%,]/ =~ line
- name = $1
- val = $2 || ""
- next if /^(INSTALL|DEFS|configure_input|srcdir|top_srcdir)$/ =~ name
- next if $install_name and /^RUBY_INSTALL_NAME$/ =~ name
- next if $so_name and /^RUBY_SO_NAME$/ =~ name
- v = " CONFIG[\"" + name + "\"] = " +
- val.strip.gsub(/\$\{?(\w+)\}?/) {"$(#{$1})"}.dump + "\n"
- if fast[name]
- v_fast << v
- else
- v_others << v
- end
- has_version = true if name == "MAJOR"
- elsif /^(?:ac_given_)?srcdir=(.*)/ =~ line
- v_fast << " CONFIG[\"srcdir\"] = \"" + File.expand_path($1) + "\"\n"
- has_srcdir = true
- elsif /^ac_given_INSTALL=(.*)/ =~ line
- v_fast << " CONFIG[\"INSTALL\"] = " + $1 + "\n"
- end
-# break if /^CEOF/
-end
-
-if not has_srcdir
- v_fast << " CONFIG[\"srcdir\"] = \"" + File.expand_path(srcdir || '.') + "\"\n"
-end
-
-if not has_version
- RUBY_VERSION.scan(/(\d+)\.(\d+)\.(\d+)/) {
- print " CONFIG[\"MAJOR\"] = \"" + $1 + "\"\n"
- print " CONFIG[\"MINOR\"] = \"" + $2 + "\"\n"
- print " CONFIG[\"TEENY\"] = \"" + $3 + "\"\n"
- }
-end
-
-v_fast.collect! do |x|
- if /"prefix"/ === x
- prefix = Regexp.quote('/lib/ruby/' + RUBY_VERSION.sub(/\.\d+$/, '') + '/' + RUBY_PLATFORM)
- puts " TOPDIR = File.dirname(__FILE__).sub!(%r'#{prefix}\\Z', '')"
- x.sub(/= (.*)/, '= (TOPDIR || DESTDIR + \1)')
- else
- x
- end
-end
-
-if $install_name
- v_fast << " CONFIG[\"ruby_install_name\"] = \"" + $install_name + "\"\n"
- v_fast << " CONFIG[\"RUBY_INSTALL_NAME\"] = \"" + $install_name + "\"\n"
-end
-if $so_name
- v_fast << " CONFIG[\"RUBY_SO_NAME\"] = \"" + $so_name + "\"\n"
-end
-
-print v_fast, v_others
-print <<EOS
- CONFIG["ruby_version"] = "$(MAJOR).$(MINOR)"
- CONFIG["rubylibdir"] = "$(libdir)/ruby/$(ruby_version)"
- CONFIG["archdir"] = "$(rubylibdir)/$(arch)"
- CONFIG["sitelibdir"] = "$(sitedir)/$(ruby_version)"
- CONFIG["sitearchdir"] = "$(sitelibdir)/$(arch)"
- CONFIG["compile_dir"] = "#{Dir.pwd}"
- MAKEFILE_CONFIG = {}
- CONFIG.each{|k,v| MAKEFILE_CONFIG[k] = v.dup}
- def Config::expand(val)
- val.gsub!(/\\$\\(([^()]+)\\)|\\$\\{([^{}]+)\\}/) do |var|
- if key = CONFIG[$1 || $2]
- Config::expand(key)
- else
- var
- end
- end
- val
- end
- CONFIG.each_value do |val|
- Config::expand(val)
- end
-end
-EOS
-$stdout.flush
-$stdout.reopen($orgout)
-config.close
-File.rename(rbconfig_rb_tmp, rbconfig_rb)
-
-# vi:set sw=2:
diff --git a/node.h b/node.h
deleted file mode 100644
index b7c9daec51..0000000000
--- a/node.h
+++ /dev/null
@@ -1,356 +0,0 @@
-/**********************************************************************
-
- node.h -
-
- $Author$
- $Date$
- created at: Fri May 28 15:14:02 JST 1993
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
-
-**********************************************************************/
-
-#ifndef NODE_H
-#define NODE_H
-
-#if defined(__cplusplus)
-extern "C" {
-#endif
-
-enum node_type {
- NODE_METHOD,
- NODE_FBODY,
- NODE_CFUNC,
- NODE_SCOPE,
- NODE_BLOCK,
- NODE_IF,
- NODE_CASE,
- NODE_WHEN,
- NODE_OPT_N,
- NODE_WHILE,
- NODE_UNTIL,
- NODE_ITER,
- NODE_FOR,
- NODE_BREAK,
- NODE_NEXT,
- NODE_REDO,
- NODE_RETRY,
- NODE_BEGIN,
- NODE_RESCUE,
- NODE_RESBODY,
- NODE_ENSURE,
- NODE_AND,
- NODE_OR,
- NODE_NOT,
- NODE_MASGN,
- NODE_LASGN,
- NODE_DASGN,
- NODE_DASGN_CURR,
- NODE_GASGN,
- NODE_IASGN,
- NODE_CDECL,
- NODE_CVASGN,
- NODE_CVDECL,
- NODE_OP_ASGN1,
- NODE_OP_ASGN2,
- NODE_OP_ASGN_AND,
- NODE_OP_ASGN_OR,
- NODE_CALL,
- NODE_FCALL,
- NODE_VCALL,
- NODE_SUPER,
- NODE_ZSUPER,
- NODE_ARRAY,
- NODE_ZARRAY,
- NODE_HASH,
- NODE_RETURN,
- NODE_YIELD,
- NODE_LVAR,
- NODE_DVAR,
- NODE_GVAR,
- NODE_IVAR,
- NODE_CONST,
- NODE_CVAR,
- NODE_NTH_REF,
- NODE_BACK_REF,
- NODE_MATCH,
- NODE_MATCH2,
- NODE_MATCH3,
- NODE_LIT,
- NODE_STR,
- NODE_DSTR,
- NODE_XSTR,
- NODE_DXSTR,
- NODE_EVSTR,
- NODE_DREGX,
- NODE_DREGX_ONCE,
- NODE_ARGS,
- NODE_ARGSCAT,
- NODE_ARGSPUSH,
- NODE_RESTARGS,
- NODE_RESTARY,
- NODE_REXPAND,
- NODE_BLOCK_ARG,
- NODE_BLOCK_PASS,
- NODE_DEFN,
- NODE_DEFS,
- NODE_ALIAS,
- NODE_VALIAS,
- NODE_UNDEF,
- NODE_CLASS,
- NODE_MODULE,
- NODE_SCLASS,
- NODE_COLON2,
- NODE_COLON3,
- NODE_CREF,
- NODE_DOT2,
- NODE_DOT3,
- NODE_FLIP2,
- NODE_FLIP3,
- NODE_ATTRSET,
- NODE_SELF,
- NODE_NIL,
- NODE_TRUE,
- NODE_FALSE,
- NODE_DEFINED,
- NODE_NEWLINE,
- NODE_POSTEXE,
-#ifdef C_ALLOCA
- NODE_ALLOCA,
-#endif
- NODE_DMETHOD,
- NODE_BMETHOD,
- NODE_MEMO,
- NODE_IFUNC,
- NODE_LAST
-};
-
-typedef struct RNode {
- unsigned long flags;
- char *nd_file;
- union {
- struct RNode *node;
- ID id;
- VALUE value;
- VALUE (*cfunc)(ANYARGS);
- ID *tbl;
- } u1;
- union {
- struct RNode *node;
- ID id;
- long argc;
- VALUE value;
- } u2;
- union {
- struct RNode *node;
- ID id;
- long state;
- struct global_entry *entry;
- long cnt;
- VALUE value;
- } u3;
-} NODE;
-
-#define RNODE(obj) (R_CAST(RNode)(obj))
-
-#define nd_type(n) (((RNODE(n))->flags>>FL_USHIFT)&0xff)
-#define nd_set_type(n,t) \
- RNODE(n)->flags=((RNODE(n)->flags&~FL_UMASK)|(((t)<<FL_USHIFT)&FL_UMASK))
-
-#define NODE_LSHIFT (FL_USHIFT+8)
-#define NODE_LMASK (((long)1<<(sizeof(NODE*)*CHAR_BIT-NODE_LSHIFT))-1)
-#define nd_line(n) (((RNODE(n))->flags>>NODE_LSHIFT)&NODE_LMASK)
-#define nd_set_line(n,l) \
- RNODE(n)->flags=((RNODE(n)->flags&~(-1<<NODE_LSHIFT))|(((l)&NODE_LMASK)<<NODE_LSHIFT))
-
-#define nd_head u1.node
-#define nd_alen u2.argc
-#define nd_next u3.node
-
-#define nd_cond u1.node
-#define nd_body u2.node
-#define nd_else u3.node
-
-#define nd_orig u3.value
-
-#define nd_resq u2.node
-#define nd_ensr u3.node
-
-#define nd_1st u1.node
-#define nd_2nd u2.node
-
-#define nd_stts u1.node
-
-#define nd_entry u3.entry
-#define nd_vid u1.id
-#define nd_cflag u2.id
-#define nd_cval u3.value
-
-#define nd_cnt u3.cnt
-#define nd_tbl u1.tbl
-
-#define nd_var u1.node
-#define nd_ibdy u2.node
-#define nd_iter u3.node
-
-#define nd_value u2.node
-#define nd_aid u3.id
-
-#define nd_lit u1.value
-
-#define nd_frml u1.node
-#define nd_rest u2.argc
-#define nd_opt u1.node
-
-#define nd_recv u1.node
-#define nd_mid u2.id
-#define nd_args u3.node
-
-#define nd_noex u1.id
-#define nd_defn u3.node
-
-#define nd_old u1.id
-#define nd_new u2.id
-
-#define nd_cfnc u1.cfunc
-#define nd_argc u2.argc
-
-#define nd_cname u1.id
-#define nd_super u3.node
-
-#define nd_modl u1.id
-#define nd_clss u1.value
-
-#define nd_beg u1.node
-#define nd_end u2.node
-#define nd_state u3.state
-#define nd_rval u2.value
-
-#define nd_nth u2.argc
-
-#define nd_tag u1.id
-#define nd_tval u2.value
-
-#define NEW_METHOD(n,x) rb_node_newnode(NODE_METHOD,x,n,0)
-#define NEW_FBODY(n,i,o) rb_node_newnode(NODE_FBODY,n,i,o)
-#define NEW_DEFN(i,a,d,p) rb_node_newnode(NODE_DEFN,p,i,NEW_RFUNC(a,d))
-#define NEW_DEFS(r,i,a,d) rb_node_newnode(NODE_DEFS,r,i,NEW_RFUNC(a,d))
-#define NEW_CFUNC(f,c) rb_node_newnode(NODE_CFUNC,f,c,0)
-#define NEW_IFUNC(f,c) rb_node_newnode(NODE_IFUNC,f,c,0)
-#define NEW_RFUNC(b1,b2) NEW_SCOPE(block_append(b1,b2))
-#define NEW_SCOPE(b) rb_node_newnode(NODE_SCOPE,local_tbl(),0,(b))
-#define NEW_BLOCK(a) rb_node_newnode(NODE_BLOCK,a,0,0)
-#define NEW_IF(c,t,e) rb_node_newnode(NODE_IF,c,t,e)
-#define NEW_UNLESS(c,t,e) NEW_IF(c,e,t)
-#define NEW_CASE(h,b) rb_node_newnode(NODE_CASE,h,b,0)
-#define NEW_WHEN(c,t,e) rb_node_newnode(NODE_WHEN,c,t,e)
-#define NEW_OPT_N(b) rb_node_newnode(NODE_OPT_N,0,b,0)
-#define NEW_WHILE(c,b,n) rb_node_newnode(NODE_WHILE,c,b,n)
-#define NEW_UNTIL(c,b,n) rb_node_newnode(NODE_UNTIL,c,b,n)
-#define NEW_FOR(v,i,b) rb_node_newnode(NODE_FOR,v,b,i)
-#define NEW_ITER(v,i,b) rb_node_newnode(NODE_ITER,v,b,i)
-#define NEW_BREAK(s) rb_node_newnode(NODE_BREAK,s,0,0)
-#define NEW_NEXT(s) rb_node_newnode(NODE_NEXT,s,0,0)
-#define NEW_REDO() rb_node_newnode(NODE_REDO,0,0,0)
-#define NEW_RETRY() rb_node_newnode(NODE_RETRY,0,0,0)
-#define NEW_BEGIN(b) rb_node_newnode(NODE_BEGIN,0,b,0)
-#define NEW_RESCUE(b,res,e) rb_node_newnode(NODE_RESCUE,b,res,e)
-#define NEW_RESBODY(a,ex,n) rb_node_newnode(NODE_RESBODY,n,ex,a)
-#define NEW_ENSURE(b,en) rb_node_newnode(NODE_ENSURE,b,0,en)
-#define NEW_RETURN(s) rb_node_newnode(NODE_RETURN,s,0,0)
-#define NEW_YIELD(a) rb_node_newnode(NODE_YIELD,a,0,0)
-#define NEW_LIST(a) NEW_ARRAY(a)
-#define NEW_ARRAY(a) rb_node_newnode(NODE_ARRAY,a,1,0)
-#define NEW_ZARRAY() rb_node_newnode(NODE_ZARRAY,0,0,0)
-#define NEW_HASH(a) rb_node_newnode(NODE_HASH,a,0,0)
-#define NEW_NOT(a) rb_node_newnode(NODE_NOT,0,a,0)
-#define NEW_MASGN(l,r) rb_node_newnode(NODE_MASGN,l,0,r)
-#define NEW_GASGN(v,val) rb_node_newnode(NODE_GASGN,v,val,rb_global_entry(v))
-#define NEW_LASGN(v,val) rb_node_newnode(NODE_LASGN,v,val,local_cnt(v))
-#define NEW_DASGN(v,val) rb_node_newnode(NODE_DASGN,v,val,0);
-#define NEW_DASGN_CURR(v,val) rb_node_newnode(NODE_DASGN_CURR,v,val,0);
-#define NEW_IASGN(v,val) rb_node_newnode(NODE_IASGN,v,val,0)
-#define NEW_CDECL(v,val) rb_node_newnode(NODE_CDECL,v,val,0)
-#define NEW_CVASGN(v,val) rb_node_newnode(NODE_CVASGN,v,val,0)
-#define NEW_CVDECL(v,val) rb_node_newnode(NODE_CVDECL,v,val,0)
-#define NEW_OP_ASGN1(p,id,a) rb_node_newnode(NODE_OP_ASGN1,p,id,a)
-#define NEW_OP_ASGN2(r,i,o,val) rb_node_newnode(NODE_OP_ASGN2,r,val,NEW_OP_ASGN22(i,o))
-#define NEW_OP_ASGN22(i,o) rb_node_newnode(NODE_OP_ASGN2,i,o,rb_id_attrset(i))
-#define NEW_OP_ASGN_OR(i,val) rb_node_newnode(NODE_OP_ASGN_OR,i,val,0)
-#define NEW_OP_ASGN_AND(i,val) rb_node_newnode(NODE_OP_ASGN_AND,i,val,0)
-#define NEW_GVAR(v) rb_node_newnode(NODE_GVAR,v,0,rb_global_entry(v))
-#define NEW_LVAR(v) rb_node_newnode(NODE_LVAR,v,0,local_cnt(v))
-#define NEW_DVAR(v) rb_node_newnode(NODE_DVAR,v,0,0);
-#define NEW_IVAR(v) rb_node_newnode(NODE_IVAR,v,0,0)
-#define NEW_CONST(v) rb_node_newnode(NODE_CONST,v,0,0)
-#define NEW_CVAR(v) rb_node_newnode(NODE_CVAR,v,0,0)
-#define NEW_NTH_REF(n) rb_node_newnode(NODE_NTH_REF,0,n,local_cnt('~'))
-#define NEW_BACK_REF(n) rb_node_newnode(NODE_BACK_REF,0,n,local_cnt('~'))
-#define NEW_MATCH(c) rb_node_newnode(NODE_MATCH,c,0,0)
-#define NEW_MATCH2(n1,n2) rb_node_newnode(NODE_MATCH2,n1,n2,0)
-#define NEW_MATCH3(r,n2) rb_node_newnode(NODE_MATCH3,r,n2,0)
-#define NEW_LIT(l) rb_node_newnode(NODE_LIT,l,0,0)
-#define NEW_STR(s) rb_node_newnode(NODE_STR,s,0,0)
-#define NEW_DSTR(s) rb_node_newnode(NODE_DSTR,s,0,0)
-#define NEW_XSTR(s) rb_node_newnode(NODE_XSTR,s,0,0)
-#define NEW_DXSTR(s) rb_node_newnode(NODE_DXSTR,s,0,0)
-#define NEW_EVSTR(s,l) rb_node_newnode(NODE_EVSTR,rb_str_new(s,l),0,0)
-#define NEW_CALL(r,m,a) rb_node_newnode(NODE_CALL,r,m,a)
-#define NEW_FCALL(m,a) rb_node_newnode(NODE_FCALL,0,m,a)
-#define NEW_VCALL(m) rb_node_newnode(NODE_VCALL,0,m,0)
-#define NEW_SUPER(a) rb_node_newnode(NODE_SUPER,0,0,a)
-#define NEW_ZSUPER() rb_node_newnode(NODE_ZSUPER,0,0,0)
-#define NEW_ARGS(f,o,r) rb_node_newnode(NODE_ARGS,o,r,f)
-#define NEW_ARGSCAT(a,b) rb_node_newnode(NODE_ARGSCAT,a,b,0)
-#define NEW_ARGSPUSH(a,b) rb_node_newnode(NODE_ARGSPUSH,a,b,0)
-#define NEW_RESTARGS(a) rb_node_newnode(NODE_RESTARGS,a,0,0)
-#define NEW_RESTARY(a) rb_node_newnode(NODE_RESTARY,a,0,0)
-#define NEW_REXPAND(a) rb_node_newnode(NODE_REXPAND,a,0,0)
-#define NEW_BLOCK_ARG(v) rb_node_newnode(NODE_BLOCK_ARG,v,0,local_cnt(v))
-#define NEW_BLOCK_PASS(b) rb_node_newnode(NODE_BLOCK_PASS,0,b,0)
-#define NEW_ALIAS(n,o) rb_node_newnode(NODE_ALIAS,o,n,0)
-#define NEW_VALIAS(n,o) rb_node_newnode(NODE_VALIAS,o,n,0)
-#define NEW_UNDEF(i) rb_node_newnode(NODE_UNDEF,0,i,0)
-#define NEW_CLASS(n,b,s) rb_node_newnode(NODE_CLASS,n,NEW_SCOPE(b),(s))
-#define NEW_SCLASS(r,b) rb_node_newnode(NODE_SCLASS,r,NEW_SCOPE(b),0)
-#define NEW_MODULE(n,b) rb_node_newnode(NODE_MODULE,n,NEW_SCOPE(b),0)
-#define NEW_COLON2(c,i) rb_node_newnode(NODE_COLON2,c,i,0)
-#define NEW_COLON3(i) rb_node_newnode(NODE_COLON3,0,i,0)
-#define NEW_CREF(c) (rb_node_newnode(NODE_CREF,0,0,c))
-#define NEW_DOT2(b,e) rb_node_newnode(NODE_DOT2,b,e,0)
-#define NEW_DOT3(b,e) rb_node_newnode(NODE_DOT3,b,e,0)
-#define NEW_ATTRSET(a) rb_node_newnode(NODE_ATTRSET,a,0,0)
-#define NEW_SELF() rb_node_newnode(NODE_SELF,0,0,0)
-#define NEW_NIL() rb_node_newnode(NODE_NIL,0,0,0)
-#define NEW_TRUE() rb_node_newnode(NODE_TRUE,0,0,0)
-#define NEW_FALSE() rb_node_newnode(NODE_FALSE,0,0,0)
-#define NEW_DEFINED(e) rb_node_newnode(NODE_DEFINED,e,0,0)
-#define NEW_NEWLINE(n) rb_node_newnode(NODE_NEWLINE,0,0,n)
-#define NEW_PREEXE(b) NEW_SCOPE(b)
-#define NEW_POSTEXE() rb_node_newnode(NODE_POSTEXE,0,0,0)
-#define NEW_DMETHOD(b) rb_node_newnode(NODE_DMETHOD,0,0,b)
-#define NEW_BMETHOD(b) rb_node_newnode(NODE_BMETHOD,0,0,b)
-
-#define NOEX_PUBLIC 0
-#define NOEX_UNDEF 1
-#define NOEX_CFUNC 1
-#define NOEX_PRIVATE 2
-#define NOEX_PROTECTED 4
-
-NODE *rb_compile_cstr _((const char*, const char*, int, int));
-NODE *rb_compile_string _((const char*, VALUE, int));
-NODE *rb_compile_file _((const char*, VALUE, int));
-
-void rb_add_method _((VALUE, ID, NODE *, int));
-NODE *rb_node_newnode(ANYARGS);
-
-struct global_entry *rb_global_entry _((ID));
-VALUE rb_gvar_get _((struct global_entry *));
-VALUE rb_gvar_set _((struct global_entry *, VALUE));
-VALUE rb_gvar_defined _((struct global_entry *));
-
-#if defined(__cplusplus)
-} /* extern "C" { */
-#endif
-
-#endif
diff --git a/numeric.c b/numeric.c
deleted file mode 100644
index 80fa1052f9..0000000000
--- a/numeric.c
+++ /dev/null
@@ -1,1763 +0,0 @@
-/**********************************************************************
-
- numeric.c -
-
- $Author$
- $Date$
- created at: Fri Aug 13 18:33:09 JST 1993
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
-
-**********************************************************************/
-
-#include "ruby.h"
-#include <math.h>
-#include <stdio.h>
-#if defined(__FreeBSD__) && __FreeBSD__ < 4
-#include <floatingpoint.h>
-#endif
-
-static ID id_coerce, id_to_i, id_div;
-
-VALUE rb_cNumeric;
-VALUE rb_cFloat;
-VALUE rb_cInteger;
-VALUE rb_cFixnum;
-
-VALUE rb_eZeroDivError;
-VALUE rb_eFloatDomainError;
-
-void
-rb_num_zerodiv()
-{
- rb_raise(rb_eZeroDivError, "divided by 0");
-}
-
-static VALUE
-num_coerce(x, y)
- VALUE x, y;
-{
- if (CLASS_OF(x) == CLASS_OF(y))
- return rb_assoc_new(y, x);
- return rb_assoc_new(rb_Float(y), rb_Float(x));
-}
-
-static VALUE
-coerce_body(x)
- VALUE *x;
-{
- return rb_funcall(x[1], id_coerce, 1, x[0]);
-}
-
-static VALUE
-coerce_rescue(x)
- VALUE *x;
-{
- rb_raise(rb_eTypeError, "%s can't be coerced into %s",
- rb_special_const_p(x[1])?
- RSTRING(rb_inspect(x[1]))->ptr:
- rb_class2name(CLASS_OF(x[1])),
- rb_class2name(CLASS_OF(x[0])));
- return Qnil; /* dummy */
-}
-
-static void
-do_coerce(x, y)
- VALUE *x, *y;
-{
- VALUE ary;
- VALUE a[2];
-
- a[0] = *x; a[1] = *y;
-
- ary = rb_rescue(coerce_body, (VALUE)a, coerce_rescue, (VALUE)a);
- if (TYPE(ary) != T_ARRAY || RARRAY(ary)->len != 2) {
- rb_raise(rb_eTypeError, "coerce must return [x, y]");
- }
-
- *x = RARRAY(ary)->ptr[0];
- *y = RARRAY(ary)->ptr[1];
-}
-
-VALUE
-rb_num_coerce_bin(x, y)
- VALUE x, y;
-{
- do_coerce(&x, &y);
- return rb_funcall(x, rb_frame_last_func(), 1, y);
-}
-
-static VALUE
-num_clone(x)
- VALUE x;
-{
- /* Numerics are immutable values, which should not be copied */
- rb_raise(rb_eTypeError, "can't clone %s", rb_class2name(CLASS_OF(x)));
- return Qnil; /* not reached */
-}
-
-static VALUE
-num_uplus(num)
- VALUE num;
-{
- return num;
-}
-
-static VALUE
-num_uminus(num)
- VALUE num;
-{
- VALUE zero;
-
- zero = INT2FIX(0);
- do_coerce(&zero, &num);
-
- return rb_funcall(zero, '-', 1, num);
-}
-
-static VALUE
-num_div(x, y)
- VALUE x, y;
-{
- return rb_funcall(x, id_div, 1, y);
-}
-
-static VALUE
-num_divmod(x, y)
- VALUE x, y;
-{
- VALUE div, mod;
-
- div = rb_funcall(x, id_div, 1, y);
- if (TYPE(div) == T_FLOAT) {
- double d = floor(RFLOAT(div)->value);
-
- if (RFLOAT(div)->value > d) {
- div = rb_float_new(d);
- }
- }
- mod = rb_funcall(x, '%', 1, y);
- return rb_assoc_new(div, mod);
-}
-
-static VALUE
-num_modulo(x, y)
- VALUE x, y;
-{
- return rb_funcall(x, '%', 1, y);
-}
-
-static VALUE
-num_remainder(x, y)
- VALUE x, y;
-{
- VALUE z = rb_funcall(x, '%', 1, y);
-
- if ((!RTEST(rb_equal(z, INT2FIX(0)))) &&
- ((RTEST(rb_funcall(x, '<', 1, INT2FIX(0))) &&
- RTEST(rb_funcall(y, '>', 1, INT2FIX(0)))) ||
- (RTEST(rb_funcall(x, '>', 1, INT2FIX(0))) &&
- RTEST(rb_funcall(y, '<', 1, INT2FIX(0)))))) {
- return rb_funcall(z, '-', 1, y);
- }
- return z;
-}
-
-static VALUE
-num_int_p(num)
- VALUE num;
-{
- return Qfalse;
-}
-
-static VALUE
-num_abs(num)
- VALUE num;
-{
- if (RTEST(rb_funcall(num, '<', 1, INT2FIX(0)))) {
- return rb_funcall(num, rb_intern("-@"), 0);
- }
- return num;
-}
-
-static VALUE
-num_zero_p(num)
- VALUE num;
-{
- if (RTEST(rb_equal(num, INT2FIX(0)))) {
- return Qtrue;
- }
- return Qfalse;
-}
-
-static VALUE
-num_nonzero_p(num)
- VALUE num;
-{
- if (RTEST(rb_funcall(num, rb_intern("zero?"), 0, 0))) {
- return Qnil;
- }
- return num;
-}
-
-VALUE
-rb_float_new(d)
- double d;
-{
- NEWOBJ(flt, struct RFloat);
- OBJSETUP(flt, rb_cFloat, T_FLOAT);
-
- flt->value = d;
- return (VALUE)flt;
-}
-
-static VALUE
-flo_to_s(flt)
- VALUE flt;
-{
- char buf[24];
- char *fmt = "%.10g";
- double value = RFLOAT(flt)->value;
- double avalue, d1, d2;
-
- if (isinf(value))
- return rb_str_new2(value < 0 ? "-Infinity" : "Infinity");
- else if(isnan(value))
- return rb_str_new2("NaN");
-
- avalue = fabs(value);
- if (avalue == 0.0) {
- fmt = "%.1f";
- }
- else if (avalue < 1.0e-3) {
- d1 = avalue;
- while (d1 < 1.0) d1 *= 10.0;
- d1 = modf(d1, &d2);
- if (d1 == 0) fmt = "%.1e";
- }
- else if (avalue >= 1.0e10) {
- d1 = avalue;
- while (d1 > 10.0) d1 /= 10.0;
- d1 = modf(d1, &d2);
- if (d1 == 0) fmt = "%.1e";
- }
- else if ((d1 = modf(value, &d2)) == 0) {
- fmt = "%.1f";
- }
- sprintf(buf, fmt, value);
-
- return rb_str_new2(buf);
-}
-
-static VALUE
-flo_coerce(x, y)
- VALUE x, y;
-{
- return rb_assoc_new(rb_Float(y), x);
-}
-
-static VALUE
-flo_uminus(flt)
- VALUE flt;
-{
- return rb_float_new(-RFLOAT(flt)->value);
-}
-
-static VALUE
-flo_plus(x, y)
- VALUE x, y;
-{
- switch (TYPE(y)) {
- case T_FIXNUM:
- return rb_float_new(RFLOAT(x)->value + (double)FIX2LONG(y));
- case T_BIGNUM:
- return rb_float_new(RFLOAT(x)->value + rb_big2dbl(y));
- case T_FLOAT:
- return rb_float_new(RFLOAT(x)->value + RFLOAT(y)->value);
- default:
- return rb_num_coerce_bin(x, y);
- }
-}
-
-static VALUE
-flo_minus(x, y)
- VALUE x, y;
-{
- switch (TYPE(y)) {
- case T_FIXNUM:
- return rb_float_new(RFLOAT(x)->value - (double)FIX2LONG(y));
- case T_BIGNUM:
- return rb_float_new(RFLOAT(x)->value - rb_big2dbl(y));
- case T_FLOAT:
- return rb_float_new(RFLOAT(x)->value - RFLOAT(y)->value);
- default:
- return rb_num_coerce_bin(x, y);
- }
-}
-
-static VALUE
-flo_mul(x, y)
- VALUE x, y;
-{
- switch (TYPE(y)) {
- case T_FIXNUM:
- return rb_float_new(RFLOAT(x)->value * (double)FIX2LONG(y));
- case T_BIGNUM:
- return rb_float_new(RFLOAT(x)->value * rb_big2dbl(y));
- case T_FLOAT:
- return rb_float_new(RFLOAT(x)->value * RFLOAT(y)->value);
- default:
- return rb_num_coerce_bin(x, y);
- }
-}
-
-static VALUE
-flo_div(x, y)
- VALUE x, y;
-{
- long f_y;
- double d;
-
- switch (TYPE(y)) {
- case T_FIXNUM:
- f_y = FIX2LONG(y);
- return rb_float_new(RFLOAT(x)->value / (double)f_y);
- case T_BIGNUM:
- d = rb_big2dbl(y);
- return rb_float_new(RFLOAT(x)->value / d);
- case T_FLOAT:
- return rb_float_new(RFLOAT(x)->value / RFLOAT(y)->value);
- default:
- return rb_num_coerce_bin(x, y);
- }
-}
-
-static void
-flodivmod(x, y, divp, modp)
- double x, y;
- double *divp, *modp;
-{
- double div, mod;
-
-#ifdef HAVE_FMOD
- mod = fmod(x, y);
-#else
- {
- double z;
-
- modf(x/y, &z);
- mod = x - z * y;
- }
-#endif
- div = (x - mod) / y;
- if (y*mod < 0) {
- mod += y;
- div -= 1.0;
- }
- if (modp) *modp = mod;
- if (divp) *divp = div;
-}
-
-static VALUE
-flo_mod(x, y)
- VALUE x, y;
-{
- double fy, mod;
-
- switch (TYPE(y)) {
- case T_FIXNUM:
- fy = (double)FIX2LONG(y);
- break;
- case T_BIGNUM:
- fy = rb_big2dbl(y);
- break;
- case T_FLOAT:
- fy = RFLOAT(y)->value;
- break;
- default:
- return rb_num_coerce_bin(x, y);
- }
- flodivmod(RFLOAT(x)->value, fy, 0, &mod);
- return rb_float_new(mod);
-}
-
-static VALUE
-flo_divmod(x, y)
- VALUE x, y;
-{
- double fy, div, mod;
-
- switch (TYPE(y)) {
- case T_FIXNUM:
- fy = (double)FIX2LONG(y);
- break;
- case T_BIGNUM:
- fy = rb_big2dbl(y);
- break;
- case T_FLOAT:
- fy = RFLOAT(y)->value;
- break;
- default:
- return rb_num_coerce_bin(x, y);
- }
- flodivmod(RFLOAT(x)->value, fy, &div, &mod);
- return rb_assoc_new(rb_float_new(div), rb_float_new(mod));
-}
-
-static VALUE
-flo_pow(x, y)
- VALUE x, y;
-{
- switch (TYPE(y)) {
- case T_FIXNUM:
- return rb_float_new(pow(RFLOAT(x)->value, (double)FIX2LONG(y)));
- case T_BIGNUM:
- return rb_float_new(pow(RFLOAT(x)->value, rb_big2dbl(y)));
- case T_FLOAT:
- return rb_float_new(pow(RFLOAT(x)->value, RFLOAT(y)->value));
- default:
- return rb_num_coerce_bin(x, y);
- }
-}
-
-static VALUE
-num_eql(x, y)
- VALUE x, y;
-{
- if (TYPE(x) != TYPE(y)) return Qfalse;
-
- return rb_equal(x, y);
-}
-
-static VALUE
-num_equal(x, y)
- VALUE x, y;
-{
- return rb_equal(y, x);
-}
-
-static VALUE
-flo_eq(x, y)
- VALUE x, y;
-{
- switch (TYPE(y)) {
- case T_FIXNUM:
- if (RFLOAT(x)->value == FIX2LONG(y)) return Qtrue;
- return Qfalse;
- case T_BIGNUM:
- return (RFLOAT(x)->value == rb_big2dbl(y))?Qtrue:Qfalse;
- case T_FLOAT:
- return (RFLOAT(x)->value == RFLOAT(y)->value)?Qtrue:Qfalse;
- default:
- return num_equal(x, y);
- }
-}
-
-static VALUE
-flo_hash(num)
- VALUE num;
-{
- double d;
- char *c;
- int i, hash;
-
- d = RFLOAT(num)->value;
- if (d == 0) d = fabs(d);
- c = (char*)&d;
- for (hash=0, i=0; i<sizeof(double);i++) {
- hash += c[i] * 971;
- }
- if (hash < 0) hash = -hash;
- return INT2FIX(hash);
-}
-
-static VALUE
-flo_cmp(x, y)
- VALUE x, y;
-{
- double a, b;
-
- a = RFLOAT(x)->value;
- switch (TYPE(y)) {
- case T_FIXNUM:
- b = (double)FIX2LONG(y);
- break;
-
- case T_BIGNUM:
- b = rb_big2dbl(y);
- break;
-
- case T_FLOAT:
- b = RFLOAT(y)->value;
- break;
-
- default:
- return rb_num_coerce_bin(x, y);
- }
- if (a == b) return INT2FIX(0);
- if (a > b) return INT2FIX(1);
- if (a < b) return INT2FIX(-1);
- rb_raise(rb_eFloatDomainError, "comparing NaN");
-}
-
-static VALUE
-flo_gt(x, y)
- VALUE x, y;
-{
- double a, b;
-
- a = RFLOAT(x)->value;
- switch (TYPE(y)) {
- case T_FIXNUM:
- b = (double)FIX2LONG(y);
- break;
-
- case T_BIGNUM:
- b = rb_big2dbl(y);
- break;
-
- case T_FLOAT:
- b = RFLOAT(y)->value;
- break;
-
- default:
- return rb_num_coerce_bin(x, y);
- }
- return (a > b)?Qtrue:Qfalse;
-}
-
-static VALUE
-flo_ge(x, y)
- VALUE x, y;
-{
- double a, b;
-
- a = RFLOAT(x)->value;
- switch (TYPE(y)) {
- case T_FIXNUM:
- b = (double)FIX2LONG(y);
- break;
-
- case T_BIGNUM:
- b = rb_big2dbl(y);
- break;
-
- case T_FLOAT:
- b = RFLOAT(y)->value;
- break;
-
- default:
- return rb_num_coerce_bin(x, y);
- }
- return (a >= b)?Qtrue:Qfalse;
-}
-
-static VALUE
-flo_lt(x, y)
- VALUE x, y;
-{
- double a, b;
-
- a = RFLOAT(x)->value;
- switch (TYPE(y)) {
- case T_FIXNUM:
- b = (double)FIX2LONG(y);
- break;
-
- case T_BIGNUM:
- b = rb_big2dbl(y);
- break;
-
- case T_FLOAT:
- b = RFLOAT(y)->value;
- break;
-
- default:
- return rb_num_coerce_bin(x, y);
- }
- return (a < b)?Qtrue:Qfalse;
-}
-
-static VALUE
-flo_le(x, y)
- VALUE x, y;
-{
- double a, b;
-
- a = RFLOAT(x)->value;
- switch (TYPE(y)) {
- case T_FIXNUM:
- b = (double)FIX2LONG(y);
- break;
-
- case T_BIGNUM:
- b = rb_big2dbl(y);
- break;
-
- case T_FLOAT:
- b = RFLOAT(y)->value;
- break;
-
- default:
- return rb_num_coerce_bin(x, y);
- }
- return (a <= b)?Qtrue:Qfalse;
-}
-
-static VALUE
-flo_eql(x, y)
- VALUE x, y;
-{
- if (TYPE(y) == T_FLOAT && RFLOAT(x)->value == RFLOAT(y)->value) {
- return Qtrue;
- }
- return Qfalse;
-}
-
-static VALUE
-flo_to_f(num)
- VALUE num;
-{
- return num;
-}
-
-static VALUE
-flo_abs(flt)
- VALUE flt;
-{
- double val = fabs(RFLOAT(flt)->value);
- return rb_float_new(val);
-}
-
-static VALUE
-flo_zero_p(num)
- VALUE num;
-{
- if (RFLOAT(num)->value == 0.0) {
- return Qtrue;
- }
- return Qfalse;
-}
-
-static VALUE flo_is_nan_p(num)
- VALUE num;
-{
-
- double value = RFLOAT(num)->value;
-
- return isnan(value) ? Qtrue : Qfalse;
-}
-
-static VALUE flo_is_infinite_p(num)
- VALUE num;
-{
- double value = RFLOAT(num)->value;
-
- if (isinf(value)) {
- return INT2FIX( value < 0 ? -1 : +1 );
- }
-
- return Qnil;
-}
-
-static VALUE flo_is_finite_p(num)
- VALUE num;
-{
- double value = RFLOAT(num)->value;
-
- if (isinf(value) || isnan(value))
- return Qfalse;
-
- return Qtrue;
-}
-
-
-static VALUE
-flo_floor(num)
- VALUE num;
-{
- double f = floor(RFLOAT(num)->value);
- long val;
-
- if (!FIXABLE(f)) {
- return rb_dbl2big(f);
- }
- val = f;
- return INT2FIX(val);
-}
-
-static VALUE
-flo_ceil(num)
- VALUE num;
-{
- double f = ceil(RFLOAT(num)->value);
- long val;
-
- if (!FIXABLE(f)) {
- return rb_dbl2big(f);
- }
- val = f;
- return INT2FIX(val);
-}
-
-static VALUE
-flo_round(num)
- VALUE num;
-{
- double f = RFLOAT(num)->value;
- long val;
-
- if (f > 0.0) f = floor(f+0.5);
- if (f < 0.0) f = ceil(f-0.5);
-
- if (!FIXABLE(f)) {
- return rb_dbl2big(f);
- }
- val = f;
- return INT2FIX(val);
-}
-
-static VALUE
-flo_truncate(num)
- VALUE num;
-{
- double f = RFLOAT(num)->value;
- long val;
-
- if (f > 0.0) f = floor(f);
- if (f < 0.0) f = ceil(f);
-
- if (!FIXABLE(f)) {
- return rb_dbl2big(f);
- }
- val = f;
- return INT2FIX(val);
-}
-
-static VALUE
-num_floor(num)
- VALUE num;
-{
- return flo_floor(rb_Float(num));
-}
-
-static VALUE
-num_ceil(num)
- VALUE num;
-{
- return flo_ceil(rb_Float(num));
-}
-
-static VALUE
-num_round(num)
- VALUE num;
-{
- return flo_round(rb_Float(num));
-}
-
-static VALUE
-num_truncate(num)
- VALUE num;
-{
- return flo_truncate(rb_Float(num));
-}
-
-long
-rb_num2long(val)
- VALUE val;
-{
- if (NIL_P(val)) {
- rb_raise(rb_eTypeError, "no implicit conversion to integer from nil");
- }
-
- if (FIXNUM_P(val)) return FIX2LONG(val);
-
- switch (TYPE(val)) {
- case T_FLOAT:
- if (RFLOAT(val)->value <= (double)LONG_MAX
- && RFLOAT(val)->value >= (double)LONG_MIN) {
- return (long)(RFLOAT(val)->value);
- }
- else {
- char buf[24];
- char *s;
-
- sprintf(buf, "%-.10g", RFLOAT(val)->value);
- if (s = strchr(buf, ' ')) *s = '\0';
- rb_raise(rb_eRangeError, "float %s out of range of integer", buf);
- }
-
- case T_BIGNUM:
- return rb_big2long(val);
-
- case T_STRING:
- rb_raise(rb_eTypeError, "no implicit conversion to integer from string");
- return Qnil; /* not reached */
-
- case T_TRUE:
- case T_FALSE:
- rb_raise(rb_eTypeError, "no implicit conversion to integer from boolean");
- return Qnil; /* not reached */
-
- default:
- val = rb_to_int(val);
- return NUM2LONG(val);
- }
-}
-
-unsigned long
-rb_num2ulong(val)
- VALUE val;
-{
- if (TYPE(val) == T_BIGNUM) {
- return rb_big2ulong(val);
- }
- return (unsigned long)rb_num2long(val);
-}
-
-#if SIZEOF_INT < SIZEOF_LONG
-int
-rb_num2int(val)
- VALUE val;
-{
- long num = rb_num2long(val);
-
- if (num < INT_MIN || INT_MAX < num) {
- rb_raise(rb_eRangeError, "integer %d too big to convert to `int'", num);
- }
- return (int)num;
-}
-
-int
-rb_fix2int(val)
- VALUE val;
-{
- long num = FIXNUM_P(val)?FIX2LONG(val):rb_num2long(val);
-
- if (num < INT_MIN || INT_MAX < num) {
- rb_raise(rb_eRangeError, "integer %d too big to convert to `int'", num);
- }
- return (int)num;
-}
-#else
-int
-rb_num2int(val)
- VALUE val;
-{
- return rb_num2long(val);
-}
-
-int
-rb_fix2int(val)
- VALUE val;
-{
- return FIX2INT(val);
-}
-#endif
-
-VALUE
-rb_num2fix(val)
- VALUE val;
-{
- long v;
-
- if (FIXNUM_P(val)) return val;
-
- v = rb_num2long(val);
- if (!FIXABLE(v))
- rb_raise(rb_eRangeError, "integer %d out of range of fixnum", v);
- return INT2FIX(v);
-}
-
-#if HAVE_LONG_LONG
-
-LONG_LONG
-rb_num2ll(val)
- VALUE val;
-{
- if (NIL_P(val)) {
- rb_raise(rb_eTypeError, "no implicit conversion from nil");
- }
-
- if (FIXNUM_P(val)) return (LONG_LONG)FIX2LONG(val);
-
- switch (TYPE(val)) {
- case T_FLOAT:
- if (RFLOAT(val)->value <= (double)LLONG_MAX
- && RFLOAT(val)->value >= (double)LLONG_MIN) {
- return (LONG_LONG)(RFLOAT(val)->value);
- }
- else {
- char buf[24];
- char *s;
-
- sprintf(buf, "%-.10g", RFLOAT(val)->value);
- if (s = strchr(buf, ' ')) *s = '\0';
- rb_raise(rb_eRangeError, "float %s out of range of long long", buf);
- }
-
- case T_BIGNUM:
- return rb_big2ll(val);
-
- case T_STRING:
- rb_raise(rb_eTypeError, "no implicit conversion from string");
- return Qnil; /* not reached */
-
- case T_TRUE:
- case T_FALSE:
- rb_raise(rb_eTypeError, "no implicit conversion from boolean");
- return Qnil; /* not reached */
-
- default:
- val = rb_to_int(val);
- return NUM2LL(val);
- }
-}
-
-unsigned LONG_LONG
-rb_num2ull(val)
- VALUE val;
-{
- if (TYPE(val) == T_BIGNUM) {
- return rb_big2ull(val);
- }
- return (unsigned LONG_LONG)rb_num2ll(val);
-}
-
-#endif /* HAVE_LONG_LONG */
-
-static VALUE
-int_to_i(num)
- VALUE num;
-{
- return num;
-}
-
-static VALUE
-int_int_p(num)
- VALUE num;
-{
- return Qtrue;
-}
-
-static VALUE
-int_succ(num)
- VALUE num;
-{
- return rb_funcall(num, '+', 1, INT2FIX(1));
-}
-
-static VALUE
-int_chr(num)
- VALUE num;
-{
- char c;
- long i = NUM2LONG(num);
-
- if (i < 0 || 0xff < i)
- rb_raise(rb_eRangeError, "%d out of char range", i);
- c = i;
- return rb_str_new(&c, 1);
-}
-
-static VALUE
-rb_fix_induced_from(klass, x)
- VALUE klass, x;
-{
- return rb_num2fix(x);
-}
-
-static VALUE
-rb_int_induced_from(klass, x)
- VALUE klass, x;
-{
- switch (TYPE(x)) {
- case T_FIXNUM:
- case T_BIGNUM:
- return x;
- case T_FLOAT:
- return rb_funcall(x, rb_intern("to_i"), 0);
- default:
- rb_raise(rb_eTypeError, "failed to convert %s into Integer",
- rb_class2name(CLASS_OF(x)));
- }
-}
-
-static VALUE
-rb_flo_induced_from(klass, x)
- VALUE klass, x;
-{
- switch (TYPE(x)) {
- case T_FIXNUM:
- case T_BIGNUM:
- return rb_funcall(x, rb_intern("to_f"), 0);
- case T_FLOAT:
- return x;
- default:
- rb_raise(rb_eTypeError, "failed to convert %s into Float",
- rb_class2name(CLASS_OF(x)));
- }
-}
-
-static VALUE
-fix_uminus(num)
- VALUE num;
-{
- return rb_int2inum(-FIX2LONG(num));
-}
-
-VALUE
-rb_fix2str(x, base)
- VALUE x;
- int base;
-{
- char fmt[4], buf[22], *b = buf;
- long val = FIX2LONG(x);
-
- fmt[0] = '%'; fmt[1] = 'l'; fmt[3] = '\0';
- if (base == 10) fmt[2] = 'd';
- else if (base == 16) fmt[2] = 'x';
- else if (base == 8) fmt[2] = 'o';
- else rb_raise(rb_eArgError, "illegal radix %d", base);
- if (val < 0) {
- val = -val;
- *b++ = '-';
- }
-
- sprintf(b, fmt, val);
- return rb_str_new2(buf);
-}
-
-static VALUE
-fix_to_s(argc, argv, x)
- int argc;
- VALUE *argv;
- VALUE x;
-{
- VALUE b;
- int base;
-
- rb_scan_args(argc, argv, "01", &b);
- if (argc == 0) base = 10;
- else base = NUM2INT(b);
-
- if (base == 2) {
- /* rb_fix2str() does not handle binary */
- return rb_big2str(rb_int2big(FIX2INT(x)), 2);
- }
- return rb_fix2str(x, base);
-}
-
-static VALUE
-fix_plus(x, y)
- VALUE x, y;
-{
- if (FIXNUM_P(y)) {
- long a, b, c;
- VALUE r;
-
- a = FIX2LONG(x);
- b = FIX2LONG(y);
- c = a + b;
- r = INT2FIX(c);
-
- if (FIX2LONG(r) != c) {
- r = rb_big_plus(rb_int2big(a), rb_int2big(b));
- }
- return r;
- }
- if (TYPE(y) == T_FLOAT) {
- return rb_float_new((double)FIX2LONG(x) + RFLOAT(y)->value);
- }
- return rb_num_coerce_bin(x, y);
-}
-
-static VALUE
-fix_minus(x, y)
- VALUE x, y;
-{
- if (FIXNUM_P(y)) {
- long a, b, c;
- VALUE r;
-
- a = FIX2LONG(x);
- b = FIX2LONG(y);
- c = a - b;
- r = INT2FIX(c);
-
- if (FIX2LONG(r) != c) {
- r = rb_big_minus(rb_int2big(a), rb_int2big(b));
- }
- return r;
- }
- if (TYPE(y) == T_FLOAT) {
- return rb_float_new((double)FIX2LONG(x) - RFLOAT(y)->value);
- }
- return rb_num_coerce_bin(x, y);
-}
-
-static VALUE
-fix_mul(x, y)
- VALUE x, y;
-{
- if (FIXNUM_P(y)) {
- long a, b, c;
- VALUE r;
-
- a = FIX2LONG(x);
- if (a == 0) return x;
-
- b = FIX2LONG(y);
- c = a * b;
- r = INT2FIX(c);
-
- if (FIX2LONG(r) != c || c/a != b) {
- r = rb_big_mul(rb_int2big(a), rb_int2big(b));
- }
- return r;
- }
- if (TYPE(y) == T_FLOAT) {
- return rb_float_new((double)FIX2LONG(x) * RFLOAT(y)->value);
- }
- return rb_num_coerce_bin(x, y);
-}
-
-static void
-fixdivmod(x, y, divp, modp)
- long x, y;
- long *divp, *modp;
-{
- long div, mod;
-
- if (y == 0) rb_num_zerodiv();
- if (y < 0) {
- if (x < 0)
- div = -x / -y;
- else
- div = - (x / -y);
- }
- else {
- if (x < 0)
- div = - (-x / y);
- else
- div = x / y;
- }
- mod = x - div*y;
- if ((mod < 0 && y > 0) || (mod > 0 && y < 0)) {
- mod += y;
- div -= 1;
- }
- if (divp) *divp = div;
- if (modp) *modp = mod;
-}
-
-static VALUE
-fix_div(x, y)
- VALUE x, y;
-{
- if (FIXNUM_P(y)) {
- long div;
-
- fixdivmod(FIX2LONG(x), FIX2LONG(y), &div, 0);
- return INT2NUM(div);
- }
- return rb_num_coerce_bin(x, y);
-}
-
-static VALUE
-fix_mod(x, y)
- VALUE x, y;
-{
- if (FIXNUM_P(y)) {
- long mod;
-
- fixdivmod(FIX2LONG(x), FIX2LONG(y), 0, &mod);
- return INT2NUM(mod);
- }
- return rb_num_coerce_bin(x, y);
-}
-
-static VALUE
-fix_divmod(x, y)
- VALUE x, y;
-{
- if (FIXNUM_P(y)) {
- long div, mod;
-
- fixdivmod(FIX2LONG(x), FIX2LONG(y), &div, &mod);
-
- return rb_assoc_new(INT2NUM(div), INT2NUM(mod));
- }
- return rb_num_coerce_bin(x, y);
-}
-
-static VALUE
-fix_pow(x, y)
- VALUE x, y;
-{
- if (FIXNUM_P(y)) {
- long a, b;
-
- b = FIX2LONG(y);
- if (b == 0) return INT2FIX(1);
- if (b == 1) return x;
- a = FIX2LONG(x);
- if (b > 0) {
- return rb_big_pow(rb_int2big(a), y);
- }
- return rb_float_new(pow((double)a, (double)b));
- }
- return rb_num_coerce_bin(x, y);
-}
-
-static VALUE
-fix_equal(x, y)
- VALUE x, y;
-{
- if (FIXNUM_P(y)) {
- return (FIX2LONG(x) == FIX2LONG(y))?Qtrue:Qfalse;
- }
- else {
- return num_equal(x, y);
- }
-}
-
-static VALUE
-fix_cmp(x, y)
- VALUE x, y;
-{
- if (FIXNUM_P(y)) {
- long a = FIX2LONG(x), b = FIX2LONG(y);
-
- if (a == b) return INT2FIX(0);
- if (a > b) return INT2FIX(1);
- return INT2FIX(-1);
- }
- else {
- return rb_num_coerce_bin(x, y);
- }
-}
-
-static VALUE
-fix_gt(x, y)
- VALUE x, y;
-{
- if (FIXNUM_P(y)) {
- long a = FIX2LONG(x), b = FIX2LONG(y);
-
- if (a > b) return Qtrue;
- return Qfalse;
- }
- else {
- return rb_num_coerce_bin(x, y);
- }
-}
-
-static VALUE
-fix_ge(x, y)
- VALUE x, y;
-{
- if (FIXNUM_P(y)) {
- long a = FIX2LONG(x), b = FIX2LONG(y);
-
- if (a >= b) return Qtrue;
- return Qfalse;
- }
- else {
- return rb_num_coerce_bin(x, y);
- }
-}
-
-static VALUE
-fix_lt(x, y)
- VALUE x, y;
-{
- if (FIXNUM_P(y)) {
- long a = FIX2LONG(x), b = FIX2LONG(y);
-
- if (a < b) return Qtrue;
- return Qfalse;
- }
- else {
- return rb_num_coerce_bin(x, y);
- }
-}
-
-static VALUE
-fix_le(x, y)
- VALUE x, y;
-{
- if (FIXNUM_P(y)) {
- long a = FIX2LONG(x), b = FIX2LONG(y);
-
- if (a <= b) return Qtrue;
- return Qfalse;
- }
- else {
- return rb_num_coerce_bin(x, y);
- }
-}
-
-static VALUE
-fix_rev(num)
- VALUE num;
-{
- long val = FIX2LONG(num);
-
- val = ~val;
- return rb_int2inum(val);
-}
-
-static VALUE
-fix_and(x, y)
- VALUE x, y;
-{
- long val;
-
- if (TYPE(y) == T_BIGNUM) {
- return rb_big_and(y, x);
- }
- val = FIX2LONG(x) & NUM2LONG(y);
- return rb_int2inum(val);
-}
-
-static VALUE
-fix_or(x, y)
- VALUE x, y;
-{
- long val;
-
- if (TYPE(y) == T_BIGNUM) {
- return rb_big_or(y, x);
- }
- val = FIX2LONG(x) | NUM2LONG(y);
- return rb_int2inum(val);
-}
-
-static VALUE
-fix_xor(x, y)
- VALUE x, y;
-{
- long val;
-
- if (TYPE(y) == T_BIGNUM) {
- return rb_big_xor(y, x);
- }
- val = FIX2LONG(x) ^ NUM2LONG(y);
- return rb_int2inum(val);
-}
-
-static VALUE
-fix_lshift(x, y)
- VALUE x, y;
-{
- long val, width;
-
- val = NUM2LONG(x);
- width = NUM2LONG(y);
- if (width > (sizeof(VALUE)*CHAR_BIT-1)
- || ((unsigned long)val)>>(sizeof(VALUE)*CHAR_BIT-1-width) > 0) {
- return rb_big_lshift(rb_int2big(val), y);
- }
- val = val << width;
- return rb_int2inum(val);
-}
-
-static VALUE
-fix_rshift(x, y)
- VALUE x, y;
-{
- long i, val;
-
- i = NUM2LONG(y);
- if (i < 0)
- return fix_lshift(x, INT2FIX(-i));
- if (i == 0) return x;
- if (i >= sizeof(long)*CHAR_BIT-1) {
- if (i < 0) return INT2FIX(-1);
- return INT2FIX(0);
- }
- val = RSHIFT(FIX2LONG(x), i);
- return INT2FIX(val);
-}
-
-static VALUE
-fix_aref(fix, idx)
- VALUE fix, idx;
-{
- long val = FIX2LONG(fix);
-
- if (TYPE(idx) == T_BIGNUM) {
- if (!RBIGNUM(idx)->sign || val >= 0)
- return INT2FIX(0);
- return INT2FIX(1);
- }
- else {
- int i = NUM2INT(idx);
-
- if (i < 0) return INT2FIX(0);
- if (sizeof(VALUE)*CHAR_BIT-1 < i) {
- if (val < 0) return INT2FIX(1);
- return INT2FIX(0);
- }
- if (val & (1L<<i))
- return INT2FIX(1);
- return INT2FIX(0);
- }
-}
-
-static VALUE
-fix_to_f(num)
- VALUE num;
-{
- double val;
-
- val = (double)FIX2LONG(num);
-
- return rb_float_new(val);
-}
-
-static VALUE
-fix_abs(fix)
- VALUE fix;
-{
- long i = FIX2LONG(fix);
-
- if (i < 0) i = -i;
-
- return rb_int2inum(i);
-}
-
-static VALUE
-fix_id2name(fix)
- VALUE fix;
-{
- char *name = rb_id2name(FIX2UINT(fix));
- if (name) return rb_str_new2(name);
- return Qnil;
-}
-
-static VALUE
-fix_succ(fix)
- VALUE fix;
-{
- long i = FIX2LONG(fix) + 1;
-
- return rb_int2inum(i);
-}
-
-static VALUE
-fix_size(fix)
- VALUE fix;
-{
- return INT2FIX(sizeof(long));
-}
-
-static VALUE
-int_upto(from, to)
- VALUE from, to;
-{
- VALUE i = from;
-
- for (;;) {
- if (RTEST(rb_funcall(i, '>', 1, to))) break;
- rb_yield(i);
- i = rb_funcall(i, '+', 1, INT2FIX(1));
- }
- return from;
-}
-
-static VALUE
-int_downto(from, to)
- VALUE from, to;
-{
- VALUE i = from;
-
- for (;;) {
- if (RTEST(rb_funcall(i, '<', 1, to))) break;
- rb_yield(i);
- i = rb_funcall(i, '-', 1, INT2FIX(1));
- }
- return from;
-}
-
-static VALUE
-int_step(from, to, step)
- VALUE from, to, step;
-{
- VALUE i = from;
- ID cmp;
-
- if (NUM2INT(step) == 0) {
- rb_raise(rb_eArgError, "step cannot be 0");
- }
-
- if (RTEST(rb_funcall(step, '>', 1, INT2FIX(0)))) {
- cmp = '>';
- }
- else {
- cmp = '<';
- }
- for (;;) {
- if (RTEST(rb_funcall(i, cmp, 1, to))) break;
- rb_yield(i);
- i = rb_funcall(i, '+', 1, step);
- }
- return from;
-}
-
-static VALUE
-int_dotimes(num)
- VALUE num;
-{
- VALUE i = INT2FIX(0);
-
- for (;;) {
- if (!RTEST(rb_funcall(i, '<', 1, num))) break;
- rb_yield(i);
- i = rb_funcall(i, '+', 1, INT2FIX(1));
- }
- return num;
-}
-
-static VALUE
-fix_upto(from, to)
- VALUE from, to;
-{
- long i, end;
-
- if (!FIXNUM_P(to)) return int_upto(from, to);
- end = FIX2LONG(to);
- for (i = FIX2LONG(from); i <= end; i++) {
- rb_yield(INT2FIX(i));
- }
-
- return from;
-}
-
-VALUE
-rb_fix_upto(from, to)
- VALUE from, to;
-{
- return fix_upto(from, to);
-}
-
-static VALUE
-fix_downto(from, to)
- VALUE from, to;
-{
- long i, end;
-
- if (!FIXNUM_P(to)) return int_downto(from, to);
- end = FIX2LONG(to);
- for (i=FIX2LONG(from); i >= end; i--) {
- rb_yield(INT2FIX(i));
- }
-
- return from;
-}
-
-static VALUE
-fix_step(from, to, step)
- VALUE from, to, step;
-{
- long i, end, diff;
-
- if (!FIXNUM_P(to) || !FIXNUM_P(step))
- return int_step(from, to, step);
-
- i = FIX2LONG(from);
- end = FIX2LONG(to);
- diff = FIX2LONG(step);
-
- if (diff == 0) {
- rb_raise(rb_eArgError, "step cannot be 0");
- }
- if (diff > 0) {
- while (i <= end) {
- rb_yield(INT2FIX(i));
- i += diff;
- }
- }
- else {
- while (i >= end) {
- rb_yield(INT2FIX(i));
- i += diff;
- }
- }
- return from;
-}
-
-static VALUE
-fix_dotimes(num)
- VALUE num;
-{
- long i, end;
-
- end = FIX2LONG(num);
- for (i=0; i<end; i++) {
- rb_yield(INT2FIX(i));
- }
- return num;
-}
-
-static VALUE
-fix_zero_p(num)
- VALUE num;
-{
- if (FIX2LONG(num) == 0) {
- return Qtrue;
- }
- return Qfalse;
-}
-
-void
-Init_Numeric()
-{
-#if defined(__FreeBSD__) && __FreeBSD__ < 4
- /* allow divide by zero -- Inf */
- fpsetmask(fpgetmask() & ~(FP_X_DZ|FP_X_INV|FP_X_OFL));
-#endif
- id_coerce = rb_intern("coerce");
- id_to_i = rb_intern("to_i");
- id_div = rb_intern("div");
-
- rb_eZeroDivError = rb_define_class("ZeroDivisionError", rb_eStandardError);
- rb_eFloatDomainError = rb_define_class("FloatDomainError", rb_eRangeError);
- rb_cNumeric = rb_define_class("Numeric", rb_cObject);
-
- rb_include_module(rb_cNumeric, rb_mComparable);
- rb_define_method(rb_cNumeric, "coerce", num_coerce, 1);
- rb_define_method(rb_cNumeric, "clone", num_clone, 0);
-
- rb_define_method(rb_cNumeric, "+@", num_uplus, 0);
- rb_define_method(rb_cNumeric, "-@", num_uminus, 0);
- rb_define_method(rb_cNumeric, "===", num_equal, 1);
- rb_define_method(rb_cNumeric, "eql?", num_eql, 1);
- rb_define_method(rb_cNumeric, "/", num_div, 1);
- rb_define_method(rb_cNumeric, "divmod", num_divmod, 1);
- rb_define_method(rb_cNumeric, "modulo", num_modulo, 1);
- rb_define_method(rb_cNumeric, "remainder", num_remainder, 1);
- rb_define_method(rb_cNumeric, "abs", num_abs, 0);
-
- rb_define_method(rb_cNumeric, "integer?", num_int_p, 0);
- rb_define_method(rb_cNumeric, "zero?", num_zero_p, 0);
- rb_define_method(rb_cNumeric, "nonzero?", num_nonzero_p, 0);
-
- rb_define_method(rb_cNumeric, "floor", num_floor, 0);
- rb_define_method(rb_cNumeric, "ceil", num_ceil, 0);
- rb_define_method(rb_cNumeric, "round", num_round, 0);
- rb_define_method(rb_cNumeric, "truncate", num_truncate, 0);
-
- rb_cInteger = rb_define_class("Integer", rb_cNumeric);
- rb_undef_method(CLASS_OF(rb_cInteger), "allocate");
- rb_undef_method(CLASS_OF(rb_cInteger), "new");
-
- rb_define_method(rb_cInteger, "integer?", int_int_p, 0);
- rb_define_method(rb_cInteger, "upto", int_upto, 1);
- rb_define_method(rb_cInteger, "downto", int_downto, 1);
- rb_define_method(rb_cInteger, "step", int_step, 2);
- rb_define_method(rb_cInteger, "times", int_dotimes, 0);
- rb_include_module(rb_cInteger, rb_mPrecision);
- rb_define_method(rb_cInteger, "succ", int_succ, 0);
- rb_define_method(rb_cInteger, "next", int_succ, 0);
- rb_define_method(rb_cInteger, "chr", int_chr, 0);
- rb_define_method(rb_cInteger, "to_i", int_to_i, 0);
- rb_define_method(rb_cInteger, "to_int", int_to_i, 0);
- rb_define_method(rb_cInteger, "floor", int_to_i, 0);
- rb_define_method(rb_cInteger, "ceil", int_to_i, 0);
- rb_define_method(rb_cInteger, "round", int_to_i, 0);
- rb_define_method(rb_cInteger, "truncate", int_to_i, 0);
-
- rb_cFixnum = rb_define_class("Fixnum", rb_cInteger);
- rb_include_module(rb_cFixnum, rb_mPrecision);
- rb_define_singleton_method(rb_cFixnum, "induced_from", rb_fix_induced_from, 1);
- rb_define_singleton_method(rb_cInteger, "induced_from", rb_int_induced_from, 1);
-
- rb_define_method(rb_cFixnum, "to_s", fix_to_s, -1);
-
- rb_define_method(rb_cFixnum, "id2name", fix_id2name, 0);
-
- rb_define_method(rb_cFixnum, "-@", fix_uminus, 0);
- rb_define_method(rb_cFixnum, "+", fix_plus, 1);
- rb_define_method(rb_cFixnum, "-", fix_minus, 1);
- rb_define_method(rb_cFixnum, "*", fix_mul, 1);
- rb_define_method(rb_cFixnum, "/", fix_div, 1);
- rb_define_method(rb_cFixnum, "div", fix_div, 1);
- rb_define_method(rb_cFixnum, "%", fix_mod, 1);
- rb_define_method(rb_cFixnum, "modulo", fix_mod, 1);
- rb_define_method(rb_cFixnum, "divmod", fix_divmod, 1);
- rb_define_method(rb_cFixnum, "**", fix_pow, 1);
-
- rb_define_method(rb_cFixnum, "abs", fix_abs, 0);
-
- rb_define_method(rb_cFixnum, "==", fix_equal, 1);
- rb_define_method(rb_cFixnum, "<=>", fix_cmp, 1);
- rb_define_method(rb_cFixnum, ">", fix_gt, 1);
- rb_define_method(rb_cFixnum, ">=", fix_ge, 1);
- rb_define_method(rb_cFixnum, "<", fix_lt, 1);
- rb_define_method(rb_cFixnum, "<=", fix_le, 1);
-
- rb_define_method(rb_cFixnum, "~", fix_rev, 0);
- rb_define_method(rb_cFixnum, "&", fix_and, 1);
- rb_define_method(rb_cFixnum, "|", fix_or, 1);
- rb_define_method(rb_cFixnum, "^", fix_xor, 1);
- rb_define_method(rb_cFixnum, "[]", fix_aref, 1);
-
- rb_define_method(rb_cFixnum, "<<", fix_lshift, 1);
- rb_define_method(rb_cFixnum, ">>", fix_rshift, 1);
-
- rb_define_method(rb_cFixnum, "to_f", fix_to_f, 0);
-
- rb_define_method(rb_cFixnum, "succ", fix_succ, 0);
- rb_define_method(rb_cFixnum, "next", fix_succ, 0);
- rb_define_method(rb_cFixnum, "size", fix_size, 0);
-
- rb_define_method(rb_cFixnum, "upto", fix_upto, 1);
- rb_define_method(rb_cFixnum, "downto", fix_downto, 1);
- rb_define_method(rb_cFixnum, "step", fix_step, 2);
- rb_define_method(rb_cFixnum, "times", fix_dotimes, 0);
- rb_define_method(rb_cFixnum, "zero?", fix_zero_p, 0);
-
- rb_cFloat = rb_define_class("Float", rb_cNumeric);
-
- rb_undef_method(CLASS_OF(rb_cFloat), "allocate");
- rb_undef_method(CLASS_OF(rb_cFloat), "new");
-
- rb_define_singleton_method(rb_cFloat, "induced_from", rb_flo_induced_from, 1);
- rb_include_module(rb_cFloat, rb_mPrecision);
-
- rb_define_method(rb_cFloat, "to_s", flo_to_s, 0);
- rb_define_method(rb_cFloat, "coerce", flo_coerce, 1);
- rb_define_method(rb_cFloat, "-@", flo_uminus, 0);
- rb_define_method(rb_cFloat, "+", flo_plus, 1);
- rb_define_method(rb_cFloat, "-", flo_minus, 1);
- rb_define_method(rb_cFloat, "*", flo_mul, 1);
- rb_define_method(rb_cFloat, "/", flo_div, 1);
- rb_define_method(rb_cFloat, "%", flo_mod, 1);
- rb_define_method(rb_cFloat, "modulo", flo_mod, 1);
- rb_define_method(rb_cFloat, "divmod", flo_divmod, 1);
- rb_define_method(rb_cFloat, "**", flo_pow, 1);
- rb_define_method(rb_cFloat, "==", flo_eq, 1);
- rb_define_method(rb_cFloat, "<=>", flo_cmp, 1);
- rb_define_method(rb_cFloat, ">", flo_gt, 1);
- rb_define_method(rb_cFloat, ">=", flo_ge, 1);
- rb_define_method(rb_cFloat, "<", flo_lt, 1);
- rb_define_method(rb_cFloat, "<=", flo_le, 1);
- rb_define_method(rb_cFloat, "eql?", flo_eql, 1);
- rb_define_method(rb_cFloat, "hash", flo_hash, 0);
- rb_define_method(rb_cFloat, "to_f", flo_to_f, 0);
- rb_define_method(rb_cFloat, "abs", flo_abs, 0);
- rb_define_method(rb_cFloat, "zero?", flo_zero_p, 0);
-
- rb_define_method(rb_cFloat, "to_i", flo_truncate, 0);
- rb_define_method(rb_cFloat, "floor", flo_floor, 0);
- rb_define_method(rb_cFloat, "ceil", flo_ceil, 0);
- rb_define_method(rb_cFloat, "round", flo_round, 0);
- rb_define_method(rb_cFloat, "truncate", flo_truncate, 0);
-
- rb_define_method(rb_cFloat, "nan?", flo_is_nan_p, 0);
- rb_define_method(rb_cFloat, "infinite?", flo_is_infinite_p, 0);
- rb_define_method(rb_cFloat, "finite?", flo_is_finite_p, 0);
-}
-
diff --git a/object.c b/object.c
deleted file mode 100644
index a954d8ad88..0000000000
--- a/object.c
+++ /dev/null
@@ -1,1380 +0,0 @@
-/**********************************************************************
-
- object.c -
-
- $Author$
- $Date$
- created at: Thu Jul 15 12:01:24 JST 1993
-
- Copyright (C) 1993-2002 Yukihiro Matsumoto
- Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
- Copyright (C) 2000 Information-technology Promotion Agency, Japan
-
-**********************************************************************/
-
-#include "ruby.h"
-#include "st.h"
-#include <stdio.h>
-#include <errno.h>
-#include <ctype.h>
-
-VALUE rb_mKernel;
-VALUE rb_cObject;
-VALUE rb_cModule;
-VALUE rb_cClass;
-VALUE rb_cData;
-
-VALUE rb_cNilClass;
-VALUE rb_cTrueClass;
-VALUE rb_cFalseClass;
-VALUE rb_cSymbol;
-
-static ID eq, eql;
-static ID inspect;
-static ID clone;
-static ID alloc;
-
-VALUE
-rb_equal(obj1, obj2)
- VALUE obj1, obj2;
-{
- VALUE result;
-
- if (obj1 == obj2) return Qtrue;
- result = rb_funcall(obj1, eq, 1, obj2);
- if (RTEST(result)) return Qtrue;
- return Qfalse;
-}
-
-int
-rb_eql(obj1, obj2)
- VALUE obj1, obj2;
-{
- return RTEST(rb_funcall(obj1, eql, 1, obj2));
-}
-
-static VALUE
-rb_obj_equal(obj1, obj2)
- VALUE obj1, obj2;
-{
- if (obj1 == obj2) return Qtrue;
- return Qfalse;
-}
-
-VALUE
-rb_obj_id(obj)
- VALUE obj;
-{
- if (SPECIAL_CONST_P(obj)) {
- return INT2NUM((long)obj);
- }
- return (VALUE)((long)obj|FIXNUM_FLAG);
-}
-
-VALUE
-rb_class_real(cl)
- VALUE cl;
-{
- while (FL_TEST(cl, FL_SINGLETON) || TYPE(cl) == T_ICLASS) {
- cl = RCLASS(cl)->super;
- }
- return cl;
-}
-
-VALUE
-rb_obj_class(obj)
- VALUE obj;
-{
- return rb_class_real(CLASS_OF(obj));
-}
-
-VALUE
-rb_obj_clone(obj)
- VALUE obj;
-{
- VALUE clone;
-
- if (rb_special_const_p(obj)) {
- rb_raise(rb_eTypeError, "can't clone %s", rb_class2name(CLASS_OF(obj)));
- }
- clone = rb_obj_alloc(rb_class_real(RBASIC(obj)->klass));
- CLONESETUP(clone,obj);
- if (TYPE(clone) == T_OBJECT && ROBJECT(obj)->iv_tbl) {
- ROBJECT(clone)->iv_tbl = st_copy(ROBJECT(obj)->iv_tbl);
- }
-
- return clone;
-}
-
-VALUE
-rb_obj_dup(obj)
- VALUE obj;
-{
- VALUE dup;
-
- if (rb_special_const_p(obj)) {
- rb_raise(rb_eTypeError, "can't dup %s", rb_class2name(CLASS_OF(obj)));
- }
- dup = rb_funcall(obj, clone, 0, 0);
- if (TYPE(dup) != TYPE(obj)) {
- rb_raise(rb_eTypeError, "dupulicated object must be same type");
- }
- if (!SPECIAL_CONST_P(dup)) {
- OBJSETUP(dup, rb_obj_class(obj), BUILTIN_TYPE(obj));
- OBJ_INFECT(dup, obj);
- if (FL_TEST(obj, FL_EXIVAR)) {
- FL_SET(dup, FL_EXIVAR);
- }
- }
- return dup;
-}
-
-static VALUE
-rb_any_to_a(obj)
- VALUE obj;
-{
- return rb_ary_new3(1, obj);
-}
-
-VALUE
-rb_any_to_s(obj)
- VALUE obj;
-{
- char *cname = rb_class2name(CLASS_OF(obj));
- VALUE str;
-
- str = rb_str_new(0, strlen(cname)+6+16+1); /* 6:tags 16:addr 1:nul */
- sprintf(RSTRING(str)->ptr, "#<%s:0x%lx>", cname, obj);
- RSTRING(str)->len = strlen(RSTRING(str)->ptr);
- if (OBJ_TAINTED(obj)) OBJ_TAINT(str);
-
- return str;
-}
-
-VALUE
-rb_inspect(obj)
- VALUE obj;
-{
- return rb_obj_as_string(rb_funcall(obj, inspect, 0, 0));
-}
-
-static int
-inspect_i(id, value, str)
- ID id;
- VALUE value;
- VALUE str;
-{
- VALUE str2;
- char *ivname;
-
- /* need not to show internal data */
- if (CLASS_OF(value) == 0) return ST_CONTINUE;
- if (!rb_is_instance_id(id)) return ST_CONTINUE;
- if (RSTRING(str)->ptr[0] == '-') { /* first element */
- RSTRING(str)->ptr[0] = '#';
- rb_str_cat2(str, " ");
- }
- else {
- rb_str_cat2(str, ", ");
- }
- ivname = rb_id2name(id);
- rb_str_cat2(str, ivname);
- rb_str_cat2(str, "=");
- str2 = rb_inspect(value);
- rb_str_append(str, str2);
- OBJ_INFECT(str, str2);
-
- return ST_CONTINUE;
-}
-
-static VALUE
-inspect_obj(obj, str)
- VALUE obj, str;
-{
- st_foreach(ROBJECT(obj)->iv_tbl, inspect_i, str);
- rb_str_cat2(str, ">");
- RSTRING(str)->ptr[0] = '#';
- OBJ_INFECT(str, obj);
-
- return str;
-}
-
-static VALUE
-rb_obj_inspect(obj)
- VALUE obj;
-{
- if (TYPE(obj) == T_OBJECT
- && ROBJECT(obj)->iv_tbl
- && ROBJECT(obj)->iv_tbl->num_entries > 0) {
- VALUE str;
- char *c;
-
- c = rb_class2name(CLASS_OF(obj));
- if (rb_inspecting_p(obj)) {
- str = rb_str_new(0, strlen(c)+10+16+1); /* 10:tags 16:addr 1:nul */
- sprintf(RSTRING(str)->ptr, "#<%s:0x%lx ...>", c, obj);
- RSTRING(str)->len = strlen(RSTRING(str)->ptr);
- return str;
- }
- str = rb_str_new(0, strlen(c)+6+16+1); /* 6:tags 16:addr 1:nul */
- sprintf(RSTRING(str)->ptr, "-<%s:0x%lx", c, obj);
- RSTRING(str)->len = strlen(RSTRING(str)->ptr);
- return rb_protect_inspect(inspect_obj, obj, str);
- }
- return rb_funcall(obj, rb_intern("to_s"), 0, 0);
-}
-
-VALUE
-rb_obj_is_instance_of(obj, c)
- VALUE obj, c;
-{
- switch (TYPE(c)) {
- case T_MODULE:
- case T_CLASS:
- case T_ICLASS:
- break;
- default:
- rb_raise(rb_eTypeError, "class or module required");
- }
-
- if (rb_obj_class(obj) == c) return Qtrue;
- return Qfalse;
-}
-
-VALUE
-rb_obj_is_kind_of(obj, c)
- VALUE obj, c;
-{
- VALUE cl = CLASS_OF(obj);
-
- switch (TYPE(c)) {
- case T_MODULE:
- case T_CLASS:
- case T_ICLASS:
- break;
-
- default:
- rb_raise(rb_eTypeError, "class or module required");
- }
-
- while (cl) {
- if (cl == c || RCLASS(cl)->m_tbl == RCLASS(c)->m_tbl)
- return Qtrue;
- cl = RCLASS(cl)->super;
- }
- return Qfalse;
-}
-
-static VALUE
-rb_obj_dummy()
-{
- return Qnil;
-}
-
-VALUE
-rb_obj_tainted(obj)
- VALUE obj;
-{
- if (OBJ_TAINTED(obj))
- return Qtrue;
- return Qfalse;
-}
-
-VALUE
-rb_obj_taint(obj)
- VALUE obj;
-{
- rb_secure(4);
- if (!OBJ_TAINTED(obj)) {
- if (OBJ_FROZEN(obj)) {
- rb_error_frozen("object");
- }
- OBJ_TAINT(obj);
- }
- return obj;
-}
-
-VALUE
-rb_obj_untaint(obj)
- VALUE obj;
-{
- rb_secure(3);
- if (OBJ_TAINTED(obj)) {
- if (OBJ_FROZEN(obj)) {
- rb_error_frozen("object");
- }
- FL_UNSET(obj, FL_TAINT);
- }
- return obj;
-}
-
-VALUE
-rb_obj_freeze(obj)
- VALUE obj;
-{
- if (!OBJ_FROZEN(obj)) {
- if (rb_safe_level() >= 4 && !OBJ_TAINTED(obj)) {
- rb_raise(rb_eSecurityError, "Insecure: can't freeze object");
- }
- OBJ_FREEZE(obj);
- }
- return obj;
-}
-
-static VALUE
-rb_obj_frozen_p(obj)
- VALUE obj;
-{
- if (OBJ_FROZEN(obj)) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-nil_to_i(obj)
- VALUE obj;
-{
- return INT2FIX(0);
-}
-
-static VALUE
-nil_to_s(obj)
- VALUE obj;
-{
- return rb_str_new2("");
-}
-
-static VALUE
-nil_to_a(obj)
- VALUE obj;
-{
- return rb_ary_new2(0);
-}
-
-static VALUE
-nil_inspect(obj)
- VALUE obj;
-{
- return rb_str_new2("nil");
-}
-
-#ifdef NIL_PLUS
-static VALUE
-nil_plus(x, y)
- VALUE x, y;
-{
- switch (TYPE(y)) {
- case T_NIL:
- case T_FIXNUM:
- case T_FLOAT:
- case T_BIGNUM:
- case T_STRING:
- case T_ARRAY:
- return y;
- default:
- rb_raise(rb_eTypeError, "tried to add %s(%s) to nil",
- RSTRING(rb_inspect(y))->ptr,
- rb_class2name(CLASS_OF(y)));
- }
- /* not reached */
-}
-#endif
-
-static VALUE
-main_to_s(obj)
- VALUE obj;
-{
- return rb_str_new2("main");
-}
-
-static VALUE
-true_to_s(obj)
- VALUE obj;
-{
- return rb_str_new2("true");
-}
-
-static VALUE
-true_and(obj, obj2)
- VALUE obj, obj2;
-{
- return RTEST(obj2)?Qtrue:Qfalse;
-}
-
-static VALUE
-true_or(obj, obj2)
- VALUE obj, obj2;
-{
- return Qtrue;
-}
-
-static VALUE
-true_xor(obj, obj2)
- VALUE obj, obj2;
-{
- return RTEST(obj2)?Qfalse:Qtrue;
-}
-
-static VALUE
-false_to_s(obj)
- VALUE obj;
-{
- return rb_str_new2("false");
-}
-
-static VALUE
-false_and(obj, obj2)
- VALUE obj, obj2;
-{
- return Qfalse;
-}
-
-static VALUE
-false_or(obj, obj2)
- VALUE obj, obj2;
-{
- return RTEST(obj2)?Qtrue:Qfalse;
-}
-
-static VALUE
-false_xor(obj, obj2)
- VALUE obj, obj2;
-{
- return RTEST(obj2)?Qtrue:Qfalse;
-}
-
-static VALUE
-rb_true(obj)
- VALUE obj;
-{
- return Qtrue;
-}
-
-static VALUE
-rb_false(obj)
- VALUE obj;
-{
- return Qfalse;
-}
-
-static VALUE
-sym_to_i(sym)
- VALUE sym;
-{
- ID id = SYM2ID(sym);
-
- return INT2FIX(id);
-}
-
-static VALUE
-sym_inspect(sym)
- VALUE sym;
-{
- VALUE str;
- char *name;
-
- name = rb_id2name(SYM2ID(sym));
- str = rb_str_new(0, strlen(name)+1);
- RSTRING(str)->ptr[0] = ':';
- strcpy(RSTRING(str)->ptr+1, name);
- return str;
-}
-
-static VALUE
-sym_to_s(sym)
- VALUE sym;
-{
- return rb_str_new2(rb_id2name(SYM2ID(sym)));
-}
-
-static VALUE
-sym_intern(sym)
- VALUE sym;
-{
- return sym;
-}
-
-static VALUE
-rb_mod_to_s(klass)
- VALUE klass;
-
-{
- if (FL_TEST(klass, FL_SINGLETON)) {
- VALUE s = rb_str_new2("#<");
- VALUE v = rb_iv_get(klass, "__attached__");
-
- rb_str_cat2(s, "Class:");
- switch (TYPE(v)) {
- case T_CLASS: case T_MODULE:
- rb_str_append(s, rb_inspect(v));
- break;
- default:
- rb_str_append(s, rb_any_to_s(v));
- break;
- }
- rb_str_cat2(s, ">");
-
- return s;
- }
- return rb_str_dup(rb_class_path(klass));
-}
-
-static VALUE
-rb_mod_eqq(mod, arg)
- VALUE mod, arg;
-{
- return rb_obj_is_kind_of(arg, mod);
-}
-
-static VALUE
-rb_mod_le(mod, arg)
- VALUE mod, arg;
-{
- if (mod == arg) return Qtrue;
- switch (TYPE(arg)) {
- case T_MODULE:
- case T_CLASS:
- break;
- default:
- rb_raise(rb_eTypeError, "compared with non class/module");
- }
-
- while (mod) {
- if (RCLASS(mod)->m_tbl == RCLASS(arg)->m_tbl)
- return Qtrue;
- mod = RCLASS(mod)->super;
- }
- return Qfalse;
-}
-
-static VALUE
-rb_mod_lt(mod, arg)
- VALUE mod, arg;
-{
- if (mod == arg) return Qfalse;
- return rb_mod_le(mod, arg);
-}
-
-static VALUE
-rb_mod_ge(mod, arg)
- VALUE mod, arg;
-{
- switch (TYPE(arg)) {
- case T_MODULE:
- case T_CLASS:
- break;
- default:
- rb_raise(rb_eTypeError, "compared with non class/module");
- }
-
- return rb_mod_le(arg, mod);
-}
-
-static VALUE
-rb_mod_gt(mod, arg)
- VALUE mod, arg;
-{
- if (mod == arg) return Qfalse;
- return rb_mod_ge(mod, arg);
-}
-
-static VALUE
-rb_mod_cmp(mod, arg)
- VALUE mod, arg;
-{
- VALUE start = mod;
-
- if (mod == arg) return INT2FIX(0);
- switch (TYPE(arg)) {
- case T_MODULE:
- case T_CLASS:
- break;
- default:
- rb_raise(rb_eTypeError, "<=> requires Class or Module (%s given)",
- rb_class2name(CLASS_OF(arg)));
- break;
- }
-
- if (rb_mod_le(mod, arg)) {
- return INT2FIX(-1);
- }
-
- while (arg) {
- if (RCLASS(arg)->m_tbl == RCLASS(start)->m_tbl)
- return INT2FIX(1);
- arg = RCLASS(arg)->super;
- }
- rb_raise(rb_eArgError, "non related class/module");
- return Qnil; /* not reached */
-}
-
-static VALUE
-rb_mod_initialize(module)
- VALUE module;
-{
- if (rb_block_given_p()) {
- rb_mod_module_eval(0, 0, module);
- }
- return Qnil;
-}
-
-static VALUE
-rb_class_initialize(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- return rb_mod_initialize(klass);
-}
-
-static VALUE
-rb_module_s_alloc(klass)
- VALUE klass;
-{
- VALUE mod = rb_module_new();
-
- RBASIC(mod)->klass = klass;
- return mod;
-}
-
-static VALUE
-rb_class_s_new(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE super, klass;
-
- if (rb_scan_args(argc, argv, "01", &super) == 0) {
- super = rb_cObject;
- }
- klass = rb_class_new(super);
- rb_make_metaclass(klass, RBASIC(super)->klass);
- rb_obj_call_init(klass, argc, argv);
- rb_class_inherited(super, klass);
-
- return klass;
-}
-
-VALUE
-rb_obj_alloc(klass)
- VALUE klass;
-{
- VALUE obj;
-
- if (FL_TEST(klass, FL_SINGLETON)) {
- rb_raise(rb_eTypeError, "can't create instance of virtual class");
- }
- obj = rb_funcall(klass, alloc, 0, 0);
-
- if (rb_obj_class(obj) != rb_class_real(klass)) {
- rb_raise(rb_eTypeError, "wrong instance allocation");
- }
- return obj;
-}
-
-static VALUE
-rb_class_allocate_instance(klass)
- VALUE klass;
-{
- NEWOBJ(obj, struct RObject);
- OBJSETUP(obj, klass, T_OBJECT);
-
- return (VALUE)obj;
-}
-
-VALUE
-rb_class_new_instance(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- VALUE obj;
-
- obj = rb_obj_alloc(klass);
- rb_obj_call_init(obj, argc, argv);
-
- return obj;
-}
-
-static VALUE
-rb_class_superclass(klass)
- VALUE klass;
-{
- VALUE super = RCLASS(klass)->super;
-
- while (TYPE(super) == T_ICLASS) {
- super = RCLASS(super)->super;
- }
- if (!super) {
- return Qnil;
- }
- return super;
-}
-
-ID
-rb_to_id(name)
- VALUE name;
-{
- ID id;
-
- switch (TYPE(name)) {
- case T_STRING:
- return rb_intern(RSTRING(name)->ptr);
- case T_FIXNUM:
- id = FIX2INT(name);
- if (!rb_id2name(id)) {
- rb_raise(rb_eArgError, "%d is not a symbol", id);
- }
- break;
- case T_SYMBOL:
- id = SYM2ID(name);
- break;
- default:
- rb_raise(rb_eTypeError, "%s is not a symbol", RSTRING(rb_inspect(name))->ptr);
- }
- return id;
-}
-
-static VALUE
-rb_mod_attr(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- VALUE name, pub;
-
- rb_scan_args(argc, argv, "11", &name, &pub);
- rb_attr(klass, rb_to_id(name), 1, RTEST(pub), Qtrue);
- return Qnil;
-}
-
-static VALUE
-rb_mod_attr_reader(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- int i;
-
- for (i=0; i<argc; i++) {
- rb_attr(klass, rb_to_id(argv[i]), 1, 0, Qtrue);
- }
- return Qnil;
-}
-
-static VALUE
-rb_mod_attr_writer(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- int i;
-
- for (i=0; i<argc; i++) {
- rb_attr(klass, rb_to_id(argv[i]), 0, 1, Qtrue);
- }
- return Qnil;
-}
-
-static VALUE
-rb_mod_attr_accessor(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- int i;
-
- for (i=0; i<argc; i++) {
- rb_attr(klass, rb_to_id(argv[i]), 1, 1, Qtrue);
- }
- return Qnil;
-}
-
-static VALUE
-rb_mod_const_get(mod, name)
- VALUE mod, name;
-{
- ID id = rb_to_id(name);
-
- if (!rb_is_const_id(id)) {
- rb_name_error(id, "wrong constant name %s", rb_id2name(id));
- }
- return rb_const_get(mod, id);
-}
-
-static VALUE
-rb_mod_const_set(mod, name, value)
- VALUE mod, name, value;
-{
- ID id = rb_to_id(name);
-
- if (!rb_is_const_id(id)) {
- rb_name_error(id, "wrong constant name %s", rb_id2name(id));
- }
- rb_const_set(mod, id, value);
- return value;
-}
-
-static VALUE
-rb_mod_const_defined(mod, name)
- VALUE mod, name;
-{
- ID id = rb_to_id(name);
-
- if (!rb_is_const_id(id)) {
- rb_name_error(id, "wrong constant name %s", rb_id2name(id));
- }
- return rb_const_defined_at(mod, id);
-}
-
-static VALUE
-rb_obj_methods(obj)
- VALUE obj;
-{
- VALUE argv[1];
-
- argv[0] = Qtrue;
- return rb_class_instance_methods(1, argv, CLASS_OF(obj));
-}
-
-static VALUE
-rb_obj_protected_methods(obj)
- VALUE obj;
-{
- VALUE argv[1];
-
- argv[0] = Qtrue;
- return rb_class_protected_instance_methods(1, argv, CLASS_OF(obj));
-}
-
-static VALUE
-rb_obj_private_methods(obj)
- VALUE obj;
-{
- VALUE argv[1];
-
- argv[0] = Qtrue;
- return rb_class_private_instance_methods(1, argv, CLASS_OF(obj));
-}
-
-static VALUE
-convert_type(val, tname, method, raise)
- VALUE val;
- const char *tname, *method;
- int raise;
-{
- ID m;
-
- m = rb_intern(method);
- if (!rb_respond_to(val, m)) {
- if (raise) {
- rb_raise(rb_eTypeError, "failed to convert %s into %s",
- NIL_P(val) ? "nil" :
- val == Qtrue ? "true" :
- val == Qfalse ? "false" :
- rb_class2name(CLASS_OF(val)),
- tname);
- }
- else {
- return Qnil;
- }
- }
- return rb_funcall(val, m, 0);
-}
-
-VALUE
-rb_convert_type(val, type, tname, method)
- VALUE val;
- int type;
- const char *tname, *method;
-{
- VALUE v;
-
- if (TYPE(val) == type) return val;
- v = convert_type(val, tname, method, Qtrue);
- if (TYPE(v) != type) {
- rb_raise(rb_eTypeError, "%s#%s should return %s",
- rb_class2name(CLASS_OF(val)), method, tname);
- }
- return v;
-}
-
-VALUE
-rb_check_convert_type(val, type, tname, method)
- VALUE val;
- int type;
- const char *tname, *method;
-{
- VALUE v;
-
- if (TYPE(val) == type) return val;
- v = convert_type(val, tname, method, Qfalse);
- if (NIL_P(v)) return Qnil;
- if (TYPE(v) != type) {
- rb_raise(rb_eTypeError, "%s#%s should return %s",
- rb_class2name(CLASS_OF(val)), method, tname);
- }
- return v;
-}
-
-static VALUE
-rb_to_integer(val, method)
- VALUE val;
- char *method;
-{
- VALUE v = convert_type(val, "Integer", method, Qtrue);
- if (!rb_obj_is_kind_of(v, rb_cInteger)) {
- rb_raise(rb_eTypeError, "%s#%s should return Integer",
- rb_class2name(CLASS_OF(val)), method);
- }
- return v;
-}
-
-VALUE
-rb_to_int(val)
- VALUE val;
-{
- return rb_to_integer(val, "to_int");
-}
-
-VALUE
-rb_Integer(val)
- VALUE val;
-{
- switch (TYPE(val)) {
- case T_FLOAT:
- if (RFLOAT(val)->value <= (double)FIXNUM_MAX
- && RFLOAT(val)->value >= (double)FIXNUM_MIN) {
- break;
- }
- return rb_dbl2big(RFLOAT(val)->value);
-
- case T_BIGNUM:
- return val;
-
- case T_STRING:
- return rb_str_to_inum(val, 0, Qtrue);
-
- case T_FIXNUM:
- return val;
-
- default:
- break;
- }
- return rb_to_integer(val, "to_i");
-}
-
-static VALUE
-rb_f_integer(obj, arg)
- VALUE obj, arg;
-{
- return rb_Integer(arg);
-}
-
-double
-rb_cstr_to_dbl(p, badcheck)
- const char *p;
- int badcheck;
-{
- const char *q;
- char *end;
- double d;
-
- q = p;
- if (badcheck) {
- while (ISSPACE(*p)) p++;
- }
- else {
- while (ISSPACE(*p) || *p == '_') p++;
- }
- d = strtod(p, &end);
- if (p == end) {
- if (badcheck) {
- bad:
- rb_invalid_str(q, "Float()");
- }
- return d;
- }
- if (*end) {
- char *buf = ALLOCA_N(char, strlen(p));
- char *n = buf;
-
- while (p < end) *n++ = *p++;
- while (*p) {
- if (*p == '_') {
- /* remove underscores between digits */
- if (badcheck) {
- if (n == buf || !ISDIGIT(n[-1])) goto bad;
- ++p;
- if (!ISDIGIT(*p)) goto bad;
- }
- else {
- while (*++p == '_');
- continue;
- }
- }
- *n++ = *p++;
- }
- *n = '\0';
- p = buf;
- d = strtod(p, &end);
- if (badcheck) {
- if (p == end) goto bad;
- while (*end && ISSPACE(*end)) end++;
- if (*end) goto bad;
- }
- }
- if (errno == ERANGE) {
- errno = 0;
- rb_raise(rb_eArgError, "Float %s out of range", q);
- }
- return d;
-}
-
-double
-rb_str_to_dbl(str, badcheck)
- VALUE str;
- int badcheck;
-{
- char *s;
- int len;
-
- StringValue(str);
- s = RSTRING(str)->ptr;
- len = RSTRING(str)->len;
- if (s[len]) { /* no sentinel somehow */
- char *p = ALLOCA_N(char, len+1);
-
- MEMCPY(p, s, char, len);
- p[len] = '\0';
- s = p;
- }
- if (badcheck && len != strlen(s)) {
- rb_raise(rb_eArgError, "string for Float contains null byte");
- }
- return rb_cstr_to_dbl(s, badcheck);
-}
-
-VALUE
-rb_Float(val)
- VALUE val;
-{
- switch (TYPE(val)) {
- case T_FIXNUM:
- return rb_float_new((double)FIX2LONG(val));
-
- case T_FLOAT:
- return val;
-
- case T_BIGNUM:
- return rb_float_new(rb_big2dbl(val));
-
- case T_STRING:
- return rb_float_new(rb_str_to_dbl(val, Qtrue));
-
- case T_NIL:
- return rb_float_new(0.0);
-
- default:
- return rb_convert_type(val, T_FLOAT, "Float", "to_f");
- }
-}
-
-static VALUE
-rb_f_float(obj, arg)
- VALUE obj, arg;
-{
- return rb_Float(arg);
-}
-
-double
-rb_num2dbl(val)
- VALUE val;
-{
- switch (TYPE(val)) {
- case T_FLOAT:
- return RFLOAT(val)->value;
-
- case T_STRING:
- rb_raise(rb_eTypeError, "no implicit conversion to float from string");
- break;
-
- case T_NIL:
- rb_raise(rb_eTypeError, "no implicit conversion to float from nil");
- break;
-
- default:
- break;
- }
-
- return RFLOAT(rb_Float(val))->value;
-}
-
-char*
-rb_str2cstr(str, len)
- VALUE str;
- int *len;
-{
- StringValue(str);
- if (len) *len = RSTRING(str)->len;
- else if (ruby_verbose && RSTRING(str)->len != strlen(RSTRING(str)->ptr)) {
- rb_warn("string contains \\0 character");
- }
- return RSTRING(str)->ptr;
-}
-
-VALUE
-rb_String(val)
- VALUE val;
-{
- return rb_convert_type(val, T_STRING, "String", "to_s");
-}
-
-static VALUE
-rb_f_string(obj, arg)
- VALUE obj, arg;
-{
- return rb_String(arg);
-}
-
-VALUE
-rb_Array(val)
- VALUE val;
-{
- ID to_ary;
-
- if (TYPE(val) == T_ARRAY) return val;
- to_ary = rb_intern("to_ary");
- if (rb_respond_to(val, to_ary)) {
- val = rb_funcall(val, to_ary, 0);
- }
- else {
- val = rb_funcall(val, rb_intern("to_a"), 0);
- }
- if (TYPE(val) != T_ARRAY) {
- rb_raise(rb_eTypeError, "`to_a' did not return Array");
- }
- return val;
-}
-
-static VALUE
-rb_f_array(obj, arg)
- VALUE obj, arg;
-{
- return rb_Array(arg);
-}
-
-static VALUE
-boot_defclass(name, super)
- char *name;
- VALUE super;
-{
- extern st_table *rb_class_tbl;
- VALUE obj = rb_class_boot(super);
- ID id = rb_intern(name);
-
- rb_name_class(obj, id);
- st_add_direct(rb_class_tbl, id, obj);
- return obj;
-}
-
-VALUE ruby_top_self;
-
-void
-Init_Object()
-{
- VALUE metaclass;
-
- alloc = rb_intern("allocate");
-
- rb_cObject = boot_defclass("Object", 0);
- rb_cModule = boot_defclass("Module", rb_cObject);
- rb_cClass = boot_defclass("Class", rb_cModule);
-
- metaclass = rb_make_metaclass(rb_cObject, rb_cClass);
- metaclass = rb_make_metaclass(rb_cModule, metaclass);
- metaclass = rb_make_metaclass(rb_cClass, metaclass);
-
- rb_mKernel = rb_define_module("Kernel");
- rb_include_module(rb_cObject, rb_mKernel);
- rb_define_private_method(rb_cObject, "initialize", rb_obj_dummy, 0);
- rb_define_private_method(rb_cClass, "inherited", rb_obj_dummy, 1);
- rb_define_private_method(rb_cModule, "included", rb_obj_dummy, 1);
- rb_define_private_method(rb_cModule, "method_added", rb_obj_dummy, 1);
- rb_define_private_method(rb_cModule, "method_removed", rb_obj_dummy, 1);
- rb_define_private_method(rb_cModule, "method_undefined", rb_obj_dummy, 1);
-
- /*
- * Ruby's Class Hierarchy Chart
- *
- * +------------------+
- * | |
- * Object---->(Object) |
- * ^ ^ ^ ^ |
- * | | | | |
- * | | +-----+ +---------+ |
- * | | | | |
- * | +-----------+ | |
- * | | | | |
- * +------+ | Module--->(Module) |
- * | | ^ ^ |
- * OtherClass-->(OtherClass) | | |
- * | | |
- * Class---->(Class) |
- * ^ |
- * | |
- * +----------------+
- *
- * + All metaclasses are instances of the class `Class'.
- */
-
- rb_define_method(rb_mKernel, "nil?", rb_false, 0);
- rb_define_method(rb_mKernel, "==", rb_obj_equal, 1);
- rb_define_method(rb_mKernel, "equal?", rb_obj_equal, 1);
- rb_define_method(rb_mKernel, "===", rb_obj_equal, 1);
- rb_define_method(rb_mKernel, "=~", rb_false, 1);
-
- rb_define_method(rb_mKernel, "eql?", rb_obj_equal, 1);
-
- rb_define_method(rb_mKernel, "hash", rb_obj_id, 0);
- rb_define_method(rb_mKernel, "id", rb_obj_id, 0);
- rb_define_method(rb_mKernel, "__id__", rb_obj_id, 0);
- rb_define_method(rb_mKernel, "type", rb_obj_class, 0);
- rb_define_method(rb_mKernel, "class", rb_obj_class, 0);
-
- rb_define_method(rb_mKernel, "clone", rb_obj_clone, 0);
- rb_define_method(rb_mKernel, "dup", rb_obj_dup, 0);
-
- rb_define_method(rb_mKernel, "taint", rb_obj_taint, 0);
- rb_define_method(rb_mKernel, "tainted?", rb_obj_tainted, 0);
- rb_define_method(rb_mKernel, "untaint", rb_obj_untaint, 0);
- rb_define_method(rb_mKernel, "freeze", rb_obj_freeze, 0);
- rb_define_method(rb_mKernel, "frozen?", rb_obj_frozen_p, 0);
-
- rb_define_method(rb_mKernel, "to_a", rb_any_to_a, 0);
- rb_define_method(rb_mKernel, "to_s", rb_any_to_s, 0);
- rb_define_method(rb_mKernel, "inspect", rb_obj_inspect, 0);
- rb_define_method(rb_mKernel, "methods", rb_obj_methods, 0);
- rb_define_method(rb_mKernel, "public_methods", rb_obj_methods, 0);
- rb_define_method(rb_mKernel, "singleton_methods", rb_obj_singleton_methods, -1);
- rb_define_method(rb_mKernel, "protected_methods", rb_obj_protected_methods, 0);
- rb_define_method(rb_mKernel, "private_methods", rb_obj_private_methods, 0);
- rb_define_method(rb_mKernel, "instance_variables", rb_obj_instance_variables, 0);
- rb_define_private_method(rb_mKernel, "remove_instance_variable",
- rb_obj_remove_instance_variable, 1);
-
- rb_define_method(rb_mKernel, "instance_of?", rb_obj_is_instance_of, 1);
- rb_define_method(rb_mKernel, "kind_of?", rb_obj_is_kind_of, 1);
- rb_define_method(rb_mKernel, "is_a?", rb_obj_is_kind_of, 1);
-
- rb_define_global_function("singleton_method_added", rb_obj_dummy, 1);
- rb_define_global_function("singleton_method_removed", rb_obj_dummy, 1);
- rb_define_global_function("singleton_method_undefined", rb_obj_dummy, 1);
-
- rb_define_global_function("sprintf", rb_f_sprintf, -1);
- rb_define_global_function("format", rb_f_sprintf, -1);
-
- rb_define_global_function("Integer", rb_f_integer, 1);
- rb_define_global_function("Float", rb_f_float, 1);
-
- rb_define_global_function("String", rb_f_string, 1);
- rb_define_global_function("Array", rb_f_array, 1);
-
- rb_cNilClass = rb_define_class("NilClass", rb_cObject);
- rb_define_method(rb_cNilClass, "to_i", nil_to_i, 0);
- rb_define_method(rb_cNilClass, "to_s", nil_to_s, 0);
- rb_define_method(rb_cNilClass, "to_a", nil_to_a, 0);
- rb_define_method(rb_cNilClass, "inspect", nil_inspect, 0);
- rb_define_method(rb_cNilClass, "&", false_and, 1);
- rb_define_method(rb_cNilClass, "|", false_or, 1);
- rb_define_method(rb_cNilClass, "^", false_xor, 1);
-
- rb_define_method(rb_cNilClass, "nil?", rb_true, 0);
- rb_undef_method(CLASS_OF(rb_cNilClass), "allocate");
- rb_undef_method(CLASS_OF(rb_cNilClass), "new");
- rb_define_global_const("NIL", Qnil);
-
- rb_cSymbol = rb_define_class("Symbol", rb_cObject);
- rb_define_singleton_method(rb_cSymbol, "all_symbols", rb_sym_all_symbols, 0);
- rb_undef_method(CLASS_OF(rb_cSymbol), "allocate");
- rb_undef_method(CLASS_OF(rb_cSymbol), "new");
-
- rb_define_method(rb_cSymbol, "to_i", sym_to_i, 0);
- rb_define_method(rb_cSymbol, "to_int", sym_to_i, 0);
- rb_define_method(rb_cSymbol, "inspect", sym_inspect, 0);
- rb_define_method(rb_cSymbol, "to_s", sym_to_s, 0);
- rb_define_method(rb_cSymbol, "id2name", sym_to_s, 0);
- rb_define_method(rb_cSymbol, "intern", sym_intern, 0);
-
- rb_define_method(rb_cModule, "===", rb_mod_eqq, 1);
- rb_define_method(rb_cModule, "<=>", rb_mod_cmp, 1);
- rb_define_method(rb_cModule, "<", rb_mod_lt, 1);
- rb_define_method(rb_cModule, "<=", rb_mod_le, 1);
- rb_define_method(rb_cModule, ">", rb_mod_gt, 1);
- rb_define_method(rb_cModule, ">=", rb_mod_ge, 1);
- rb_define_method(rb_cModule, "clone", rb_mod_clone, 0);
- rb_define_method(rb_cModule, "dup", rb_mod_dup, 0);
- rb_define_method(rb_cModule, "to_s", rb_mod_to_s, 0);
- rb_define_method(rb_cModule, "included_modules", rb_mod_included_modules, 0);
- rb_define_method(rb_cModule, "include?", rb_mod_include_p, 1);
- rb_define_method(rb_cModule, "name", rb_mod_name, 0);
- rb_define_method(rb_cModule, "ancestors", rb_mod_ancestors, 0);
-
- rb_define_private_method(rb_cModule, "attr", rb_mod_attr, -1);
- rb_define_private_method(rb_cModule, "attr_reader", rb_mod_attr_reader, -1);
- rb_define_private_method(rb_cModule, "attr_writer", rb_mod_attr_writer, -1);
- rb_define_private_method(rb_cModule, "attr_accessor", rb_mod_attr_accessor, -1);
-
- rb_define_singleton_method(rb_cModule, "allocate", rb_module_s_alloc, 0);
- rb_define_method(rb_cModule, "initialize", rb_mod_initialize, 0);
- rb_define_method(rb_cModule, "instance_methods", rb_class_instance_methods, -1);
- rb_define_method(rb_cModule, "public_instance_methods", rb_class_instance_methods, -1);
- rb_define_method(rb_cModule, "protected_instance_methods", rb_class_protected_instance_methods, -1);
- rb_define_method(rb_cModule, "private_instance_methods", rb_class_private_instance_methods, -1);
-
- rb_define_method(rb_cModule, "constants", rb_mod_constants, 0);
- rb_define_method(rb_cModule, "const_get", rb_mod_const_get, 1);
- rb_define_method(rb_cModule, "const_set", rb_mod_const_set, 2);
- rb_define_method(rb_cModule, "const_defined?", rb_mod_const_defined, 1);
- rb_define_private_method(rb_cModule, "remove_const", rb_mod_remove_const, 1);
- rb_define_method(rb_cModule, "class_variables", rb_mod_class_variables, 0);
- rb_define_private_method(rb_cModule, "remove_class_variable", rb_mod_remove_cvar, 1);
-
- rb_define_method(rb_cClass, "allocate", rb_class_allocate_instance, 0);
- rb_define_method(rb_cClass, "new", rb_class_new_instance, -1);
- rb_define_method(rb_cClass, "initialize", rb_class_initialize, -1);
- rb_define_method(rb_cClass, "superclass", rb_class_superclass, 0);
- rb_undef_method(CLASS_OF(rb_cClass), "allocate");
- rb_define_singleton_method(rb_cClass, "new", rb_class_s_new, -1);
- rb_undef_method(rb_cClass, "extend_object");
- rb_undef_method(rb_cClass, "append_features");
-
- rb_cData = rb_define_class("Data", rb_cObject);
- rb_undef_method(CLASS_OF(rb_cData), "allocate");
-
- ruby_top_self = rb_obj_alloc(rb_cObject);
- rb_global_variable(&ruby_top_self);
- rb_define_singleton_method(ruby_top_self, "to_s", main_to_s, 0);
-
- rb_cTrueClass = rb_define_class("TrueClass", rb_cObject);
- rb_define_method(rb_cTrueClass, "to_s", true_to_s, 0);
- rb_define_method(rb_cTrueClass, "&", true_and, 1);
- rb_define_method(rb_cTrueClass, "|", true_or, 1);
- rb_define_method(rb_cTrueClass, "^", true_xor, 1);
- rb_undef_method(CLASS_OF(rb_cTrueClass), "allocate");
- rb_undef_method(CLASS_OF(rb_cTrueClass), "new");
- rb_define_global_const("TRUE", Qtrue);
-
- rb_cFalseClass = rb_define_class("FalseClass", rb_cObject);
- rb_define_method(rb_cFalseClass, "to_s", false_to_s, 0);
- rb_define_method(rb_cFalseClass, "&", false_and, 1);
- rb_define_method(rb_cFalseClass, "|", false_or, 1);
- rb_define_method(rb_cFalseClass, "^", false_xor, 1);
- rb_undef_method(CLASS_OF(rb_cFalseClass), "allocate");
- rb_undef_method(CLASS_OF(rb_cFalseClass), "new");
- rb_define_global_const("FALSE", Qfalse);
-
- eq = rb_intern("==");
- eql = rb_intern("eql?");
- inspect = rb_intern("inspect");
- clone = rb_intern("clone");
-}
diff --git a/pack.c b/pack.c
deleted file mode 100644
index 33870d28fc..0000000000
--- a/pack.c
+++ /dev/null
@@ -1,1835 +0,0 @@
-/**********************************************************************
-
- pack.c -
-
- $Author$
- $Date$
- created at: Thu Feb 10 15:17:05 JST 1994
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
-
-**********************************************************************/
-
-#include "ruby.h"
-#include <sys/types.h>
-#include <ctype.h>
-
-#define SIZE16 2
-#define SIZE32 4
-
-#if SIZEOF_SHORT != 2 || SIZEOF_LONG != 4
-# define NATINT_PACK
-#endif
-
-#ifdef NATINT_PACK
-# define OFF16B(p) ((char*)(p) + (natint?0:(sizeof(short) - SIZE16)))
-# define OFF32B(p) ((char*)(p) + (natint?0:(sizeof(long) - SIZE32)))
-# define NATINT_I32(x) (natint?NUM2LONG(x):(NUM2I32(x)))
-# define NATINT_U32(x) (natint?NUM2ULONG(x):(NUM2U32(x)))
-# define NATINT_LEN(type,len) (natint?sizeof(type):(len))
-# ifdef WORDS_BIGENDIAN
-# define OFF16(p) OFF16B(p)
-# define OFF32(p) OFF32B(p)
-# endif
-#else
-# define NATINT_I32(x) NUM2I32(x)
-# define NATINT_U32(x) NUM2U32(x)
-# define NATINT_LEN(type,len) sizeof(type)
-#endif
-
-#ifndef OFF16
-# define OFF16(p) (char*)(p)
-# define OFF32(p) (char*)(p)
-#endif
-
-#ifndef OFF16B
-# define OFF16B(p) (char*)(p)
-# define OFF32B(p) (char*)(p)
-#endif
-
-#define define_swapx(x, xtype) \
-static xtype \
-TOKEN_PASTE(swap,x)(z) \
- xtype z; \
-{ \
- xtype r; \
- xtype *zp; \
- unsigned char *s, *t; \
- int i; \
- \
- zp = (xtype *)malloc(sizeof(xtype));\
- *zp = z; \
- s = (char *)zp; \
- t = (char *)malloc(sizeof(xtype)); \
- for (i=0; i<sizeof(xtype); i++) { \
- t[sizeof(xtype)-i-1] = s[i]; \
- } \
- r = *(xtype *)t; \
- free(t); \
- free(zp); \
- return r; \
-}
-
-#if SIZEOF_SHORT == 2
-#define swaps(x) ((((x)&0xFF)<<8) | (((x)>>8)&0xFF))
-#else
-#if SIZEOF_SHORT == 4
-#define swaps(x) ((((x)&0xFF)<<24) \
- |(((x)>>24)&0xFF) \
- |(((x)&0x0000FF00)<<8) \
- |(((x)&0x00FF0000)>>8) )
-#else
-define_swapx(s,short);
-#endif
-#endif
-
-#if SIZEOF_LONG == 4
-#define swapl(x) ((((x)&0xFF)<<24) \
- |(((x)>>24)&0xFF) \
- |(((x)&0x0000FF00)<<8) \
- |(((x)&0x00FF0000)>>8) )
-#else
-#if SIZEOF_LONG == 8
-#define swapl(x) ((((x)&0x00000000000000FF)<<56) \
- |(((x)&0xFF00000000000000)>>56) \
- |(((x)&0x000000000000FF00)<<40) \
- |(((x)&0x00FF000000000000)>>40) \
- |(((x)&0x0000000000FF0000)<<24) \
- |(((x)&0x0000FF0000000000)>>24) \
- |(((x)&0x00000000FF000000)<<8) \
- |(((x)&0x000000FF00000000)>>8))
-#else
-define_swapx(l,long);
-#endif
-#endif
-
-#if SIZEOF_FLOAT == 4
-#if SIZEOF_LONG == 4 /* SIZEOF_FLOAT == 4 == SIZEOF_LONG */
-#define swapf(x) swapl(x)
-#define FLOAT_SWAPPER unsigned long
-#else
-#if SIZEOF_SHORT == 4 /* SIZEOF_FLOAT == 4 == SIZEOF_SHORT */
-#define swapf(x) swaps(x)
-#define FLOAT_SWAPPER unsigned short
-#else /* SIZEOF_FLOAT == 4 but undivide by known size of int */
-define_swapx(f,float);
-#endif /* #if SIZEOF_SHORT == 4 */
-#endif /* #if SIZEOF_LONG == 4 */
-#else /* SIZEOF_FLOAT != 4 */
-define_swapx(f,float);
-#endif /* #if SIZEOF_FLOAT == 4 */
-
-#if SIZEOF_DOUBLE == 8
-#if SIZEOF_LONG == 8 /* SIZEOF_DOUBLE == 8 == SIZEOF_LONG */
-#define swapd(x) swapl(x)
-#define DOUBLE_SWAPPER unsigned long
-#else
-#if SIZEOF_LONG == 4 /* SIZEOF_DOUBLE == 8 && 4 == SIZEOF_LONG */
-static double
-swapd(d)
- const double d;
-{
- double dtmp = d;
- unsigned long utmp[2];
- unsigned long utmp0;
-
- utmp[0] = 0; utmp[1] = 0;
- memcpy(utmp,&dtmp,sizeof(double));
- utmp0 = utmp[0];
- utmp[0] = swapl(utmp[1]);
- utmp[1] = swapl(utmp0);
- memcpy(&dtmp,utmp,sizeof(double));
- return dtmp;
-}
-#else
-#if SIZEOF_SHORT == 4 /* SIZEOF_DOUBLE == 8 && 4 == SIZEOF_SHORT */
-static double
-swapd(d)
- const double d;
-{
- double dtmp = d;
- unsigned short utmp[2];
- unsigned short utmp0;
-
- utmp[0] = 0; utmp[1] = 0;
- memcpy(utmp,&dtmp,sizeof(double));
- utmp0 = utmp[0];
- utmp[0] = swaps(utmp[1]);
- utmp[1] = swaps(utmp0);
- memcpy(&dtmp,utmp,sizeof(double));
- return dtmp;
-}
-#else /* SIZEOF_DOUBLE == 8 but undivied by known size of int */
-define_swapx(d, double);
-#endif /* #if SIZEOF_SHORT == 4 */
-#endif /* #if SIZEOF_LONG == 4 */
-#endif /* #if SIZEOF_LONG == 8 */
-#else /* SIZEOF_DOUBLE != 8 */
-define_swapx(d, double);
-#endif /* #if SIZEOF_DPOUBLE == 8 */
-
-#undef define_swapx
-
-#ifdef DYNAMIC_ENDIAN
-#ifdef ntohs
-#undef ntohs
-#undef ntohl
-#undef htons
-#undef htonl
-#endif
-static int
-endian()
-{
- static int init = 0;
- static int endian_value;
- char *p;
-
- if (init) return endian_value;
- init = 1;
- p = (char*)&init;
- return endian_value = p[0]?0:1;
-}
-
-#define ntohs(x) (endian()?(x):swaps(x))
-#define ntohl(x) (endian()?(x):swapl(x))
-#define ntohf(x) (endian()?(x):swapf(x))
-#define ntohd(x) (endian()?(x):swapd(x))
-#define htons(x) (endian()?(x):swaps(x))
-#define htonl(x) (endian()?(x):swapl(x))
-#define htonf(x) (endian()?(x):swapf(x))
-#define htond(x) (endian()?(x):swapd(x))
-#define htovs(x) (endian()?swaps(x):(x))
-#define htovl(x) (endian()?swapl(x):(x))
-#define htovf(x) (endian()?swapf(x):(x))
-#define htovd(x) (endian()?swapd(x):(x))
-#define vtohs(x) (endian()?swaps(x):(x))
-#define vtohl(x) (endian()?swapl(x):(x))
-#define vtohf(x) (endian()?swapf(x):(x))
-#define vtohd(x) (endian()?swapd(x):(x))
-#else
-#ifdef WORDS_BIGENDIAN
-#ifndef ntohs
-#define ntohs(x) (x)
-#define ntohl(x) (x)
-#define htons(x) (x)
-#define htonl(x) (x)
-#endif
-#define ntohf(x) (x)
-#define ntohd(x) (x)
-#define htonf(x) (x)
-#define htond(x) (x)
-#define htovs(x) swaps(x)
-#define htovl(x) swapl(x)
-#define htovf(x) swapf(x)
-#define htovd(x) swapd(x)
-#define vtohs(x) swaps(x)
-#define vtohl(x) swapl(x)
-#define vtohf(x) swapf(x)
-#define vtohd(x) swapd(x)
-#else /* LITTLE ENDIAN */
-#ifndef ntohs
-#undef ntohs
-#undef ntohl
-#undef htons
-#undef htonl
-#define ntohs(x) swaps(x)
-#define ntohl(x) swapl(x)
-#define htons(x) swaps(x)
-#define htonl(x) swapl(x)
-#endif
-#define ntohf(x) swapf(x)
-#define ntohd(x) swapd(x)
-#define htonf(x) swapf(x)
-#define htond(x) swapd(x)
-#define htovs(x) (x)
-#define htovl(x) (x)
-#define htovf(x) (x)
-#define htovd(x) (x)
-#define vtohs(x) (x)
-#define vtohl(x) (x)
-#define vtohf(x) (x)
-#define vtohd(x) (x)
-#endif
-#endif
-
-#ifdef FLOAT_SWAPPER
-#define FLOAT_CONVWITH(y) FLOAT_SWAPPER y;
-#define HTONF(x,y) (memcpy(&y,&x,sizeof(float)), \
- y = htonf((FLOAT_SWAPPER)y), \
- memcpy(&x,&y,sizeof(float)), \
- x)
-#define HTOVF(x,y) (memcpy(&y,&x,sizeof(float)), \
- y = htovf((FLOAT_SWAPPER)y), \
- memcpy(&x,&y,sizeof(float)), \
- x)
-#define NTOHF(x,y) (memcpy(&y,&x,sizeof(float)), \
- y = ntohf((FLOAT_SWAPPER)y), \
- memcpy(&x,&y,sizeof(float)), \
- x)
-#define VTOHF(x,y) (memcpy(&y,&x,sizeof(float)), \
- y = vtohf((FLOAT_SWAPPER)y), \
- memcpy(&x,&y,sizeof(float)), \
- x)
-#else
-#define FLOAT_CONVWITH(y)
-#define HTONF(x,y) htonf(x)
-#define HTOVF(x,y) htovf(x)
-#define NTOHF(x,y) ntohf(x)
-#define VTOHF(x,y) vtohf(x)
-#endif
-
-#ifdef DOUBLE_SWAPPER
-#define DOUBLE_CONVWITH(y) DOUBLE_SWAPPER y;
-#define HTOND(x,y) (memcpy(&y,&x,sizeof(double)), \
- y = htond((DOUBLE_SWAPPER)y), \
- memcpy(&x,&y,sizeof(double)), \
- x)
-#define HTOVD(x,y) (memcpy(&y,&x,sizeof(double)), \
- y = htovd((DOUBLE_SWAPPER)y), \
- memcpy(&x,&y,sizeof(double)), \
- x)
-#define NTOHD(x,y) (memcpy(&y,&x,sizeof(double)), \
- y = ntohd((DOUBLE_SWAPPER)y), \
- memcpy(&x,&y,sizeof(double)), \
- x)
-#define VTOHD(x,y) (memcpy(&y,&x,sizeof(double)), \
- y = vtohd((DOUBLE_SWAPPER)y), \
- memcpy(&x,&y,sizeof(double)), \
- x)
-#else
-#define DOUBLE_CONVWITH(y)
-#define HTOND(x,y) htond(x)
-#define HTOVD(x,y) htovd(x)
-#define NTOHD(x,y) ntohd(x)
-#define VTOHD(x,y) vtohd(x)
-#endif
-
-#if SIZEOF_LONG == SIZE32
-typedef long I32;
-typedef unsigned long U32;
-#define NUM2I32(x) NUM2LONG(x)
-#define NUM2U32(x) NUM2ULONG(x)
-#elif SIZEOF_INT == SIZE32
-typedef int I32;
-typedef unsigned int U32;
-#define NUM2I32(x) NUM2INT(x)
-#define NUM2U32(x) NUM2UINT(x)
-#endif
-
-#ifdef HAVE_LONG_LONG
-# define QUAD_SIZE sizeof(LONG_LONG)
-#else
-# define QUAD_SIZE 8
-#endif
-static char *toofew = "too few arguments";
-
-static void encodes _((VALUE,char*,int,int));
-static void qpencode _((VALUE,VALUE,int));
-
-static int uv_to_utf8 _((char*,unsigned long));
-static unsigned long utf8_to_uv _((char*,int*));
-
-static VALUE
-pack_pack(ary, fmt)
- VALUE ary, fmt;
-{
- static char *nul10 = "\0\0\0\0\0\0\0\0\0\0";
- static char *spc10 = " ";
- char *p, *pend;
- VALUE res, from, associates = 0;
- char type;
- int items, len, idx;
- char *ptr;
- int plen;
-#ifdef NATINT_PACK
- int natint; /* native integer */
-#endif
-
- StringValue(fmt);
- p = RSTRING(fmt)->ptr;
- pend = p + RSTRING(fmt)->len;
- res = rb_str_buf_new(0);
-
- items = RARRAY(ary)->len;
- idx = 0;
-
-#define THISFROM RARRAY(ary)->ptr[idx]
-#define NEXTFROM (items-- > 0 ? RARRAY(ary)->ptr[idx++] : (rb_raise(rb_eArgError, toofew),0))
-
- while (p < pend) {
- type = *p++; /* get data type */
-#ifdef NATINT_PACK
- natint = 0;
-#endif
-
- if (ISSPACE(type)) continue;
- if (type == '#') {
- while ((p < pend) && (*p != '\n')) {
- p++;
- }
- continue;
- }
- if (*p == '_' || *p == '!') {
- char *natstr = "sSiIlL";
-
- if (strchr(natstr, type)) {
-#ifdef NATINT_PACK
- natint = 1;
-#endif
- p++;
- }
- else {
- rb_raise(rb_eArgError, "'%c' allowed only after types %s", *p, natstr);
- }
- }
- if (*p == '*') { /* set data length */
- len = strchr("@Xxu", type) ? 0 : items;
- p++;
- }
- else if (ISDIGIT(*p)) {
- len = strtoul(p, (char**)&p, 10);
- }
- else {
- len = 1;
- }
-
- switch (type) {
- case 'A': case 'a': case 'Z':
- case 'B': case 'b':
- case 'H': case 'h':
- from = NEXTFROM;
- if (NIL_P(from)) {
- ptr = "";
- plen = 0;
- }
- else {
- StringValue(from);
- ptr = RSTRING(from)->ptr;
- plen = RSTRING(from)->len;
- }
-
- if (p[-1] == '*')
- len = plen;
-
- switch (type) {
- case 'a':
- case 'A':
- case 'Z':
- if (plen >= len)
- rb_str_buf_cat(res, ptr, len);
- else {
- rb_str_buf_cat(res, ptr, plen);
- len -= plen;
- while (len >= 10) {
- rb_str_buf_cat(res, (type == 'A')?spc10:nul10, 10);
- len -= 10;
- }
- rb_str_buf_cat(res, (type == 'A')?spc10:nul10, len);
- }
- break;
-
- case 'b':
- {
- int byte = 0;
- int i, j = 0;
-
- if (len > plen) {
- j = (len - plen + 1)/2;
- len = plen;
- }
- for (i=0; i++ < len; ptr++) {
- if (*ptr & 1)
- byte |= 128;
- if (i & 7)
- byte >>= 1;
- else {
- char c = byte & 0xff;
- rb_str_buf_cat(res, &c, 1);
- byte = 0;
- }
- }
- if (len & 7) {
- char c;
- byte >>= 7 - (len & 7);
- c = byte & 0xff;
- rb_str_buf_cat(res, &c, 1);
- }
- rb_str_buf_cat(res, 0, j);
- }
- break;
-
- case 'B':
- {
- int byte = 0;
- int i, j = 0;
-
- if (len > plen) {
- j = (len - plen + 1)/2;
- len = plen;
- }
- for (i=0; i++ < len; ptr++) {
- byte |= *ptr & 1;
- if (i & 7)
- byte <<= 1;
- else {
- char c = byte & 0xff;
- rb_str_buf_cat(res, &c, 1);
- byte = 0;
- }
- }
- if (len & 7) {
- char c;
- byte <<= 7 - (len & 7);
- c = byte & 0xff;
- rb_str_buf_cat(res, &c, 1);
- }
- rb_str_buf_cat(res, 0, j);
- }
- break;
-
- case 'h':
- {
- int byte = 0;
- int i, j = 0;
-
- if (len > plen) {
- j = (len - plen + 1)/2;
- len = plen;
- }
- for (i=0; i++ < len; ptr++) {
- if (ISALPHA(*ptr))
- byte |= (((*ptr & 15) + 9) & 15) << 4;
- else
- byte |= (*ptr & 15) << 4;
- if (i & 1)
- byte >>= 4;
- else {
- char c = byte & 0xff;
- rb_str_buf_cat(res, &c, 1);
- byte = 0;
- }
- }
- if (len & 1) {
- char c = byte & 0xff;
- rb_str_buf_cat(res, &c, 1);
- }
- rb_str_buf_cat(res, 0, j);
- }
- break;
-
- case 'H':
- {
- int byte = 0;
- int i, j = 0;
-
- if (len > plen) {
- j = (len - plen + 1)/2;
- len = plen;
- }
- for (i=0; i++ < len; ptr++) {
- if (ISALPHA(*ptr))
- byte |= ((*ptr & 15) + 9) & 15;
- else
- byte |= *ptr & 15;
- if (i & 1)
- byte <<= 4;
- else {
- char c = byte & 0xff;
- rb_str_buf_cat(res, &c, 1);
- byte = 0;
- }
- }
- if (len & 1) {
- char c = byte & 0xff;
- rb_str_buf_cat(res, &c, 1);
- }
- rb_str_buf_cat(res, 0, j);
- }
- break;
- }
- break;
-
- case 'c':
- case 'C':
- while (len-- > 0) {
- char c;
-
- from = NEXTFROM;
- if (NIL_P(from)) c = 0;
- else {
- c = NUM2INT(from);
- }
- rb_str_buf_cat(res, &c, sizeof(char));
- }
- break;
-
- case 's':
- case 'S':
- while (len-- > 0) {
- short s;
-
- from = NEXTFROM;
- if (NIL_P(from)) s = 0;
- else {
- s = NUM2INT(from);
- }
- rb_str_buf_cat(res, OFF16(&s), NATINT_LEN(short,2));
- }
- break;
-
- case 'i':
- case 'I':
- while (len-- > 0) {
- int i;
-
- from = NEXTFROM;
- if (NIL_P(from)) i = 0;
- else {
- i = NUM2UINT(from);
- }
- rb_str_buf_cat(res, (char*)&i, sizeof(int));
- }
- break;
-
- case 'l':
- case 'L':
- while (len-- > 0) {
- long l;
-
- from = NEXTFROM;
- if (NIL_P(from)) l = 0;
- else {
- l = NATINT_U32(from);
- }
- rb_str_buf_cat(res, OFF32(&l), NATINT_LEN(long,4));
- }
- break;
-
- case 'q':
- case 'Q':
- while (len-- > 0) {
- char tmp[QUAD_SIZE];
-
- from = NEXTFROM;
- if (NIL_P(from)) from = INT2FIX(0);
- rb_quad_pack(tmp, from);
- rb_str_buf_cat(res, (char*)&tmp, QUAD_SIZE);
- }
- break;
-
- case 'n':
- while (len-- > 0) {
- unsigned short s;
-
- from = NEXTFROM;
- if (NIL_P(from)) s = 0;
- else {
- s = NUM2INT(from);
- }
- s = htons(s);
- rb_str_buf_cat(res, OFF16B(&s), NATINT_LEN(short,2));
- }
- break;
-
- case 'N':
- while (len-- > 0) {
- unsigned long l;
-
- from = NEXTFROM;
- if (NIL_P(from)) l = 0;
- else {
- l = NATINT_U32(from);
- }
- l = htonl(l);
- rb_str_buf_cat(res, OFF32B(&l), NATINT_LEN(long,4));
- }
- break;
-
- case 'v':
- while (len-- > 0) {
- unsigned short s;
-
- from = NEXTFROM;
- if (NIL_P(from)) s = 0;
- else {
- s = NUM2INT(from);
- }
- s = htovs(s);
- rb_str_buf_cat(res, OFF16(&s), NATINT_LEN(short,2));
- }
- break;
-
- case 'V':
- while (len-- > 0) {
- unsigned long l;
-
- from = NEXTFROM;
- if (NIL_P(from)) l = 0;
- else {
- l = NATINT_U32(from);
- }
- l = htovl(l);
- rb_str_buf_cat(res, OFF32(&l), NATINT_LEN(long,4));
- }
- break;
-
- case 'f':
- case 'F':
- while (len-- > 0) {
- float f;
-
- from = NEXTFROM;
- f = RFLOAT(rb_Float(from))->value;
- rb_str_buf_cat(res, (char*)&f, sizeof(float));
- }
- break;
-
- case 'e':
- while (len-- > 0) {
- float f;
- FLOAT_CONVWITH(ftmp);
-
- from = NEXTFROM;
- f = RFLOAT(rb_Float(from))->value;
- f = HTOVF(f,ftmp);
- rb_str_buf_cat(res, (char*)&f, sizeof(float));
- }
- break;
-
- case 'E':
- while (len-- > 0) {
- double d;
- DOUBLE_CONVWITH(dtmp);
-
- from = NEXTFROM;
- d = RFLOAT(rb_Float(from))->value;
- d = HTOVD(d,dtmp);
- rb_str_buf_cat(res, (char*)&d, sizeof(double));
- }
- break;
-
- case 'd':
- case 'D':
- while (len-- > 0) {
- double d;
-
- from = NEXTFROM;
- d = RFLOAT(rb_Float(from))->value;
- rb_str_buf_cat(res, (char*)&d, sizeof(double));
- }
- break;
-
- case 'g':
- while (len-- > 0) {
- float f;
- FLOAT_CONVWITH(ftmp);
-
- from = NEXTFROM;
- f = RFLOAT(rb_Float(from))->value;
- f = HTONF(f,ftmp);
- rb_str_buf_cat(res, (char*)&f, sizeof(float));
- }
- break;
-
- case 'G':
- while (len-- > 0) {
- double d;
- DOUBLE_CONVWITH(dtmp);
-
- from = NEXTFROM;
- d = RFLOAT(rb_Float(from))->value;
- d = HTOND(d,dtmp);
- rb_str_buf_cat(res, (char*)&d, sizeof(double));
- }
- break;
-
- case 'x':
- grow:
- while (len >= 10) {
- rb_str_buf_cat(res, nul10, 10);
- len -= 10;
- }
- rb_str_buf_cat(res, nul10, len);
- break;
-
- case 'X':
- shrink:
- plen = RSTRING(res)->len;
- if (plen < len)
- rb_raise(rb_eArgError, "X outside of string");
- RSTRING(res)->len = plen - len;
- RSTRING(res)->ptr[plen - len] = '\0';
- break;
-
- case '@':
- len -= RSTRING(res)->len;
- if (len > 0) goto grow;
- len = -len;
- if (len > 0) goto shrink;
- break;
-
- case '%':
- rb_raise(rb_eArgError, "%% is not supported");
- break;
-
- case 'U':
- while (len-- > 0) {
- unsigned long l;
- char buf[8];
- int le;
-
- from = NEXTFROM;
- if (NIL_P(from)) l = 0;
- else {
- l = NUM2ULONG(from);
- }
- le = uv_to_utf8(buf, l);
- rb_str_buf_cat(res, (char*)buf, le);
- }
- break;
-
- case 'u':
- case 'm':
- from = NEXTFROM;
- StringValue(from);
- ptr = RSTRING(from)->ptr;
- plen = RSTRING(from)->len;
-
- if (len <= 2)
- len = 45;
- else
- len = len / 3 * 3;
- while (plen > 0) {
- int todo;
-
- if (plen > len)
- todo = len;
- else
- todo = plen;
- encodes(res, ptr, todo, type);
- plen -= todo;
- ptr += todo;
- }
- break;
-
- case 'M':
- from = rb_obj_as_string(NEXTFROM);
- if (len <= 1)
- len = 72;
- qpencode(res, from, len);
- break;
-
- case 'P':
- from = THISFROM;
- if (!NIL_P(from)) {
- StringValue(from);
- if (RSTRING(from)->len < len) {
- rb_raise(rb_eArgError, "too short buffer for P(%d for %d)",
- RSTRING(from)->len, len);
- }
- }
- len = 1;
- /* FALL THROUGH */
- case 'p':
- while (len-- > 0) {
- char *t;
- from = NEXTFROM;
- if (NIL_P(from)) {
- t = 0;
- }
- else {
- StringValue(from);
- t = RSTRING(from)->ptr;
- }
- if (!associates) {
- associates = rb_ary_new();
- }
- rb_ary_push(associates, from);
- rb_str_buf_cat(res, (char*)&t, sizeof(char*));
- }
- break;
-
- case 'w':
- while (len-- > 0) {
- unsigned long ul;
- VALUE buf = rb_str_new(0, 0);
- char c, *bufs, *bufe;
-
- from = NEXTFROM;
- if (TYPE(from) == T_BIGNUM) {
- VALUE big128 = rb_uint2big(128);
- while (TYPE(from) == T_BIGNUM) {
- from = rb_big_divmod(from, big128);
- c = NUM2INT(RARRAY(from)->ptr[1]) | 0x80; /* mod */
- rb_str_buf_cat(buf, &c, sizeof(char));
- from = RARRAY(from)->ptr[0]; /* div */
- }
- }
-
- if (NIL_P(from)) ul = 0;
- else {
- ul = NUM2ULONG(from);
- }
-
- while (ul) {
- c = ((ul & 0x7f) | 0x80);
- rb_str_buf_cat(buf, &c, sizeof(char));
- ul >>= 7;
- }
-
- if (RSTRING(buf)->len) {
- bufs = RSTRING(buf)->ptr;
- bufe = bufs + RSTRING(buf)->len - 1;
- *bufs &= 0x7f; /* clear continue bit */
- while (bufs < bufe) { /* reverse */
- c = *bufs;
- *bufs++ = *bufe;
- *bufe-- = c;
- }
- rb_str_buf_cat(res, RSTRING(buf)->ptr, RSTRING(buf)->len);
- }
- else {
- c = 0;
- rb_str_buf_cat(res, &c, sizeof(char));
- }
- }
- break;
-
- default:
- break;
- }
- }
-
- if (associates) {
- rb_str_associate(res, associates);
- }
- return res;
-}
-
-static char uu_table[] =
-"`!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
-static char b64_table[] =
-"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
-
-static void
-encodes(str, s, len, type)
- VALUE str;
- char *s;
- int len;
- int type;
-{
- char *buff = ALLOCA_N(char, len * 4 / 3 + 6);
- int i = 0;
- char *trans = type == 'u' ? uu_table : b64_table;
- int padding;
-
- if (type == 'u') {
- buff[i++] = len + ' ';
- padding = '`';
- }
- else {
- padding = '=';
- }
- while (len >= 3) {
- buff[i++] = trans[077 & (*s >> 2)];
- buff[i++] = trans[077 & (((*s << 4) & 060) | ((s[1] >> 4) & 017))];
- buff[i++] = trans[077 & (((s[1] << 2) & 074) | ((s[2] >> 6) & 03))];
- buff[i++] = trans[077 & s[2]];
- s += 3;
- len -= 3;
- }
- if (len == 2) {
- buff[i++] = trans[077 & (*s >> 2)];
- buff[i++] = trans[077 & (((*s << 4) & 060) | ((s[1] >> 4) & 017))];
- buff[i++] = trans[077 & (((s[1] << 2) & 074) | (('\0' >> 6) & 03))];
- buff[i++] = padding;
- }
- else if (len == 1) {
- buff[i++] = trans[077 & (*s >> 2)];
- buff[i++] = trans[077 & (((*s << 4) & 060) | (('\0' >> 4) & 017))];
- buff[i++] = padding;
- buff[i++] = padding;
- }
- buff[i++] = '\n';
- rb_str_buf_cat(str, buff, i);
-}
-
-static char hex_table[] = "0123456789ABCDEF";
-
-static void
-qpencode(str, from, len)
- VALUE str, from;
- int len;
-{
- char buff[1024];
- int i = 0, n = 0, prev = EOF;
- unsigned char *s = (unsigned char*)RSTRING(from)->ptr;
- unsigned char *send = s + RSTRING(from)->len;
-
- while (s < send) {
- if ((*s > 126) ||
- (*s < 32 && *s != '\n' && *s != '\t') ||
- (*s == '=')) {
- buff[i++] = '=';
- buff[i++] = hex_table[*s >> 4];
- buff[i++] = hex_table[*s & 0x0f];
- n += 3;
- prev = EOF;
- }
- else if (*s == '\n') {
- if (prev == ' ' || prev == '\t') {
- buff[i++] = '=';
- buff[i++] = *s;
- }
- buff[i++] = *s;
- n = 0;
- prev = *s;
- }
- else {
- buff[i++] = *s;
- n++;
- prev = *s;
- }
- if (n > len) {
- buff[i++] = '=';
- buff[i++] = '\n';
- n = 0;
- prev = '\n';
- }
- if (i > 1024 - 5) {
- rb_str_buf_cat(str, buff, i);
- i = 0;
- }
- s++;
- }
- if (n > 0) {
- buff[i++] = '=';
- buff[i++] = '\n';
- }
- if (i > 0) {
- rb_str_buf_cat(str, buff, i);
- }
-}
-
-static inline int
-hex2num(c)
- char c;
-{
- switch (c) {
- case '0': case '1': case '2': case '3': case '4':
- case '5': case '6': case '7': case '8': case '9':
- return c - '0';
- case 'a': case 'b': case 'c':
- case 'd': case 'e': case 'f':
- return c - 'a' + 10;
- case 'A': case 'B': case 'C':
- case 'D': case 'E': case 'F':
- return c - 'A' + 10;
- default:
- return -1;
- }
-}
-
-#define PACK_LENGTH_ADJUST_SIZE(sz) do { \
- tmp = 0; \
- if (len > (send-s)/sz) { \
- if (!star) { \
- tmp = len-(send-s)/sz; \
- } \
- len = (send-s)/sz; \
- } \
-} while (0)
-
-#ifdef NATINT_PACK
-#define PACK_LENGTH_ADJUST(type,sz) do { \
- int t__len = NATINT_LEN(type,(sz)); \
- PACK_LENGTH_ADJUST_SIZE(t__len); \
-} while (0)
-#else
-#define PACK_LENGTH_ADJUST(type,sz) do { \
- PACK_LENGTH_ADJUST_SIZE(sizeof(type)); \
-} while (0)
-#endif
-
-#define PACK_ITEM_ADJUST() while (tmp--) rb_ary_push(ary, Qnil);
-
-static VALUE
-pack_unpack(str, fmt)
- VALUE str, fmt;
-{
- static char *hexdigits = "0123456789abcdef0123456789ABCDEFx";
- char *s, *send;
- char *p, *pend;
- VALUE ary;
- char type;
- int len, tmp, star;
-#ifdef NATINT_PACK
- int natint; /* native integer */
-#endif
-
- StringValue(str);
- s = RSTRING(str)->ptr;
- send = s + RSTRING(str)->len;
- StringValue(fmt);
- p = RSTRING(fmt)->ptr;
- pend = p + RSTRING(fmt)->len;
-
- ary = rb_ary_new();
- while (p < pend) {
- type = *p++;
-#ifdef NATINT_PACK
- natint = 0;
-#endif
-
- if (ISSPACE(type)) continue;
- if (type == '#') {
- while ((p < pend) && (*p != '\n')) {
- p++;
- }
- continue;
- }
- star = 0;
- if (*p == '_' || *p == '!') {
- char *natstr = "sSiIlL";
-
- if (strchr(natstr, type)) {
-#ifdef NATINT_PACK
- natint = 1;
-#endif
- p++;
- }
- else {
- rb_raise(rb_eArgError, "'%c' allowed only after types %s", *p, natstr);
- }
- }
- if (p >= pend)
- len = 1;
- else if (*p == '*') {
- star = 1;
- len = send - s;
- p++;
- }
- else if (ISDIGIT(*p)) {
- len = strtoul(p, (char**)&p, 10);
- }
- else {
- len = (type != '@');
- }
-
- switch (type) {
- case '%':
- rb_raise(rb_eArgError, "%% is not supported");
- break;
-
- case 'A':
- if (len > send - s) len = send - s;
- {
- int end = len;
- char *t = s + len - 1;
-
- while (t >= s) {
- if (*t != ' ' && *t != '\0') break;
- t--; len--;
- }
- rb_ary_push(ary, rb_str_new(s, len));
- s += end;
- }
- break;
-
- case 'Z':
- if (len > send - s) len = send - s;
- {
- int end = len;
- char *t = s + len - 1;
-
- while (t >= s) {
- if (*t) break;
- t--; len--;
- }
- rb_ary_push(ary, rb_str_new(s, len));
- s += end;
- }
- break;
-
- case 'a':
- if (len > send - s) len = send - s;
- rb_ary_push(ary, rb_str_new(s, len));
- s += len;
- break;
-
-
- case 'b':
- {
- VALUE bitstr;
- char *t;
- int bits, i;
-
- if (p[-1] == '*' || len > (send - s) * 8)
- len = (send - s) * 8;
- bits = 0;
- rb_ary_push(ary, bitstr = rb_str_new(0, len));
- t = RSTRING(bitstr)->ptr;
- for (i=0; i<len; i++) {
- if (i & 7) bits >>= 1;
- else bits = *s++;
- *t++ = (bits & 1) ? '1' : '0';
- }
- }
- break;
-
- case 'B':
- {
- VALUE bitstr;
- char *t;
- int bits, i;
-
- if (p[-1] == '*' || len > (send - s) * 8)
- len = (send - s) * 8;
- bits = 0;
- rb_ary_push(ary, bitstr = rb_str_new(0, len));
- t = RSTRING(bitstr)->ptr;
- for (i=0; i<len; i++) {
- if (i & 7) bits <<= 1;
- else bits = *s++;
- *t++ = (bits & 128) ? '1' : '0';
- }
- }
- break;
-
- case 'h':
- {
- VALUE bitstr;
- char *t;
- int bits, i;
-
- if (p[-1] == '*' || len > (send - s) * 2)
- len = (send - s) * 2;
- bits = 0;
- rb_ary_push(ary, bitstr = rb_str_new(0, len));
- t = RSTRING(bitstr)->ptr;
- for (i=0; i<len; i++) {
- if (i & 1)
- bits >>= 4;
- else
- bits = *s++;
- *t++ = hexdigits[bits & 15];
- }
- }
- break;
-
- case 'H':
- {
- VALUE bitstr;
- char *t;
- int bits, i;
-
- if (p[-1] == '*' || len > (send - s) * 2)
- len = (send - s) * 2;
- bits = 0;
- rb_ary_push(ary, bitstr = rb_str_new(0, len));
- t = RSTRING(bitstr)->ptr;
- for (i=0; i<len; i++) {
- if (i & 1)
- bits <<= 4;
- else
- bits = *s++;
- *t++ = hexdigits[(bits >> 4) & 15];
- }
- }
- break;
-
- case 'c':
- PACK_LENGTH_ADJUST(char,sizeof(char));
- while (len-- > 0) {
- int c = *s++;
- if (c > (char)127) c-=256;
- rb_ary_push(ary, INT2FIX(c));
- }
- PACK_ITEM_ADJUST();
- break;
-
- case 'C':
- PACK_LENGTH_ADJUST(unsigned char,sizeof(unsigned char));
- while (len-- > 0) {
- unsigned char c = *s++;
- rb_ary_push(ary, INT2FIX(c));
- }
- PACK_ITEM_ADJUST();
- break;
-
- case 's':
- PACK_LENGTH_ADJUST(short,2);
- while (len-- > 0) {
- short tmp = 0;
- memcpy(OFF16(&tmp), s, NATINT_LEN(short,2));
- s += NATINT_LEN(short,2);
- rb_ary_push(ary, INT2FIX(tmp));
- }
- PACK_ITEM_ADJUST();
- break;
-
- case 'S':
- PACK_LENGTH_ADJUST(unsigned short,2);
- while (len-- > 0) {
- unsigned short tmp = 0;
- memcpy(OFF16(&tmp), s, NATINT_LEN(unsigned short,2));
- s += NATINT_LEN(unsigned short,2);
- rb_ary_push(ary, INT2FIX(tmp));
- }
- PACK_ITEM_ADJUST();
- break;
-
- case 'i':
- PACK_LENGTH_ADJUST(int,sizeof(int));
- while (len-- > 0) {
- int tmp;
- memcpy(&tmp, s, sizeof(int));
- s += sizeof(int);
- rb_ary_push(ary, rb_int2inum(tmp));
- }
- PACK_ITEM_ADJUST();
- break;
-
- case 'I':
- PACK_LENGTH_ADJUST(unsigned int,sizeof(unsigned int));
- while (len-- > 0) {
- unsigned int tmp;
- memcpy(&tmp, s, sizeof(unsigned int));
- s += sizeof(unsigned int);
- rb_ary_push(ary, rb_uint2inum(tmp));
- }
- PACK_ITEM_ADJUST();
- break;
-
- case 'l':
- PACK_LENGTH_ADJUST(long,4);
- while (len-- > 0) {
- long tmp = 0;
- memcpy(OFF32(&tmp), s, NATINT_LEN(long,4));
- s += NATINT_LEN(long,4);
- rb_ary_push(ary, rb_int2inum(tmp));
- }
- PACK_ITEM_ADJUST();
- break;
-
- case 'L':
- PACK_LENGTH_ADJUST(unsigned long,4);
- while (len-- > 0) {
- unsigned long tmp = 0;
- memcpy(OFF32(&tmp), s, NATINT_LEN(unsigned long,4));
- s += NATINT_LEN(unsigned long,4);
- rb_ary_push(ary, rb_uint2inum(tmp));
- }
- PACK_ITEM_ADJUST();
- break;
-
- case 'q':
- PACK_LENGTH_ADJUST_SIZE(QUAD_SIZE);
- while (len-- > 0) {
- char *tmp = (char*)s;
- s += QUAD_SIZE;
- rb_ary_push(ary, rb_quad_unpack(tmp, 1));
- }
- PACK_ITEM_ADJUST();
- break;
- case 'Q':
- PACK_LENGTH_ADJUST_SIZE(QUAD_SIZE);
- while (len-- > 0) {
- char *tmp = (char*)s;
- s += QUAD_SIZE;
- rb_ary_push(ary, rb_quad_unpack(tmp, 0));
- }
- break;
-
- case 'n':
- PACK_LENGTH_ADJUST(unsigned short,2);
- while (len-- > 0) {
- unsigned short tmp = 0;
- memcpy(OFF16B(&tmp), s, NATINT_LEN(unsigned short,2));
- s += NATINT_LEN(unsigned short,2);
- rb_ary_push(ary, rb_uint2inum(ntohs(tmp)));
- }
- PACK_ITEM_ADJUST();
- break;
-
- case 'N':
- PACK_LENGTH_ADJUST(unsigned long,4);
- while (len-- > 0) {
- unsigned long tmp = 0;
- memcpy(OFF32B(&tmp), s, NATINT_LEN(unsigned long,4));
- s += NATINT_LEN(unsigned long,4);
- rb_ary_push(ary, rb_uint2inum(ntohl(tmp)));
- }
- PACK_ITEM_ADJUST();
- break;
-
- case 'v':
- PACK_LENGTH_ADJUST(unsigned short,2);
- while (len-- > 0) {
- unsigned short tmp = 0;
- memcpy(OFF16(&tmp), s, NATINT_LEN(unsigned short,2));
- s += NATINT_LEN(unsigned short,2);
- rb_ary_push(ary, rb_uint2inum(vtohs(tmp)));
- }
- PACK_ITEM_ADJUST();
- break;
-
- case 'V':
- PACK_LENGTH_ADJUST(unsigned long,4);
- while (len-- > 0) {
- unsigned long tmp = 0;
- memcpy(OFF32(&tmp), s, NATINT_LEN(long,4));
- s += NATINT_LEN(long,4);
- rb_ary_push(ary, rb_uint2inum(vtohl(tmp)));
- }
- PACK_ITEM_ADJUST();
- break;
-
- case 'f':
- case 'F':
- PACK_LENGTH_ADJUST(float,sizeof(float));
- while (len-- > 0) {
- float tmp;
- memcpy(&tmp, s, sizeof(float));
- s += sizeof(float);
- rb_ary_push(ary, rb_float_new((double)tmp));
- }
- PACK_ITEM_ADJUST();
- break;
-
- case 'e':
- PACK_LENGTH_ADJUST(float,sizeof(float));
- while (len-- > 0) {
- float tmp;
- FLOAT_CONVWITH(ftmp);
-
- memcpy(&tmp, s, sizeof(float));
- s += sizeof(float);
- tmp = VTOHF(tmp,ftmp);
- rb_ary_push(ary, rb_float_new((double)tmp));
- }
- PACK_ITEM_ADJUST();
- break;
-
- case 'E':
- PACK_LENGTH_ADJUST(double,sizeof(double));
- while (len-- > 0) {
- double tmp;
- DOUBLE_CONVWITH(dtmp);
-
- memcpy(&tmp, s, sizeof(double));
- s += sizeof(double);
- tmp = VTOHD(tmp,dtmp);
- rb_ary_push(ary, rb_float_new(tmp));
- }
- PACK_ITEM_ADJUST();
- break;
-
- case 'D':
- case 'd':
- PACK_LENGTH_ADJUST(double,sizeof(double));
- while (len-- > 0) {
- double tmp;
- memcpy(&tmp, s, sizeof(double));
- s += sizeof(double);
- rb_ary_push(ary, rb_float_new(tmp));
- }
- PACK_ITEM_ADJUST();
- break;
-
- case 'g':
- PACK_LENGTH_ADJUST(float,sizeof(float));
- while (len-- > 0) {
- float tmp;
- FLOAT_CONVWITH(ftmp;)
-
- memcpy(&tmp, s, sizeof(float));
- s += sizeof(float);
- tmp = NTOHF(tmp,ftmp);
- rb_ary_push(ary, rb_float_new((double)tmp));
- }
- PACK_ITEM_ADJUST();
- break;
-
- case 'G':
- PACK_LENGTH_ADJUST(double,sizeof(double));
- while (len-- > 0) {
- double tmp;
- DOUBLE_CONVWITH(dtmp);
-
- memcpy(&tmp, s, sizeof(double));
- s += sizeof(double);
- tmp = NTOHD(tmp,dtmp);
- rb_ary_push(ary, rb_float_new(tmp));
- }
- PACK_ITEM_ADJUST();
- break;
-
- case 'U':
- if (len > send - s) len = send - s;
- while (len > 0 && s < send) {
- int alen = len;
- unsigned long l;
-
- l = utf8_to_uv(s, &alen);
- s += alen; len -= alen;
- rb_ary_push(ary, rb_uint2inum(l));
- }
- break;
-
- case 'u':
- {
- VALUE str = rb_str_new(0, (send - s)*3/4);
- char *ptr = RSTRING(str)->ptr;
- int total = 0;
-
- while (s < send && *s > ' ' && *s < 'a') {
- long a,b,c,d;
- char hunk[4];
-
- hunk[3] = '\0';
- len = (*s++ - ' ') & 077;
- total += len;
- if (total > RSTRING(str)->len) {
- len -= total - RSTRING(str)->len;
- total = RSTRING(str)->len;
- }
-
- while (len > 0) {
- int mlen = len > 3 ? 3 : len;
-
- if (s < send && *s >= ' ')
- a = (*s++ - ' ') & 077;
- else
- a = 0;
- if (s < send && *s >= ' ')
- b = (*s++ - ' ') & 077;
- else
- b = 0;
- if (s < send && *s >= ' ')
- c = (*s++ - ' ') & 077;
- else
- c = 0;
- if (s < send && *s >= ' ')
- d = (*s++ - ' ') & 077;
- else
- d = 0;
- hunk[0] = a << 2 | b >> 4;
- hunk[1] = b << 4 | c >> 2;
- hunk[2] = c << 6 | d;
- memcpy(ptr, hunk, mlen);
- ptr += mlen;
- len -= mlen;
- }
- if (*s == '\r') s++;
- if (*s == '\n') s++;
- else if (s < send && (s+1 == send || s[1] == '\n'))
- s += 2; /* possible checksum byte */
- }
-
- RSTRING(str)->ptr[total] = '\0';
- RSTRING(str)->len = total;
- rb_ary_push(ary, str);
- }
- break;
-
- case 'm':
- {
- VALUE str = rb_str_new(0, (send - s)*3/4);
- char *ptr = RSTRING(str)->ptr;
- int a,b,c,d;
- static int first = 1;
- static int b64_xtable[256];
-
- if (first) {
- int i;
- first = 0;
-
- for (i = 0; i < 256; i++) {
- b64_xtable[i] = -1;
- }
- for (i = 0; i < 64; i++) {
- b64_xtable[(int)b64_table[i]] = i;
- }
- }
- for (;;) {
- while (s[0] == '\r' || s[0] == '\n') { s++; }
- if ((a = b64_xtable[(int)s[0]]) == -1) break;
- if ((b = b64_xtable[(int)s[1]]) == -1) break;
- if ((c = b64_xtable[(int)s[2]]) == -1) break;
- if ((d = b64_xtable[(int)s[3]]) == -1) break;
- *ptr++ = a << 2 | b >> 4;
- *ptr++ = b << 4 | c >> 2;
- *ptr++ = c << 6 | d;
- s += 4;
- }
- if (a != -1 && b != -1 && s[2] == '=') {
- *ptr++ = a << 2 | b >> 4;
- }
- if (a != -1 && b != -1 && c != -1 && s[3] == '=') {
- *ptr++ = a << 2 | b >> 4;
- *ptr++ = b << 4 | c >> 2;
- }
- *ptr = '\0';
- RSTRING(str)->len = ptr - RSTRING(str)->ptr;
- rb_ary_push(ary, str);
- }
- break;
-
- case 'M':
- {
- VALUE str = rb_str_new(0, send - s);
- char *ptr = RSTRING(str)->ptr;
- int c1, c2;
-
- while (s < send) {
- if (*s == '=') {
- if (++s == send) break;
- if (*s != '\n') {
- if ((c1 = hex2num(*s)) == -1) break;
- if (++s == send) break;
- if ((c2 = hex2num(*s)) == -1) break;
- *ptr++ = c1 << 4 | c2;
- }
- }
- else {
- *ptr++ = *s;
- }
- s++;
- }
- *ptr = '\0';
- RSTRING(str)->len = ptr - RSTRING(str)->ptr;
- rb_ary_push(ary, str);
- }
- break;
-
- case '@':
- s = RSTRING(str)->ptr + len;
- break;
-
- case 'X':
- if (len > s - RSTRING(str)->ptr)
- rb_raise(rb_eArgError, "X outside of string");
- s -= len;
- break;
-
- case 'x':
- if (len > send - s)
- rb_raise(rb_eArgError, "x outside of string");
- s += len;
- break;
-
- case 'P':
- if (sizeof(char *) <= send - s) {
- char *t;
- VALUE tmp;
-
- memcpy(&t, s, sizeof(char *));
- s += sizeof(char *);
-
- if (t) {
- VALUE a, *p, *pend;
-
- if (!(a = rb_str_associated(str))) {
- rb_raise(rb_eArgError, "no associated pointer");
- }
- p = RARRAY(a)->ptr;
- pend = p + RARRAY(a)->len;
- while (p < pend) {
- if (TYPE(*p) == T_STRING && RSTRING(*p)->ptr == t) {
- if (len > RSTRING(*p)->len) {
- len = RSTRING(*p)->len;
- }
- break;
- }
- p++;
- }
- if (p == pend) {
- rb_raise(rb_eArgError, "non associated pointer");
- }
- tmp = rb_tainted_str_new(t, len);
- }
- else {
- tmp = Qnil;
- }
- rb_ary_push(ary, tmp);
- }
- break;
-
- case 'p':
- if (len > (send - s) / sizeof(char *))
- len = (send - s) / sizeof(char *);
- while (len-- > 0) {
- if (send - s < sizeof(char *))
- break;
- else {
- VALUE tmp;
- char *t;
-
- memcpy(&t, s, sizeof(char *));
- s += sizeof(char *);
-
- if (t) {
- VALUE a, *p, *pend;
-
- if (!(a = rb_str_associated(str))) {
- rb_raise(rb_eArgError, "no associated pointer");
- }
- p = RARRAY(a)->ptr;
- pend = p + RARRAY(a)->len;
- while (p < pend) {
- if (TYPE(*p) == T_STRING && RSTRING(*p)->ptr == t) {
- break;
- }
- p++;
- }
- if (p == pend) {
- rb_raise(rb_eArgError, "non associated pointer");
- }
- tmp = rb_str_new2(t);
- }
- else {
- tmp = Qnil;
- }
- rb_ary_push(ary, tmp);
- }
- }
- break;
-
- case 'w':
- {
- unsigned long ul = 0;
- unsigned long ulmask = 0xfeL << ((sizeof(unsigned long) - 1) * 8);
-
- while (len > 0 && s < send) {
- ul <<= 7;
- ul |= (*s & 0x7f);
- if (!(*s++ & 0x80)) {
- rb_ary_push(ary, rb_uint2inum(ul));
- len--;
- ul = 0;
- }
- else if (ul & ulmask) {
- VALUE big = rb_uint2big(ul);
- VALUE big128 = rb_uint2big(128);
- while (s < send) {
- big = rb_big_mul(big, big128);
- big = rb_big_plus(big, rb_uint2big(*s & 0x7f));
- if (!(*s++ & 0x80)) {
- rb_ary_push(ary, big);
- len--;
- ul = 0;
- break;
- }
- }
- }
- }
- }
- break;
-
- default:
- break;
- }
- }
-
- return ary;
-}
-
-#define BYTEWIDTH 8
-
-static int
-uv_to_utf8(buf, uv)
- char *buf;
- unsigned long uv;
-{
- if (uv <= 0x7f) {
- buf[0] = (char)uv;
- return 1;
- }
- if (uv <= 0x7ff) {
- buf[0] = ((uv>>6)&0xff)|0xc0;
- buf[1] = (uv&0x3f)|0x80;
- return 2;
- }
- if (uv <= 0xffff) {
- buf[0] = ((uv>>12)&0xff)|0xe0;
- buf[1] = ((uv>>6)&0x3f)|0x80;
- buf[2] = (uv&0x3f)|0x80;
- return 3;
- }
- if (uv <= 0x1fffff) {
- buf[0] = ((uv>>18)&0xff)|0xf0;
- buf[1] = ((uv>>12)&0x3f)|0x80;
- buf[2] = ((uv>>6)&0x3f)|0x80;
- buf[3] = (uv&0x3f)|0x80;
- return 4;
- }
- if (uv <= 0x3ffffff) {
- buf[0] = ((uv>>24)&0xff)|0xf8;
- buf[1] = ((uv>>18)&0x3f)|0x80;
- buf[2] = ((uv>>12)&0x3f)|0x80;
- buf[3] = ((uv>>6)&0x3f)|0x80;
- buf[4] = (uv&0x3f)|0x80;
- return 5;
- }
- if (uv <= 0x7fffffff) {
- buf[0] = ((uv>>30)&0xff)|0xfc;
- buf[1] = ((uv>>24)&0x3f)|0x80;
- buf[2] = ((uv>>18)&0x3f)|0x80;
- buf[3] = ((uv>>12)&0x3f)|0x80;
- buf[4] = ((uv>>6)&0x3f)|0x80;
- buf[5] = (uv&0x3f)|0x80;
- return 6;
- }
-#if SIZEOF_LONG > 4
- if (uv <= 0xfffffffff) {
-#endif
- buf[0] = 0xfe;
- buf[1] = ((uv>>30)&0x3f)|0x80;
- buf[2] = ((uv>>24)&0x3f)|0x80;
- buf[3] = ((uv>>18)&0x3f)|0x80;
- buf[4] = ((uv>>12)&0x3f)|0x80;
- buf[5] = ((uv>>6)&0x3f)|0x80;
- buf[6] = (uv&0x3f)|0x80;
- return 7;
-#if SIZEOF_LONG > 4
- }
- rb_raise(rb_eArgError, "uv_to_utf8(); too big value");
-#endif
-}
-
-static unsigned long
-utf8_to_uv(p, lenp)
- char *p;
- int *lenp;
-{
- int c = (*p++)&0xff;
- unsigned long uv;
- int n = 1;
-
- if (c < 0xc0) n = 1;
- else if (c < 0xe0) n = 2;
- else if (c < 0xf0) n = 3;
- else if (c < 0xf8) n = 4;
- else if (c < 0xfc) n = 5;
- else if (c < 0xfe) n = 6;
- else if (c == 0xfe) n = 7;
- if (n > *lenp) return 0;
- *lenp = n--;
-
- uv = c;
- if (n != 0) {
- uv &= (1<<(BYTEWIDTH-2-n)) - 1;
- while (n--) {
- uv = uv << 6 | *p++ & ((1<<6)-1);
- }
- }
- return uv;
-}
-
-void
-Init_pack()
-{
- rb_define_method(rb_cArray, "pack", pack_pack, 1);
- rb_define_method(rb_cString, "unpack", pack_unpack, 1);
-}
diff --git a/parse.y b/parse.y
deleted file mode 100644
index fda72e2801..0000000000
--- a/parse.y
+++ /dev/null
@@ -1,5424 +0,0 @@
-/**********************************************************************
-
- parse.y -
-
- $Author$
- $Date$
- created at: Fri May 28 18:02:42 JST 1993
-
- Copyright (C) 1993-2002 Yukihiro Matsumoto
-
-**********************************************************************/
-
-%{
-
-#define YYDEBUG 1
-#include "ruby.h"
-#include "env.h"
-#include "node.h"
-#include "st.h"
-#include <stdio.h>
-#include <errno.h>
-#include <ctype.h>
-
-#define ID_SCOPE_SHIFT 3
-#define ID_SCOPE_MASK 0x07
-#define ID_LOCAL 0x01
-#define ID_INSTANCE 0x02
-#define ID_GLOBAL 0x03
-#define ID_ATTRSET 0x04
-#define ID_CONST 0x05
-#define ID_CLASS 0x06
-#define ID_JUNK 0x07
-#define ID_INTERNAL ID_JUNK
-
-#define is_notop_id(id) ((id)>LAST_TOKEN)
-#define is_local_id(id) (is_notop_id(id)&&((id)&ID_SCOPE_MASK)==ID_LOCAL)
-#define is_global_id(id) (is_notop_id(id)&&((id)&ID_SCOPE_MASK)==ID_GLOBAL)
-#define is_instance_id(id) (is_notop_id(id)&&((id)&ID_SCOPE_MASK)==ID_INSTANCE)
-#define is_attrset_id(id) (is_notop_id(id)&&((id)&ID_SCOPE_MASK)==ID_ATTRSET)
-#define is_const_id(id) (is_notop_id(id)&&((id)&ID_SCOPE_MASK)==ID_CONST)
-#define is_class_id(id) (is_notop_id(id)&&((id)&ID_SCOPE_MASK)==ID_CLASS)
-
-NODE *ruby_eval_tree_begin = 0;
-NODE *ruby_eval_tree = 0;
-
-char *ruby_sourcefile; /* current source file */
-int ruby_sourceline; /* current line no. */
-
-static int yylex();
-static int yyerror();
-
-static enum lex_state {
- EXPR_BEG, /* ignore newline, +/- is a sign. */
- EXPR_END, /* newline significant, +/- is a operator. */
- EXPR_ARG, /* newline significant, +/- is a operator. */
- EXPR_CMDARG, /* newline significant, +/- is a operator. */
- EXPR_ENDARG, /* newline significant, +/- is a operator. */
- EXPR_MID, /* newline significant, +/- is a operator. */
- EXPR_FNAME, /* ignore newline, no reserved words. */
- EXPR_DOT, /* right after `.' or `::', no reserved words. */
- EXPR_CLASS, /* immediate after `class', no here document. */
-} lex_state;
-
-#ifdef HAVE_LONG_LONG
-typedef unsigned LONG_LONG stack_type;
-#else
-typedef unsigned long stack_type;
-#endif
-
-static stack_type cond_stack = 0;
-#define COND_PUSH(n) do {\
- cond_stack = (cond_stack<<1)|((n)&1);\
-} while(0)
-#define COND_POP() do {\
- cond_stack >>= 1;\
-} while (0)
-#define COND_LEXPOP() do {\
- int last = COND_P();\
- cond_stack >>= 1;\
- if (last) cond_stack |= 1;\
-} while (0)
-#define COND_P() (cond_stack&1)
-
-static stack_type cmdarg_stack = 0;
-#define CMDARG_PUSH(n) do {\
- cmdarg_stack = (cmdarg_stack<<1)|((n)&1);\
-} while(0)
-#define CMDARG_POP() do {\
- cmdarg_stack >>= 1;\
-} while (0)
-#define CMDARG_LEXPOP() do {\
- int last = CMDARG_P();\
- cmdarg_stack >>= 1;\
- if (last) cmdarg_stack |= 1;\
-} while (0)
-#define CMDARG_P() (cmdarg_stack&1)
-
-static int class_nest = 0;
-static int in_single = 0;
-static int in_def = 0;
-static int compile_for_eval = 0;
-static ID cur_mid = 0;
-
-static NODE *cond();
-static NODE *logop();
-
-static NODE *newline_node();
-static void fixpos();
-
-static int value_expr();
-static void void_expr();
-static void void_stmts();
-
-static NODE *block_append();
-static NODE *list_append();
-static NODE *list_concat();
-static NODE *arg_concat();
-static NODE *arg_prepend();
-static NODE *call_op();
-static int in_defined = 0;
-
-static NODE *ret_args();
-static NODE *arg_blk_pass();
-static NODE *new_call();
-static NODE *new_fcall();
-static NODE *new_super();
-
-static NODE *gettable();
-static NODE *assignable();
-static NODE *aryset();
-static NODE *attrset();
-static void rb_backref_error();
-static NODE *node_assign();
-
-static NODE *match_gen();
-static void local_push();
-static void local_pop();
-static int local_append();
-static int local_cnt();
-static int local_id();
-static ID *local_tbl();
-static ID internal_id();
-
-static struct RVarmap *dyna_push();
-static void dyna_pop();
-static int dyna_in_block();
-
-static void top_local_init();
-static void top_local_setup();
-
-%}
-
-%union {
- NODE *node;
- VALUE val;
- ID id;
- int num;
- struct RVarmap *vars;
-}
-
-%token kCLASS
- kMODULE
- kDEF
- kUNDEF
- kBEGIN
- kRESCUE
- kENSURE
- kEND
- kIF
- kUNLESS
- kTHEN
- kELSIF
- kELSE
- kCASE
- kWHEN
- kWHILE
- kUNTIL
- kFOR
- kBREAK
- kNEXT
- kREDO
- kRETRY
- kIN
- kDO
- kDO_COND
- kDO_BLOCK
- kRETURN
- kYIELD
- kSUPER
- kSELF
- kNIL
- kTRUE
- kFALSE
- kAND
- kOR
- kNOT
- kIF_MOD
- kUNLESS_MOD
- kWHILE_MOD
- kUNTIL_MOD
- kRESCUE_MOD
- kALIAS
- kDEFINED
- klBEGIN
- klEND
- k__LINE__
- k__FILE__
-
-%token <id> tIDENTIFIER tFID tGVAR tIVAR tCONSTANT tCVAR
-%token <val> tINTEGER tFLOAT tSTRING tXSTRING tREGEXP
-%token <node> tDSTRING tDXSTRING tDREGEXP tNTH_REF tBACK_REF tQWORDS
-
-%type <node> singleton string
-%type <val> literal numeric
-%type <node> compstmt stmts stmt expr arg primary command command_call method_call
-%type <node> expr_value arg_value primary_value block_call_value
-%type <node> if_tail opt_else case_body cases rescue exc_list exc_var ensure
-%type <node> args when_args call_args call_args2 open_args paren_args opt_paren_args
-%type <node> command_args aref_args opt_block_arg block_arg var_ref var_lhs
-%type <node> mrhs mrhs_basic superclass block_call block_command
-%type <node> f_arglist f_args f_optarg f_opt f_block_arg opt_f_block_arg
-%type <node> assoc_list assocs assoc undef_list backref
-%type <node> block_var opt_block_var brace_block do_block lhs none
-%type <node> mlhs mlhs_head mlhs_basic mlhs_entry mlhs_item mlhs_node
-%type <id> fitem variable sym symbol operation operation2 operation3
-%type <id> cname fname op f_rest_arg
-%type <num> f_norm_arg f_arg
-%token tUPLUS /* unary+ */
-%token tUMINUS /* unary- */
-%token tPOW /* ** */
-%token tCMP /* <=> */
-%token tEQ /* == */
-%token tEQQ /* === */
-%token tNEQ /* != */
-%token tGEQ /* >= */
-%token tLEQ /* <= */
-%token tANDOP tOROP /* && and || */
-%token tMATCH tNMATCH /* =~ and !~ */
-%token tDOT2 tDOT3 /* .. and ... */
-%token tAREF tASET /* [] and []= */
-%token tLSHFT tRSHFT /* << and >> */
-%token tCOLON2 /* :: */
-%token tCOLON3 /* :: at EXPR_BEG */
-%token <id> tOP_ASGN /* +=, -= etc. */
-%token tASSOC /* => */
-%token tLPAREN /* ( */
-%token tLPAREN_ARG /* ( */
-%token tRPAREN /* ) */
-%token tLBRACK /* [ */
-%token tLBRACE /* { */
-%token tLBRACE_ARG /* { */
-%token tSTAR /* * */
-%token tAMPER /* & */
-%token tSYMBEG
-
-/*
- * precedence table
- */
-
-%left kIF_MOD kUNLESS_MOD kWHILE_MOD kUNTIL_MOD kRESCUE_MOD
-%left kOR kAND
-%right kNOT
-%nonassoc kDEFINED
-%right '=' tOP_ASGN
-%right '?' ':'
-%nonassoc tDOT2 tDOT3
-%left tOROP
-%left tANDOP
-%nonassoc tCMP tEQ tEQQ tNEQ tMATCH tNMATCH
-%left '>' tGEQ '<' tLEQ
-%left '|' '^'
-%left '&'
-%left tLSHFT tRSHFT
-%left '+' '-'
-%left '*' '/' '%'
-%right '!' '~' tUPLUS tUMINUS
-%right tPOW
-
-%token LAST_TOKEN
-
-%%
-program : {
- $<vars>$ = ruby_dyna_vars;
- lex_state = EXPR_BEG;
- top_local_init();
- if ((VALUE)ruby_class == rb_cObject) class_nest = 0;
- else class_nest = 1;
- }
- compstmt
- {
- if ($2 && !compile_for_eval) {
- /* last expression should not be void */
- if (nd_type($2) != NODE_BLOCK) void_expr($2);
- else {
- NODE *node = $2;
- while (node->nd_next) {
- node = node->nd_next;
- }
- void_expr(node->nd_head);
- }
- }
- ruby_eval_tree = block_append(ruby_eval_tree, $2);
- top_local_setup();
- class_nest = 0;
- ruby_dyna_vars = $<vars>1;
- }
-
-compstmt : stmts opt_terms
- {
- void_stmts($1);
- $$ = $1;
- }
-
-stmts : none
- | stmt
- {
- $$ = newline_node($1);
- }
- | stmts terms stmt
- {
- $$ = block_append($1, newline_node($3));
- }
- | error stmt
- {
- $$ = $2;
- }
-
-stmt : kALIAS fitem {lex_state = EXPR_FNAME;} fitem
- {
- if (in_def || in_single)
- yyerror("alias within method");
- $$ = NEW_ALIAS($2, $4);
- }
- | kALIAS tGVAR tGVAR
- {
- if (in_def || in_single)
- yyerror("alias within method");
- $$ = NEW_VALIAS($2, $3);
- }
- | kALIAS tGVAR tBACK_REF
- {
- char buf[3];
-
- if (in_def || in_single)
- yyerror("alias within method");
- sprintf(buf, "$%c", $3->nd_nth);
- $$ = NEW_VALIAS($2, rb_intern(buf));
- }
- | kALIAS tGVAR tNTH_REF
- {
- yyerror("can't make alias for the number variables");
- $$ = 0;
- }
- | kUNDEF undef_list
- {
- if (in_def || in_single)
- yyerror("undef within method");
- $$ = $2;
- }
- | stmt kIF_MOD expr_value
- {
- $$ = NEW_IF(cond($3), $1, 0);
- fixpos($$, $3);
- }
- | stmt kUNLESS_MOD expr_value
- {
- $$ = NEW_UNLESS(cond($3), $1, 0);
- fixpos($$, $3);
- }
- | stmt kWHILE_MOD expr_value
- {
- if ($1 && nd_type($1) == NODE_BEGIN) {
- $$ = NEW_WHILE(cond($3), $1->nd_body, 0);
- }
- else {
- $$ = NEW_WHILE(cond($3), $1, 1);
- }
- }
- | stmt kUNTIL_MOD expr_value
- {
- if ($1 && nd_type($1) == NODE_BEGIN) {
- $$ = NEW_UNTIL(cond($3), $1->nd_body, 0);
- }
- else {
- $$ = NEW_UNTIL(cond($3), $1, 1);
- }
- }
- | stmt kRESCUE_MOD stmt
- {
- $$ = NEW_RESCUE($1, NEW_RESBODY(0,$3,0), 0);
- }
- | klBEGIN
- {
- if (in_def || in_single) {
- yyerror("BEGIN in method");
- }
- local_push(0);
- }
- '{' compstmt '}'
- {
- ruby_eval_tree_begin = block_append(ruby_eval_tree_begin,
- NEW_PREEXE($4));
- local_pop();
- $$ = 0;
- }
- | klEND '{' compstmt '}'
- {
- if (compile_for_eval && (in_def || in_single)) {
- yyerror("END in method; use at_exit");
- }
-
- $$ = NEW_ITER(0, NEW_POSTEXE(), $3);
- }
- | lhs '=' command_call
- {
- value_expr($3);
- $$ = node_assign($1, $3);
- }
- | mlhs '=' command_call
- {
- value_expr($3);
- $1->nd_value = $3;
- $$ = $1;
- }
- | var_lhs tOP_ASGN command_call
- {
- if ($1) {
- ID vid = $1->nd_vid;
- if ($2 == tOROP) {
- $1->nd_value = $3;
- $$ = NEW_OP_ASGN_OR(gettable(vid), $1);
- if (is_instance_id(vid)) {
- $$->nd_aid = vid;
- }
- }
- else if ($2 == tANDOP) {
- $1->nd_value = $3;
- $$ = NEW_OP_ASGN_AND(gettable(vid), $1);
- }
- else {
- $$ = $1;
- $$->nd_value = call_op(gettable(vid),$2,1,$3);
- }
- fixpos($$, $3);
- }
- else {
- $$ = 0;
- }
- }
- | primary_value '[' aref_args ']' tOP_ASGN command_call
- {
- NODE *tmp, *args = NEW_LIST($6);
-
- $3 = list_append($3, NEW_NIL());
- list_concat(args, $3);
- if ($5 == tOROP) {
- $5 = 0;
- }
- else if ($5 == tANDOP) {
- $5 = 1;
- }
- $$ = NEW_OP_ASGN1($1, $5, args);
- fixpos($$, $1);
- }
- | primary_value '.' tIDENTIFIER tOP_ASGN command_call
- {
- if ($4 == tOROP) {
- $4 = 0;
- }
- else if ($4 == tANDOP) {
- $4 = 1;
- }
- $$ = NEW_OP_ASGN2($1, $3, $4, $5);
- fixpos($$, $1);
- }
- | primary_value '.' tCONSTANT tOP_ASGN command_call
- {
- if ($4 == tOROP) {
- $4 = 0;
- }
- else if ($4 == tANDOP) {
- $4 = 1;
- }
- $$ = NEW_OP_ASGN2($1, $3, $4, $5);
- fixpos($$, $1);
- }
- | primary_value tCOLON2 tIDENTIFIER tOP_ASGN command_call
- {
- if ($4 == tOROP) {
- $4 = 0;
- }
- else if ($4 == tANDOP) {
- $4 = 1;
- }
- $$ = NEW_OP_ASGN2($1, $3, $4, $5);
- fixpos($$, $1);
- }
- | backref tOP_ASGN command_call
- {
- rb_backref_error($1);
- $$ = 0;
- }
- | lhs '=' mrhs_basic
- {
- $$ = node_assign($1, NEW_REXPAND($3));
- }
- | mlhs '=' mrhs
- {
- $1->nd_value = $3;
- $$ = $1;
- }
- | expr
-
-expr : kRETURN call_args
- {
- if (!compile_for_eval && !in_def && !in_single)
- yyerror("return appeared outside of method");
- $$ = NEW_RETURN(ret_args($2));
- }
- | kBREAK call_args
- {
- $$ = NEW_BREAK(ret_args($2));
- }
- | kNEXT call_args
- {
- $$ = NEW_NEXT(ret_args($2));
- }
- | command_call
- | expr kAND expr
- {
- $$ = logop(NODE_AND, $1, $3);
- }
- | expr kOR expr
- {
- $$ = logop(NODE_OR, $1, $3);
- }
- | kNOT expr
- {
- $$ = NEW_NOT(cond($2));
- }
- | '!' command_call
- {
- $$ = NEW_NOT(cond($2));
- }
- | arg
-
-expr_value : expr
- {
- value_expr($$);
- $$ = $1;
- }
-
-command_call : command
- | block_command
-
-block_command : block_call
- | block_call_value '.' operation2 command_args
- {
- $$ = new_call($1, $3, $4);
- }
- | block_call_value tCOLON2 operation2 command_args
- {
- $$ = new_call($1, $3, $4);
- }
-
-command : operation command_args
- {
- $$ = new_fcall($1, $2);
- fixpos($$, $2);
- }
- | primary_value '.' operation2 command_args
- {
- $$ = new_call($1, $3, $4);
- fixpos($$, $1);
- }
- | primary_value tCOLON2 operation2 command_args
- {
- $$ = new_call($1, $3, $4);
- fixpos($$, $1);
- }
- | kSUPER command_args
- {
- if (!compile_for_eval && !in_def && !in_single)
- yyerror("super called outside of method");
- $$ = new_super($2);
- fixpos($$, $2);
- }
- | kYIELD command_args
- {
- $$ = NEW_YIELD(ret_args($2));
- fixpos($$, $2);
- }
-
-mlhs : mlhs_basic
- | tLPAREN mlhs_entry ')'
- {
- $$ = $2;
- }
-
-mlhs_entry : mlhs_basic
- | tLPAREN mlhs_entry ')'
- {
- $$ = NEW_MASGN(NEW_LIST($2), 0);
- }
-
-mlhs_basic : mlhs_head
- {
- $$ = NEW_MASGN($1, 0);
- }
- | mlhs_head mlhs_item
- {
- $$ = NEW_MASGN(list_append($1,$2), 0);
- }
- | mlhs_head tSTAR mlhs_node
- {
- $$ = NEW_MASGN($1, $3);
- }
- | mlhs_head tSTAR
- {
- $$ = NEW_MASGN($1, -1);
- }
- | tSTAR mlhs_node
- {
- $$ = NEW_MASGN(0, $2);
- }
- | tSTAR
- {
- $$ = NEW_MASGN(0, -1);
- }
-
-mlhs_item : mlhs_node
- | tLPAREN mlhs_entry ')'
- {
- $$ = $2;
- }
-
-mlhs_head : mlhs_item ','
- {
- $$ = NEW_LIST($1);
- }
- | mlhs_head mlhs_item ','
- {
- $$ = list_append($1, $2);
- }
-
-mlhs_node : variable
- {
- $$ = assignable($1, 0);
- }
- | primary_value '[' aref_args ']'
- {
- $$ = aryset($1, $3);
- }
- | primary_value '.' tIDENTIFIER
- {
- $$ = attrset($1, $3);
- }
- | primary_value tCOLON2 tIDENTIFIER
- {
- $$ = attrset($1, $3);
- }
- | primary_value '.' tCONSTANT
- {
- $$ = attrset($1, $3);
- }
- | backref
- {
- rb_backref_error($1);
- $$ = 0;
- }
-
-lhs : variable
- {
- $$ = assignable($1, 0);
- }
- | primary_value '[' aref_args ']'
- {
- $$ = aryset($1, $3);
- }
- | primary_value '.' tIDENTIFIER
- {
- $$ = attrset($1, $3);
- }
- | primary_value tCOLON2 tIDENTIFIER
- {
- $$ = attrset($1, $3);
- }
- | primary_value '.' tCONSTANT
- {
- $$ = attrset($1, $3);
- }
- | backref
- {
- rb_backref_error($1);
- $$ = 0;
- }
-
-cname : tIDENTIFIER
- {
- yyerror("class/module name must be CONSTANT");
- }
- | tCONSTANT
-
-fname : tIDENTIFIER
- | tCONSTANT
- | tFID
- | op
- {
- lex_state = EXPR_END;
- $$ = $1;
- }
- | reswords
- {
- lex_state = EXPR_END;
- $$ = $<id>1;
- }
-
-fitem : fname
- | symbol
-
-undef_list : fitem
- {
- $$ = NEW_UNDEF($1);
- }
- | undef_list ',' {lex_state = EXPR_FNAME;} fitem
- {
- $$ = block_append($1, NEW_UNDEF($4));
- }
-
-op : '|' { $$ = '|'; }
- | '^' { $$ = '^'; }
- | '&' { $$ = '&'; }
- | tCMP { $$ = tCMP; }
- | tEQ { $$ = tEQ; }
- | tEQQ { $$ = tEQQ; }
- | tMATCH { $$ = tMATCH; }
- | '>' { $$ = '>'; }
- | tGEQ { $$ = tGEQ; }
- | '<' { $$ = '<'; }
- | tLEQ { $$ = tLEQ; }
- | tLSHFT { $$ = tLSHFT; }
- | tRSHFT { $$ = tRSHFT; }
- | '+' { $$ = '+'; }
- | '-' { $$ = '-'; }
- | '*' { $$ = '*'; }
- | tSTAR { $$ = '*'; }
- | '/' { $$ = '/'; }
- | '%' { $$ = '%'; }
- | tPOW { $$ = tPOW; }
- | '~' { $$ = '~'; }
- | tUPLUS { $$ = tUPLUS; }
- | tUMINUS { $$ = tUMINUS; }
- | tAREF { $$ = tAREF; }
- | tASET { $$ = tASET; }
- | '`' { $$ = '`'; }
-
-reswords : k__LINE__ | k__FILE__ | klBEGIN | klEND
- | kALIAS | kAND | kBEGIN | kBREAK | kCASE | kCLASS | kDEF
- | kDEFINED | kDO | kELSE | kELSIF | kEND | kENSURE | kFALSE
- | kFOR | kIF_MOD | kIN | kMODULE | kNEXT | kNIL | kNOT
- | kOR | kREDO | kRESCUE | kRETRY | kRETURN | kSELF | kSUPER
- | kTHEN | kTRUE | kUNDEF | kUNLESS_MOD | kUNTIL_MOD | kWHEN
- | kWHILE_MOD | kYIELD | kRESCUE_MOD
-
-arg : lhs '=' arg
- {
- value_expr($3);
- $$ = node_assign($1, $3);
- }
- | var_lhs tOP_ASGN arg
- {
- if ($1) {
- ID vid = $1->nd_vid;
- if ($2 == tOROP) {
- $1->nd_value = $3;
- $$ = NEW_OP_ASGN_OR(gettable(vid), $1);
- if (is_instance_id(vid)) {
- $$->nd_aid = vid;
- }
- }
- else if ($2 == tANDOP) {
- $1->nd_value = $3;
- $$ = NEW_OP_ASGN_AND(gettable(vid), $1);
- }
- else {
- $$ = $1;
- $$->nd_value = call_op(gettable(vid),$2,1,$3);
- }
- fixpos($$, $3);
- }
- else {
- $$ = 0;
- }
- }
- | primary_value '[' aref_args ']' tOP_ASGN arg
- {
- NODE *tmp, *args = NEW_LIST($6);
-
- $3 = list_append($3, NEW_NIL());
- list_concat(args, $3);
- if ($5 == tOROP) {
- $5 = 0;
- }
- else if ($5 == tANDOP) {
- $5 = 1;
- }
- $$ = NEW_OP_ASGN1($1, $5, args);
- fixpos($$, $1);
- }
- | primary_value '.' tIDENTIFIER tOP_ASGN arg
- {
- if ($4 == tOROP) {
- $4 = 0;
- }
- else if ($4 == tANDOP) {
- $4 = 1;
- }
- $$ = NEW_OP_ASGN2($1, $3, $4, $5);
- fixpos($$, $1);
- }
- | primary_value '.' tCONSTANT tOP_ASGN arg
- {
- if ($4 == tOROP) {
- $4 = 0;
- }
- else if ($4 == tANDOP) {
- $4 = 1;
- }
- $$ = NEW_OP_ASGN2($1, $3, $4, $5);
- fixpos($$, $1);
- }
- | primary_value tCOLON2 tIDENTIFIER tOP_ASGN arg
- {
- if ($4 == tOROP) {
- $4 = 0;
- }
- else if ($4 == tANDOP) {
- $4 = 1;
- }
- $$ = NEW_OP_ASGN2($1, $3, $4, $5);
- fixpos($$, $1);
- }
- | backref tOP_ASGN arg
- {
- rb_backref_error($1);
- $$ = 0;
- }
- | arg tDOT2 arg
- {
- $$ = NEW_DOT2($1, $3);
- }
- | arg tDOT3 arg
- {
- $$ = NEW_DOT3($1, $3);
- }
- | arg '+' arg
- {
- $$ = call_op($1, '+', 1, $3);
- }
- | arg '-' arg
- {
- $$ = call_op($1, '-', 1, $3);
- }
- | arg '*' arg
- {
- $$ = call_op($1, '*', 1, $3);
- }
- | arg '/' arg
- {
- $$ = call_op($1, '/', 1, $3);
- }
- | arg '%' arg
- {
- $$ = call_op($1, '%', 1, $3);
- }
- | arg tPOW arg
- {
- int need_negate = Qfalse;
-
- if (nd_type($1) == NODE_LIT) {
- switch (TYPE($1->nd_lit)) {
- case T_FIXNUM:
- case T_FLOAT:
- case T_BIGNUM:
- if (RTEST(rb_funcall($1->nd_lit,'<',1,INT2FIX(0)))) {
- $1->nd_lit = rb_funcall($1->nd_lit,rb_intern("-@"),0,0);
- need_negate = Qtrue;
- }
- default:
- break;
- }
- }
- $$ = call_op($1, tPOW, 1, $3);
- if (need_negate) {
- $$ = call_op($$, tUMINUS, 0, 0);
- }
- }
- | tUPLUS arg
- {
- if ($2 && nd_type($2) == NODE_LIT) {
- $$ = $2;
- }
- else {
- $$ = call_op($2, tUPLUS, 0, 0);
- }
- }
- | tUMINUS arg
- {
- if ($2 && nd_type($2) == NODE_LIT && FIXNUM_P($2->nd_lit)) {
- long i = FIX2LONG($2->nd_lit);
-
- $2->nd_lit = INT2FIX(-i);
- $$ = $2;
- }
- else {
- $$ = call_op($2, tUMINUS, 0, 0);
- }
- }
- | arg '|' arg
- {
- $$ = call_op($1, '|', 1, $3);
- }
- | arg '^' arg
- {
- $$ = call_op($1, '^', 1, $3);
- }
- | arg '&' arg
- {
- $$ = call_op($1, '&', 1, $3);
- }
- | arg tCMP arg
- {
- $$ = call_op($1, tCMP, 1, $3);
- }
- | arg '>' arg
- {
- $$ = call_op($1, '>', 1, $3);
- }
- | arg tGEQ arg
- {
- $$ = call_op($1, tGEQ, 1, $3);
- }
- | arg '<' arg
- {
- $$ = call_op($1, '<', 1, $3);
- }
- | arg tLEQ arg
- {
- $$ = call_op($1, tLEQ, 1, $3);
- }
- | arg tEQ arg
- {
- $$ = call_op($1, tEQ, 1, $3);
- }
- | arg tEQQ arg
- {
- $$ = call_op($1, tEQQ, 1, $3);
- }
- | arg tNEQ arg
- {
- $$ = NEW_NOT(call_op($1, tEQ, 1, $3));
- }
- | arg tMATCH arg
- {
- $$ = match_gen($1, $3);
- }
- | arg tNMATCH arg
- {
- $$ = NEW_NOT(match_gen($1, $3));
- }
- | '!' arg
- {
- value_expr($2);
- $$ = NEW_NOT(cond($2));
- }
- | '~' arg
- {
- $$ = call_op($2, '~', 0, 0);
- }
- | arg tLSHFT arg
- {
- $$ = call_op($1, tLSHFT, 1, $3);
- }
- | arg tRSHFT arg
- {
- $$ = call_op($1, tRSHFT, 1, $3);
- }
- | arg tANDOP arg
- {
- $$ = logop(NODE_AND, $1, $3);
- }
- | arg tOROP arg
- {
- $$ = logop(NODE_OR, $1, $3);
- }
- | kDEFINED opt_nl {in_defined = 1;} arg
- {
- in_defined = 0;
- $$ = NEW_DEFINED($4);
- }
- | arg '?' arg ':' arg
- {
- $$ = NEW_IF(cond($1), $3, $5);
- fixpos($$, $1);
- }
- | primary
- {
- $$ = $1;
- }
-
-arg_value : arg
- {
- value_expr($1);
- $$ = $1;
- }
-
-aref_args : none
- | command opt_nl
- {
- $$ = NEW_LIST($1);
- }
- | args trailer
- {
- $$ = $1;
- }
- | args ',' tSTAR arg opt_nl
- {
- value_expr($4);
- $$ = arg_concat($1, $4);
- }
- | assocs trailer
- {
- $$ = NEW_LIST(NEW_HASH($1));
- }
- | tSTAR arg opt_nl
- {
- value_expr($2);
- $$ = NEW_RESTARY($2);
- }
-
-paren_args : '(' none ')'
- {
- $$ = $2;
- }
- | '(' call_args opt_nl ')'
- {
- $$ = $2;
- }
- | '(' block_call opt_nl ')'
- {
- $$ = NEW_LIST($2);
- }
- | '(' args ',' block_call opt_nl ')'
- {
- $$ = list_append($2, $4);
- }
-
-opt_paren_args : none
- | paren_args
-
-call_args : command
- {
- $$ = NEW_LIST($1);
- }
- | args opt_block_arg
- {
- $$ = arg_blk_pass($1, $2);
- }
- | args ',' tSTAR arg_value opt_block_arg
- {
- $$ = arg_concat($1, $4);
- $$ = arg_blk_pass($$, $5);
- }
- | assocs opt_block_arg
- {
- $$ = NEW_LIST(NEW_HASH($1));
- $$ = arg_blk_pass($$, $2);
- }
- | assocs ',' tSTAR arg_value opt_block_arg
- {
- $$ = arg_concat(NEW_LIST(NEW_HASH($1)), $4);
- $$ = arg_blk_pass($$, $5);
- }
- | args ',' assocs opt_block_arg
- {
- $$ = list_append($1, NEW_HASH($3));
- $$ = arg_blk_pass($$, $4);
- }
- | args ',' assocs ',' tSTAR arg opt_block_arg
- {
- value_expr($6);
- $$ = arg_concat(list_append($1, NEW_HASH($3)), $6);
- $$ = arg_blk_pass($$, $7);
- }
- | tSTAR arg_value opt_block_arg
- {
- $$ = arg_blk_pass(NEW_RESTARGS($2), $3);
- }
- | block_arg
-
-call_args2 : arg_value ',' args opt_block_arg
- {
- $$ = arg_blk_pass(list_concat(NEW_LIST($1),$3), $4);
- }
- | arg_value ',' block_arg
- {
- $$ = arg_blk_pass($1, $3);
- }
- | arg_value ',' tSTAR arg_value opt_block_arg
- {
- $$ = arg_concat(NEW_LIST($1), $4);
- $$ = arg_blk_pass($$, $5);
- }
- | arg_value ',' args ',' tSTAR arg_value opt_block_arg
- {
- $$ = arg_concat(list_concat($1,$3), $6);
- $$ = arg_blk_pass($$, $7);
- }
- | assocs opt_block_arg
- {
- $$ = NEW_LIST(NEW_HASH($1));
- $$ = arg_blk_pass($$, $2);
- }
- | assocs ',' tSTAR arg_value opt_block_arg
- {
- $$ = arg_concat(NEW_LIST(NEW_HASH($1)), $4);
- $$ = arg_blk_pass($$, $5);
- }
- | arg_value ',' assocs opt_block_arg
- {
- $$ = list_append(NEW_LIST($1), NEW_HASH($3));
- $$ = arg_blk_pass($$, $4);
- }
- | arg_value ',' args ',' assocs opt_block_arg
- {
- $$ = list_append(list_concat(NEW_LIST($1),$3), NEW_HASH($5));
- $$ = arg_blk_pass($$, $6);
- }
- | arg_value ',' assocs ',' tSTAR arg_value opt_block_arg
- {
- $$ = arg_concat(list_append(NEW_LIST($1), NEW_HASH($3)), $6);
- $$ = arg_blk_pass($$, $7);
- }
- | arg_value ',' args ',' assocs ',' tSTAR arg_value opt_block_arg
- {
- $$ = arg_concat(list_append(list_concat(NEW_LIST($1), $3), NEW_HASH($5)), $8);
- $$ = arg_blk_pass($$, $9);
- }
- | tSTAR arg_value opt_block_arg
- {
- $$ = arg_blk_pass(NEW_RESTARGS($2), $3);
- }
- | block_arg
-
-command_args : {
- $<num>$ = cmdarg_stack;
- CMDARG_PUSH(1);
- }
- open_args
- {
- /* CMDARG_POP() */
- cmdarg_stack = $<num>1;
- $$ = $2;
- }
-
-open_args : call_args
- | tLPAREN_ARG {lex_state = EXPR_ENDARG;} ')'
- {
- rb_warning("%s (...) interpreted as method call",
- rb_id2name($<id>1));
- $$ = 0;
- }
- | tLPAREN_ARG call_args2 {lex_state = EXPR_ENDARG;} ')'
- {
- rb_warning("%s (...) interpreted as method call",
- rb_id2name($<id>1));
- $$ = $2;
- }
-
-block_arg : tAMPER arg_value
- {
- $$ = NEW_BLOCK_PASS($2);
- }
-
-opt_block_arg : ',' block_arg
- {
- $$ = $2;
- }
- | none
-
-args : arg_value
- {
- $$ = NEW_LIST($1);
- }
- | args ',' arg_value
- {
- $$ = list_append($1, $3);
- }
-
-mrhs : arg_value
- {
- $$ = $1;
- }
- | mrhs_basic
- {
- $$ = NEW_REXPAND($1);
- }
-
-mrhs_basic : args ',' arg_value
- {
- $$ = list_append($1, $3);
- }
- | args ',' tSTAR arg_value
- {
- $$ = arg_concat($1, $4);
- }
- | tSTAR arg_value
- {
- $$ = $2;
- }
-
-primary : literal
- {
- $$ = NEW_LIT($1);
- }
- | string
- | tXSTRING
- {
- $$ = NEW_XSTR($1);
- }
- | tQWORDS
- | tDXSTRING
- | tDREGEXP
- | var_ref
- | backref
- | tFID
- {
- $$ = NEW_VCALL($1);
- }
- | kBEGIN
- compstmt
- rescue
- opt_else
- ensure
- kEND
- {
- if (!$3 && !$4 && !$5)
- $$ = NEW_BEGIN($2);
- else {
- if ($3) $2 = NEW_RESCUE($2, $3, $4);
- else if ($4) {
- rb_warn("else without rescue is useless");
- $2 = block_append($2, $4);
- }
- if ($5) $2 = NEW_ENSURE($2, $5);
- $$ = $2;
- }
- fixpos($$, $2);
- }
- | tLPAREN_ARG expr {lex_state = EXPR_ENDARG;} ')'
- {
- rb_warning("%s (...) interpreted as grouped expression", rb_id2name($<id>1));
- $$ = $2;
- }
- | tLPAREN compstmt ')'
- {
- $$ = $2;
- }
- | primary_value tCOLON2 tCONSTANT
- {
- $$ = NEW_COLON2($1, $3);
- }
- | tCOLON3 cname
- {
- $$ = NEW_COLON3($2);
- }
- | primary_value '[' aref_args ']'
- {
- $$ = NEW_CALL($1, tAREF, $3);
- }
- | tLBRACK aref_args ']'
- {
- if ($2 == 0) {
- $$ = NEW_ZARRAY(); /* zero length array*/
- }
- else {
- $$ = $2;
- }
- }
- | tLBRACE assoc_list '}'
- {
- $$ = NEW_HASH($2);
- }
- | kRETURN
- {
- if (!compile_for_eval && !in_def && !in_single)
- yyerror("return appeared outside of method");
- $$ = NEW_RETURN(0);
- }
- | kYIELD '(' call_args ')'
- {
- $$ = NEW_YIELD(ret_args($3));
- }
- | kYIELD '(' ')'
- {
- $$ = NEW_YIELD(0);
- }
- | kYIELD
- {
- $$ = NEW_YIELD(0);
- }
- | kDEFINED opt_nl '(' {in_defined = 1;} expr ')'
- {
- in_defined = 0;
- $$ = NEW_DEFINED($5);
- }
- | operation brace_block
- {
- $2->nd_iter = NEW_FCALL($1, 0);
- $$ = $2;
- }
- | method_call
- | method_call brace_block
- {
- if ($1 && nd_type($1) == NODE_BLOCK_PASS) {
- rb_compile_error("both block arg and actual block given");
- }
- $2->nd_iter = $1;
- $$ = $2;
- fixpos($$, $1);
- }
- | kIF expr_value then
- compstmt
- if_tail
- kEND
- {
- $$ = NEW_IF(cond($2), $4, $5);
- fixpos($$, $2);
- }
- | kUNLESS expr_value then
- compstmt
- opt_else
- kEND
- {
- $$ = NEW_UNLESS(cond($2), $4, $5);
- fixpos($$, $2);
- }
- | kWHILE {COND_PUSH(1);} expr_value do {COND_POP();}
- compstmt
- kEND
- {
- $$ = NEW_WHILE(cond($3), $6, 1);
- fixpos($$, $3);
- }
- | kUNTIL {COND_PUSH(1);} expr_value do {COND_POP();}
- compstmt
- kEND
- {
- $$ = NEW_UNTIL(cond($3), $6, 1);
- fixpos($$, $3);
- }
- | kCASE expr_value opt_terms
- case_body
- kEND
- {
- $$ = NEW_CASE($2, $4);
- fixpos($$, $2);
- }
- | kCASE opt_terms case_body kEND
- {
- $$ = $3;
- }
- | kFOR block_var kIN {COND_PUSH(1);} expr_value do {COND_POP();}
- compstmt
- kEND
- {
- $$ = NEW_FOR($2, $5, $8);
- fixpos($$, $2);
- }
- | kCLASS cname superclass
- {
- if (in_def || in_single)
- yyerror("class definition in method body");
- class_nest++;
- local_push(0);
- $<num>$ = ruby_sourceline;
- }
- compstmt
- kEND
- {
- $$ = NEW_CLASS($2, $5, $3);
- nd_set_line($$, $<num>4);
- local_pop();
- class_nest--;
- }
- | kCLASS tLSHFT expr
- {
- $<num>$ = in_def;
- in_def = 0;
- }
- term
- {
- $<num>$ = in_single;
- in_single = 0;
- class_nest++;
- local_push(0);
- }
- compstmt
- kEND
- {
- $$ = NEW_SCLASS($3, $7);
- fixpos($$, $3);
- local_pop();
- class_nest--;
- in_def = $<num>4;
- in_single = $<num>6;
- }
- | kMODULE cname
- {
- if (in_def || in_single)
- yyerror("module definition in method body");
- class_nest++;
- local_push(0);
- $<num>$ = ruby_sourceline;
- }
- compstmt
- kEND
- {
- $$ = NEW_MODULE($2, $4);
- nd_set_line($$, $<num>3);
- local_pop();
- class_nest--;
- }
- | kDEF fname
- {
- if (in_def || in_single)
- yyerror("nested method definition");
- $<id>$ = cur_mid;
- cur_mid = $2;
- in_def++;
- local_push(0);
- }
- f_arglist
- compstmt
- rescue
- opt_else
- ensure
- kEND
- {
- if ($6) $5 = NEW_RESCUE($5, $6, $7);
- else if ($7) {
- rb_warn("else without rescue is useless");
- $5 = block_append($5, $7);
- }
- if ($8) $5 = NEW_ENSURE($5, $8);
-
- /* NOEX_PRIVATE for toplevel */
- $$ = NEW_DEFN($2, $4, $5, class_nest?NOEX_PUBLIC:NOEX_PRIVATE);
- if (is_attrset_id($2)) $$->nd_noex = NOEX_PUBLIC;
- fixpos($$, $4);
- local_pop();
- in_def--;
- cur_mid = $<id>3;
- }
- | kDEF singleton dot_or_colon {lex_state = EXPR_FNAME;} fname
- {
- in_single++;
- local_push(0);
- lex_state = EXPR_END; /* force for args */
- }
- f_arglist
- compstmt
- rescue
- opt_else
- ensure
- kEND
- {
- if ($9) $8 = NEW_RESCUE($8, $9, $10);
- else if ($10) {
- rb_warn("else without rescue is useless");
- $8 = block_append($8, $10);
- }
- if ($11) $8 = NEW_ENSURE($8, $11);
-
- $$ = NEW_DEFS($2, $5, $7, $8);
- fixpos($$, $2);
- local_pop();
- in_single--;
- }
- | kBREAK
- {
- $$ = NEW_BREAK(0);
- }
- | kNEXT
- {
- $$ = NEW_NEXT(0);
- }
- | kREDO
- {
- $$ = NEW_REDO();
- }
- | kRETRY
- {
- $$ = NEW_RETRY();
- }
-
-primary_value : primary
- {
- value_expr($1);
- $$ = $1;
- }
-
-then : term
- | kTHEN
- | term kTHEN
-
-do : term
- | kDO_COND
-
-if_tail : opt_else
- | kELSIF expr_value then
- compstmt
- if_tail
- {
- $$ = NEW_IF(cond($2), $4, $5);
- fixpos($$, $2);
- }
-
-opt_else : none
- | kELSE compstmt
- {
- $$ = $2;
- }
-
-block_var : lhs
- | mlhs
-
-opt_block_var : none
- | '|' /* none */ '|'
- {
- $$ = (NODE*)1;
- }
- | tOROP
- {
- $$ = (NODE*)1;
- }
- | '|' block_var '|'
- {
- $$ = $2;
- }
-
-do_block : kDO_BLOCK
- {
- $<vars>$ = dyna_push();
- }
- opt_block_var
- compstmt
- kEND
- {
- $$ = NEW_ITER($3, 0, $4);
- fixpos($$, $3?$3:$4);
- dyna_pop($<vars>2);
- }
- | tLBRACE_ARG {$<vars>$ = dyna_push();}
- opt_block_var
- compstmt
- '}'
- {
- $$ = NEW_ITER($3, 0, $4);
- fixpos($$, $3?$3:$4);
- dyna_pop($<vars>2);
- }
-
-
-block_call : command do_block
- {
- if ($1 && nd_type($1) == NODE_BLOCK_PASS) {
- rb_compile_error("both block arg and actual block given");
- }
- $2->nd_iter = $1;
- $$ = $2;
- fixpos($$, $2);
- }
- | block_call_value '.' operation2 opt_paren_args
- {
- $$ = new_call($1, $3, $4);
- }
- | block_call_value tCOLON2 operation2 opt_paren_args
- {
- $$ = new_call($1, $3, $4);
- }
-
-block_call_value : block_call
- {
- value_expr($$);
- $$ = $1;
- }
-
-method_call : operation paren_args
- {
- $$ = new_fcall($1, $2);
- fixpos($$, $2);
- }
- | primary_value '.' operation2 opt_paren_args
- {
- $$ = new_call($1, $3, $4);
- fixpos($$, $1);
- }
- | primary_value tCOLON2 operation2 paren_args
- {
- $$ = new_call($1, $3, $4);
- fixpos($$, $1);
- }
- | primary_value tCOLON2 operation3
- {
- $$ = new_call($1, $3, 0);
- }
- | kSUPER paren_args
- {
- if (!compile_for_eval && !in_def &&
- !in_single && !in_defined)
- yyerror("super called outside of method");
- $$ = new_super($2);
- }
- | kSUPER
- {
- if (!compile_for_eval && !in_def &&
- !in_single && !in_defined)
- yyerror("super called outside of method");
- $$ = NEW_ZSUPER();
- }
-
-brace_block : '{'
- {
- $<vars>$ = dyna_push();
- }
- opt_block_var
- compstmt '}'
- {
- $$ = NEW_ITER($3, 0, $4);
- fixpos($$, $4);
- dyna_pop($<vars>2);
- }
- | kDO
- {
- $<vars>$ = dyna_push();
- }
- opt_block_var
- compstmt kEND
- {
- $$ = NEW_ITER($3, 0, $4);
- fixpos($$, $4);
- dyna_pop($<vars>2);
- }
-
-case_body : kWHEN when_args then
- compstmt
- cases
- {
- $$ = NEW_WHEN($2, $4, $5);
- }
-
-when_args : args
- | args ',' tSTAR arg_value
- {
- $$ = list_append($1, NEW_WHEN($4, 0, 0));
- }
- | tSTAR arg_value
- {
- $$ = NEW_LIST(NEW_WHEN($2, 0, 0));
- }
-
-cases : opt_else
- | case_body
-
-exc_list : none
- | args
-
-exc_var : tASSOC lhs
- {
- $$ = $2;
- }
- | none
-
-rescue : kRESCUE exc_list exc_var then
- compstmt
- rescue
- {
- if ($3) {
- $3 = node_assign($3, NEW_GVAR(rb_intern("$!")));
- $5 = block_append($3, $5);
- }
- $$ = NEW_RESBODY($2, $5, $6);
- fixpos($$, $2?$2:$5);
- }
- | none
-
-ensure : none
- | kENSURE compstmt
- {
- if ($2)
- $$ = $2;
- else
- /* place holder */
- $$ = NEW_NIL();
- }
-
-literal : numeric
- | symbol
- {
- $$ = ID2SYM($1);
- }
- | tREGEXP
-
-string : tSTRING
- {
- $$ = NEW_STR($1);
- }
- | tDSTRING
- | string tSTRING
- {
- if (nd_type($1) == NODE_DSTR) {
- list_append($1, NEW_STR($2));
- }
- else {
- rb_str_concat($1->nd_lit, $2);
- }
- $$ = $1;
- }
- | string tDSTRING
- {
- if (nd_type($1) == NODE_STR) {
- $$ = NEW_DSTR($1->nd_lit);
- }
- else {
- $$ = $1;
- }
- $2->nd_head = NEW_STR($2->nd_lit);
- nd_set_type($2, NODE_ARRAY);
- list_concat($$, $2);
- }
-
-symbol : tSYMBEG sym
- {
- lex_state = EXPR_END;
- $$ = $2;
- }
-
-sym : fname
- | tIVAR
- | tGVAR
- | tCVAR
-
-numeric : tINTEGER
- | tFLOAT
-
-variable : tIDENTIFIER
- | tIVAR
- | tGVAR
- | tCONSTANT
- | tCVAR
- | kNIL {$$ = kNIL;}
- | kSELF {$$ = kSELF;}
- | kTRUE {$$ = kTRUE;}
- | kFALSE {$$ = kFALSE;}
- | k__FILE__ {$$ = k__FILE__;}
- | k__LINE__ {$$ = k__LINE__;}
-
-var_ref : variable
- {
- $$ = gettable($1);
- }
-
-var_lhs : variable
- {
- $$ = assignable($1, 0);
- }
-
-backref : tNTH_REF
- | tBACK_REF
-
-superclass : term
- {
- $$ = 0;
- }
- | '<'
- {
- lex_state = EXPR_BEG;
- }
- expr_value term
- {
- $$ = $3;
- }
- | error term {yyerrok; $$ = 0;}
-
-f_arglist : '(' f_args opt_nl ')'
- {
- $$ = $2;
- lex_state = EXPR_BEG;
- }
- | f_args term
- {
- $$ = $1;
- }
-
-f_args : f_arg ',' f_optarg ',' f_rest_arg opt_f_block_arg
- {
- $$ = block_append(NEW_ARGS($1, $3, $5), $6);
- }
- | f_arg ',' f_optarg opt_f_block_arg
- {
- $$ = block_append(NEW_ARGS($1, $3, -1), $4);
- }
- | f_arg ',' f_rest_arg opt_f_block_arg
- {
- $$ = block_append(NEW_ARGS($1, 0, $3), $4);
- }
- | f_arg opt_f_block_arg
- {
- $$ = block_append(NEW_ARGS($1, 0, -1), $2);
- }
- | f_optarg ',' f_rest_arg opt_f_block_arg
- {
- $$ = block_append(NEW_ARGS(0, $1, $3), $4);
- }
- | f_optarg opt_f_block_arg
- {
- $$ = block_append(NEW_ARGS(0, $1, -1), $2);
- }
- | f_rest_arg opt_f_block_arg
- {
- $$ = block_append(NEW_ARGS(0, 0, $1), $2);
- }
- | f_block_arg
- {
- $$ = block_append(NEW_ARGS(0, 0, -1), $1);
- }
- | /* none */
- {
- $$ = NEW_ARGS(0, 0, -1);
- }
-
-f_norm_arg : tCONSTANT
- {
- yyerror("formal argument cannot be a constant");
- }
- | tIVAR
- {
- yyerror("formal argument cannot be an instance variable");
- }
- | tGVAR
- {
- yyerror("formal argument cannot be a global variable");
- }
- | tCVAR
- {
- yyerror("formal argument cannot be a class variable");
- }
- | tIDENTIFIER
- {
- if (!is_local_id($1))
- yyerror("formal argument must be local variable");
- else if (local_id($1))
- yyerror("duplicate argument name");
- local_cnt($1);
- $$ = 1;
- }
-
-f_arg : f_norm_arg
- | f_arg ',' f_norm_arg
- {
- $$ += 1;
- }
-
-f_opt : tIDENTIFIER '=' arg_value
- {
- if (!is_local_id($1))
- yyerror("formal argument must be local variable");
- else if (local_id($1))
- yyerror("duplicate optional argument name");
- $$ = assignable($1, $3);
- }
-
-f_optarg : f_opt
- {
- $$ = NEW_BLOCK($1);
- $$->nd_end = $$;
- }
- | f_optarg ',' f_opt
- {
- $$ = block_append($1, $3);
- }
-
-f_rest_arg : tSTAR tIDENTIFIER
- {
- if (!is_local_id($2))
- yyerror("rest argument must be local variable");
- else if (local_id($2))
- yyerror("duplicate rest argument name");
- $$ = local_cnt($2);
- }
- | tSTAR
- {
- $$ = -2;
- }
-
-f_block_arg : tAMPER tIDENTIFIER
- {
- if (!is_local_id($2))
- yyerror("block argument must be local variable");
- else if (local_id($2))
- yyerror("duplicate block argument name");
- $$ = NEW_BLOCK_ARG($2);
- }
-
-opt_f_block_arg : ',' f_block_arg
- {
- $$ = $2;
- }
- | none
-
-singleton : var_ref
- {
- if (nd_type($1) == NODE_SELF) {
- $$ = NEW_SELF();
- }
- else {
- $$ = $1;
- value_expr($$);
- }
- }
- | '(' {lex_state = EXPR_BEG;} expr opt_nl ')'
- {
- switch (nd_type($3)) {
- case NODE_STR:
- case NODE_DSTR:
- case NODE_XSTR:
- case NODE_DXSTR:
- case NODE_DREGX:
- case NODE_LIT:
- case NODE_ARRAY:
- case NODE_ZARRAY:
- yyerror("can't define single method for literals.");
- default:
- value_expr($3);
- break;
- }
- $$ = $3;
- }
-
-assoc_list : none
- | assocs trailer
- {
- $$ = $1;
- }
- | args trailer
- {
- if ($1->nd_alen%2 != 0) {
- yyerror("odd number list for Hash");
- }
- $$ = $1;
- }
-
-assocs : assoc
- | assocs ',' assoc
- {
- $$ = list_concat($1, $3);
- }
-
-assoc : arg_value tASSOC arg_value
- {
- $$ = list_append(NEW_LIST($1), $3);
- }
-
-operation : tIDENTIFIER
- | tCONSTANT
- | tFID
-
-operation2 : tIDENTIFIER
- | tCONSTANT
- | tFID
- | op
-
-operation3 : tIDENTIFIER
- | tFID
- | op
-
-dot_or_colon : '.'
- | tCOLON2
-
-opt_terms : /* none */
- | terms
-
-opt_nl : /* none */
- | '\n'
-
-trailer : /* none */
- | '\n'
- | ','
-
-term : ';' {yyerrok;}
- | '\n'
-
-terms : term
- | terms ';' {yyerrok;}
-
-none : /* none */
- {
- $$ = 0;
- }
-%%
-#include "regex.h"
-#include "util.h"
-
-/* We remove any previous definition of `SIGN_EXTEND_CHAR',
- since ours (we hope) works properly with all combinations of
- machines, compilers, `char' and `unsigned char' argument types.
- (Per Bothner suggested the basic approach.) */
-#undef SIGN_EXTEND_CHAR
-#if __STDC__
-# define SIGN_EXTEND_CHAR(c) ((signed char)(c))
-#else /* not __STDC__ */
-/* As in Harbison and Steele. */
-# define SIGN_EXTEND_CHAR(c) ((((unsigned char)(c)) ^ 128) - 128)
-#endif
-#define is_identchar(c) (SIGN_EXTEND_CHAR(c)!=-1&&(ISALNUM(c) || (c) == '_' || ismbchar(c)))
-
-static char *tokenbuf = NULL;
-static int tokidx, toksiz = 0;
-
-static NODE *str_extend _((NODE*,int,int));
-
-#define LEAVE_BS 1
-
-static VALUE (*lex_gets)(); /* gets function */
-static VALUE lex_input; /* non-nil if File */
-static VALUE lex_lastline; /* gc protect */
-static char *lex_pbeg;
-static char *lex_p;
-static char *lex_pend;
-
-static int
-yyerror(msg)
- char *msg;
-{
- char *p, *pe, *buf;
- int len, i;
-
- rb_compile_error("%s", msg);
- p = lex_p;
- while (lex_pbeg <= p) {
- if (*p == '\n') break;
- p--;
- }
- p++;
-
- pe = lex_p;
- while (pe < lex_pend) {
- if (*pe == '\n') break;
- pe++;
- }
-
- len = pe - p;
- if (len > 4) {
- buf = ALLOCA_N(char, len+2);
- MEMCPY(buf, p, char, len);
- buf[len] = '\0';
- rb_compile_error_append("%s", buf);
-
- i = lex_p - p;
- p = buf; pe = p + len;
-
- while (p < pe) {
- if (*p != '\t') *p = ' ';
- p++;
- }
- buf[i] = '^';
- buf[i+1] = '\0';
- rb_compile_error_append("%s", buf);
- }
-
- return 0;
-}
-
-static int heredoc_end;
-static int command_start = Qtrue;
-
-int ruby_in_compile = 0;
-int ruby__end__seen;
-
-static VALUE ruby_debug_lines;
-
-static NODE*
-yycompile(f, line)
- char *f;
- int line;
-{
- int n;
- NODE *node = 0;
-
- if (!compile_for_eval && rb_safe_level() == 0 &&
- rb_const_defined(rb_cObject, rb_intern("SCRIPT_LINES__"))) {
- VALUE hash, fname;
-
- hash = rb_const_get(rb_cObject, rb_intern("SCRIPT_LINES__"));
- if (TYPE(hash) == T_HASH) {
- fname = rb_str_new2(f);
- ruby_debug_lines = rb_hash_aref(hash, fname);
- if (NIL_P(ruby_debug_lines)) {
- ruby_debug_lines = rb_ary_new();
- rb_hash_aset(hash, fname, ruby_debug_lines);
- }
- }
- if (line > 1) {
- VALUE str = rb_str_new(0,0);
- while (line > 1) {
- rb_ary_push(ruby_debug_lines, str);
- line--;
- }
- }
- }
-
- ruby__end__seen = 0;
- ruby_eval_tree = 0;
- heredoc_end = 0;
- ruby_sourcefile = rb_source_filename(f);
- ruby_in_compile = 1;
- n = yyparse();
- ruby_debug_lines = 0;
- compile_for_eval = 0;
- ruby_in_compile = 0;
- cond_stack = 0;
- cmdarg_stack = 0;
- command_start = 1;
- class_nest = 0;
- in_single = 0;
- in_def = 0;
- cur_mid = 0;
-
- if (n == 0) node = ruby_eval_tree;
- return node;
-}
-
-static int lex_gets_ptr;
-
-static VALUE
-lex_get_str(s)
- VALUE s;
-{
- char *beg, *end, *pend;
-
- beg = RSTRING(s)->ptr;
- if (lex_gets_ptr) {
- if (RSTRING(s)->len == lex_gets_ptr) return Qnil;
- beg += lex_gets_ptr;
- }
- pend = RSTRING(s)->ptr + RSTRING(s)->len;
- end = beg;
- while (end < pend) {
- if (*end++ == '\n') break;
- }
- lex_gets_ptr = end - RSTRING(s)->ptr;
- return rb_str_new(beg, end - beg);
-}
-
-static VALUE
-lex_getline()
-{
- VALUE line = (*lex_gets)(lex_input);
- if (ruby_debug_lines && !NIL_P(line)) {
- rb_ary_push(ruby_debug_lines, line);
- }
- return line;
-}
-
-NODE*
-rb_compile_string(f, s, line)
- const char *f;
- VALUE s;
- int line;
-{
- lex_gets = lex_get_str;
- lex_gets_ptr = 0;
- lex_input = s;
- lex_pbeg = lex_p = lex_pend = 0;
- ruby_sourceline = line - 1;
- compile_for_eval = ruby_in_eval;
-
- return yycompile(f, line);
-}
-
-NODE*
-rb_compile_cstr(f, s, len, line)
- const char *f, *s;
- int len, line;
-{
- return rb_compile_string(f, rb_str_new(s, len), line);
-}
-
-NODE*
-rb_compile_file(f, file, start)
- const char *f;
- VALUE file;
- int start;
-{
- lex_gets = rb_io_gets;
- lex_input = file;
- lex_pbeg = lex_p = lex_pend = 0;
- ruby_sourceline = start - 1;
-
- return yycompile(f, start);
-}
-
-static inline int
-nextc()
-{
- int c;
-
- if (lex_p == lex_pend) {
- if (lex_input) {
- VALUE v = lex_getline();
-
- if (NIL_P(v)) return -1;
- if (heredoc_end > 0) {
- ruby_sourceline = heredoc_end;
- heredoc_end = 0;
- }
- ruby_sourceline++;
- lex_pbeg = lex_p = RSTRING(v)->ptr;
- lex_pend = lex_p + RSTRING(v)->len;
- if (strncmp(lex_pbeg, "__END__", 7) == 0 &&
- (RSTRING(v)->len == 7 || lex_pbeg[7] == '\n' || lex_pbeg[7] == '\r')) {
- ruby__end__seen = 1;
- lex_lastline = 0;
- return -1;
- }
- lex_lastline = v;
- }
- else {
- lex_lastline = 0;
- return -1;
- }
- }
- c = (unsigned char)*lex_p++;
- if (c == '\r' && lex_p <= lex_pend && *lex_p == '\n') {
- lex_p++;
- c = '\n';
- }
-
- return c;
-}
-
-static void
-pushback(c)
- int c;
-{
- if (c == -1) return;
- lex_p--;
-}
-
-#define peek(c) (lex_p != lex_pend && (c) == *lex_p)
-
-#define tokfix() (tokenbuf[tokidx]='\0')
-#define tok() tokenbuf
-#define toklen() tokidx
-#define toklast() (tokidx>0?tokenbuf[tokidx-1]:0)
-
-static char*
-newtok()
-{
- tokidx = 0;
- if (!tokenbuf) {
- toksiz = 60;
- tokenbuf = ALLOC_N(char, 60);
- }
- if (toksiz > 4096) {
- toksiz = 60;
- REALLOC_N(tokenbuf, char, 60);
- }
- return tokenbuf;
-}
-
-static void
-tokadd(c)
- char c;
-{
- tokenbuf[tokidx++] = c;
- if (tokidx >= toksiz) {
- toksiz *= 2;
- REALLOC_N(tokenbuf, char, toksiz);
- }
-}
-
-static int
-read_escape()
-{
- int c;
-
- switch (c = nextc()) {
- case '\\': /* Backslash */
- return c;
-
- case 'n': /* newline */
- return '\n';
-
- case 't': /* horizontal tab */
- return '\t';
-
- case 'r': /* carriage-return */
- return '\r';
-
- case 'f': /* form-feed */
- return '\f';
-
- case 'v': /* vertical tab */
- return '\13';
-
- case 'a': /* alarm(bell) */
- return '\007';
-
- case 'e': /* escape */
- return 033;
-
- case '0': case '1': case '2': case '3': /* octal constant */
- case '4': case '5': case '6': case '7':
- {
- int numlen;
-
- pushback(c);
- c = scan_oct(lex_p, 3, &numlen);
- lex_p += numlen;
- }
- return c;
-
- case 'x': /* hex constant */
- {
- int numlen;
-
- c = scan_hex(lex_p, 2, &numlen);
- lex_p += numlen;
- }
- return c;
-
- case 'b': /* backspace */
- return '\010';
-
- case 's': /* space */
- return ' ';
-
- case 'M':
- if ((c = nextc()) != '-') {
- yyerror("Invalid escape character syntax");
- pushback(c);
- return '\0';
- }
- if ((c = nextc()) == '\\') {
- return read_escape() | 0x80;
- }
- else if (c == -1) goto eof;
- else {
- return ((c & 0xff) | 0x80);
- }
-
- case 'C':
- if ((c = nextc()) != '-') {
- yyerror("Invalid escape character syntax");
- pushback(c);
- return '\0';
- }
- case 'c':
- if ((c = nextc())== '\\') {
- c = read_escape();
- }
- else if (c == '?')
- return 0177;
- else if (c == -1) goto eof;
- return c & 0x9f;
-
- eof:
- case -1:
- yyerror("Invalid escape character syntax");
- return '\0';
-
- default:
- return c;
- }
-}
-
-static int
-tokadd_escape(term)
- int term;
-{
- int c;
-
- switch (c = nextc()) {
- case '\n':
- return 0; /* just ignore */
-
- case '0': case '1': case '2': case '3': /* octal constant */
- case '4': case '5': case '6': case '7':
- {
- int i;
-
- tokadd('\\');
- tokadd(c);
- for (i=0; i<2; i++) {
- c = nextc();
- if (c == -1) goto eof;
- if (c < '0' || '7' < c) {
- pushback(c);
- break;
- }
- tokadd(c);
- }
- }
- return 0;
-
- case 'x': /* hex constant */
- {
- int numlen;
-
- tokadd('\\');
- tokadd(c);
- scan_hex(lex_p, 2, &numlen);
- while (numlen--)
- tokadd(nextc());
- }
- return 0;
-
- case 'M':
- if ((c = nextc()) != '-') {
- yyerror("Invalid escape character syntax");
- pushback(c);
- return 0;
- }
- tokadd('\\'); tokadd('M'); tokadd('-');
- goto escaped;
-
- case 'C':
- if ((c = nextc()) != '-') {
- yyerror("Invalid escape character syntax");
- pushback(c);
- return 0;
- }
- tokadd('\\'); tokadd('C'); tokadd('-');
- goto escaped;
-
- case 'c':
- tokadd('\\'); tokadd('c');
- escaped:
- if ((c = nextc()) == '\\') {
- return tokadd_escape(term);
- }
- else if (c == -1) goto eof;
- tokadd(c);
- return 0;
-
- eof:
- case -1:
- yyerror("Invalid escape character syntax");
- return -1;
-
- default:
- if (c != '/' || c != term)
- tokadd('\\');
- tokadd(c);
- }
- return 0;
-}
-
-static int
-parse_regx(term, paren)
- int term, paren;
-{
- register int c;
- char kcode = 0;
- int once = 0;
- int nest = 0;
- int options = 0;
- int re_start = ruby_sourceline;
- NODE *list = 0;
-
- newtok();
- while ((c = nextc()) != -1) {
- if (c == term && nest == 0) {
- goto regx_end;
- }
-
- switch (c) {
- case '#':
- list = str_extend(list, term, paren);
- if (list == (NODE*)-1) goto unterminated;
- continue;
-
- case '\\':
- if (tokadd_escape(term) < 0)
- return 0;
- continue;
-
- case -1:
- goto unterminated;
-
- default:
- if (paren) {
- if (c == paren) nest++;
- if (c == term) nest--;
- }
- if (ismbchar(c)) {
- int i, len = mbclen(c)-1;
-
- for (i = 0; i < len; i++) {
- tokadd(c);
- c = nextc();
- }
- }
- break;
-
- regx_end:
- for (;;) {
- switch (c = nextc()) {
- case 'i':
- options |= RE_OPTION_IGNORECASE;
- break;
- case 'x':
- options |= RE_OPTION_EXTENDED;
- break;
- case 'p': /* /p is obsolete */
- rb_warn("/p option is obsolete; use /m\n\tnote: /m does not change ^, $ behavior");
- options |= RE_OPTION_POSIXLINE;
- break;
- case 'm':
- options |= RE_OPTION_MULTILINE;
- break;
- case 'o':
- once = 1;
- break;
- case 'n':
- kcode = 16;
- break;
- case 'e':
- kcode = 32;
- break;
- case 's':
- kcode = 48;
- break;
- case 'u':
- kcode = 64;
- break;
- default:
- pushback(c);
- goto end_options;
- }
- }
-
- end_options:
- tokfix();
- lex_state = EXPR_END;
- if (list) {
- nd_set_line(list, re_start);
- if (toklen() > 0) {
- VALUE ss = rb_str_new(tok(), toklen());
- list_append(list, NEW_STR(ss));
- }
- nd_set_type(list, once?NODE_DREGX_ONCE:NODE_DREGX);
- list->nd_cflag = options | kcode;
- yylval.node = list;
- return tDREGEXP;
- }
- else {
- yylval.val = rb_reg_new(tok(), toklen(), options | kcode);
- return tREGEXP;
- }
- }
- tokadd(c);
- }
- unterminated:
- ruby_sourceline = re_start;
- rb_compile_error("unterminated regexp meets end of file");
- return 0;
-}
-
-static int parse_qstring _((int,int));
-
-static int
-parse_string(func, term, paren)
- int func, term, paren;
-{
- int c;
- NODE *list = 0;
- int strstart;
- int nest = 0;
-
- if (func == '\'') {
- return parse_qstring(term, paren);
- }
- if (func == 0) { /* read 1 line for heredoc */
- /* -1 for chomp */
- yylval.val = rb_str_new(lex_pbeg, lex_pend - lex_pbeg - 1);
- lex_p = lex_pend;
- return tSTRING;
- }
- strstart = ruby_sourceline;
- newtok();
- while ((c = nextc()) != term || nest > 0) {
- if (c == -1) {
- unterm_str:
- ruby_sourceline = strstart;
- rb_compile_error("unterminated string meets end of file");
- return 0;
- }
- if (paren) {
- if (c == paren) nest++;
- if (c == term && nest-- == 0) break;
- }
- if (ismbchar(c)) {
- int i, len = mbclen(c)-1;
-
- for (i = 0; i < len; i++) {
- tokadd(c);
- c = nextc();
- }
- }
- else if (c == '#') {
- list = str_extend(list, term, paren);
- if (list == (NODE*)-1) goto unterm_str;
- continue;
- }
- else if (c == '\\') {
- c = nextc();
- if (c == '\n')
- continue;
- if (c == term) {
- tokadd(c);
- }
- else {
- pushback(c);
- if (func != '"') tokadd('\\');
- tokadd(read_escape());
- }
- continue;
- }
- tokadd(c);
- }
-
- tokfix();
- lex_state = EXPR_END;
-
- if (list) {
- nd_set_line(list, strstart);
- if (toklen() > 0) {
- VALUE ss = rb_str_new(tok(), toklen());
- list_append(list, NEW_STR(ss));
- }
- yylval.node = list;
- if (func == '`') {
- nd_set_type(list, NODE_DXSTR);
- return tDXSTRING;
- }
- else {
- return tDSTRING;
- }
- }
- else {
- yylval.val = rb_str_new(tok(), toklen());
- return (func == '`') ? tXSTRING : tSTRING;
- }
-}
-
-static int
-parse_qstring(term, paren)
- int term, paren;
-{
- int strstart;
- int c;
- int nest = 0;
-
- strstart = ruby_sourceline;
- newtok();
- while ((c = nextc()) != term || nest > 0) {
- if (c == -1) {
- ruby_sourceline = strstart;
- rb_compile_error("unterminated string meets end of file");
- return 0;
- }
- if (paren) {
- if (c == paren) nest++;
- if (c == term && nest-- == 0) break;
- }
- if (ismbchar(c)) {
- int i, len = mbclen(c)-1;
-
- for (i = 0; i < len; i++) {
- tokadd(c);
- c = nextc();
- }
- }
- else if (c == '\\') {
- c = nextc();
- switch (c) {
- case '\n':
- continue;
-
- case '\\':
- c = '\\';
- break;
-
- default:
- /* fall through */
- if (c == term || (paren && c == paren)) {
- tokadd(c);
- continue;
- }
- tokadd('\\');
- }
- }
- tokadd(c);
- }
-
- tokfix();
- yylval.val = rb_str_new(tok(), toklen());
- lex_state = EXPR_END;
- return tSTRING;
-}
-
-static int
-parse_quotedwords(term, paren)
- int term, paren;
-{
- NODE *qwords = 0;
- int strstart;
- int c;
- int nest = 0;
-
- strstart = ruby_sourceline;
- newtok();
-
- while (c = nextc(),ISSPACE(c))
- ; /* skip preceding spaces */
- pushback(c);
- while ((c = nextc()) != term || nest > 0) {
- if (c == -1) {
- ruby_sourceline = strstart;
- rb_compile_error("unterminated string meets end of file");
- return 0;
- }
- if (paren) {
- if (c == paren) nest++;
- if (c == term && nest-- == 0) break;
- }
- if (ismbchar(c)) {
- int i, len = mbclen(c)-1;
-
- for (i = 0; i < len; i++) {
- tokadd(c);
- c = nextc();
- }
- }
- else if (c == '\\') {
- c = nextc();
- switch (c) {
- case '\n':
- continue;
- case '\\':
- c = '\\';
- break;
- default:
- if (c == term || (paren && c == paren)) {
- tokadd(c);
- continue;
- }
- if (!ISSPACE(c))
- tokadd('\\');
- break;
- }
- }
- else if (ISSPACE(c)) {
- NODE *str;
-
- tokfix();
- str = NEW_STR(rb_str_new(tok(), toklen()));
- newtok();
- if (!qwords) qwords = NEW_LIST(str);
- else list_append(qwords, str);
- while (c = nextc(),ISSPACE(c))
- ; /* skip continuous spaces */
- pushback(c);
- continue;
- }
- tokadd(c);
- }
-
- tokfix();
- if (toklen() > 0) {
- NODE *str;
-
- str = NEW_STR(rb_str_new(tok(), toklen()));
- if (!qwords) qwords = NEW_LIST(str);
- else list_append(qwords, str);
- }
- if (!qwords) qwords = NEW_ZARRAY();
- yylval.node = qwords;
- lex_state = EXPR_END;
- return tQWORDS;
-}
-
-static int
-here_document(term, indent)
- char term;
- int indent;
-{
- int c;
- char *eos, *p;
- int len;
- VALUE str;
- volatile VALUE line = 0;
- VALUE lastline_save;
- int offset_save;
- NODE *list = 0;
- int linesave = ruby_sourceline;
-
- newtok();
- switch (term) {
- case '\'':
- case '"':
- case '`':
- while ((c = nextc()) != term) {
- tokadd(c);
- }
- if (term == '\'') term = 0;
- break;
-
- default:
- c = term;
- term = '"';
- if (!is_identchar(c)) {
- rb_warn("use of bare << to mean <<\"\" is deprecated");
- break;
- }
- while (is_identchar(c)) {
- tokadd(c);
- c = nextc();
- }
- pushback(c);
- break;
- }
- tokfix();
- lastline_save = lex_lastline;
- offset_save = lex_p - lex_pbeg;
- eos = strdup(tok());
- len = strlen(eos);
-
- str = rb_str_new(0,0);
- for (;;) {
- lex_lastline = line = lex_getline();
- if (NIL_P(line)) {
- error:
- ruby_sourceline = linesave;
- rb_compile_error("can't find string \"%s\" anywhere before EOF", eos);
- free(eos);
- return 0;
- }
- ruby_sourceline++;
- p = RSTRING(line)->ptr;
- if (indent) {
- while (*p && (*p == ' ' || *p == '\t')) {
- p++;
- }
- }
- if (strncmp(eos, p, len) == 0) {
- if (p[len] == '\n' || p[len] == '\r')
- break;
- if (len == RSTRING(line)->len)
- break;
- }
-
- lex_pbeg = lex_p = RSTRING(line)->ptr;
- lex_pend = lex_p + RSTRING(line)->len;
- retry:
- switch (parse_string(term, '\n', 0)) {
- case tSTRING:
- case tXSTRING:
- rb_str_cat2(yylval.val, "\n");
- if (!list) {
- rb_str_append(str, yylval.val);
- }
- else {
- list_append(list, NEW_STR(yylval.val));
- }
- break;
- case tDSTRING:
- if (!list) list = NEW_DSTR(str);
- /* fall through */
- case tDXSTRING:
- if (!list) list = NEW_DXSTR(str);
-
- list_append(yylval.node, NEW_STR(rb_str_new2("\n")));
- nd_set_type(yylval.node, NODE_STR);
- yylval.node = NEW_LIST(yylval.node);
- yylval.node->nd_next = yylval.node->nd_head->nd_next;
- list_concat(list, yylval.node);
- break;
-
- case 0:
- goto error;
- }
- if (lex_p != lex_pend) {
- goto retry;
- }
- }
- free(eos);
- lex_lastline = lastline_save;
- lex_pbeg = RSTRING(lex_lastline)->ptr;
- lex_pend = lex_pbeg + RSTRING(lex_lastline)->len;
- lex_p = lex_pbeg + offset_save;
-
- lex_state = EXPR_END;
- heredoc_end = ruby_sourceline;
- ruby_sourceline = linesave;
-
- if (list) {
- nd_set_line(list, linesave+1);
- yylval.node = list;
- }
- switch (term) {
- case '\0':
- case '\'':
- case '"':
- if (list) return tDSTRING;
- yylval.val = str;
- return tSTRING;
- case '`':
- if (list) return tDXSTRING;
- yylval.val = str;
- return tXSTRING;
- }
- return 0;
-}
-
-#include "lex.c"
-
-static void
-arg_ambiguous()
-{
- rb_warning("ambiguous first argument; make sure");
-}
-
-#if !defined(strtod) && !defined(HAVE_STDLIB_H)
-double strtod ();
-#endif
-
-#define IS_ARG() (lex_state == EXPR_ARG || lex_state == EXPR_CMDARG)
-
-static int
-yylex()
-{
- static ID last_id = 0;
- register int c;
- int space_seen = 0;
- int cmd_state;
-
- cmd_state = command_start;
- command_start = Qfalse;
- retry:
- switch (c = nextc()) {
- case '\0': /* NUL */
- case '\004': /* ^D */
- case '\032': /* ^Z */
- case -1: /* end of script. */
- return 0;
-
- /* white spaces */
- case ' ': case '\t': case '\f': case '\r':
- case '\13': /* '\v' */
- space_seen++;
- goto retry;
-
- case '#': /* it's a comment */
- while ((c = nextc()) != '\n') {
- if (c == -1)
- return 0;
- }
- /* fall through */
- case '\n':
- switch (lex_state) {
- case EXPR_BEG:
- case EXPR_FNAME:
- case EXPR_DOT:
- case EXPR_CLASS:
- goto retry;
- default:
- break;
- }
- command_start = Qtrue;
- lex_state = EXPR_BEG;
- return '\n';
-
- case '*':
- if ((c = nextc()) == '*') {
- if (nextc() == '=') {
- lex_state = EXPR_BEG;
- yylval.id = tPOW;
- return tOP_ASGN;
- }
- pushback(c);
- c = tPOW;
- }
- else {
- if (c == '=') {
- yylval.id = '*';
- lex_state = EXPR_BEG;
- return tOP_ASGN;
- }
- pushback(c);
- if (IS_ARG() && space_seen && !ISSPACE(c)){
- rb_warning("`*' interpreted as argument prefix");
- c = tSTAR;
- }
- else if (lex_state == EXPR_BEG || lex_state == EXPR_MID) {
- c = tSTAR;
- }
- else {
- c = '*';
- }
- }
- switch (lex_state) {
- case EXPR_FNAME: case EXPR_DOT:
- lex_state = EXPR_ARG; break;
- default:
- lex_state = EXPR_BEG; break;
- }
- return c;
-
- case '!':
- lex_state = EXPR_BEG;
- if ((c = nextc()) == '=') {
- return tNEQ;
- }
- if (c == '~') {
- return tNMATCH;
- }
- pushback(c);
- return '!';
-
- case '=':
- if (lex_p == lex_pbeg + 1) {
- /* skip embedded rd document */
- if (strncmp(lex_p, "begin", 5) == 0 && ISSPACE(lex_p[5])) {
- for (;;) {
- lex_p = lex_pend;
- c = nextc();
- if (c == -1) {
- rb_compile_error("embedded document meets end of file");
- return 0;
- }
- if (c != '=') continue;
- if (strncmp(lex_p, "end", 3) == 0 &&
- (lex_p + 3 == lex_pend || ISSPACE(lex_p[3]))) {
- break;
- }
- }
- lex_p = lex_pend;
- goto retry;
- }
- }
-
- switch (lex_state) {
- case EXPR_FNAME: case EXPR_DOT:
- lex_state = EXPR_ARG; break;
- default:
- lex_state = EXPR_BEG; break;
- }
- if ((c = nextc()) == '=') {
- if ((c = nextc()) == '=') {
- return tEQQ;
- }
- pushback(c);
- return tEQ;
- }
- if (c == '~') {
- return tMATCH;
- }
- else if (c == '>') {
- return tASSOC;
- }
- pushback(c);
- return '=';
-
- case '<':
- c = nextc();
- if (c == '<' &&
- lex_state != EXPR_END &&
- lex_state != EXPR_ENDARG
- && lex_state != EXPR_CLASS &&
- (!IS_ARG() || space_seen)) {
- int c2 = nextc();
- int indent = 0;
- if (c2 == '-') {
- indent = 1;
- c2 = nextc();
- }
- if (!ISSPACE(c2) && (strchr("\"'`", c2) || is_identchar(c2))) {
- return here_document(c2, indent);
- }
- pushback(c2);
- }
- switch (lex_state) {
- case EXPR_FNAME: case EXPR_DOT:
- lex_state = EXPR_ARG; break;
- default:
- lex_state = EXPR_BEG; break;
- }
- if (c == '=') {
- if ((c = nextc()) == '>') {
- return tCMP;
- }
- pushback(c);
- return tLEQ;
- }
- if (c == '<') {
- if (nextc() == '=') {
- lex_state = EXPR_BEG;
- yylval.id = tLSHFT;
- return tOP_ASGN;
- }
- pushback(c);
- return tLSHFT;
- }
- pushback(c);
- return '<';
-
- case '>':
- switch (lex_state) {
- case EXPR_FNAME: case EXPR_DOT:
- lex_state = EXPR_ARG; break;
- default:
- lex_state = EXPR_BEG; break;
- }
- if ((c = nextc()) == '=') {
- return tGEQ;
- }
- if (c == '>') {
- if ((c = nextc()) == '=') {
- lex_state = EXPR_BEG;
- yylval.id = tRSHFT;
- return tOP_ASGN;
- }
- pushback(c);
- return tRSHFT;
- }
- pushback(c);
- return '>';
-
- case '"':
- return parse_string(c,c,c);
- case '`':
- if (lex_state == EXPR_FNAME) return c;
- if (lex_state == EXPR_DOT) return c;
- return parse_string(c,c,c);
-
- case '\'':
- return parse_qstring(c,0);
-
- case '?':
- if (lex_state == EXPR_END || lex_state == EXPR_ENDARG) {
- lex_state = EXPR_BEG;
- return '?';
- }
- c = nextc();
- if (c == -1) {
- rb_compile_error("incomplete character syntax");
- return 0;
- }
- if (IS_ARG() && ISSPACE(c)){
- pushback(c);
- lex_state = EXPR_BEG;
- return '?';
- }
- if (c == '\\') {
- c = read_escape();
- }
- c &= 0xff;
- yylval.val = INT2FIX(c);
- lex_state = EXPR_END;
- return tINTEGER;
-
- case '&':
- if ((c = nextc()) == '&') {
- lex_state = EXPR_BEG;
- if ((c = nextc()) == '=') {
- yylval.id = tANDOP;
- return tOP_ASGN;
- }
- pushback(c);
- return tANDOP;
- }
- else if (c == '=') {
- yylval.id = '&';
- lex_state = EXPR_BEG;
- return tOP_ASGN;
- }
- pushback(c);
- if (IS_ARG() && space_seen && !ISSPACE(c)){
- rb_warning("`&' interpeted as argument prefix");
- c = tAMPER;
- }
- else if (lex_state == EXPR_BEG || lex_state == EXPR_MID) {
- c = tAMPER;
- }
- else {
- c = '&';
- }
- switch (lex_state) {
- case EXPR_FNAME: case EXPR_DOT:
- lex_state = EXPR_ARG; break;
- default:
- lex_state = EXPR_BEG;
- }
- return c;
-
- case '|':
- if ((c = nextc()) == '|') {
- lex_state = EXPR_BEG;
- if ((c = nextc()) == '=') {
- yylval.id = tOROP;
- return tOP_ASGN;
- }
- pushback(c);
- return tOROP;
- }
- if (c == '=') {
- lex_state = EXPR_BEG;
- yylval.id = '|';
- return tOP_ASGN;
- }
- if (lex_state == EXPR_FNAME || lex_state == EXPR_DOT) {
- lex_state = EXPR_ARG;
- }
- else {
- lex_state = EXPR_BEG;
- }
- pushback(c);
- return '|';
-
- case '+':
- c = nextc();
- if (lex_state == EXPR_FNAME || lex_state == EXPR_DOT) {
- lex_state = EXPR_ARG;
- if (c == '@') {
- return tUPLUS;
- }
- pushback(c);
- return '+';
- }
- if (c == '=') {
- lex_state = EXPR_BEG;
- yylval.id = '+';
- return tOP_ASGN;
- }
- if (lex_state == EXPR_BEG || lex_state == EXPR_MID ||
- (IS_ARG() && space_seen && !ISSPACE(c))) {
- if (IS_ARG()) arg_ambiguous();
- lex_state = EXPR_BEG;
- pushback(c);
- if (ISDIGIT(c)) {
- c = '+';
- goto start_num;
- }
- return tUPLUS;
- }
- lex_state = EXPR_BEG;
- pushback(c);
- return '+';
-
- case '-':
- c = nextc();
- if (lex_state == EXPR_FNAME || lex_state == EXPR_DOT) {
- lex_state = EXPR_ARG;
- if (c == '@') {
- return tUMINUS;
- }
- pushback(c);
- return '-';
- }
- if (c == '=') {
- lex_state = EXPR_BEG;
- yylval.id = '-';
- return tOP_ASGN;
- }
- if (lex_state == EXPR_BEG || lex_state == EXPR_MID ||
- (IS_ARG() && space_seen && !ISSPACE(c))) {
- if (IS_ARG()) arg_ambiguous();
- lex_state = EXPR_BEG;
- pushback(c);
- if (ISDIGIT(c)) {
- c = '-';
- goto start_num;
- }
- return tUMINUS;
- }
- lex_state = EXPR_BEG;
- pushback(c);
- return '-';
-
- case '.':
- lex_state = EXPR_BEG;
- if ((c = nextc()) == '.') {
- if ((c = nextc()) == '.') {
- return tDOT3;
- }
- pushback(c);
- return tDOT2;
- }
- pushback(c);
- if (!ISDIGIT(c)) {
- lex_state = EXPR_DOT;
- return '.';
- }
- c = '.';
- /* fall through */
-
- start_num:
- case '0': case '1': case '2': case '3': case '4':
- case '5': case '6': case '7': case '8': case '9':
- {
- int is_float, seen_point, seen_e, nondigit;
-
- is_float = seen_point = seen_e = nondigit = 0;
- lex_state = EXPR_END;
- newtok();
- if (c == '-' || c == '+') {
- tokadd(c);
- c = nextc();
- }
- if (c == '0') {
- int start = toklen();
- c = nextc();
- if (c == 'x' || c == 'X') {
- /* hexadecimal */
- c = nextc();
- if (ISXDIGIT(c)) {
- do {
- if (c == '_') {
- if (nondigit) break;
- nondigit = c;
- continue;
- }
- if (!ISXDIGIT(c)) break;
- nondigit = 0;
- tokadd(c);
- } while (c = nextc());
- }
- pushback(c);
- tokfix();
- if (toklen() == start) {
- yyerror("hexadecimal number without hex-digits");
- }
- else if (nondigit) goto trailing_uc;
- yylval.val = rb_cstr_to_inum(tok(), 16, Qfalse);
- return tINTEGER;
- }
- if (c == 'b' || c == 'B') {
- /* binary */
- c = nextc();
- if (c == '0' || c == '1') {
- do {
- if (c == '_') {
- if (nondigit) break;
- nondigit = c;
- continue;
- }
- if (c != '0' && c != '1') break;
- nondigit = 0;
- tokadd(c);
- } while (c = nextc());
- }
- pushback(c);
- tokfix();
- if (toklen() == start) {
- yyerror("numeric literal without digits");
- }
- else if (nondigit) goto trailing_uc;
- yylval.val = rb_cstr_to_inum(tok(), 2, Qfalse);
- return tINTEGER;
- }
- if (c >= '0' && c <= '7' || c == '_') {
- /* octal */
- do {
- if (c == '_') {
- if (nondigit) break;
- nondigit = c;
- continue;
- }
- if (c < '0' || c > '7') break;
- nondigit = 0;
- tokadd(c);
- } while (c = nextc());
- if (toklen() > start) {
- pushback(c);
- tokfix();
- if (nondigit) goto trailing_uc;
- yylval.val = rb_cstr_to_inum(tok(), 8, Qfalse);
- return tINTEGER;
- }
- }
- if (c > '7' && c <= '9') {
- yyerror("Illegal octal digit");
- }
- else if (c == '.' || c == 'e' || c == 'E') {
- tokadd('0');
- }
- else {
- pushback(c);
- yylval.val = INT2FIX(0);
- return tINTEGER;
- }
- }
-
- for (;;) {
- switch (c) {
- case '0': case '1': case '2': case '3': case '4':
- case '5': case '6': case '7': case '8': case '9':
- nondigit = 0;
- tokadd(c);
- break;
-
- case '.':
- if (nondigit) goto trailing_uc;
- if (seen_point || seen_e) {
- goto decode_num;
- }
- else {
- int c0 = nextc();
- if (!ISDIGIT(c0)) {
- pushback(c0);
- goto decode_num;
- }
- c = c0;
- }
- tokadd('.');
- tokadd(c);
- is_float++;
- seen_point++;
- nondigit = 0;
- break;
-
- case 'e':
- case 'E':
- if (nondigit) {
- pushback(c);
- c = nondigit;
- goto decode_num;
- }
- if (seen_e) {
- goto decode_num;
- }
- tokadd(c);
- seen_e++;
- is_float++;
- nondigit = c;
- c = nextc();
- if (c != '-' && c != '+') continue;
- tokadd(c);
- nondigit = c;
- break;
-
- case '_': /* `_' in number just ignored */
- if (nondigit) goto decode_num;
- nondigit = c;
- break;
-
- default:
- goto decode_num;
- }
- c = nextc();
- }
-
- decode_num:
- pushback(c);
- tokfix();
- if (nondigit) {
- char tmp[30];
- trailing_uc:
- sprintf(tmp, "trailing `%c' in number", nondigit);
- yyerror(tmp);
- }
- if (is_float) {
- double d = strtod(tok(), 0);
- if (errno == ERANGE) {
- rb_warn("Float %s out of range", tok());
- errno = 0;
- }
- yylval.val = rb_float_new(d);
- return tFLOAT;
- }
- yylval.val = rb_cstr_to_inum(tok(), 10, Qfalse);
- return tINTEGER;
- }
-
- case ']':
- case '}':
- case ')':
- COND_LEXPOP();
- CMDARG_LEXPOP();
- lex_state = EXPR_END;
- return c;
-
- case ':':
- c = nextc();
- if (c == ':') {
- if (lex_state == EXPR_BEG || lex_state == EXPR_MID ||
- (IS_ARG() && space_seen)) {
- lex_state = EXPR_BEG;
- return tCOLON3;
- }
- lex_state = EXPR_DOT;
- return tCOLON2;
- }
- pushback(c);
- if (lex_state == EXPR_END || lex_state == EXPR_ENDARG || ISSPACE(c)) {
- lex_state = EXPR_BEG;
- return ':';
- }
- lex_state = EXPR_FNAME;
- return tSYMBEG;
-
- case '/':
- if (lex_state == EXPR_BEG || lex_state == EXPR_MID) {
- return parse_regx('/', '/');
- }
- if ((c = nextc()) == '=') {
- lex_state = EXPR_BEG;
- yylval.id = '/';
- return tOP_ASGN;
- }
- pushback(c);
- if (IS_ARG() && space_seen) {
- if (!ISSPACE(c)) {
- arg_ambiguous();
- return parse_regx('/', '/');
- }
- }
- switch (lex_state) {
- case EXPR_FNAME: case EXPR_DOT:
- lex_state = EXPR_ARG; break;
- default:
- lex_state = EXPR_BEG; break;
- }
- return '/';
-
- case '^':
- if ((c = nextc()) == '=') {
- lex_state = EXPR_BEG;
- yylval.id = '^';
- return tOP_ASGN;
- }
- switch (lex_state) {
- case EXPR_FNAME: case EXPR_DOT:
- lex_state = EXPR_ARG; break;
- default:
- lex_state = EXPR_BEG; break;
- }
- pushback(c);
- return '^';
-
- case ';':
- command_start = Qtrue;
- case ',':
- lex_state = EXPR_BEG;
- return c;
-
- case '~':
- if (lex_state == EXPR_FNAME || lex_state == EXPR_DOT) {
- if ((c = nextc()) != '@') {
- pushback(c);
- }
- }
- switch (lex_state) {
- case EXPR_FNAME: case EXPR_DOT:
- lex_state = EXPR_ARG; break;
- default:
- lex_state = EXPR_BEG; break;
- }
- return '~';
-
- case '(':
- command_start = Qtrue;
- if (lex_state == EXPR_BEG || lex_state == EXPR_MID) {
- c = tLPAREN;
- }
- else if (space_seen) {
- if (lex_state == EXPR_CMDARG) {
- c = tLPAREN_ARG;
- }
- else if (lex_state == EXPR_ARG) {
- c = tLPAREN_ARG;
- yylval.id = last_id;
- }
- }
- COND_PUSH(0);
- CMDARG_PUSH(0);
- lex_state = EXPR_BEG;
- return c;
-
- case '[':
- if (lex_state == EXPR_FNAME || lex_state == EXPR_DOT) {
- lex_state = EXPR_ARG;
- if ((c = nextc()) == ']') {
- if ((c = nextc()) == '=') {
- return tASET;
- }
- pushback(c);
- return tAREF;
- }
- pushback(c);
- return '[';
- }
- else if (lex_state == EXPR_BEG || lex_state == EXPR_MID) {
- c = tLBRACK;
- }
- else if (IS_ARG() && space_seen) {
- c = tLBRACK;
- }
- lex_state = EXPR_BEG;
- COND_PUSH(0);
- CMDARG_PUSH(0);
- return c;
-
- case '{':
- if (!IS_ARG()) {
- if (space_seen && lex_state == EXPR_ENDARG)
- c = tLBRACE_ARG;
- if (lex_state != EXPR_END && lex_state != EXPR_ENDARG)
- c = tLBRACE;
- }
- COND_PUSH(0);
- CMDARG_PUSH(0);
- lex_state = EXPR_BEG;
- return c;
-
- case '\\':
- c = nextc();
- if (c == '\n') {
- space_seen = 1;
- goto retry; /* skip \\n */
- }
- pushback(c);
- return '\\';
-
- case '%':
- if (lex_state == EXPR_BEG || lex_state == EXPR_MID) {
- int term;
- int paren;
-
- c = nextc();
- quotation:
- if (!ISALNUM(c)) {
- term = c;
- c = 'Q';
- }
- else {
- term = nextc();
- if (ISALNUM(term) || ismbchar(term)) {
- yyerror("unknown type of %string");
- return 0;
- }
- }
- if (c == -1 || term == -1) {
- rb_compile_error("unterminated quoted string meets end of file");
- return 0;
- }
- paren = term;
- if (term == '(') term = ')';
- else if (term == '[') term = ']';
- else if (term == '{') term = '}';
- else if (term == '<') term = '>';
- else paren = 0;
-
- switch (c) {
- case 'Q':
- return parse_string('"', term, paren);
-
- case 'q':
- return parse_qstring(term, paren);
-
- case 'w':
- return parse_quotedwords(term, paren);
-
- case 'x':
- return parse_string('`', term, paren);
-
- case 'r':
- return parse_regx(term, paren);
-
- default:
- yyerror("unknown type of %string");
- return 0;
- }
- }
- if ((c = nextc()) == '=') {
- yylval.id = '%';
- return tOP_ASGN;
- }
- if (IS_ARG() && space_seen && !ISSPACE(c)) {
- goto quotation;
- }
- switch (lex_state) {
- case EXPR_FNAME: case EXPR_DOT:
- lex_state = EXPR_ARG; break;
- default:
- lex_state = EXPR_BEG; break;
- }
- pushback(c);
- return '%';
-
- case '$':
- lex_state = EXPR_END;
- newtok();
- c = nextc();
- switch (c) {
- case '_': /* $_: last read line string */
- c = nextc();
- if (is_identchar(c)) {
- tokadd('$');
- tokadd('_');
- break;
- }
- pushback(c);
- c = '_';
- /* fall through */
- case '~': /* $~: match-data */
- local_cnt(c);
- /* fall through */
- case '*': /* $*: argv */
- case '$': /* $$: pid */
- case '?': /* $?: last status */
- case '!': /* $!: error string */
- case '@': /* $@: error position */
- case '/': /* $/: input record separator */
- case '\\': /* $\: output record separator */
- case ';': /* $;: field separator */
- case ',': /* $,: output field separator */
- case '.': /* $.: last read line number */
- case '=': /* $=: ignorecase */
- case ':': /* $:: load path */
- case '<': /* $<: reading filename */
- case '>': /* $>: default output handle */
- case '\"': /* $": already loaded files */
- tokadd('$');
- tokadd(c);
- tokfix();
- yylval.id = rb_intern(tok());
- return tGVAR;
-
- case '-':
- tokadd('$');
- tokadd(c);
- c = nextc();
- tokadd(c);
- tokfix();
- yylval.id = rb_intern(tok());
- /* xxx shouldn't check if valid option variable */
- return tGVAR;
-
- case '&': /* $&: last match */
- case '`': /* $`: string before last match */
- case '\'': /* $': string after last match */
- case '+': /* $+: string matches last paren. */
- yylval.node = NEW_BACK_REF(c);
- return tBACK_REF;
-
- case '1': case '2': case '3':
- case '4': case '5': case '6':
- case '7': case '8': case '9':
- tokadd('$');
- while (ISDIGIT(c)) {
- tokadd(c);
- c = nextc();
- }
- if (is_identchar(c))
- break;
- pushback(c);
- tokfix();
- yylval.node = NEW_NTH_REF(atoi(tok()+1));
- return tNTH_REF;
-
- default:
- if (!is_identchar(c)) {
- pushback(c);
- return '$';
- }
- case '0':
- tokadd('$');
- }
- break;
-
- case '@':
- c = nextc();
- newtok();
- tokadd('@');
- if (c == '@') {
- tokadd('@');
- c = nextc();
- }
- if (ISDIGIT(c)) {
- rb_compile_error("`@%c' is not a valid instance variable name", c);
- }
- if (!is_identchar(c)) {
- pushback(c);
- return '@';
- }
- break;
-
- default:
- if (!is_identchar(c) || ISDIGIT(c)) {
- rb_compile_error("Invalid char `\\%03o' in expression", c);
- goto retry;
- }
-
- newtok();
- break;
- }
-
- while (is_identchar(c)) {
- tokadd(c);
- if (ismbchar(c)) {
- int i, len = mbclen(c)-1;
-
- for (i = 0; i < len; i++) {
- c = nextc();
- tokadd(c);
- }
- }
- c = nextc();
- }
- if ((c == '!' || c == '?') && is_identchar(tok()[0]) && !peek('=')) {
- tokadd(c);
- }
- else {
- pushback(c);
- }
- tokfix();
-
- {
- int result = 0;
-
- switch (tok()[0]) {
- case '$':
- lex_state = EXPR_END;
- result = tGVAR;
- break;
- case '@':
- lex_state = EXPR_END;
- if (tok()[1] == '@')
- result = tCVAR;
- else
- result = tIVAR;
- break;
-
- default:
- if (toklast() == '!' || toklast() == '?') {
- result = tFID;
- }
- else {
- if (lex_state == EXPR_FNAME) {
- if ((c = nextc()) == '=' && !peek('~') && !peek('>') &&
- (!peek('=') || lex_p + 1 < lex_pend && lex_p[1] == '>')) {
- result = tIDENTIFIER;
- tokadd(c);
- }
- else {
- pushback(c);
- }
- }
- if (result == 0 && ISUPPER(tok()[0])) {
- result = tCONSTANT;
- }
- else {
- result = tIDENTIFIER;
- }
- }
-
- if (lex_state != EXPR_DOT) {
- struct kwtable *kw;
-
- /* See if it is a reserved word. */
- kw = rb_reserved_word(tok(), toklen());
- if (kw) {
- enum lex_state state = lex_state;
- lex_state = kw->state;
- if (state == EXPR_FNAME) {
- yylval.id = rb_intern(kw->name);
- }
- if (kw->id[0] == kDO) {
- if (COND_P()) return kDO_COND;
- if (CMDARG_P() && state != EXPR_CMDARG)
- return kDO_BLOCK;
- return kDO;
- }
- if (state == EXPR_BEG)
- return kw->id[0];
- else {
- if (kw->id[0] != kw->id[1])
- lex_state = EXPR_BEG;
- return kw->id[1];
- }
- }
- }
-
- if (lex_state == EXPR_BEG ||
- lex_state == EXPR_DOT ||
- lex_state == EXPR_ARG ||
- lex_state == EXPR_CMDARG) {
- if (cmd_state)
- lex_state = EXPR_CMDARG;
- else
- lex_state = EXPR_ARG;
- }
- else {
- lex_state = EXPR_END;
- }
- }
- tokfix();
- last_id = yylval.id = rb_intern(tok());
- return result;
- }
-}
-
-static NODE*
-str_extend(list, term, paren)
- NODE *list;
- int term, paren;
-{
- int c;
- int brace = -1;
- VALUE ss;
- NODE *node;
- int brace_nest = 0;
- int paren_nest = 0;
-
- c = nextc();
- switch (c) {
- case '$':
- case '@':
- case '{':
- break;
- default:
- tokadd('#');
- pushback(c);
- return list;
- }
-
- ss = rb_str_new(tok(), toklen());
- if (list == 0) {
- list = NEW_DSTR(ss);
- }
- else if (toklen() > 0) {
- list_append(list, NEW_STR(ss));
- }
- newtok();
-
- switch (c) {
- case '$':
- tokadd('$');
- c = nextc();
- if (c == -1) return (NODE*)-1;
- switch (c) {
- case '1': case '2': case '3':
- case '4': case '5': case '6':
- case '7': case '8': case '9':
- while (ISDIGIT(c)) {
- tokadd(c);
- c = nextc();
- }
- pushback(c);
- goto fetch_id;
-
- case '&': case '+':
- case '_': case '~':
- case '*': case '$': case '?':
- case '!': case '@': case ',':
- case '.': case '=': case ':':
- case '<': case '>': case '\\':
- case ';':
- refetch:
- tokadd(c);
- goto fetch_id;
-
- case '-':
- tokadd(c);
- c = nextc();
- if (!is_identchar(c)) {
- pushback();
- goto invalid_interporate;
- }
- tokadd(c);
- goto fetch_id;
-
- default:
- if (c == term) {
- list_append(list, NEW_STR(rb_str_new2("#$")));
- pushback(c);
- newtok();
- return list;
- }
- switch (c) {
- case '\"':
- case '/':
- case '\'':
- case '`':
- goto refetch;
- }
- if (!is_identchar(c)) {
- pushback(c);
- invalid_interporate:
- {
- VALUE s = rb_str_new2("#");
- rb_str_cat(s, tok(), toklen());
- list_append(list, NEW_STR(s));
- newtok();
- return list;
- }
- }
- }
-
- while (is_identchar(c)) {
- tokadd(c);
- if (ismbchar(c)) {
- int i, len = mbclen(c)-1;
-
- for (i = 0; i < len; i++) {
- c = nextc();
- tokadd(c);
- }
- }
- c = nextc();
- }
- pushback(c);
- break;
-
- case '@':
- tokadd(c);
- c = nextc();
- if (c == '@') {
- tokadd(c);
- c = nextc();
- }
- while (is_identchar(c)) {
- tokadd(c);
- if (ismbchar(c)) {
- int i, len = mbclen(c)-1;
-
- for (i = 0; i < len; i++) {
- c = nextc();
- tokadd(c);
- }
- }
- c = nextc();
- }
- pushback(c);
- if (toklen() == 1) {
- goto invalid_interporate;
- }
- break;
-
- case '{':
- if (c == '{') brace = '}';
- brace_nest = 0;
- do {
- loop_again:
- c = nextc();
- switch (c) {
- case -1:
- if (brace_nest > 0) {
- yyerror("bad substitution in string");
- newtok();
- return list;
- }
- return (NODE*)-1;
- case '}':
- if (c == brace) {
- if (brace_nest == 0) break;
- brace_nest--;
- }
- tokadd(c);
- goto loop_again;
- case '\\':
- c = nextc();
- if (c == -1) return (NODE*)-1;
- if (c == term) {
- tokadd(c);
- }
- else {
- tokadd('\\');
- tokadd(c);
- }
- goto loop_again;
- case '{':
- if (brace != -1) brace_nest++;
- default:
- if (c == paren) paren_nest++;
- else if (c == term && (!paren || paren_nest-- == 0)) {
- pushback(c);
- list_append(list, NEW_STR(rb_str_new2("#")));
- rb_warn("bad substitution in string");
- tokfix();
- list_append(list, NEW_STR(rb_str_new(tok(), toklen())));
- newtok();
- return list;
- }
- else if (ismbchar(c)) {
- int i, len = mbclen(c)-1;
-
- for (i = 0; i < len; i++) {
- tokadd(c);
- c = nextc();
- }
- }
- case '\n':
- tokadd(c);
- break;
- }
- } while (c != brace);
- }
-
- fetch_id:
- tokfix();
- node = NEW_EVSTR(tok(),toklen());
- list_append(list, node);
- newtok();
-
- return list;
-}
-
-NODE*
-rb_node_newnode(type, a0, a1, a2)
- enum node_type type;
- NODE *a0, *a1, *a2;
-{
- NODE *n = (NODE*)rb_newobj();
-
- n->flags |= T_NODE;
- nd_set_type(n, type);
- nd_set_line(n, ruby_sourceline);
- n->nd_file = ruby_sourcefile;
-
- n->u1.node = a0;
- n->u2.node = a1;
- n->u3.node = a2;
-
- return n;
-}
-
-static enum node_type
-nodetype(node) /* for debug */
- NODE *node;
-{
- return (enum node_type)nd_type(node);
-}
-
-static int
-nodeline(node)
- NODE *node;
-{
- return nd_line(node);
-}
-
-static NODE*
-newline_node(node)
- NODE *node;
-{
- NODE *nl = 0;
- if (node) {
- nl = NEW_NEWLINE(node);
- fixpos(nl, node);
- nl->nd_nth = nd_line(node);
- }
- return nl;
-}
-
-static void
-fixpos(node, orig)
- NODE *node, *orig;
-{
- if (!node) return;
- if (!orig) return;
- if (orig == (NODE*)1) return;
- node->nd_file = orig->nd_file;
- nd_set_line(node, nd_line(orig));
-}
-
-static NODE*
-block_append(head, tail)
- NODE *head, *tail;
-{
- NODE *end;
-
- if (tail == 0) return head;
- if (head == 0) return tail;
-
- if (nd_type(head) != NODE_BLOCK) {
- end = NEW_BLOCK(head);
- end->nd_end = end;
- fixpos(end, head);
- head = end;
- }
- else {
- end = head->nd_end;
- }
-
- if (RTEST(ruby_verbose)) {
- NODE *nd = end->nd_head;
- newline:
- switch (nd_type(nd)) {
- case NODE_RETURN:
- case NODE_BREAK:
- case NODE_NEXT:
- case NODE_REDO:
- case NODE_RETRY:
- rb_warning("statement not reached");
- break;
-
- case NODE_NEWLINE:
- nd = nd->nd_next;
- goto newline;
-
- default:
- break;
- }
- }
-
- if (nd_type(tail) != NODE_BLOCK) {
- tail = NEW_BLOCK(tail);
- tail->nd_end = tail;
- }
- end->nd_next = tail;
- head->nd_end = tail->nd_end;
- return head;
-}
-
-static NODE*
-list_append(head, tail)
- NODE *head, *tail;
-{
- NODE *last;
-
- if (head == 0) return NEW_LIST(tail);
-
- last = head;
- while (last->nd_next) {
- last = last->nd_next;
- }
-
- last->nd_next = NEW_LIST(tail);
- head->nd_alen += 1;
- return head;
-}
-
-static NODE*
-list_concat(head, tail)
- NODE *head, *tail;
-{
- NODE *last;
-
- last = head;
- while (last->nd_next) {
- last = last->nd_next;
- }
-
- last->nd_next = tail;
- head->nd_alen += tail->nd_alen;
-
- return head;
-}
-
-static NODE *
-call_op(recv, id, narg, arg1)
- NODE *recv;
- ID id;
- int narg;
- NODE *arg1;
-{
- value_expr(recv);
- if (narg == 1) {
- value_expr(arg1);
- }
-
- return NEW_CALL(recv, id, narg==1?NEW_LIST(arg1):0);
-}
-
-static NODE*
-match_gen(node1, node2)
- NODE *node1;
- NODE *node2;
-{
- local_cnt('~');
-
- switch (nd_type(node1)) {
- case NODE_DREGX:
- case NODE_DREGX_ONCE:
- return NEW_MATCH2(node1, node2);
-
- case NODE_LIT:
- if (TYPE(node1->nd_lit) == T_REGEXP) {
- return NEW_MATCH2(node1, node2);
- }
- }
-
- switch (nd_type(node2)) {
- case NODE_DREGX:
- case NODE_DREGX_ONCE:
- return NEW_MATCH3(node2, node1);
-
- case NODE_LIT:
- if (TYPE(node2->nd_lit) == T_REGEXP) {
- return NEW_MATCH3(node2, node1);
- }
- }
-
- return NEW_CALL(node1, tMATCH, NEW_LIST(node2));
-}
-
-static NODE*
-gettable(id)
- ID id;
-{
- if (id == kSELF) {
- return NEW_SELF();
- }
- else if (id == kNIL) {
- return NEW_NIL();
- }
- else if (id == kTRUE) {
- return NEW_TRUE();
- }
- else if (id == kFALSE) {
- return NEW_FALSE();
- }
- else if (id == k__FILE__) {
- return NEW_STR(rb_str_new2(ruby_sourcefile));
- }
- else if (id == k__LINE__) {
- return NEW_LIT(INT2FIX(ruby_sourceline));
- }
- else if (is_local_id(id)) {
- if (dyna_in_block() && rb_dvar_defined(id)) return NEW_DVAR(id);
- if (local_id(id)) return NEW_LVAR(id);
- /* method call without arguments */
-#if 0
- /* Rite will warn this */
- rb_warn("ambiguous identifier; %s() or self.%s is better for method call",
- rb_id2name(id), rb_id2name(id));
-#endif
- return NEW_VCALL(id);
- }
- else if (is_global_id(id)) {
- return NEW_GVAR(id);
- }
- else if (is_instance_id(id)) {
- return NEW_IVAR(id);
- }
- else if (is_const_id(id)) {
- return NEW_CONST(id);
- }
- else if (is_class_id(id)) {
- return NEW_CVAR(id);
- }
- rb_compile_error("identifier %s is not valid", rb_id2name(id));
- return 0;
-}
-
-static NODE*
-assignable(id, val)
- ID id;
- NODE *val;
-{
- value_expr(val);
- if (id == kSELF) {
- yyerror("Can't change the value of self");
- }
- else if (id == kNIL) {
- yyerror("Can't assign to nil");
- }
- else if (id == kTRUE) {
- yyerror("Can't assign to true");
- }
- else if (id == kFALSE) {
- yyerror("Can't assign to false");
- }
- else if (id == k__FILE__) {
- yyerror("Can't assign to __FILE__");
- }
- else if (id == k__LINE__) {
- yyerror("Can't assign to __LINE__");
- }
- else if (is_local_id(id)) {
- if (rb_dvar_curr(id)) {
- return NEW_DASGN_CURR(id, val);
- }
- else if (rb_dvar_defined(id)) {
- return NEW_DASGN(id, val);
- }
- else if (local_id(id) || !dyna_in_block()) {
- return NEW_LASGN(id, val);
- }
- else{
- rb_dvar_push(id, Qnil);
- return NEW_DASGN_CURR(id, val);
- }
- }
- else if (is_global_id(id)) {
- return NEW_GASGN(id, val);
- }
- else if (is_instance_id(id)) {
- return NEW_IASGN(id, val);
- }
- else if (is_const_id(id)) {
- if (in_def || in_single)
- yyerror("dynamic constant assignment");
- return NEW_CDECL(id, val);
- }
- else if (is_class_id(id)) {
- if (in_def || in_single) return NEW_CVASGN(id, val);
- return NEW_CVDECL(id, val);
- }
- else {
- rb_bug("bad id for variable");
- }
- return 0;
-}
-
-static NODE *
-aryset(recv, idx)
- NODE *recv, *idx;
-{
- value_expr(recv);
-
- return NEW_CALL(recv, tASET, idx);
-}
-
-ID
-rb_id_attrset(id)
- ID id;
-{
- id &= ~ID_SCOPE_MASK;
- id |= ID_ATTRSET;
- return id;
-}
-
-static NODE *
-attrset(recv, id)
- NODE *recv;
- ID id;
-{
- value_expr(recv);
-
- return NEW_CALL(recv, rb_id_attrset(id), 0);
-}
-
-static void
-rb_backref_error(node)
- NODE *node;
-{
- switch (nd_type(node)) {
- case NODE_NTH_REF:
- rb_compile_error("Can't set variable $%d", node->nd_nth);
- break;
- case NODE_BACK_REF:
- rb_compile_error("Can't set variable $%c", node->nd_nth);
- break;
- }
-}
-
-static NODE *
-arg_concat(node1, node2)
- NODE *node1;
- NODE *node2;
-{
- if (!node2) return node1;
- return NEW_ARGSCAT(node1, node2);
-}
-
-static NODE *
-arg_add(node1, node2)
- NODE *node1;
- NODE *node2;
-{
- if (!node1) return NEW_LIST(node2);
- if (nd_type(node1) == NODE_ARRAY) {
- return list_append(node1, node2);
- }
- else {
- return NEW_ARGSPUSH(node1, node2);
- }
-}
-
-static NODE*
-node_assign(lhs, rhs)
- NODE *lhs, *rhs;
-{
- if (!lhs) return 0;
-
- value_expr(rhs);
- switch (nd_type(lhs)) {
- case NODE_GASGN:
- case NODE_IASGN:
- case NODE_LASGN:
- case NODE_DASGN:
- case NODE_DASGN_CURR:
- case NODE_MASGN:
- case NODE_CDECL:
- case NODE_CVDECL:
- case NODE_CVASGN:
- lhs->nd_value = rhs;
- break;
-
- case NODE_CALL:
- lhs->nd_args = arg_add(lhs->nd_args, rhs);
- break;
-
- default:
- /* should not happen */
- break;
- }
-
- if (rhs) fixpos(lhs, rhs);
- return lhs;
-}
-
-static int
-value_expr(node)
- NODE *node;
-{
- if (node == 0) return Qtrue;
-
- switch (nd_type(node)) {
- case NODE_WHILE:
- case NODE_UNTIL:
- case NODE_CLASS:
- case NODE_MODULE:
- case NODE_DEFN:
- case NODE_DEFS:
- rb_warning("void value expression");
- return Qfalse;
-
- case NODE_RETURN:
- case NODE_BREAK:
- case NODE_NEXT:
- case NODE_REDO:
- case NODE_RETRY:
- yyerror("void value expression");
- return Qfalse;
-
- case NODE_BLOCK:
- while (node->nd_next) {
- node = node->nd_next;
- }
- return value_expr(node->nd_head);
-
- case NODE_BEGIN:
- return value_expr(node->nd_body);
-
- case NODE_IF:
- return value_expr(node->nd_body) && value_expr(node->nd_else);
-
- case NODE_NEWLINE:
- return value_expr(node->nd_next);
-
- default:
- return Qtrue;
- }
-}
-
-static void
-void_expr(node)
- NODE *node;
-{
- char *useless = 0;
-
- if (!ruby_verbose) return;
- if (!node) return;
-
- again:
- switch (nd_type(node)) {
- case NODE_NEWLINE:
- node = node->nd_next;
- goto again;
-
- case NODE_CALL:
- switch (node->nd_mid) {
- case '+':
- case '-':
- case '*':
- case '/':
- case '%':
- case tPOW:
- case tUPLUS:
- case tUMINUS:
- case '|':
- case '^':
- case '&':
- case tCMP:
- case '>':
- case tGEQ:
- case '<':
- case tLEQ:
- case tEQ:
- case tNEQ:
- useless = rb_id2name(node->nd_mid);
- break;
- }
- break;
-
- case NODE_LVAR:
- case NODE_DVAR:
- case NODE_GVAR:
- case NODE_IVAR:
- case NODE_CVAR:
- case NODE_NTH_REF:
- case NODE_BACK_REF:
- useless = "a variable";
- break;
- case NODE_CONST:
- case NODE_CREF:
- useless = "a constant";
- break;
- case NODE_LIT:
- case NODE_STR:
- case NODE_DSTR:
- case NODE_DREGX:
- case NODE_DREGX_ONCE:
- useless = "a literal";
- break;
- case NODE_COLON2:
- case NODE_COLON3:
- useless = "::";
- break;
- case NODE_DOT2:
- useless = "..";
- break;
- case NODE_DOT3:
- useless = "...";
- break;
- case NODE_SELF:
- useless = "self";
- break;
- case NODE_NIL:
- useless = "nil";
- break;
- case NODE_TRUE:
- useless = "true";
- break;
- case NODE_FALSE:
- useless = "false";
- break;
- case NODE_DEFINED:
- useless = "defined?";
- break;
- }
-
- if (useless) {
- int line = ruby_sourceline;
-
- ruby_sourceline = nd_line(node);
- rb_warn("useless use of %s in void context", useless);
- ruby_sourceline = line;
- }
-}
-
-static void
-void_stmts(node)
- NODE *node;
-{
- if (!ruby_verbose) return;
- if (!node) return;
- if (nd_type(node) != NODE_BLOCK) return;
-
- for (;;) {
- if (!node->nd_next) return;
- void_expr(node->nd_head);
- node = node->nd_next;
- }
-}
-
-static int
-assign_in_cond(node)
- NODE *node;
-{
- switch (nd_type(node)) {
- case NODE_MASGN:
- yyerror("multiple assignment in conditional");
- return 1;
-
- case NODE_LASGN:
- case NODE_DASGN:
- case NODE_GASGN:
- case NODE_IASGN:
- break;
-
- case NODE_NEWLINE:
- default:
- return 0;
- }
-
- switch (nd_type(node->nd_value)) {
- case NODE_LIT:
- case NODE_STR:
- case NODE_NIL:
- case NODE_TRUE:
- case NODE_FALSE:
- /* reports always */
- rb_warn("found = in conditional, should be ==");
- return 1;
-
- case NODE_DSTR:
- case NODE_XSTR:
- case NODE_DXSTR:
- case NODE_EVSTR:
- case NODE_DREGX:
- default:
- break;
- }
-#if 0
- if (assign_in_cond(node->nd_value) == 0) {
- rb_warning("assignment in condition");
- }
-#endif
- return 1;
-}
-
-static int
-e_option_supplied()
-{
- if (strcmp(ruby_sourcefile, "-e") == 0)
- return Qtrue;
- return Qfalse;
-}
-
-static void
-warn_unless_e_option(str)
- const char *str;
-{
- if (!e_option_supplied()) rb_warn(str);
-}
-
-static void
-warning_unless_e_option(str)
- const char *str;
-{
- if (!e_option_supplied()) rb_warning(str);
-}
-
-static NODE *cond0();
-
-static NODE*
-range_op(node)
- NODE *node;
-{
- enum node_type type;
-
- if (!e_option_supplied()) return node;
-
- node = cond0(node);
- type = nd_type(node);
- if (type == NODE_NEWLINE) node = node->nd_next;
- if (type == NODE_LIT && FIXNUM_P(node->nd_lit)) {
- warn_unless_e_option("integer literal in conditional range");
- return call_op(node,tEQ,1,NEW_GVAR(rb_intern("$.")));
- }
- return node;
-}
-
-static NODE*
-cond0(node)
- NODE *node;
-{
- enum node_type type = nd_type(node);
-
- assign_in_cond(node);
-
- switch (type) {
- case NODE_DSTR:
- case NODE_STR:
- rb_warn("string literal in condition");
- break;
-
- case NODE_DREGX:
- case NODE_DREGX_ONCE:
- warning_unless_e_option("regex literal in condition");
- local_cnt('_');
- local_cnt('~');
- return NEW_MATCH2(node, NEW_GVAR(rb_intern("$_")));
-
- case NODE_AND:
- case NODE_OR:
- node->nd_1st = cond0(node->nd_1st);
- node->nd_2nd = cond0(node->nd_2nd);
- break;
-
- case NODE_DOT2:
- case NODE_DOT3:
- node->nd_beg = range_op(node->nd_beg);
- node->nd_end = range_op(node->nd_end);
- if (type == NODE_DOT2) nd_set_type(node,NODE_FLIP2);
- else if (type == NODE_DOT3) nd_set_type(node, NODE_FLIP3);
- node->nd_cnt = local_append(internal_id());
- warning_unless_e_option("range literal in condition");
- break;
-
- case NODE_LIT:
- if (TYPE(node->nd_lit) == T_REGEXP) {
- warn_unless_e_option("regex literal in condition");
- nd_set_type(node, NODE_MATCH);
- local_cnt('_');
- local_cnt('~');
- }
- else {
- rb_warning("literal in condition");
- }
- }
- return node;
-}
-
-static NODE*
-cond(node)
- NODE *node;
-{
- if (node == 0) return 0;
- if (nd_type(node) == NODE_NEWLINE){
- node->nd_next = cond0(node->nd_next);
- return node;
- }
- return cond0(node);
-}
-
-static NODE*
-logop(type, left, right)
- enum node_type type;
- NODE *left, *right;
-{
- value_expr(left);
- return rb_node_newnode(type, left, right, 0);
-}
-
-static NODE *
-ret_args(node)
- NODE *node;
-{
- if (node) {
- if (nd_type(node) == NODE_BLOCK_PASS) {
- rb_compile_error("block argument should not be given");
- }
- }
- return node;
-}
-
-static NODE *
-arg_blk_pass(node1, node2)
- NODE *node1;
- NODE *node2;
-{
- if (node2) {
- node2->nd_head = node1;
- return node2;
- }
- return node1;
-}
-
-static NODE*
-arg_prepend(node1, node2)
- NODE *node1, *node2;
-{
- switch (nodetype(node2)) {
- case NODE_ARRAY:
- return list_concat(NEW_LIST(node1), node2);
-
- case NODE_RESTARGS:
- return arg_concat(node1, node2->nd_head);
-
- case NODE_BLOCK_PASS:
- node2->nd_body = arg_prepend(node1, node2->nd_body);
- return node2;
-
- default:
- rb_bug("unknown nodetype(%d) for arg_prepend");
- }
- return 0; /* not reached */
-}
-
-static NODE*
-new_call(r,m,a)
- NODE *r;
- ID m;
- NODE *a;
-{
- if (a && nd_type(a) == NODE_BLOCK_PASS) {
- a->nd_iter = NEW_CALL(r,m,a->nd_head);
- return a;
- }
- return NEW_CALL(r,m,a);
-}
-
-static NODE*
-new_fcall(m,a)
- ID m;
- NODE *a;
-{
- if (a && nd_type(a) == NODE_BLOCK_PASS) {
- a->nd_iter = NEW_FCALL(m,a->nd_head);
- return a;
- }
- return NEW_FCALL(m,a);
-}
-
-static NODE*
-new_super(a)
- NODE *a;
-{
- if (a && nd_type(a) == NODE_BLOCK_PASS) {
- a->nd_iter = NEW_SUPER(a->nd_head);
- return a;
- }
- return NEW_SUPER(a);
-}
-
-static struct local_vars {
- ID *tbl;
- int nofree;
- int cnt;
- int dlev;
- struct RVarmap* dyna_vars;
- struct local_vars *prev;
-} *lvtbl;
-
-static void
-local_push(top)
- int top;
-{
- struct local_vars *local;
-
- local = ALLOC(struct local_vars);
- local->prev = lvtbl;
- local->nofree = 0;
- local->cnt = 0;
- local->tbl = 0;
- local->dlev = 0;
- local->dyna_vars = ruby_dyna_vars;
- lvtbl = local;
- if (!top) {
- /* preserve reference for GC, but link should be cut. */
- rb_dvar_push(0, (VALUE)ruby_dyna_vars);
- ruby_dyna_vars->next = 0;
- }
-}
-
-static void
-local_pop()
-{
- struct local_vars *local = lvtbl->prev;
-
- if (lvtbl->tbl) {
- if (!lvtbl->nofree) free(lvtbl->tbl);
- else lvtbl->tbl[0] = lvtbl->cnt;
- }
- ruby_dyna_vars = lvtbl->dyna_vars;
- free(lvtbl);
- lvtbl = local;
-}
-
-static ID*
-local_tbl()
-{
- lvtbl->nofree = 1;
- return lvtbl->tbl;
-}
-
-static int
-local_append(id)
- ID id;
-{
- if (lvtbl->tbl == 0) {
- lvtbl->tbl = ALLOC_N(ID, 4);
- lvtbl->tbl[0] = 0;
- lvtbl->tbl[1] = '_';
- lvtbl->tbl[2] = '~';
- lvtbl->cnt = 2;
- if (id == '_') return 0;
- if (id == '~') return 1;
- }
- else {
- REALLOC_N(lvtbl->tbl, ID, lvtbl->cnt+2);
- }
-
- lvtbl->tbl[lvtbl->cnt+1] = id;
- return lvtbl->cnt++;
-}
-
-static int
-local_cnt(id)
- ID id;
-{
- int cnt, max;
-
- if (id == 0) return lvtbl->cnt;
-
- for (cnt=1, max=lvtbl->cnt+1; cnt<max;cnt++) {
- if (lvtbl->tbl[cnt] == id) return cnt-1;
- }
- return local_append(id);
-}
-
-static int
-local_id(id)
- ID id;
-{
- int i, max;
-
- if (lvtbl == 0) return Qfalse;
- for (i=3, max=lvtbl->cnt+1; i<max; i++) {
- if (lvtbl->tbl[i] == id) return Qtrue;
- }
- return Qfalse;
-}
-
-static void
-top_local_init()
-{
- local_push(1);
- lvtbl->cnt = ruby_scope->local_tbl?ruby_scope->local_tbl[0]:0;
- if (lvtbl->cnt > 0) {
- lvtbl->tbl = ALLOC_N(ID, lvtbl->cnt+3);
- MEMCPY(lvtbl->tbl, ruby_scope->local_tbl, ID, lvtbl->cnt+1);
- }
- else {
- lvtbl->tbl = 0;
- }
- if (ruby_dyna_vars)
- lvtbl->dlev = 1;
- else
- lvtbl->dlev = 0;
-}
-
-static void
-top_local_setup()
-{
- int len = lvtbl->cnt;
- int i;
-
- if (len > 0) {
- i = ruby_scope->local_tbl?ruby_scope->local_tbl[0]:0;
-
- if (i < len) {
- if (i == 0 || (ruby_scope->flags & SCOPE_MALLOC) == 0) {
- VALUE *vars = ALLOC_N(VALUE, len+1);
- if (ruby_scope->local_vars) {
- *vars++ = ruby_scope->local_vars[-1];
- MEMCPY(vars, ruby_scope->local_vars, VALUE, i);
- rb_mem_clear(vars+i, len-i);
- }
- else {
- *vars++ = 0;
- rb_mem_clear(vars, len);
- }
- ruby_scope->local_vars = vars;
- ruby_scope->flags |= SCOPE_MALLOC;
- }
- else {
- VALUE *vars = ruby_scope->local_vars-1;
- REALLOC_N(vars, VALUE, len+1);
- ruby_scope->local_vars = vars+1;
- rb_mem_clear(ruby_scope->local_vars+i, len-i);
- }
- if (ruby_scope->local_tbl && ruby_scope->local_vars[-1] == 0) {
- free(ruby_scope->local_tbl);
- }
- ruby_scope->local_vars[-1] = 0;
- ruby_scope->local_tbl = local_tbl();
- }
- }
- local_pop();
-}
-
-static struct RVarmap*
-dyna_push()
-{
- struct RVarmap* vars = ruby_dyna_vars;
-
- rb_dvar_push(0, 0);
- lvtbl->dlev++;
- return vars;
-}
-
-static void
-dyna_pop(vars)
- struct RVarmap* vars;
-{
- lvtbl->dlev--;
- ruby_dyna_vars = vars;
-}
-
-static int
-dyna_in_block()
-{
- return (lvtbl->dlev > 0);
-}
-
-void
-rb_parser_append_print()
-{
- ruby_eval_tree =
- block_append(ruby_eval_tree,
- NEW_FCALL(rb_intern("print"),
- NEW_ARRAY(NEW_GVAR(rb_intern("$_")))));
-}
-
-void
-rb_parser_while_loop(chop, split)
- int chop, split;
-{
- if (split) {
- ruby_eval_tree =
- block_append(NEW_GASGN(rb_intern("$F"),
- NEW_CALL(NEW_GVAR(rb_intern("$_")),
- rb_intern("split"), 0)),
- ruby_eval_tree);
- }
- if (chop) {
- ruby_eval_tree =
- block_append(NEW_CALL(NEW_GVAR(rb_intern("$_")),
- rb_intern("chop!"), 0), ruby_eval_tree);
- }
- ruby_eval_tree = NEW_OPT_N(ruby_eval_tree);
-}
-
-static struct {
- ID token;
- char *name;
-} op_tbl[] = {
- tDOT2, "..",
- tDOT3, "...",
- '+', "+",
- '-', "-",
- '+', "+(binary)",
- '-', "-(binary)",
- '*', "*",
- '/', "/",
- '%', "%",
- tPOW, "**",
- tUPLUS, "+@",
- tUMINUS, "-@",
- tUPLUS, "+(unary)",
- tUMINUS, "-(unary)",
- '|', "|",
- '^', "^",
- '&', "&",
- tCMP, "<=>",
- '>', ">",
- tGEQ, ">=",
- '<', "<",
- tLEQ, "<=",
- tEQ, "==",
- tEQQ, "===",
- tNEQ, "!=",
- tMATCH, "=~",
- tNMATCH, "!~",
- '!', "!",
- '~', "~",
- '!', "!(unary)",
- '~', "~(unary)",
- '!', "!@",
- '~', "~@",
- tAREF, "[]",
- tASET, "[]=",
- tLSHFT, "<<",
- tRSHFT, ">>",
- tCOLON2, "::",
- '`', "`",
- 0, 0,
-};
-
-static st_table *sym_tbl;
-static st_table *sym_rev_tbl;
-
-void
-Init_sym()
-{
- sym_tbl = st_init_strtable_with_size(200);
- sym_rev_tbl = st_init_numtable_with_size(200);
- rb_global_variable((VALUE*)&lex_lastline);
-}
-
-static ID last_id = LAST_TOKEN;
-
-static ID
-internal_id()
-{
- return ID_INTERNAL | (++last_id << ID_SCOPE_SHIFT);
-}
-
-ID
-rb_intern(name)
- const char *name;
-{
- const char *m = name;
- ID id;
- int last;
-
- if (st_lookup(sym_tbl, name, &id))
- return id;
-
- id = 0;
- switch (*name) {
- case '$':
- id |= ID_GLOBAL;
- m++;
- if (!is_identchar(*m)) m++;
- break;
- case '@':
- if (name[1] == '@') {
- m++;
- id |= ID_CLASS;
- }
- else {
- id |= ID_INSTANCE;
- }
- m++;
- break;
- default:
- if (name[0] != '_' && !ISALPHA(name[0]) && !ismbchar(name[0])) {
- /* operators */
- int i;
-
- for (i=0; op_tbl[i].token; i++) {
- if (*op_tbl[i].name == *name &&
- strcmp(op_tbl[i].name, name) == 0) {
- id = op_tbl[i].token;
- goto id_regist;
- }
- }
- }
-
- last = strlen(name)-1;
- if (name[last] == '=') {
- /* attribute assignment */
- char *buf = ALLOCA_N(char,last+1);
-
- strncpy(buf, name, last);
- buf[last] = '\0';
- id = rb_intern(buf);
- if (id > LAST_TOKEN && !is_attrset_id(id)) {
- id = rb_id_attrset(id);
- goto id_regist;
- }
- id = ID_ATTRSET;
- }
- else if (ISUPPER(name[0])) {
- id = ID_CONST;
- }
- else {
- id = ID_LOCAL;
- }
- break;
- }
- while (*m && is_identchar(*m)) {
- m++;
- }
- if (*m) id = ID_JUNK;
- id |= ++last_id << ID_SCOPE_SHIFT;
- id_regist:
- name = strdup(name);
- st_add_direct(sym_tbl, name, id);
- st_add_direct(sym_rev_tbl, id, name);
- return id;
-}
-
-char *
-rb_id2name(id)
- ID id;
-{
- char *name;
-
- if (id < LAST_TOKEN) {
- int i = 0;
-
- for (i=0; op_tbl[i].token; i++) {
- if (op_tbl[i].token == id)
- return op_tbl[i].name;
- }
- }
-
- if (st_lookup(sym_rev_tbl, id, &name))
- return name;
-
- if (is_attrset_id(id)) {
- ID id2 = (id & ~ID_SCOPE_MASK) | ID_LOCAL;
-
- again:
- name = rb_id2name(id2);
- if (name) {
- char *buf = ALLOCA_N(char, strlen(name)+2);
-
- strcpy(buf, name);
- strcat(buf, "=");
- rb_intern(buf);
- return rb_id2name(id);
- }
- if (is_local_id(id2)) {
- id2 = (id & ~ID_SCOPE_MASK) | ID_CONST;
- goto again;
- }
- }
- return 0;
-}
-
-static int
-symbols_i(key, value, ary)
- char *key;
- ID value;
- VALUE ary;
-{
- rb_ary_push(ary, ID2SYM(value));
- return ST_CONTINUE;
-}
-
-VALUE
-rb_sym_all_symbols()
-{
- VALUE ary = rb_ary_new2(sym_tbl->num_entries);
-
- st_foreach(sym_tbl, symbols_i, ary);
- return ary;
-}
-
-int
-rb_is_const_id(id)
- ID id;
-{
- if (is_const_id(id)) return Qtrue;
- return Qfalse;
-}
-
-int
-rb_is_class_id(id)
- ID id;
-{
- if (is_class_id(id)) return Qtrue;
- return Qfalse;
-}
-
-int
-rb_is_instance_id(id)
- ID id;
-{
- if (is_instance_id(id)) return Qtrue;
- return Qfalse;
-}
-
-int
-rb_is_local_id(id)
- ID id;
-{
- if (is_local_id(id)) return Qtrue;
- return Qfalse;
-}
-
-static void
-special_local_set(c, val)
- char c;
- VALUE val;
-{
- int cnt;
-
- top_local_init();
- cnt = local_cnt(c);
- top_local_setup();
- ruby_scope->local_vars[cnt] = val;
-}
-
-VALUE *rb_svar _((int cnt));
-
-VALUE
-rb_backref_get()
-{
- VALUE *var = rb_svar(1);
- if (var) {
- return *var;
- }
- return Qnil;
-}
-
-void
-rb_backref_set(val)
- VALUE val;
-{
- VALUE *var = rb_svar(1);
- if (var) {
- *var = val;
- }
- else {
- special_local_set('~', val);
- }
-}
-
-VALUE
-rb_lastline_get()
-{
- VALUE *var = rb_svar(0);
- if (var) {
- return *var;
- }
- return Qnil;
-}
-
-void
-rb_lastline_set(val)
- VALUE val;
-{
- VALUE *var = rb_svar(0);
- if (var) {
- *var = val;
- }
- else {
- special_local_set('_', val);
- }
-}
diff --git a/prec.c b/prec.c
deleted file mode 100644
index 436b4d5bbc..0000000000
--- a/prec.c
+++ /dev/null
@@ -1,81 +0,0 @@
-/**********************************************************************
-
- prec.c -
-
- $Author$
- $Date$
- created at: Tue Jan 26 02:40:41 2000
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
-
-**********************************************************************/
-
-#include "ruby.h"
-
-VALUE rb_mPrecision;
-
-static ID prc_pr, prc_if;
-
-static VALUE
-prec_prec(x, klass)
- VALUE x, klass;
-{
- return rb_funcall(klass, prc_if, 1, x);
-}
-
-static VALUE
-prec_prec_i(x)
- VALUE x;
-{
- VALUE klass = rb_cInteger;
-
- return rb_funcall(x, prc_pr, 1, klass);
-}
-
-static VALUE
-prec_prec_f(x)
- VALUE x;
-{
- VALUE klass = rb_cFloat;
-
- return rb_funcall(x, prc_pr, 1, klass);
-}
-
-static VALUE
-prec_induced_from(module, x)
- VALUE module, x;
-{
- rb_raise(rb_eTypeError, "undefined conversion from %s into %s",
- rb_class2name(CLASS_OF(x)), rb_class2name(module));
- return Qnil; /* not reached */
-}
-
-static VALUE
-prec_included(module, include)
- VALUE module, include;
-{
- switch (TYPE(include)) {
- case T_CLASS:
- case T_MODULE:
- break;
- default:
- Check_Type(include, T_CLASS);
- break;
- }
- rb_define_singleton_method(include, "induced_from", prec_induced_from, 1);
- return module;
-}
-
-
-void
-Init_Precision()
-{
- rb_mPrecision = rb_define_module("Precision");
- rb_define_singleton_method(rb_mPrecision, "included", prec_included, 1);
- rb_define_method(rb_mPrecision, "prec", prec_prec, 1);
- rb_define_method(rb_mPrecision, "prec_i", prec_prec_i, 0);
- rb_define_method(rb_mPrecision, "prec_f", prec_prec_f, 0);
-
- prc_pr = rb_intern("prec");
- prc_if = rb_intern("induced_from");
-}
diff --git a/process.c b/process.c
deleted file mode 100644
index 4763a87631..0000000000
--- a/process.c
+++ /dev/null
@@ -1,1356 +0,0 @@
-/**********************************************************************
-
- process.c -
-
- $Author$
- $Date$
- created at: Tue Aug 10 14:30:50 JST 1993
-
- Copyright (C) 1993-2002 Yukihiro Matsumoto
- Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
- Copyright (C) 2000 Information-technology Promotion Agency, Japan
-
-**********************************************************************/
-
-#include "ruby.h"
-#include "rubysig.h"
-#include <stdio.h>
-#include <errno.h>
-#include <signal.h>
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-
-#include <time.h>
-#ifndef NT
-#ifdef HAVE_SYS_TIME_H
-# include <sys/time.h>
-#else
-struct timeval {
- long tv_sec; /* seconds */
- long tv_usec; /* and microseconds */
-};
-#endif
-#endif /* NT */
-#include <ctype.h>
-
-struct timeval rb_time_interval _((VALUE));
-
-#ifdef HAVE_SYS_WAIT_H
-# include <sys/wait.h>
-#endif
-#ifdef HAVE_GETPRIORITY
-# include <sys/resource.h>
-#endif
-#include "st.h"
-
-#ifdef __EMX__
-#undef HAVE_GETPGRP
-#endif
-
-#ifdef HAVE_SYS_TIMES_H
-#include <sys/times.h>
-#endif
-
-#if defined(HAVE_TIMES) || defined(NT)
-static VALUE S_Tms;
-#endif
-
-#ifndef WIFEXITED
-#define WIFEXITED(w) (((w) & 0xff) == 0)
-#endif
-#ifndef WIFSIGNALED
-#define WIFSIGNALED(w) (((w) & 0x7f) > 0 && (((w) & 0x7f) < 0x7f))
-#endif
-#ifndef WIFSTOPPED
-#define WIFSTOPPED(w) (((w) & 0xff) == 0x7f)
-#endif
-#ifndef WEXITSTATUS
-#define WEXITSTATUS(w) (((w) >> 8) & 0xff)
-#endif
-#ifndef WTERMSIG
-#define WTERMSIG(w) ((w) & 0x7f)
-#endif
-#ifndef WSTOPSIG
-#define WSTOPSIG WEXITSTATUS
-#endif
-
-static VALUE
-get_pid()
-{
- return INT2FIX(getpid());
-}
-
-static VALUE
-get_ppid()
-{
-#ifdef NT
- return INT2FIX(0);
-#else
- return INT2FIX(getppid());
-#endif
-}
-
-static VALUE rb_cProcStatus;
-VALUE rb_last_status = Qnil;
-
-static void
-last_status_set(status)
- int status;
-{
- rb_last_status = rb_obj_alloc(rb_cProcStatus);
- rb_iv_set(rb_last_status, "status", INT2FIX(status));
-}
-
-static VALUE
-pst_to_i(st)
- VALUE st;
-{
- return rb_iv_get(st, "status");
-}
-
-static VALUE
-pst_to_s(st)
- VALUE st;
-{
- return rb_fix2str(pst_to_i(st), 10);
-}
-
-static VALUE
-pst_equal(st1, st2)
- VALUE st1, st2;
-{
- if (st1 == st2) return Qtrue;
- return rb_equal(pst_to_i(st1), st2);
-}
-
-static VALUE
-pst_bitand(st1, st2)
- VALUE st1, st2;
-{
- int status = NUM2INT(st1) & NUM2INT(st2);
-
- return INT2NUM(status);
-}
-
-static VALUE
-pst_rshift(st1, st2)
- VALUE st1, st2;
-{
- int status = NUM2INT(st1) >> NUM2INT(st2);
-
- return INT2NUM(status);
-}
-
-static VALUE
-pst_wifstopped(st)
- VALUE st;
-{
- int status = NUM2INT(st);
-
- if (WIFSTOPPED(status))
- return Qtrue;
- else
- return Qfalse;
-}
-
-static VALUE
-pst_wstopsig(st)
- VALUE st;
-{
- int status = NUM2INT(st);
-
- if (WIFSTOPPED(status))
- return INT2NUM(WSTOPSIG(status));
- return Qnil;
-}
-
-static VALUE
-pst_wifsignaled(st)
- VALUE st;
-{
- int status = NUM2INT(st);
-
- if (WIFSIGNALED(status))
- return Qtrue;
- else
- return Qfalse;
-}
-
-static VALUE
-pst_wtermsig(st)
- VALUE st;
-{
- int status = NUM2INT(st);
-
- if (WIFSIGNALED(status))
- return INT2NUM(WTERMSIG(status));
- return Qnil;
-}
-
-static VALUE
-pst_wifexited(st)
- VALUE st;
-{
- int status = NUM2INT(st);
-
- if (WIFEXITED(status))
- return Qtrue;
- else
- return Qfalse;
-}
-
-static VALUE
-pst_wexitstatus(st)
- VALUE st;
-{
- int status = NUM2INT(st);
-
- if (WIFEXITED(status))
- return INT2NUM(WEXITSTATUS(status));
- return Qnil;
-}
-
-static VALUE
-pst_wcoredump(st)
- VALUE st;
-{
-#ifdef WCOREDUMP
- int status = NUM2INT(st);
-
- if (WCOREDUMP(status))
- return Qtrue;
- else
- return Qfalse;
-#else
- return Qfalse;
-#endif
-}
-
-#if !defined(HAVE_WAITPID) && !defined(HAVE_WAIT4)
-#define NO_WAITPID
-static st_table *pid_tbl;
-#endif
-
-int
-rb_waitpid(pid, st, flags)
- int pid;
- int *st;
- int flags;
-{
- int result;
-#ifndef NO_WAITPID
- int oflags = flags;
- if (!rb_thread_alone()) { /* there're other threads to run */
- flags |= WNOHANG;
- }
-
- retry:
- TRAP_BEG;
-#ifdef HAVE_WAITPID
- result = waitpid(pid, st, flags);
-#else /* HAVE_WAIT4 */
- result = wait4(pid, st, flags, NULL);
-#endif
- TRAP_END;
- if (result < 0) {
- if (errno == EINTR) {
- rb_thread_polling();
- goto retry;
- }
- return -1;
- }
- if (result == 0) {
- if (oflags & WNOHANG) return 0;
- rb_thread_polling();
- if (rb_thread_alone()) flags = oflags;
- goto retry;
- }
-#else /* NO_WAITPID */
- if (pid_tbl && st_lookup(pid_tbl, pid, st)) {
- last_status_set(*st);
- st_delete(pid_tbl, &pid, NULL);
- return pid;
- }
-
- if (flags) {
- rb_raise(rb_eArgError, "can't do waitpid with flags");
- }
-
- for (;;) {
- TRAP_BEG;
- result = wait(st);
- TRAP_END;
- if (result < 0) {
- if (errno == EINTR) {
- rb_thread_schedule();
- continue;
- }
- return -1;
- }
- if (result == pid) {
- break;
- }
- if (!pid_tbl)
- pid_tbl = st_init_numtable();
- st_insert(pid_tbl, pid, st);
- if (!rb_thread_alone()) rb_thread_schedule();
- }
-#endif
- last_status_set(*st);
- return result;
-}
-
-#ifdef NO_WAITPID
-struct wait_data {
- int pid;
- int status;
-};
-
-static int
-wait_each(key, value, data)
- int key, value;
- struct wait_data *data;
-{
- if (data->status != -1) return ST_STOP;
-
- data->pid = key;
- data->status = value;
- return ST_DELETE;
-}
-
-static int
-waitall_each(key, value, data)
- int key, value;
- VALUE data;
-{
- last_status_set(value);
- rb_ary_push(data, rb_assoc_new(INT2NUM(key), rb_last_status));
- return ST_DELETE;
-}
-#endif
-
-static VALUE
-proc_wait(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE vpid, vflags;
- int pid, flags, status;
-
- flags = 0;
- rb_scan_args(argc, argv, "02", &vpid, &vflags);
- if (argc == 0) {
- pid = -1;
- }
- else {
- pid = NUM2INT(vpid);
- if (argc == 2 && !NIL_P(vflags)) {
- flags = NUM2UINT(vflags);
- }
- }
- if ((pid = rb_waitpid(pid, &status, flags)) < 0)
- rb_sys_fail(0);
- if (pid == 0) {
- rb_last_status = Qnil;
- return Qnil;
- }
- return INT2FIX(pid);
-}
-
-static VALUE
-proc_wait2(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE pid = proc_wait(argc, argv);
- if (NIL_P(pid)) return Qnil;
- return rb_assoc_new(pid, rb_last_status);
-}
-
-static VALUE
-proc_waitall()
-{
- VALUE result;
- int pid, status;
-
- result = rb_ary_new();
-#ifdef NO_WAITPID
- if (pid_tbl) {
- st_foreach(pid_tbl, waitall_each, result);
- }
-
- for (pid = -1;;) {
- pid = wait(&status);
- if (pid == -1) {
- if (errno == ECHILD)
- break;
- if (errno == EINTR) {
- rb_thread_schedule();
- continue;
- }
- rb_sys_fail(0);
- }
- last_status_set(status);
- rb_ary_push(result, rb_assoc_new(INT2NUM(pid), rb_last_status));
- }
-#else
- rb_last_status = Qnil;
- for (pid = -1;;) {
- pid = rb_waitpid(-1, &status, 0);
- if (pid == -1) {
- if (errno == ECHILD)
- break;
- rb_sys_fail(0);
- }
- rb_ary_push(result, rb_assoc_new(INT2NUM(pid), rb_last_status));
- }
-#endif
- return result;
-}
-
-#ifndef HAVE_STRING_H
-char *strtok();
-#endif
-
-#ifdef HAVE_SETITIMER
-#define before_exec() rb_thread_stop_timer()
-#define after_exec() rb_thread_start_timer()
-#else
-#define before_exec()
-#define after_exec()
-#endif
-
-extern char *dln_find_exe();
-
-static void
-security(str)
- char *str;
-{
- if (rb_env_path_tainted()) {
- if (rb_safe_level() > 0) {
- rb_raise(rb_eSecurityError, "Insecure PATH - %s", str);
- }
- }
-}
-
-static int
-proc_exec_v(argv, prog)
- char **argv;
- char *prog;
-{
- if (prog) {
- security(prog);
- }
- else {
- security(argv[0]);
- prog = dln_find_exe(argv[0], 0);
- if (!prog) {
- errno = ENOENT;
- return -1;
- }
- }
-#if (defined(MSDOS) && !defined(DJGPP)) || defined(__human68k__) || defined(__EMX__) || defined(OS2)
- {
-#if defined(__human68k__)
-#define COMMAND "command.x"
-#endif
-#if defined(__EMX__) || defined(OS2) /* OS/2 emx */
-#define COMMAND "cmd.exe"
-#endif
-#if (defined(MSDOS) && !defined(DJGPP))
-#define COMMAND "command.com"
-#endif
- char *extension;
-
- if ((extension = strrchr(prog, '.')) != NULL && strcasecmp(extension, ".bat") == 0) {
- char **new_argv;
- char *p;
- int n;
-
- for (n = 0; argv[n]; n++)
- /* no-op */;
- new_argv = ALLOCA_N(char*, n + 2);
- for (; n > 0; n--)
- new_argv[n + 1] = argv[n];
- new_argv[1] = strcpy(ALLOCA_N(char, strlen(argv[0]) + 1), argv[0]);
- for (p = new_argv[1]; *p != '\0'; p++)
- if (*p == '/')
- *p = '\\';
- new_argv[0] = COMMAND;
- argv = new_argv;
- prog = dln_find_exe(argv[0], 0);
- if (!prog) {
- errno = ENOENT;
- return -1;
- }
- }
- }
-#endif /* MSDOS or __human68k__ or __EMX__ */
- before_exec();
- execv(prog, argv);
- after_exec();
- return -1;
-}
-
-static int
-proc_exec_n(argc, argv, progv)
- int argc;
- VALUE *argv;
- VALUE progv;
-{
- char *prog = 0;
- char **args;
- int i;
-
- if (progv) {
- prog = RSTRING(progv)->ptr;
- }
- args = ALLOCA_N(char*, argc+1);
- for (i=0; i<argc; i++) {
- SafeStringValue(argv[i]);
- args[i] = RSTRING(argv[i])->ptr;
- }
- args[i] = 0;
- if (args[0]) {
- return proc_exec_v(args, prog);
- }
- return -1;
-}
-
-int
-rb_proc_exec(str)
- const char *str;
-{
- const char *s = str;
- char *ss, *t;
- char **argv, **a;
-
- while (*str && ISSPACE(*str))
- str++;
-
- for (s=str; *s; s++) {
- if (*s != ' ' && !ISALPHA(*s) && strchr("*?{}[]<>()~&|\\$;'`\"\n",*s)) {
-#if defined(MSDOS)
- int status;
- before_exec();
- status = system(str);
- after_exec();
- if (status != -1)
- exit(status);
-#else
-#if defined(__human68k__) || defined(__CYGWIN32__) || defined(__EMX__)
- char *shell = dln_find_exe("sh", 0);
- int status = -1;
- before_exec();
- if (shell)
- execl(shell, "sh", "-c", str, (char *) NULL);
- else
- status = system(str);
- after_exec();
- if (status != -1)
- exit(status);
-#else
- before_exec();
- execl("/bin/sh", "sh", "-c", str, (char *)NULL);
- after_exec();
-#endif
-#endif
- return -1;
- }
- }
- a = argv = ALLOCA_N(char*, (s-str)/2+2);
- ss = ALLOCA_N(char, s-str+1);
- strcpy(ss, str);
- if (*a++ = strtok(ss, " \t")) {
- while (t = strtok(NULL, " \t")) {
- *a++ = t;
- }
- *a = NULL;
- }
- if (argv[0]) {
- return proc_exec_v(argv, 0);
- }
- errno = ENOENT;
- return -1;
-}
-
-#if defined(__human68k__)
-static int
-proc_spawn_v(argv, prog)
- char **argv;
- char *prog;
-{
- char *extension;
- int status;
-
- if (prog) {
- security(prog);
- }
- else {
- security(argv[0]);
- prog = dln_find_exe(argv[0], 0);
- if (!prog)
- return -1;
- }
-
- if ((extension = strrchr(prog, '.')) != NULL && strcasecmp(extension, ".bat") == 0) {
- char **new_argv;
- char *p;
- int n;
-
- for (n = 0; argv[n]; n++)
- /* no-op */;
- new_argv = ALLOCA_N(char*, n + 2);
- for (; n > 0; n--)
- new_argv[n + 1] = argv[n];
- new_argv[1] = strcpy(ALLOCA_N(char, strlen(argv[0]) + 1), argv[0]);
- for (p = new_argv[1]; *p != '\0'; p++)
- if (*p == '/')
- *p = '\\';
- new_argv[0] = COMMAND;
- argv = new_argv;
- prog = dln_find_exe(argv[0], 0);
- if (!prog) {
- errno = ENOENT;
- return -1;
- }
- }
- before_exec();
- status = spawnv(P_WAIT, prog, argv);
- after_exec();
- return status;
-}
-
-static int
-proc_spawn_n(argc, argv, prog)
- int argc;
- VALUE *argv;
- VALUE prog;
-{
- char **args;
- int i;
-
- args = ALLOCA_N(char*, argc + 1);
- for (i = 0; i < argc; i++) {
- SafeStr(argv[i]);
- args[i] = RSTRING(argv[i])->ptr;
- }
- SafeStringValue(prog);
- args[i] = (char*) 0;
- if (args[0])
- return proc_spawn_v(args, RSTRING(prog)->ptr);
- return -1;
-}
-
-static int
-proc_spawn(sv)
- VALUE sv;
-{
- char *str;
- char *s, *t;
- char **argv, **a;
- int status;
-
- SafeStringValue(sv);
- str = s = RSTRING(sv)->ptr;
- for (s = str; *s; s++) {
- if (*s != ' ' && !ISALPHA(*s) && strchr("*?{}[]<>()~&|\\$;'`\"\n",*s)) {
- char *shell = dln_find_exe("sh", 0);
- before_exec();
- status = shell?spawnl(P_WAIT,shell,"sh","-c",str,(char*)NULL):system(str);
- after_exec();
- return status;
- }
- }
- a = argv = ALLOCA_N(char*, (s - str) / 2 + 2);
- s = ALLOCA_N(char, s - str + 1);
- strcpy(s, str);
- if (*a++ = strtok(s, " \t")) {
- while (t = strtok(NULL, " \t"))
- *a++ = t;
- *a = NULL;
- }
- return argv[0] ? proc_spawn_v(argv, 0) : -1;
-}
-#endif /* __human68k__ */
-
-VALUE
-rb_f_exec(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE prog = 0;
-
- if (argc == 0) {
- rb_raise(rb_eArgError, "wrong number of arguments");
- }
-
- if (TYPE(argv[0]) == T_ARRAY) {
- if (RARRAY(argv[0])->len != 2) {
- rb_raise(rb_eArgError, "wrong first argument");
- }
- prog = RARRAY(argv[0])->ptr[0];
- argv[0] = RARRAY(argv[0])->ptr[1];
- }
- if (prog) {
- SafeStringValue(prog);
- }
- if (argc == 1 && prog == 0) {
- VALUE cmd = argv[0];
-
- SafeStringValue(cmd);
- rb_proc_exec(RSTRING(cmd)->ptr);
- }
- else {
- proc_exec_n(argc, argv, prog);
- }
- rb_sys_fail(RSTRING(argv[0])->ptr);
- return Qnil; /* dummy */
-}
-
-static VALUE
-rb_f_fork(obj)
- VALUE obj;
-{
-#if !defined(__human68k__) && !defined(NT) && !defined(__MACOS__) && !defined(__EMX__)
- int pid;
-
- rb_secure(2);
- switch (pid = fork()) {
- case 0:
-#ifdef linux
- after_exec();
-#endif
- rb_thread_atfork();
- if (rb_block_given_p()) {
- int status;
-
- rb_protect(rb_yield, Qnil, &status);
- ruby_stop(status);
- }
- return Qnil;
-
- case -1:
- rb_sys_fail("fork(2)");
- return Qnil;
-
- default:
- return INT2FIX(pid);
- }
-#else
- rb_notimplement();
-#endif
-}
-
-static VALUE
-rb_f_exit_bang(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- VALUE status;
- int istatus;
-
- rb_secure(4);
- if (rb_scan_args(argc, argv, "01", &status) == 1) {
- istatus = NUM2INT(status);
- }
- else {
- istatus = -1;
- }
- _exit(istatus);
-
- return Qnil; /* not reached */
-}
-
-void
-rb_syswait(pid)
- int pid;
-{
- static int overriding;
- RETSIGTYPE (*hfunc)_((int)), (*qfunc)_((int)), (*ifunc)_((int));
- int status;
- int i, hooked = Qfalse;
-
- if (!overriding) {
-#ifdef SIGHUP
- hfunc = signal(SIGHUP, SIG_IGN);
-#endif
-#ifdef SIGQUIT
- qfunc = signal(SIGQUIT, SIG_IGN);
-#endif
- ifunc = signal(SIGINT, SIG_IGN);
- overriding = Qtrue;
- hooked = Qtrue;
- }
-
- do {
- i = rb_waitpid(pid, &status, 0);
- } while (i == -1 && errno == EINTR);
-
- if (hooked) {
-#ifdef SIGHUP
- signal(SIGHUP, hfunc);
-#endif
-#ifdef SIGQUIT
- signal(SIGQUIT, qfunc);
-#endif
- signal(SIGINT, ifunc);
- overriding = Qfalse;
- }
-}
-
-static VALUE
-rb_f_system(argc, argv)
- int argc;
- VALUE *argv;
-{
-#if defined(NT) || defined(__EMX__)
- VALUE cmd;
- int status;
-
- fflush(stdout);
- fflush(stderr);
- if (argc == 0) {
- rb_last_status = Qnil;
- rb_raise(rb_eArgError, "wrong number of arguments");
- }
-
- if (TYPE(argv[0]) == T_ARRAY) {
- if (RARRAY(argv[0])->len != 2) {
- rb_raise(rb_eArgError, "wrong first argument");
- }
- argv[0] = RARRAY(argv[0])->ptr[0];
- }
- cmd = rb_ary_join(rb_ary_new4(argc, argv), rb_str_new2(" "));
-
- SafeStringValue(cmd);
- status = do_spawn(RSTRING(cmd)->ptr);
- last_status_set(status);
-
- if (status == 0) return Qtrue;
- return Qfalse;
-#else
-#ifdef DJGPP
- VALUE cmd;
- int status;
-
- if (argc == 0) {
- rb_last_status = Qnil;
- rb_raise(rb_eArgError, "wrong number of arguments");
- }
-
- if (TYPE(argv[0]) == T_ARRAY) {
- if (RARRAY(argv[0])->len != 2) {
- rb_raise(rb_eArgError, "wrong first argument");
- }
- argv[0] = RARRAY(argv[0])->ptr[0];
- }
- cmd = rb_ary_join(rb_ary_new4(argc, argv), rb_str_new2(" "));
-
- SafeStringValue(cmd);
- status = system(RSTRING(cmd)->ptr);
- last_status_set((status & 0xff) << 8);
-
- if (status == 0) return Qtrue;
- return Qfalse;
-#else
-#if defined(__human68k__)
- VALUE prog = 0;
- int i;
- int status;
-
- fflush(stdin);
- fflush(stdout);
- fflush(stderr);
- if (argc == 0) {
- rb_last_status = Qnil;
- rb_raise(rb_eArgError, "wrong number of arguments");
- }
-
- if (TYPE(argv[0]) == T_ARRAY) {
- if (RARRAY(argv[0])->len != 2) {
- rb_raise(rb_eArgError, "wrong first argument");
- }
- prog = RARRAY(argv[0])->ptr[0];
- argv[0] = RARRAY(argv[0])->ptr[1];
- }
-
- if (argc == 1 && prog == 0) {
- status = proc_spawn(argv[0]);
- }
- else {
- status = proc_spawn_n(argc, argv, prog);
- }
- last_status_set(status == -1 ? 127 : status);
- return status == 0 ? Qtrue : Qfalse;
-#else
- volatile VALUE prog = 0;
- int pid;
- int i;
-
- fflush(stdout);
- fflush(stderr);
- if (argc == 0) {
- rb_last_status = Qnil;
- rb_raise(rb_eArgError, "wrong number of arguments");
- }
-
- if (TYPE(argv[0]) == T_ARRAY) {
- if (RARRAY(argv[0])->len != 2) {
- rb_raise(rb_eArgError, "wrong first argument");
- }
- prog = RARRAY(argv[0])->ptr[0];
- argv[0] = RARRAY(argv[0])->ptr[1];
- }
-
- if (prog) {
- SafeStringValue(prog);
- }
- for (i = 0; i < argc; i++) {
- SafeStringValue(argv[i]);
- }
- retry:
- switch (pid = fork()) {
- case 0:
- if (argc == 1 && prog == 0) {
- rb_proc_exec(RSTRING(argv[0])->ptr);
- }
- else {
- proc_exec_n(argc, argv, prog);
- }
- _exit(127);
- break; /* not reached */
-
- case -1:
- if (errno == EAGAIN) {
- rb_thread_sleep(1);
- goto retry;
- }
- rb_sys_fail(0);
- break;
-
- default:
- rb_syswait(pid);
- }
-
- if (NUM2INT(rb_last_status) == 0)
- return Qtrue;
- return Qfalse;
-#endif /* __human68k__ */
-#endif /* DJGPP */
-#endif /* NT */
-}
-
-static VALUE
-rb_f_sleep(argc, argv)
- int argc;
- VALUE *argv;
-{
- int beg, end;
-
- beg = time(0);
- if (argc == 0) {
- rb_thread_sleep_forever();
- }
- else if (argc == 1) {
- rb_thread_wait_for(rb_time_interval(argv[0]));
- }
- else {
- rb_raise(rb_eArgError, "wrong number of arguments");
- }
-
- end = time(0) - beg;
-
- return INT2FIX(end);
-}
-
-static VALUE
-proc_getpgrp()
-{
- int pgrp;
-
-#if defined(HAVE_GETPGRP) && defined(GETPGRP_VOID)
- pgrp = getpgrp();
- if (pgrp < 0) rb_sys_fail(0);
- return INT2FIX(pgrp);
-#else
-# ifdef HAVE_GETPGID
- pgrp = getpgid(0);
- if (pgrp < 0) rb_sys_fail(0);
- return INT2FIX(pgrp);
-# else
- rb_notimplement();
-# endif
-#endif
-}
-
-static VALUE
-proc_setpgrp()
-{
-#if defined(HAVE_SETPGRP) && defined(SETPGRP_VOID)
- if (setpgrp() < 0) rb_sys_fail(0);
-#else
-# ifdef HAVE_SETPGID
- if (setpgid(0, 0) < 0) rb_sys_fail(0);
-# else
- rb_notimplement();
-# endif
-#endif
- return INT2FIX(0);
-}
-
-static VALUE
-proc_getpgid(obj, pid)
- VALUE obj, pid;
-{
-#if defined(HAVE_GETPGID) && !defined(__CHECKER__)
- int i;
-
- i = getpgid(NUM2INT(pid));
- if (i < 0) rb_sys_fail(0);
- return INT2NUM(i);
-#else
- rb_notimplement();
-#endif
-}
-
-static VALUE
-proc_setpgid(obj, pid, pgrp)
- VALUE obj, pid, pgrp;
-{
-#ifdef HAVE_SETPGID
- int ipid, ipgrp;
-
- rb_secure(2);
- ipid = NUM2INT(pid);
- ipgrp = NUM2INT(pgrp);
-
- if (setpgid(ipid, ipgrp) < 0) rb_sys_fail(0);
- return INT2FIX(0);
-#else
- rb_notimplement();
-#endif
-}
-
-static VALUE
-proc_setsid()
-{
-#if defined(HAVE_SETSID)
- int pid;
-
- rb_secure(2);
- pid = setsid();
- if (pid < 0) rb_sys_fail(0);
- return INT2FIX(pid);
-#elif defined(HAVE_SETPGRP) && defined(TIOCNOTTY)
- pid_t pid;
- int ret;
-
- rb_secure(2);
- pid = getpid();
-#if defined(SETPGRP_VOID)
- ret = setpgrp();
- /* If `pid_t setpgrp(void)' is equivalent to setsid(),
- `ret' will be the same value as `pid', and following open() will fail.
- In Linux, `int setpgrp(void)' is equivalent to setpgid(0, 0). */
-#else
- ret = setpgrp(0, pid);
-#endif
- if (ret == -1) rb_sys_fail(0);
-
- if ((fd = open("/dev/tty", O_RDWR)) >= 0) {
- ioctl(fd, TIOCNOTTY, NULL);
- close(fd);
- }
- return INT2FIX(pid);
-#else
- rb_notimplement();
-#endif
-}
-
-static VALUE
-proc_getpriority(obj, which, who)
- VALUE obj, which, who;
-{
-#ifdef HAVE_GETPRIORITY
- int prio, iwhich, iwho;
-
- iwhich = NUM2INT(which);
- iwho = NUM2INT(who);
-
- errno = 0;
- prio = getpriority(iwhich, iwho);
- if (errno) rb_sys_fail(0);
- return INT2FIX(prio);
-#else
- rb_notimplement();
-#endif
-}
-
-static VALUE
-proc_setpriority(obj, which, who, prio)
- VALUE obj, which, who, prio;
-{
-#ifdef HAVE_GETPRIORITY
- int iwhich, iwho, iprio;
-
- rb_secure(2);
- iwhich = NUM2INT(which);
- iwho = NUM2INT(who);
- iprio = NUM2INT(prio);
-
- if (setpriority(iwhich, iwho, iprio) < 0)
- rb_sys_fail(0);
- return INT2FIX(0);
-#else
- rb_notimplement();
-#endif
-}
-
-static VALUE
-proc_getuid(obj)
- VALUE obj;
-{
- int uid = getuid();
- return INT2FIX(uid);
-}
-
-static VALUE
-proc_setuid(obj, id)
- VALUE obj, id;
-{
- int uid;
-
- uid = NUM2INT(id);
-#if defined(HAVE_SETRESUID) && !defined(__CHECKER__)
- if (setresuid(uid, -1, -1) < 0) rb_sys_fail(0);
-#elif defined HAVE_SETREUID
- if (setreuid(uid, -1) < 0) rb_sys_fail(0);
-#elif defined HAVE_SETRUID
- if (setruid(uid) < 0) rb_sys_fail(0);
-#else
- {
- if (geteuid() == uid) {
- if (setuid(uid) < 0) rb_sys_fail(0);
- }
- else {
- rb_notimplement();
- }
- }
-#endif
- return INT2FIX(uid);
-}
-
-static VALUE
-proc_getgid(obj)
- VALUE obj;
-{
- int gid = getgid();
- return INT2FIX(gid);
-}
-
-static VALUE
-proc_setgid(obj, id)
- VALUE obj, id;
-{
- int gid;
-
- gid = NUM2INT(id);
-#if defined(HAVE_SETRESGID) && !defined(__CHECKER__)
- if (setresgid(gid, -1, -1) < 0) rb_sys_fail(0);
-#elif defined HAVE_SETREGID
- if (setregid(gid, -1) < 0) rb_sys_fail(0);
-#elif defined HAS_SETRGID
- if (setrgid((GIDTYPE)gid) < 0) rb_sys_fail(0);
-#else
- {
- if (getegid() == gid) {
- if (setgid(gid) < 0) rb_sys_fail(0);
- }
- else {
- rb_notimplement();
- }
- }
-#endif
- return INT2FIX(gid);
-}
-
-static VALUE
-proc_geteuid(obj)
- VALUE obj;
-{
- int euid = geteuid();
- return INT2FIX(euid);
-}
-
-static VALUE
-proc_seteuid(obj, euid)
- VALUE obj, euid;
-{
-#if defined(HAVE_SETRESUID) && !defined(__CHECKER__)
- if (setresuid(-1, NUM2INT(euid), -1) < 0) rb_sys_fail(0);
-#elif defined HAVE_SETREUID
- if (setreuid(-1, NUM2INT(euid)) < 0) rb_sys_fail(0);
-#elif defined HAVE_SETEUID
- if (seteuid(NUM2INT(euid)) < 0) rb_sys_fail(0);
-#else
- euid = NUM2INT(euid);
- if (euid == getuid()) {
- if (setuid(euid) < 0) rb_sys_fail(0);
- }
- else {
- rb_notimplement();
- }
-#endif
- return euid;
-}
-
-static VALUE
-proc_getegid(obj)
- VALUE obj;
-{
- int egid = getegid();
- return INT2FIX(egid);
-}
-
-static VALUE
-proc_setegid(obj, egid)
- VALUE obj, egid;
-{
- rb_secure(2);
-#if defined(HAVE_SETRESGID) && !defined(__CHECKER__)
- if (setresgid(-1, NUM2INT(egid), -1) < 0) rb_sys_fail(0);
-#elif defined HAVE_SETREGID
- if (setregid(-1, NUM2INT(egid)) < 0) rb_sys_fail(0);
-#elif defined HAVE_SETEGID
- if (setegid(NUM2INT(egid)) < 0) rb_sys_fail(0);
-#else
- egid = NUM2INT(egid);
- if (egid == getgid()) {
- if (setgid(egid) < 0) rb_sys_fail(0);
- }
- else {
- rb_notimplement();
- }
-#endif
- return egid;
-}
-
-VALUE
-rb_proc_times(obj)
- VALUE obj;
-{
-#if defined(HAVE_TIMES) && !defined(__CHECKER__)
-#ifndef HZ
-# ifdef CLK_TCK
-# define HZ CLK_TCK
-# else
-# define HZ 60
-# endif
-#endif /* HZ */
- struct tms buf;
-
- times(&buf);
- return rb_struct_new(S_Tms,
- rb_float_new((double)buf.tms_utime / HZ),
- rb_float_new((double)buf.tms_stime / HZ),
- rb_float_new((double)buf.tms_cutime / HZ),
- rb_float_new((double)buf.tms_cstime / HZ));
-#else
- rb_notimplement();
-#endif
-}
-
-VALUE rb_mProcess;
-
-void
-Init_process()
-{
- rb_define_virtual_variable("$$", get_pid, 0);
- rb_define_readonly_variable("$?", &rb_last_status);
- rb_define_global_function("exec", rb_f_exec, -1);
- rb_define_global_function("fork", rb_f_fork, 0);
- rb_define_global_function("exit!", rb_f_exit_bang, -1);
- rb_define_global_function("system", rb_f_system, -1);
- rb_define_global_function("sleep", rb_f_sleep, -1);
-
- rb_mProcess = rb_define_module("Process");
-
-#if !defined(NT) && !defined(DJGPP)
-#ifdef WNOHANG
- rb_define_const(rb_mProcess, "WNOHANG", INT2FIX(WNOHANG));
-#else
- rb_define_const(rb_mProcess, "WNOHANG", INT2FIX(0));
-#endif
-#ifdef WUNTRACED
- rb_define_const(rb_mProcess, "WUNTRACED", INT2FIX(WUNTRACED));
-#else
- rb_define_const(rb_mProcess, "WUNTRACED", INT2FIX(0));
-#endif
-#endif
-
- rb_define_singleton_method(rb_mProcess, "fork", rb_f_fork, 0);
- rb_define_singleton_method(rb_mProcess, "exit!", rb_f_exit_bang, -1);
-
- rb_define_module_function(rb_mProcess, "kill", rb_f_kill, -1);
- rb_define_module_function(rb_mProcess, "wait", proc_wait, -1);
- rb_define_module_function(rb_mProcess, "wait2", proc_wait2, -1);
- rb_define_module_function(rb_mProcess, "waitpid", proc_wait, -1);
- rb_define_module_function(rb_mProcess, "waitpid2", proc_wait2, -1);
- rb_define_module_function(rb_mProcess, "waitall", proc_waitall, 0);
-
- rb_cProcStatus = rb_define_class_under(rb_mProcess, "Status", rb_cObject);
- rb_undef_method(CLASS_OF(rb_cProcStatus), "new");
-
- rb_define_method(rb_cProcStatus, "==", pst_equal, 1);
- rb_define_method(rb_cProcStatus, "&", pst_bitand, 1);
- rb_define_method(rb_cProcStatus, ">>", pst_rshift, 1);
- rb_define_method(rb_cProcStatus, "to_i", pst_to_i, 0);
- rb_define_method(rb_cProcStatus, "to_int", pst_to_i, 0);
- rb_define_method(rb_cProcStatus, "to_s", pst_to_s, 0);
- rb_define_method(rb_cProcStatus, "inspect", pst_to_s, 0);
-
- rb_define_method(rb_cProcStatus, "stopped?", pst_wifstopped, 0);
- rb_define_method(rb_cProcStatus, "stopsig", pst_wstopsig, 0);
- rb_define_method(rb_cProcStatus, "signaled?", pst_wifsignaled, 0);
- rb_define_method(rb_cProcStatus, "termsig", pst_wtermsig, 0);
- rb_define_method(rb_cProcStatus, "exited?", pst_wifexited, 0);
- rb_define_method(rb_cProcStatus, "exitstatus", pst_wexitstatus, 0);
- rb_define_method(rb_cProcStatus, "coredump?", pst_wcoredump, 0);
-
- rb_define_module_function(rb_mProcess, "pid", get_pid, 0);
- rb_define_module_function(rb_mProcess, "ppid", get_ppid, 0);
-
- rb_define_module_function(rb_mProcess, "getpgrp", proc_getpgrp, 0);
- rb_define_module_function(rb_mProcess, "setpgrp", proc_setpgrp, 0);
- rb_define_module_function(rb_mProcess, "getpgid", proc_getpgid, 1);
- rb_define_module_function(rb_mProcess, "setpgid", proc_setpgid, 2);
-
- rb_define_module_function(rb_mProcess, "setsid", proc_setsid, 0);
-
- rb_define_module_function(rb_mProcess, "getpriority", proc_getpriority, 2);
- rb_define_module_function(rb_mProcess, "setpriority", proc_setpriority, 3);
-
-#ifdef HAVE_GETPRIORITY
- rb_define_const(rb_mProcess, "PRIO_PROCESS", INT2FIX(PRIO_PROCESS));
- rb_define_const(rb_mProcess, "PRIO_PGRP", INT2FIX(PRIO_PGRP));
- rb_define_const(rb_mProcess, "PRIO_USER", INT2FIX(PRIO_USER));
-#endif
-
- rb_define_module_function(rb_mProcess, "uid", proc_getuid, 0);
- rb_define_module_function(rb_mProcess, "uid=", proc_setuid, 1);
- rb_define_module_function(rb_mProcess, "gid", proc_getgid, 0);
- rb_define_module_function(rb_mProcess, "gid=", proc_setgid, 1);
- rb_define_module_function(rb_mProcess, "euid", proc_geteuid, 0);
- rb_define_module_function(rb_mProcess, "euid=", proc_seteuid, 1);
- rb_define_module_function(rb_mProcess, "egid", proc_getegid, 0);
- rb_define_module_function(rb_mProcess, "egid=", proc_setegid, 1);
-
- rb_define_module_function(rb_mProcess, "times", rb_proc_times, 0);
-
-#if defined(HAVE_TIMES) || defined(NT)
- S_Tms = rb_struct_define("Tms", "utime", "stime", "cutime", "cstime", 0);
-#endif
-}
diff --git a/random.c b/random.c
deleted file mode 100644
index e76437285b..0000000000
--- a/random.c
+++ /dev/null
@@ -1,181 +0,0 @@
-/**********************************************************************
-
- random.c -
-
- $Author$
- $Date$
- created at: Fri Dec 24 16:39:21 JST 1993
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
-
-**********************************************************************/
-
-#include "ruby.h"
-
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-#include <time.h>
-#ifndef NT
-#ifdef HAVE_SYS_TIME_H
-# include <sys/time.h>
-#else
-struct timeval {
- long tv_sec; /* seconds */
- long tv_usec; /* and microseconds */
-};
-#endif
-#endif /* NT */
-
-#ifdef HAVE_STDLIB_H
-# include <stdlib.h>
-#endif
-
-/*
- * Prefer to use drand48, otherwise use random, or rand as a last resort.
- */
-#ifdef HAVE_DRAND48
-
-#ifndef HAVE_DRAND48_DECL
-double drand48 _((void));
-void srand48 _((long));
-#endif
-
-#define SRANDOM(s) srand48((long)(s))
-#define RANDOM_NUMBER drand48()
-
-#else /* not HAVE_DRAND48 */
-
-/*
- * The largest number returned by the random number generator is
- * RANDOM_MAX. If we're using `rand' it's RAND_MAX, but if we're
- * using `random' it's 2^31-1.
- */
-#ifndef RANDOM_MAX
-# ifndef HAVE_RANDOM
-# define RANDOM_MAX RAND_MAX
-# else
-# define RANDOM_MAX 2147483647.0
-# endif
-#endif
-
-#ifdef HAVE_RANDOM
-
-#define RANDOM random
-#define SRANDOM srandom
-
-#else /* HAVE_RANDOM */
-
-#define RANDOM rand
-#define SRANDOM srand
-
-#endif /* HAVE_RANDOM */
-
-/* 0 <= RANDOM_NUMBER < 1 */
-#define RANDOM_NUMBER (((double)RANDOM())/((double)RANDOM_MAX+1))
-
-#endif /* not HAVE_DRAND48 */
-
-static int first = 1;
-#ifdef HAVE_RANDOM
-static char state[256];
-#endif
-
-static int
-rand_init(seed)
- long seed;
-{
- int old;
- static unsigned int saved_seed;
-
-#if defined HAVE_RANDOM && !defined __UCLIBC__
- if (first == 1) {
- initstate(1, state, sizeof state);
- }
- else {
- setstate(state);
- }
-#endif
- first = 0;
-
- SRANDOM(seed);
- old = saved_seed;
- saved_seed = seed;
-
- return old;
-}
-
-static VALUE
-rb_f_srand(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- VALUE a;
- unsigned int seed, old;
-
- rb_secure(4);
- if (rb_scan_args(argc, argv, "01", &a) == 0) {
- static int n = 0;
- struct timeval tv;
-
- gettimeofday(&tv, 0);
- seed = tv.tv_sec ^ tv.tv_usec ^ getpid() ^ n++;
- }
- else {
- seed = NUM2UINT(a);
- }
- old = rand_init(seed);
-
- return rb_uint2inum(old);
-}
-
-static VALUE
-rb_f_rand(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- VALUE vmax;
- long val, max;
-
- rb_scan_args(argc, argv, "01", &vmax);
- if (first) {
- struct timeval tv;
-
- gettimeofday(&tv, 0);
- rand_init(tv.tv_sec ^ tv.tv_usec ^ getpid());
- }
- switch (TYPE(vmax)) {
- case T_FLOAT:
- if (RFLOAT(vmax)->value <= LONG_MAX && RFLOAT(vmax)->value >= LONG_MIN) {
- max = (long)RFLOAT(vmax)->value;
- break;
- }
- vmax = rb_dbl2big(RFLOAT(vmax)->value);
- /* fall through */
- case T_BIGNUM:
- return rb_big_rand(vmax, RANDOM_NUMBER);
- case T_NIL:
- max = 0;
- break;
- default:
- max = NUM2LONG(vmax);
- break;
- }
-
- if (max == 0) {
- return rb_float_new(RANDOM_NUMBER);
- }
- val = max*RANDOM_NUMBER;
-
- if (val < 0) val = -val;
- return rb_int2inum(val);
-}
-
-void
-Init_Random()
-{
- rb_define_global_function("srand", rb_f_srand, -1);
- rb_define_global_function("rand", rb_f_rand, -1);
-}
diff --git a/range.c b/range.c
deleted file mode 100644
index 684566e3b5..0000000000
--- a/range.c
+++ /dev/null
@@ -1,583 +0,0 @@
-/**********************************************************************
-
- range.c -
-
- $Author$
- $Date$
- created at: Thu Aug 19 17:46:47 JST 1993
-
- Copyright (C) 1993-2002 Yukihiro Matsumoto
-
-**********************************************************************/
-
-#include "ruby.h"
-
-VALUE rb_cRange;
-static ID id_cmp, id_succ, id_beg, id_end, id_excl;
-
-#define EXCL(r) RTEST(rb_ivar_get((r), id_excl))
-#define SET_EXCL(r,v) rb_ivar_set((r), id_excl, (v)?Qtrue:Qfalse)
-
-static VALUE
-range_check(args)
- VALUE *args;
-{
- rb_funcall(args[0], id_cmp, 1, args[1]);
- if (!FIXNUM_P(args[0]) && !rb_obj_is_kind_of(args[0], rb_cNumeric)) {
- rb_funcall(args[0], id_succ, 0, 0);
- }
- return Qnil;
-}
-
-static VALUE
-range_failed()
-{
- rb_raise(rb_eArgError, "bad value for range");
- return Qnil; /* dummy */
-}
-
-static void
-range_init(obj, beg, end, exclude_end)
- VALUE obj, beg, end;
- int exclude_end;
-{
- VALUE args[2];
-
- args[0] = beg; args[1] = end;
- if (!FIXNUM_P(beg) || !FIXNUM_P(end)) {
- rb_rescue(range_check, (VALUE)args, range_failed, 0);
- }
-
- SET_EXCL(obj, exclude_end);
- rb_ivar_set(obj, id_beg, beg);
- rb_ivar_set(obj, id_end, end);
-}
-
-VALUE
-rb_range_new(beg, end, exclude_end)
- VALUE beg, end;
- int exclude_end;
-{
- VALUE obj = rb_obj_alloc(rb_cRange);
-
- range_init(obj, beg, end, exclude_end);
- return obj;
-}
-
-static VALUE
-range_initialize(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- VALUE beg, end, flags;
-
- rb_scan_args(argc, argv, "21", &beg, &end, &flags);
- /* Ranges are immutable, so that they should be initialized only once. */
- if (rb_ivar_defined(obj, id_beg)) {
- rb_name_error(rb_intern("initialized"), "`initialize' called twice");
- }
- range_init(obj, beg, end, RTEST(flags));
- return Qnil;
-}
-
-static VALUE
-range_exclude_end_p(range)
- VALUE range;
-{
- return EXCL(range)?Qtrue:Qfalse;
-}
-
-static VALUE
-range_eq(range, obj)
- VALUE range, obj;
-{
- if (range == obj) return Qtrue;
- if (!rb_obj_is_kind_of(obj, rb_cRange)) return Qfalse;
-
- if (!rb_equal(rb_ivar_get(range, id_beg), rb_ivar_get(obj, id_beg)))
- return Qfalse;
- if (!rb_equal(rb_ivar_get(range, id_end), rb_ivar_get(obj, id_end)))
- return Qfalse;
-
- if (EXCL(range) != EXCL(obj)) return Qfalse;
-
- return Qtrue;
-}
-
-static int
-r_eq(a, b)
- VALUE a, b;
-{
- VALUE r;
-
- if (a == b) return Qtrue;
-
- if (rb_funcall(a, id_cmp, 1, b) == INT2FIX(0))
- return Qtrue;
- return Qfalse;
-}
-
-static int
-r_lt(a, b)
- VALUE a, b;
-{
- VALUE r = rb_funcall(a, id_cmp, 1, b);
-
- if (rb_cmpint(r) < 0) return Qtrue;
- return Qfalse;
-}
-
-static int
-r_le(a, b)
- VALUE a, b;
-{
- VALUE r = rb_funcall(a, id_cmp, 1, b);
-
- if (rb_cmpint(r) <= 0) return Qtrue;
- return Qfalse;
-}
-
-static int
-r_gt(a,b)
- VALUE a, b;
-{
- VALUE r = rb_funcall(a, id_cmp, 1, b);
-
- if (rb_cmpint(r) > 0) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-r_eqq_str_i(i, data)
- VALUE i;
- VALUE *data;
-{
- if (rb_str_cmp(i, data[0]) == 0) {
- data[1] = Qtrue;
- rb_iter_break();
- }
- return Qnil;
-}
-
-static VALUE
-range_eqq(range, obj)
- VALUE range, obj;
-{
- VALUE beg, end;
-
- beg = rb_ivar_get(range, id_beg);
- end = rb_ivar_get(range, id_end);
-
- if (FIXNUM_P(beg) && FIXNUM_P(obj) && FIXNUM_P(end)) {
- if (FIX2LONG(beg) <= FIX2LONG(obj)) {
- if (EXCL(range)) {
- if (FIX2LONG(obj) < FIX2LONG(end)) return Qtrue;
- }
- else {
- if (FIX2LONG(obj) <= FIX2LONG(end)) return Qtrue;
- }
- }
- return Qfalse;
- }
- else if (TYPE(beg) == T_STRING &&
- TYPE(obj) == T_STRING &&
- TYPE(end) == T_STRING) {
- VALUE data[2];
-
- data[0] = obj; data[1] = Qfalse;
- rb_iterate(rb_each, range, r_eqq_str_i, (VALUE)data);
- return data[1];
- }
- else if (r_le(beg, obj)) {
- if (EXCL(range)) {
- if (r_lt(obj, end)) return Qtrue;
- }
- else {
- if (r_le(obj, end)) return Qtrue;
- }
- }
- return Qfalse;
-}
-
-static VALUE
-range_eql(range, obj)
- VALUE range, obj;
-{
- if (range == obj) return Qtrue;
- if (!rb_obj_is_kind_of(obj, rb_cRange)) return Qfalse;
-
- if (!rb_eql(rb_ivar_get(range, id_beg), rb_ivar_get(obj, id_beg)))
- return Qfalse;
- if (!rb_eql(rb_ivar_get(range, id_end), rb_ivar_get(obj, id_end)))
- return Qfalse;
-
- if (EXCL(range) != EXCL(obj)) return Qfalse;
-
- return Qtrue;
-}
-
-static VALUE
-range_hash(range, obj)
- VALUE range, obj;
-{
- long hash = EXCL(range);
- VALUE v;
-
- v = rb_hash(rb_ivar_get(range, id_beg));
- hash ^= v << 1;
- v = rb_hash(rb_ivar_get(range, id_end));
- hash ^= v << 9;
-
- return INT2FIX(hash);
-}
-
-static VALUE
-range_each(range)
- VALUE range;
-{
- VALUE b, e;
-
- b = rb_ivar_get(range, id_beg);
- e = rb_ivar_get(range, id_end);
-
- if (FIXNUM_P(b) && FIXNUM_P(e)) { /* fixnums are special */
- long end = FIX2LONG(e);
- long i;
-
- if (!EXCL(range)) end += 1;
- for (i=FIX2LONG(b); i<end; i++) {
- rb_yield(INT2NUM(i));
- }
- }
- else if (TYPE(b) == T_STRING) {
- rb_str_upto(b, e, EXCL(range));
- }
- else if (rb_obj_is_kind_of(b, rb_cNumeric)) {
- b = rb_Integer(b);
- e = rb_Integer(e);
-
- if (!EXCL(range)) e = rb_funcall(e, '+', 1, INT2FIX(1));
- while (RTEST(rb_funcall(b, '<', 1, e))) {
- rb_yield(b);
- b = rb_funcall(b, '+', 1, INT2FIX(1));
- }
- }
- else { /* generic each */
- VALUE v = b;
-
- if (EXCL(range)) {
- while (r_lt(v, e)) {
- if (r_eq(v, e)) break;
- rb_yield(v);
- v = rb_funcall(v, id_succ, 0, 0);
- }
- }
- else {
- while (r_le(v, e)) {
- rb_yield(v);
- if (r_eq(v, e)) break;
- v = rb_funcall(v, id_succ, 0, 0);
- }
- }
- }
-
- return range;
-}
-
-static VALUE
-r_step_str(args)
- VALUE *args;
-{
- return rb_str_upto(args[0], args[1], EXCL(args[2]));
-}
-
-static VALUE
-r_step_str_i(i, iter)
- VALUE i;
- long *iter;
-{
- iter[0]--;
- if (iter[0] == 0) {
- rb_yield(i);
- iter[0] = iter[1];
- }
- return Qnil;
-}
-
-static VALUE
-range_step(argc, argv, range)
- int argc;
- VALUE *argv;
- VALUE range;
-{
- VALUE b, e, step;
-
- b = rb_ivar_get(range, id_beg);
- e = rb_ivar_get(range, id_end);
- rb_scan_args(argc, argv, "01", &step);
-
- if (FIXNUM_P(b) && FIXNUM_P(e)) { /* fixnums are special */
- long end = FIX2LONG(e);
- long i, s = (argc == 0) ? 1 : NUM2LONG(step);
-
- if (!EXCL(range)) end += 1;
- for (i=FIX2LONG(b); i<end; i+=s) {
- rb_yield(INT2NUM(i));
- }
- }
- else if (rb_obj_is_kind_of(b, rb_cNumeric)) {
- b = rb_Integer(b);
- e = rb_Integer(e);
- step = rb_Integer(step);
-
- if (!EXCL(range)) e = rb_funcall(e, '+', 1, INT2FIX(1));
- while (RTEST(rb_funcall(b, '<', 1, e))) {
- rb_yield(b);
- b = rb_funcall(b, '+', 1, step);
- }
- }
- else if (TYPE(b) == T_STRING) {
- VALUE args[5];
- long iter[2];
-
- args[0] = b; args[1] = e; args[2] = range;
- iter[0] = 1; iter[1] = NUM2LONG(step);
- rb_iterate((VALUE(*)_((VALUE)))r_step_str, (VALUE)args, r_step_str_i,
- (VALUE)iter);
- }
- else { /* generic each */
- VALUE v = b;
- long lim = NUM2INT(step);
- long i;
-
- if (EXCL(range)) {
- while (r_lt(v, e)) {
- if (r_eq(v, e)) break;
- rb_yield(v);
- for (i=0; i<lim; i++)
- v = rb_funcall(v, id_succ, 0, 0);
- }
- }
- else {
- while (r_le(v, e)) {
- rb_yield(v);
- if (r_eq(v, e)) break;
- for (i=0; i<lim; i++)
- v = rb_funcall(v, id_succ, 0, 0);
- }
- }
- }
-
- return range;
-}
-
-static VALUE
-range_first(obj)
- VALUE obj;
-{
- VALUE b;
-
- b = rb_ivar_get(obj, id_beg);
- return b;
-}
-
-static VALUE
-range_last(obj)
- VALUE obj;
-{
- VALUE e;
-
- e = rb_ivar_get(obj, id_end);
- return e;
-}
-
-VALUE
-rb_range_beg_len(range, begp, lenp, len, err)
- VALUE range;
- long *begp, *lenp;
- long len;
- int err;
-{
- long beg, end, b, e;
-
- if (!rb_obj_is_kind_of(range, rb_cRange)) return Qfalse;
-
- beg = b = NUM2LONG(rb_ivar_get(range, id_beg));
- end = e = NUM2LONG(rb_ivar_get(range, id_end));
-
- if (beg < 0) {
- beg += len;
- if (beg < 0) goto out_of_range;
- }
- if (err == 0 || err == 2) {
- if (beg > len) goto out_of_range;
- if (end > len || (!EXCL(range) && end == len))
- end = len;
- }
- if (end < 0) {
- end += len;
- if (end < 0) {
- if (beg == 0 && end == -1 && !EXCL(range)) {
- len = 0;
- goto length_set;
- }
- goto out_of_range;
- }
- }
- len = end - beg;
- if (!EXCL(range)) len++; /* include end point */
- if (len < 0) goto out_of_range;
-
- length_set:
- *begp = beg;
- *lenp = len;
-
- return Qtrue;
-
- out_of_range:
- if (err) {
- rb_raise(rb_eRangeError, "%d..%s%d out of range",
- b, EXCL(range)? "." : "", e);
- }
- return Qnil;
-}
-
-static VALUE
-range_to_s(range)
- VALUE range;
-{
- VALUE str, str2;
-
- str = rb_obj_as_string(rb_ivar_get(range, id_beg));
- str2 = rb_obj_as_string(rb_ivar_get(range, id_end));
- str = rb_str_dup(str);
- rb_str_cat(str, "...", EXCL(range)?3:2);
- rb_str_append(str, str2);
- OBJ_INFECT(str, str2);
-
- return str;
-}
-
-static VALUE
-range_inspect(range)
- VALUE range;
-{
- VALUE str, str2;
-
- str = rb_inspect(rb_ivar_get(range, id_beg));
- str2 = rb_inspect(rb_ivar_get(range, id_end));
- str = rb_str_dup(str);
- rb_str_cat(str, "...", EXCL(range)?3:2);
- rb_str_append(str, str2);
- OBJ_INFECT(str, str2);
-
- return str;
-}
-
-static VALUE
-length_i(i, length)
- VALUE i;
- int *length;
-{
- (*length)++;
- return Qnil;
-}
-
-VALUE
-rb_length_by_each(obj)
- VALUE obj;
-{
- int length = 0;
-
- rb_iterate(rb_each, obj, length_i, (VALUE)&length);
- return INT2FIX(length);
-}
-
-static VALUE
-range_length(range)
- VALUE range;
-{
- VALUE beg, end;
- long size;
-
- beg = rb_ivar_get(range, id_beg);
- end = rb_ivar_get(range, id_end);
-
- if (r_gt(beg, end)) {
- return INT2FIX(0);
- }
- if (FIXNUM_P(beg) && FIXNUM_P(end)) {
- if (EXCL(range)) {
- return INT2NUM(NUM2LONG(end) - NUM2LONG(beg));
- }
- else {
- return INT2NUM(NUM2LONG(end) - NUM2LONG(beg) + 1);
- }
- }
- if (!rb_obj_is_kind_of(beg, rb_cInteger)) {
- return rb_length_by_each(range);
- }
- size = rb_funcall(end, '-', 1, beg);
- if (!EXCL(range)) {
- size = rb_funcall(size, '+', 1, INT2FIX(1));
- }
- if (TYPE(size) == T_FLOAT) {
- size = rb_funcall(size, rb_intern("floor"), 0);
- }
-
- return size;
-}
-
-static VALUE
-range_member(range, val)
- VALUE range, val;
-{
- VALUE beg, end;
-
- beg = rb_ivar_get(range, id_beg);
- end = rb_ivar_get(range, id_end);
-
- if (r_gt(beg, val)) return Qfalse;
- if (EXCL(range)) {
- if (r_lt(val, end)) return Qtrue;
- }
- else {
- if (r_le(val, end)) return Qtrue;
- }
- return Qfalse;
-}
-
-void
-Init_Range()
-{
- rb_cRange = rb_define_class("Range", rb_cObject);
- rb_include_module(rb_cRange, rb_mEnumerable);
- rb_define_method(rb_cRange, "initialize", range_initialize, -1);
- rb_define_method(rb_cRange, "==", range_eq, 1);
- rb_define_method(rb_cRange, "===", range_eqq, 1);
- rb_define_method(rb_cRange, "eql?", range_eql, 1);
- rb_define_method(rb_cRange, "hash", range_hash, 0);
- rb_define_method(rb_cRange, "each", range_each, 0);
- rb_define_method(rb_cRange, "step", range_step, -1);
- rb_define_method(rb_cRange, "first", range_first, 0);
- rb_define_method(rb_cRange, "last", range_last, 0);
- rb_define_method(rb_cRange, "begin", range_first, 0);
- rb_define_method(rb_cRange, "end", range_last, 0);
- rb_define_method(rb_cRange, "to_s", range_to_s, 0);
- rb_define_method(rb_cRange, "inspect", range_inspect, 0);
- rb_define_alias(rb_cRange, "to_ary", "to_a");
-
- rb_define_method(rb_cRange, "exclude_end?", range_exclude_end_p, 0);
-
- rb_define_method(rb_cRange, "length", range_length, 0);
- rb_define_method(rb_cRange, "size", range_length, 0);
- rb_define_method(rb_cRange, "member?", range_member, 1);
- rb_define_method(rb_cRange, "include?", range_member, 1);
-
- id_cmp = rb_intern("<=>");
- id_succ = rb_intern("succ");
- id_beg = rb_intern("begin");
- id_end = rb_intern("end");
- id_excl = rb_intern("excl");
-}
diff --git a/re.c b/re.c
deleted file mode 100644
index 67ee4dfc1b..0000000000
--- a/re.c
+++ /dev/null
@@ -1,1489 +0,0 @@
-/**********************************************************************
-
- re.c -
-
- $Author$
- created at: Mon Aug 9 18:24:49 JST 1993
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
-
-**********************************************************************/
-
-#include "ruby.h"
-#include "re.h"
-#include <ctype.h>
-
-static VALUE rb_eRegexpError;
-
-#define BEG(no) regs->beg[no]
-#define END(no) regs->end[no]
-
-#if 'a' == 97 /* it's ascii */
-static const char casetable[] = {
- '\000', '\001', '\002', '\003', '\004', '\005', '\006', '\007',
- '\010', '\011', '\012', '\013', '\014', '\015', '\016', '\017',
- '\020', '\021', '\022', '\023', '\024', '\025', '\026', '\027',
- '\030', '\031', '\032', '\033', '\034', '\035', '\036', '\037',
- /* ' ' '!' '"' '#' '$' '%' '&' ''' */
- '\040', '\041', '\042', '\043', '\044', '\045', '\046', '\047',
- /* '(' ')' '*' '+' ',' '-' '.' '/' */
- '\050', '\051', '\052', '\053', '\054', '\055', '\056', '\057',
- /* '0' '1' '2' '3' '4' '5' '6' '7' */
- '\060', '\061', '\062', '\063', '\064', '\065', '\066', '\067',
- /* '8' '9' ':' ';' '<' '=' '>' '?' */
- '\070', '\071', '\072', '\073', '\074', '\075', '\076', '\077',
- /* '@' 'A' 'B' 'C' 'D' 'E' 'F' 'G' */
- '\100', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
- /* 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' */
- '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157',
- /* 'P' 'Q' 'R' 'S' 'T' 'U' 'V' 'W' */
- '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167',
- /* 'X' 'Y' 'Z' '[' '\' ']' '^' '_' */
- '\170', '\171', '\172', '\133', '\134', '\135', '\136', '\137',
- /* '`' 'a' 'b' 'c' 'd' 'e' 'f' 'g' */
- '\140', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
- /* 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' */
- '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157',
- /* 'p' 'q' 'r' 's' 't' 'u' 'v' 'w' */
- '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167',
- /* 'x' 'y' 'z' '{' '|' '}' '~' */
- '\170', '\171', '\172', '\173', '\174', '\175', '\176', '\177',
- '\200', '\201', '\202', '\203', '\204', '\205', '\206', '\207',
- '\210', '\211', '\212', '\213', '\214', '\215', '\216', '\217',
- '\220', '\221', '\222', '\223', '\224', '\225', '\226', '\227',
- '\230', '\231', '\232', '\233', '\234', '\235', '\236', '\237',
- '\240', '\241', '\242', '\243', '\244', '\245', '\246', '\247',
- '\250', '\251', '\252', '\253', '\254', '\255', '\256', '\257',
- '\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267',
- '\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277',
- '\300', '\301', '\302', '\303', '\304', '\305', '\306', '\307',
- '\310', '\311', '\312', '\313', '\314', '\315', '\316', '\317',
- '\320', '\321', '\322', '\323', '\324', '\325', '\326', '\327',
- '\330', '\331', '\332', '\333', '\334', '\335', '\336', '\337',
- '\340', '\341', '\342', '\343', '\344', '\345', '\346', '\347',
- '\350', '\351', '\352', '\353', '\354', '\355', '\356', '\357',
- '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367',
- '\370', '\371', '\372', '\373', '\374', '\375', '\376', '\377',
-};
-#else
->>> "You lose. You will need a translation table for your character set." <<<
-#endif
-
-#define MIN(a,b) (((a)>(b))?(b):(a))
-
-int
-rb_memcicmp(p1, p2, len)
- char *p1, *p2;
- long len;
-{
- int tmp;
-
- while (len--) {
- if (tmp = casetable[(unsigned)*p1++] - casetable[(unsigned)*p2++])
- return tmp;
- }
- return 0;
-}
-
-int
-rb_memcmp(p1, p2, len)
- char *p1, *p2;
- long len;
-{
- int tmp;
-
- if (!ruby_ignorecase) {
- return memcmp(p1, p2, len);
- }
- return rb_memcicmp(p1, p2, len);
-}
-
-#define REG_CASESTATE FL_USER0
-#define KCODE_NONE 0
-#define KCODE_EUC FL_USER1
-#define KCODE_SJIS FL_USER2
-#define KCODE_UTF8 FL_USER3
-#define KCODE_FIXED FL_USER4
-#define KCODE_MASK (KCODE_EUC|KCODE_SJIS|KCODE_UTF8)
-
-static int reg_kcode = DEFAULT_KCODE;
-
-static void
-kcode_euc(re)
- struct RRegexp *re;
-{
- FL_UNSET(re, KCODE_MASK);
- FL_SET(re, KCODE_EUC);
- FL_SET(re, KCODE_FIXED);
-}
-
-static void
-kcode_sjis(re)
- struct RRegexp *re;
-{
- FL_UNSET(re, KCODE_MASK);
- FL_SET(re, KCODE_SJIS);
- FL_SET(re, KCODE_FIXED);
-}
-
-static void
-kcode_utf8(re)
- struct RRegexp *re;
-{
- FL_UNSET(re, KCODE_MASK);
- FL_SET(re, KCODE_UTF8);
- FL_SET(re, KCODE_FIXED);
-}
-
-static void
-kcode_none(re)
- struct RRegexp *re;
-{
- FL_UNSET(re, KCODE_MASK);
- FL_SET(re, KCODE_FIXED);
-}
-
-static int curr_kcode;
-
-static void
-kcode_set_option(re)
- VALUE re;
-{
- if (!FL_TEST(re, KCODE_FIXED)) return;
-
- curr_kcode = RBASIC(re)->flags & KCODE_MASK;
- if (reg_kcode == curr_kcode) return;
- switch (curr_kcode) {
- case KCODE_NONE:
- re_mbcinit(MBCTYPE_ASCII);
- break;
- case KCODE_EUC:
- re_mbcinit(MBCTYPE_EUC);
- break;
- case KCODE_SJIS:
- re_mbcinit(MBCTYPE_SJIS);
- break;
- case KCODE_UTF8:
- re_mbcinit(MBCTYPE_UTF8);
- break;
- }
-}
-
-static void
-kcode_reset_option()
-{
- if (reg_kcode == curr_kcode) return;
- switch (reg_kcode) {
- case KCODE_NONE:
- re_mbcinit(MBCTYPE_ASCII);
- break;
- case KCODE_EUC:
- re_mbcinit(MBCTYPE_EUC);
- break;
- case KCODE_SJIS:
- re_mbcinit(MBCTYPE_SJIS);
- break;
- case KCODE_UTF8:
- re_mbcinit(MBCTYPE_UTF8);
- break;
- }
-}
-
-int
-rb_reg_mbclen2(c, re)
- unsigned int c;
- VALUE re;
-{
- int len;
-
- if (!FL_TEST(re, KCODE_FIXED))
- return mbclen(c);
- kcode_set_option(re);
- len = mbclen(c);
- kcode_reset_option();
- return len;
-}
-
-static void
-rb_reg_check(re)
- VALUE re;
-{
- if (!RREGEXP(re)->ptr || !RREGEXP(re)->str) {
- rb_raise(rb_eTypeError, "uninitialized Regexp");
- }
-}
-
-extern int ruby_in_compile;
-
-static void
-rb_reg_expr_str(str, s, len)
- VALUE str;
- const char *s;
- int len;
-{
- const char *p, *pend;
- int need_escape = 0;
-
- p = s; pend = p + len;
- while (p<pend) {
- if (*p == '/' || (!ISPRINT(*p) && !ismbchar(*p))) {
- need_escape = 1;
- break;
- }
- p++;
- }
- if (!need_escape) {
- rb_str_buf_cat(str, s, len);
- }
- else {
- p = s;
- while (p<pend) {
- if (*p == '/') {
- char c = '\\';
- rb_str_buf_cat(str, &c, 1);
- rb_str_buf_cat(str, p, 1);
- }
- else if (ismbchar(*p)) {
- rb_str_buf_cat(str, p, mbclen(*p));
- p += mbclen(*p);
- continue;
- }
- else if (ISPRINT(*p)) {
- rb_str_buf_cat(str, p, 1);
- }
- else {
- char b[8];
- switch (*p) {
- case '\r':
- rb_str_buf_cat(str, "\\r", 2);
- break;
- case '\n':
- rb_str_buf_cat(str, "\\n", 2);
- break;
- case '\t':
- rb_str_buf_cat(str, "\\t", 2);
- break;
- case '\f':
- rb_str_buf_cat(str, "\\f", 2);
- break;
- case 007:
- rb_str_buf_cat(str, "\\a", 2);
- break;
- case 013:
- rb_str_buf_cat(str, "\\v", 2);
- break;
- case 033:
- rb_str_buf_cat(str, "\\e", 2);
- break;
- default:
- sprintf(b, "\\%03o", *p & 0377);
- rb_str_buf_cat(str, b, 4);
- break;
- }
- }
- p++;
- }
- }
-}
-
-static VALUE
-rb_reg_desc(s, len, re)
- const char *s;
- int len;
- VALUE re;
-{
- VALUE str = rb_str_buf_new2("/");
-
- rb_reg_expr_str(str, s, len);
- rb_str_buf_cat2(str, "/");
- if (re) {
- rb_reg_check(re);
- /* /p is obsolete; to be removed */
- if ((RREGEXP(re)->ptr->options & RE_OPTION_POSIXLINE) == RE_OPTION_POSIXLINE)
- rb_str_buf_cat2(str, "p");
- else if (RREGEXP(re)->ptr->options & RE_OPTION_MULTILINE)
- rb_str_buf_cat2(str, "m");
- if (RREGEXP(re)->ptr->options & RE_OPTION_IGNORECASE)
- rb_str_buf_cat2(str, "i");
- if (RREGEXP(re)->ptr->options & RE_OPTION_EXTENDED)
- rb_str_buf_cat2(str, "x");
-
- if (FL_TEST(re, KCODE_FIXED)) {
- switch ((RBASIC(re)->flags & KCODE_MASK)) {
- case KCODE_NONE:
- rb_str_buf_cat2(str, "n");
- break;
- case KCODE_EUC:
- rb_str_buf_cat2(str, "e");
- break;
- case KCODE_SJIS:
- rb_str_buf_cat2(str, "s");
- break;
- case KCODE_UTF8:
- rb_str_buf_cat2(str, "u");
- break;
- }
- }
- }
- OBJ_INFECT(str, re);
- return str;
-}
-
-static VALUE
-rb_reg_source(re)
- VALUE re;
-{
- VALUE str;
-
- rb_reg_check(re);
- str = rb_str_new(RREGEXP(re)->str,RREGEXP(re)->len);
- if (OBJ_TAINTED(re)) OBJ_TAINT(str);
- return str;
-}
-
-static VALUE
-rb_reg_inspect(re)
- VALUE re;
-{
- rb_reg_check(re);
- return rb_reg_desc(RREGEXP(re)->str, RREGEXP(re)->len, re);
-}
-
-static void
-rb_reg_raise(s, len, err, re)
- const char *s;
- int len;
- const char *err;
- VALUE re;
-{
- VALUE desc = rb_reg_desc(s, len, re);
-
- if (ruby_in_compile)
- rb_compile_error("%s: %s", err, RSTRING(desc)->ptr);
- else
- rb_raise(rb_eRegexpError, "%s: %s", err, RSTRING(desc)->ptr);
-}
-
-static VALUE
-rb_reg_casefold_p(re)
- VALUE re;
-{
- rb_reg_check(re);
- if (RREGEXP(re)->ptr->options & RE_OPTION_IGNORECASE) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-rb_reg_options_m(re)
- VALUE re;
-{
- rb_reg_check(re);
- return INT2NUM(RREGEXP(re)->ptr->options);
-}
-
-static VALUE
-rb_reg_kcode_m(re)
- VALUE re;
-{
- char *kcode;
-
- if (FL_TEST(re, KCODE_FIXED)) {
- switch (RBASIC(re)->flags & KCODE_MASK) {
- case KCODE_NONE:
- kcode = "none"; break;
- case KCODE_EUC:
- kcode = "euc"; break;
- case KCODE_SJIS:
- kcode = "sjis"; break;
- case KCODE_UTF8:
- kcode = "utf8"; break;
- default:
- rb_bug("unknow kcode - should not happen");
- break;
- }
- return rb_str_new2(kcode);
- }
- return Qnil;
-}
-
-static Regexp*
-make_regexp(s, len, flags)
- const char *s;
- int len, flags;
-{
- Regexp *rp;
- char *err;
-
- /* Handle escaped characters first. */
-
- /* Build a copy of the string (in dest) with the
- escaped characters translated, and generate the regex
- from that.
- */
-
- rp = ALLOC(Regexp);
- MEMZERO((char *)rp, Regexp, 1);
- rp->buffer = ALLOC_N(char, 16);
- rp->allocated = 16;
- rp->fastmap = ALLOC_N(char, 256);
- if (flags) {
- rp->options = flags;
- }
- err = re_compile_pattern(s, len, rp);
- if (err != NULL) {
- rb_reg_raise(s, len, err, 0);
- }
-
- return rp;
-}
-
-static VALUE rb_cMatch;
-
-static VALUE
-match_alloc()
-{
- NEWOBJ(match, struct RMatch);
- OBJSETUP(match, rb_cMatch, T_MATCH);
-
- match->str = 0;
- match->regs = 0;
- match->regs = ALLOC(struct re_registers);
- MEMZERO(match->regs, struct re_registers, 1);
-
- return (VALUE)match;
-}
-
-static VALUE
-match_clone(match)
- VALUE match;
-{
- NEWOBJ(clone, struct RMatch);
- CLONESETUP(clone, match);
-
- clone->str = RMATCH(match)->str;
- clone->regs = 0;
-
- clone->regs = ALLOC(struct re_registers);
- clone->regs->allocated = 0;
- re_copy_registers(clone->regs, RMATCH(match)->regs);
-
- return (VALUE)clone;
-}
-
-static VALUE
-match_size(match)
- VALUE match;
-{
- return INT2FIX(RMATCH(match)->regs->num_regs);
-}
-
-static VALUE
-match_offset(match, n)
- VALUE match, n;
-{
- int i = NUM2INT(n);
-
- if (i < 0 || RMATCH(match)->regs->num_regs <= i)
- rb_raise(rb_eIndexError, "index %d out of matches", i);
-
- if (RMATCH(match)->regs->beg[i] < 0)
- return rb_assoc_new(Qnil, Qnil);
-
- return rb_assoc_new(INT2FIX(RMATCH(match)->regs->beg[i]),
- INT2FIX(RMATCH(match)->regs->end[i]));
-}
-
-static VALUE
-match_begin(match, n)
- VALUE match, n;
-{
- int i = NUM2INT(n);
-
- if (i < 0 || RMATCH(match)->regs->num_regs <= i)
- rb_raise(rb_eIndexError, "index %d out of matches", i);
-
- if (RMATCH(match)->regs->beg[i] < 0)
- return Qnil;
-
- return INT2FIX(RMATCH(match)->regs->beg[i]);
-}
-
-static VALUE
-match_end(match, n)
- VALUE match, n;
-{
- int i = NUM2INT(n);
-
- if (i < 0 || RMATCH(match)->regs->num_regs <= i)
- rb_raise(rb_eIndexError, "index %d out of matches", i);
-
- if (RMATCH(match)->regs->beg[i] < 0)
- return Qnil;
-
- return INT2FIX(RMATCH(match)->regs->end[i]);
-}
-
-#define MATCH_BUSY FL_USER2
-
-void
-rb_match_busy(match)
- VALUE match;
-{
- FL_SET(match, MATCH_BUSY);
-}
-
-int ruby_ignorecase;
-static int may_need_recompile;
-
-static void
-rb_reg_prepare_re(re)
- VALUE re;
-{
- int need_recompile = 0;
- int state;
-
- rb_reg_check(re);
- state = FL_TEST(re, REG_CASESTATE);
- /* ignorecase status */
- if (ruby_ignorecase && !state) {
- FL_SET(re, REG_CASESTATE);
- RREGEXP(re)->ptr->options |= RE_OPTION_IGNORECASE;
- need_recompile = 1;
- }
- if (!ruby_ignorecase && state) {
- FL_UNSET(re, REG_CASESTATE);
- RREGEXP(re)->ptr->options &= ~RE_OPTION_IGNORECASE;
- need_recompile = 1;
- }
-
- if (!FL_TEST(re, KCODE_FIXED) &&
- (RBASIC(re)->flags & KCODE_MASK) != reg_kcode) {
- need_recompile = 1;
- RBASIC(re)->flags &= ~KCODE_MASK;
- RBASIC(re)->flags |= reg_kcode;
- }
-
- if (need_recompile) {
- char *err;
-
- if (FL_TEST(re, KCODE_FIXED))
- kcode_set_option(re);
- rb_reg_check(re);
- RREGEXP(re)->ptr->fastmap_accurate = 0;
- err = re_compile_pattern(RREGEXP(re)->str, RREGEXP(re)->len, RREGEXP(re)->ptr);
- if (err != NULL) {
- rb_reg_raise(RREGEXP(re)->str, RREGEXP(re)->len, err, re);
- }
- }
-}
-
-int
-rb_reg_adjust_startpos(re, str, pos, reverse)
- VALUE re, str;
- int pos, reverse;
-{
- int range;
-
- rb_reg_check(re);
- if (may_need_recompile) rb_reg_prepare_re(re);
-
- if (FL_TEST(re, KCODE_FIXED))
- kcode_set_option(re);
- else if (reg_kcode != curr_kcode)
- kcode_reset_option();
-
- if (reverse) {
- range = -pos;
- }
- else {
- range = RSTRING(str)->len - pos;
- }
- return re_adjust_startpos(RREGEXP(re)->ptr,
- RSTRING(str)->ptr, RSTRING(str)->len,
- pos, range);
-}
-
-int
-rb_reg_search(re, str, pos, reverse)
- VALUE re, str;
- int pos, reverse;
-{
- int result;
- VALUE match;
- static struct re_registers regs;
- int range;
-
- if (pos > RSTRING(str)->len || pos < 0) {
- rb_backref_set(Qnil);
- return -1;
- }
-
- rb_reg_check(re);
- if (may_need_recompile) rb_reg_prepare_re(re);
-
- if (FL_TEST(re, KCODE_FIXED))
- kcode_set_option(re);
- else if (reg_kcode != curr_kcode)
- kcode_reset_option();
-
- if (reverse) {
- range = -pos;
- }
- else {
- range = RSTRING(str)->len - pos;
- }
- result = re_search(RREGEXP(re)->ptr,RSTRING(str)->ptr,RSTRING(str)->len,
- pos, range, &regs);
-
- if (FL_TEST(re, KCODE_FIXED))
- kcode_reset_option();
-
- if (result == -2) {
- rb_reg_raise(RREGEXP(re)->str, RREGEXP(re)->len,
- "Stack overflow in regexp matcher", re);
- }
-
- if (result < 0) {
- rb_backref_set(Qnil);
- return result;
- }
-
- match = rb_backref_get();
- if (NIL_P(match) || FL_TEST(match, MATCH_BUSY)) {
- match = match_alloc();
- }
- else {
- if (rb_safe_level() >= 3)
- OBJ_TAINT(match);
- else
- FL_UNSET(match, FL_TAINT);
- }
-
- re_copy_registers(RMATCH(match)->regs, &regs);
- RMATCH(match)->str = rb_str_new4(str);
- rb_backref_set(match);
-
- OBJ_INFECT(match, re);
- OBJ_INFECT(match, str);
- return result;
-}
-
-VALUE
-rb_reg_nth_defined(nth, match)
- int nth;
- VALUE match;
-{
- if (NIL_P(match)) return Qnil;
- if (nth >= RMATCH(match)->regs->num_regs) {
- return Qnil;
- }
- if (nth < 0) {
- nth += RMATCH(match)->regs->num_regs;
- if (nth <= 0) return Qnil;
- }
- if (RMATCH(match)->BEG(nth) == -1) return Qfalse;
- return Qtrue;
-}
-
-VALUE
-rb_reg_nth_match(nth, match)
- int nth;
- VALUE match;
-{
- VALUE str;
- int start, end, len;
-
- if (NIL_P(match)) return Qnil;
- if (nth >= RMATCH(match)->regs->num_regs) {
- return Qnil;
- }
- if (nth < 0) {
- nth += RMATCH(match)->regs->num_regs;
- if (nth <= 0) return Qnil;
- }
- start = RMATCH(match)->BEG(nth);
- if (start == -1) return Qnil;
- end = RMATCH(match)->END(nth);
- len = end - start;
- str = rb_str_new(RSTRING(RMATCH(match)->str)->ptr + start, len);
- if (OBJ_TAINTED(match)) OBJ_TAINT(str);
- return str;
-}
-
-VALUE
-rb_reg_last_match(match)
- VALUE match;
-{
- return rb_reg_nth_match(0, match);
-}
-
-VALUE
-rb_reg_match_pre(match)
- VALUE match;
-{
- VALUE str;
-
- if (NIL_P(match)) return Qnil;
- if (RMATCH(match)->BEG(0) == -1) return Qnil;
- str = rb_str_new(RSTRING(RMATCH(match)->str)->ptr, RMATCH(match)->BEG(0));
- if (OBJ_TAINTED(match)) OBJ_TAINT(str);
- return str;
-}
-
-VALUE
-rb_reg_match_post(match)
- VALUE match;
-{
- VALUE str;
-
- if (NIL_P(match)) return Qnil;
- if (RMATCH(match)->BEG(0) == -1) return Qnil;
- str = rb_str_new(RSTRING(RMATCH(match)->str)->ptr+RMATCH(match)->END(0),
- RSTRING(RMATCH(match)->str)->len-RMATCH(match)->END(0));
- if (OBJ_TAINTED(match)) OBJ_TAINT(str);
- return str;
-}
-
-VALUE
-rb_reg_match_last(match)
- VALUE match;
-{
- int i;
-
- if (NIL_P(match)) return Qnil;
- if (RMATCH(match)->BEG(0) == -1) return Qnil;
-
- for (i=RMATCH(match)->regs->num_regs-1; RMATCH(match)->BEG(i) == -1 && i > 0; i--)
- ;
- if (i == 0) return Qnil;
- return rb_reg_nth_match(i, match);
-}
-
-static VALUE
-last_match_getter()
-{
- return rb_reg_last_match(rb_backref_get());
-}
-
-static VALUE
-prematch_getter()
-{
- return rb_reg_match_pre(rb_backref_get());
-}
-
-static VALUE
-postmatch_getter()
-{
- return rb_reg_match_post(rb_backref_get());
-}
-
-static VALUE
-last_paren_match_getter()
-{
- return rb_reg_match_last(rb_backref_get());
-}
-
-static VALUE
-match_to_a(match)
- VALUE match;
-{
- struct re_registers *regs = RMATCH(match)->regs;
- VALUE ary = rb_ary_new2(regs->num_regs);
- char *ptr = RSTRING(RMATCH(match)->str)->ptr;
- int i;
- int taint = OBJ_TAINTED(match);
-
- for (i=0; i<regs->num_regs; i++) {
- if (regs->beg[i] == -1) {
- rb_ary_push(ary, Qnil);
- } else {
- VALUE str = rb_str_new(ptr+regs->beg[i], regs->end[i]-regs->beg[i]);
- if (taint) OBJ_TAINT(str);
- rb_ary_push(ary, str);
- }
- }
- return ary;
-}
-
-static VALUE
-match_aref(argc, argv, match)
- int argc;
- VALUE *argv;
- VALUE match;
-{
- VALUE idx, rest;
-
- rb_scan_args(argc, argv, "11", &idx, &rest);
-
- if (!NIL_P(rest) || !FIXNUM_P(idx) || FIX2INT(idx) < 0) {
- return rb_ary_aref(argc, argv, match_to_a(match));
- }
- return rb_reg_nth_match(FIX2INT(idx), match);
-}
-
-static VALUE
-match_select(argc, argv, match)
- int argc;
- VALUE *argv;
- VALUE match;
-{
- struct re_registers *regs = RMATCH(match)->regs;
- char *ptr = RSTRING(RMATCH(match)->str)->ptr;
- VALUE result = rb_ary_new();
- int i;
- long idx;
- int taint = OBJ_TAINTED(match);
-
- for (i=0; i<argc; i++) {
- idx = NUM2LONG(argv[i]);
- if (idx < 0) idx += regs->num_regs;
- if (idx < 0 || regs->num_regs <= idx) {
- rb_ary_push(result, Qnil);
- }
- else {
- VALUE str = rb_str_new(ptr+regs->beg[i], regs->end[i]-regs->beg[i]);
- if (taint) OBJ_TAINT(str);
- rb_ary_push(result, str);
- }
- }
- return result;
-}
-
-static VALUE
-match_to_s(match)
- VALUE match;
-{
- VALUE str = rb_reg_last_match(match);
-
- if (NIL_P(str)) str = rb_str_new(0,0);
- if (OBJ_TAINTED(match)) OBJ_TAINT(str);
- if (OBJ_TAINTED(RMATCH(match)->str)) OBJ_TAINT(str);
- return str;
-}
-
-static VALUE
-match_string(match)
- VALUE match;
-{
- return RMATCH(match)->str; /* str is frozen */
-}
-
-VALUE rb_cRegexp;
-
-static void
-rb_reg_initialize(obj, s, len, options)
- VALUE obj;
- const char *s;
- int len;
- int options; /* CASEFOLD = 1 */
- /* EXTENDED = 2 */
- /* MULTILINE = 4 */
- /* CODE_NONE = 16 */
- /* CODE_EUC = 32 */
- /* CODE_SJIS = 48 */
- /* CODE_UTF8 = 64 */
-{
- struct RRegexp *re = RREGEXP(obj);
-
- if (re->ptr) re_free_pattern(re->ptr);
- if (re->str) free(re->str);
- re->ptr = 0;
- re->str = 0;
-
- switch (options & ~0xf) {
- case 0:
- default:
- FL_SET(re, reg_kcode);
- break;
- case 16:
- kcode_none(re);
- break;
- case 32:
- kcode_euc(re);
- break;
- case 48:
- kcode_sjis(re);
- break;
- case 64:
- kcode_utf8(re);
- break;
- }
-
- if (options & ~0xf) {
- kcode_set_option((VALUE)re);
- }
- if (ruby_ignorecase) {
- options |= RE_OPTION_IGNORECASE;
- FL_SET(re, REG_CASESTATE);
- }
- re->ptr = make_regexp(s, len, options & 0xf);
- re->str = ALLOC_N(char, len+1);
- memcpy(re->str, s, len);
- re->str[len] = '\0';
- re->len = len;
- if (options & ~0xf) {
- kcode_reset_option();
- }
-}
-
-static VALUE
-rb_reg_s_alloc(klass)
- VALUE klass;
-{
- NEWOBJ(re, struct RRegexp);
- OBJSETUP(re, klass, T_REGEXP);
-
- re->ptr = 0;
- re->len = 0;
- re->str = 0;
-
- return (VALUE)re;
-}
-
-VALUE
-rb_reg_new(s, len, options)
- const char *s;
- long len;
- int options;
-{
- VALUE re = rb_reg_s_alloc(rb_cRegexp);
-
- rb_reg_initialize(re, s, len, options);
- return (VALUE)re;
-}
-
-static int case_cache;
-static int kcode_cache;
-static VALUE reg_cache;
-
-VALUE
-rb_reg_regcomp(str)
- VALUE str;
-{
- if (reg_cache && RREGEXP(reg_cache)->len == RSTRING(str)->len
- && case_cache == ruby_ignorecase
- && kcode_cache == reg_kcode
- && memcmp(RREGEXP(reg_cache)->str, RSTRING(str)->ptr, RSTRING(str)->len) == 0)
- return reg_cache;
-
- case_cache = ruby_ignorecase;
- kcode_cache = reg_kcode;
- return reg_cache = rb_reg_new(RSTRING(str)->ptr, RSTRING(str)->len,
- ruby_ignorecase);
-}
-
-static int
-rb_reg_cur_kcode(re)
- VALUE re;
-{
- if (FL_TEST(re, KCODE_FIXED)) {
- return RBASIC(re)->flags & KCODE_MASK;
- }
- return 0;
-}
-
-static VALUE
-rb_reg_equal(re1, re2)
- VALUE re1, re2;
-{
- if (re1 == re2) return Qtrue;
- if (TYPE(re2) != T_REGEXP) return Qfalse;
- rb_reg_check(re1); rb_reg_check(re2);
- if (RREGEXP(re1)->len != RREGEXP(re2)->len) return Qfalse;
- if (memcmp(RREGEXP(re1)->str, RREGEXP(re2)->str, RREGEXP(re1)->len) == 0 &&
- rb_reg_cur_kcode(re1) == rb_reg_cur_kcode(re2) &&
- RREGEXP(re1)->ptr->options == RREGEXP(re2)->ptr->options) {
- return Qtrue;
- }
- return Qfalse;
-}
-
-VALUE
-rb_reg_match(re, str)
- VALUE re, str;
-{
- int start;
-
- if (NIL_P(str)) {
- rb_backref_set(Qnil);
- return Qnil;
- }
- StringValue(str);
- start = rb_reg_search(re, str, 0, 0);
- if (start < 0) {
- return Qnil;
- }
- return INT2FIX(start);
-}
-
-VALUE
-rb_reg_match2(re)
- VALUE re;
-{
- int start;
- VALUE line = rb_lastline_get();
-
- if (TYPE(line) != T_STRING) {
- rb_backref_set(Qnil);
- return Qnil;
- }
-
- start = rb_reg_search(re, line, 0, 0);
- if (start < 0) {
- return Qnil;
- }
- return INT2FIX(start);
-}
-
-static VALUE
-rb_reg_match_m(re, str)
- VALUE re, str;
-{
- VALUE result = rb_reg_match(re, str);
-
- if (NIL_P(result)) return Qnil;
- result = rb_backref_get();
- rb_match_busy(result);
- return result;
-}
-
-static VALUE
-rb_reg_initialize_m(argc, argv, self)
- int argc;
- VALUE *argv;
- VALUE self;
-{
- VALUE src;
- int flags = 0;
-
- if (argc == 0 || argc > 3) {
- rb_raise(rb_eArgError, "wrong number of argument");
- }
- if (argc >= 2) {
- if (FIXNUM_P(argv[1])) flags = FIX2INT(argv[1]);
- else if (RTEST(argv[1])) flags = RE_OPTION_IGNORECASE;
- }
- if (argc == 3) {
- char *kcode = StringValuePtr(argv[2]);
-
- switch (kcode[0]) {
- case 'n': case 'N':
- flags |= 16;
- break;
- case 'e': case 'E':
- flags |= 32;
- break;
- case 's': case 'S':
- flags |= 48;
- break;
- case 'u': case 'U':
- flags |= 64;
- break;
- default:
- break;
- }
- }
-
- src = argv[0];
- if (TYPE(src) == T_REGEXP) {
- rb_reg_check(src);
- rb_reg_initialize(self, RREGEXP(src)->str, RREGEXP(src)->len, flags);
- }
- else {
- StringValue(src);
- rb_reg_initialize(self, RSTRING(src)->ptr, RSTRING(src)->len, flags);
- }
- return self;
-}
-
-static VALUE
-rb_reg_s_quote(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE str, kcode;
- int kcode_saved = reg_kcode;
- char *s, *send, *t;
- VALUE tmp;
-
- rb_scan_args(argc, argv, "11", &str, &kcode);
- if (!NIL_P(kcode)) {
- rb_set_kcode(StringValuePtr(kcode));
- curr_kcode = reg_kcode;
- reg_kcode = kcode_saved;
- }
- StringValue(str);
- s = RSTRING(str)->ptr;
- send = s + RSTRING(str)->len;
- tmp = rb_str_new(0, RSTRING(str)->len*2);
- t = RSTRING(tmp)->ptr;
-
- for (; s < send; s++) {
- if (ismbchar(*s)) {
- int n = mbclen(*s);
-
- while (n-- && s < send)
- *t++ = *s++;
- s--;
- continue;
- }
- if (*s == '[' || *s == ']'
- || *s == '{' || *s == '}'
- || *s == '(' || *s == ')'
- || *s == '|' || *s == '-'
- || *s == '*' || *s == '.' || *s == '\\'
- || *s == '?' || *s == '+'
- || *s == '^' || *s == '$') {
- *t++ = '\\';
- }
- *t++ = *s;
- }
- kcode_reset_option();
- rb_str_resize(tmp, t - RSTRING(tmp)->ptr);
- OBJ_INFECT(tmp, str);
- return tmp;
-}
-
-int
-rb_kcode()
-{
- switch (reg_kcode) {
- case KCODE_EUC:
- return MBCTYPE_EUC;
- case KCODE_SJIS:
- return MBCTYPE_SJIS;
- case KCODE_UTF8:
- return MBCTYPE_UTF8;
- case KCODE_NONE:
- return MBCTYPE_ASCII;
- }
- rb_bug("wrong reg_kcode value (0x%x)", reg_kcode);
-}
-
-static int
-rb_reg_get_kcode(re)
- VALUE re;
-{
- switch (RBASIC(re)->flags & KCODE_MASK) {
- case KCODE_NONE:
- return 16;
- case KCODE_EUC:
- return 32;
- case KCODE_SJIS:
- return 48;
- case KCODE_UTF8:
- return 64;
- default:
- return 0;
- }
-}
-
-int
-rb_reg_options(re)
- VALUE re;
-{
- int options = 0;
-
- rb_reg_check(re);
- if (RREGEXP(re)->ptr->options & RE_OPTION_IGNORECASE)
- options |= RE_OPTION_IGNORECASE;
- if ((RREGEXP(re)->ptr->options & RE_OPTION_POSIXLINE) == RE_OPTION_POSIXLINE)
- options |= RE_OPTION_POSIXLINE;
- else if (RREGEXP(re)->ptr->options & RE_OPTION_MULTILINE)
- options |= RE_OPTION_MULTILINE;
- if (RREGEXP(re)->ptr->options & RE_OPTION_EXTENDED)
- options |= RE_OPTION_EXTENDED;
- if (FL_TEST(re, KCODE_FIXED)) {
- options |= rb_reg_get_kcode(re);
- }
- return options;
-}
-
-static VALUE
-rb_reg_clone(re)
- VALUE re;
-{
- VALUE clone = rb_obj_clone(re);
-
- RREGEXP(clone)->ptr = 0;
- RREGEXP(clone)->len = 0;
- RREGEXP(clone)->str = 0;
- rb_reg_check(re);
- rb_reg_initialize(clone, RREGEXP(re)->str, RREGEXP(re)->len,
- rb_reg_options(re));
- return clone;
-}
-
-VALUE
-rb_reg_regsub(str, src, regs)
- VALUE str, src;
- struct re_registers *regs;
-{
- VALUE val = 0;
- char *p, *s, *e, c;
- int no;
-
- p = s = RSTRING(str)->ptr;
- e = s + RSTRING(str)->len;
-
- while (s < e) {
- char *ss = s;
-
- c = *s++;
- if (ismbchar(c)) {
- s += mbclen(c) - 1;
- continue;
- }
- if (c != '\\' || s == e) continue;
-
- if (!val) {
- val = rb_str_buf_new(ss-p);
- rb_str_buf_cat(val, p, ss-p);
- }
- else {
- rb_str_buf_cat(val, p, ss-p);
- }
-
- c = *s++;
- p = s;
- switch (c) {
- case '0': case '1': case '2': case '3': case '4':
- case '5': case '6': case '7': case '8': case '9':
- no = c - '0';
- break;
- case '&':
- no = 0;
- break;
-
- case '`':
- rb_str_buf_cat(val, RSTRING(src)->ptr, BEG(0));
- continue;
-
- case '\'':
- rb_str_buf_cat(val, RSTRING(src)->ptr+END(0), RSTRING(src)->len-END(0));
- continue;
-
- case '+':
- no = regs->num_regs-1;
- while (BEG(no) == -1 && no > 0) no--;
- if (no == 0) continue;
- break;
-
- case '\\':
- rb_str_buf_cat(val, s-1, 1);
- continue;
-
- default:
- rb_str_buf_cat(val, s-2, 2);
- continue;
- }
-
- if (no >= 0) {
- if (no >= regs->num_regs) continue;
- if (BEG(no) == -1) continue;
- rb_str_buf_cat(val, RSTRING(src)->ptr+BEG(no), END(no)-BEG(no));
- }
- }
-
- if (p < e) {
- if (!val) {
- val = rb_str_buf_new(e-p);
- rb_str_buf_cat(val, p, e-p);
- }
- else {
- rb_str_buf_cat(val, p, e-p);
- }
- }
- if (!val) return str;
-
- return val;
-}
-
-const char*
-rb_get_kcode()
-{
- switch (reg_kcode) {
- case KCODE_SJIS:
- return "SJIS";
- case KCODE_EUC:
- return "EUC";
- case KCODE_UTF8:
- return "UTF8";
- default:
- return "NONE";
- }
-}
-
-static VALUE
-kcode_getter()
-{
- return rb_str_new2(rb_get_kcode());
-}
-
-void
-rb_set_kcode(code)
- const char *code;
-{
- if (code == 0) goto set_no_conversion;
-
- switch (code[0]) {
- case 'E':
- case 'e':
- reg_kcode = KCODE_EUC;
- re_mbcinit(MBCTYPE_EUC);
- break;
- case 'S':
- case 's':
- reg_kcode = KCODE_SJIS;
- re_mbcinit(MBCTYPE_SJIS);
- break;
- case 'U':
- case 'u':
- reg_kcode = KCODE_UTF8;
- re_mbcinit(MBCTYPE_UTF8);
- break;
- default:
- case 'N':
- case 'n':
- case 'A':
- case 'a':
- set_no_conversion:
- reg_kcode = KCODE_NONE;
- re_mbcinit(MBCTYPE_ASCII);
- break;
- }
-}
-
-static void
-kcode_setter(val)
- VALUE val;
-{
- may_need_recompile = 1;
- rb_set_kcode(StringValuePtr(val));
-}
-
-static VALUE
-ignorecase_getter()
-{
- return ruby_ignorecase?Qtrue:Qfalse;
-}
-
-static void
-ignorecase_setter(val, id)
- VALUE val;
- ID id;
-{
- rb_warn("modifying %s is deperecated", rb_id2name(id));
- may_need_recompile = 1;
- ruby_ignorecase = RTEST(val);
-}
-
-static VALUE
-match_getter()
-{
- VALUE match = rb_backref_get();
-
- if (NIL_P(match)) return Qnil;
- rb_match_busy(match);
- return match;
-}
-
-static void
-match_setter(val)
- VALUE val;
-{
- Check_Type(val, T_MATCH);
- rb_backref_set(val);
-}
-
-static VALUE
-rb_reg_s_last_match(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE nth;
-
- if (rb_scan_args(argc, argv, "01", &nth) == 1) {
- return rb_reg_nth_match(NUM2INT(nth), rb_backref_get());
- }
- return match_getter();
-}
-
-void
-Init_Regexp()
-{
- rb_eRegexpError = rb_define_class("RegexpError", rb_eStandardError);
-
- re_set_casetable(casetable);
-#if DEFAULT_KCODE == KCODE_EUC
- re_mbcinit(MBCTYPE_EUC);
-#else
-#if DEFAULT_KCODE == KCODE_SJIS
- re_mbcinit(MBCTYPE_SJIS);
-#else
-#if DEFAULT_KCODE == KCODE_UTF8
- re_mbcinit(MBCTYPE_UTF8);
-#else
- re_mbcinit(MBCTYPE_ASCII);
-#endif
-#endif
-#endif
-
- rb_define_virtual_variable("$~", match_getter, match_setter);
- rb_define_virtual_variable("$&", last_match_getter, 0);
- rb_define_virtual_variable("$`", prematch_getter, 0);
- rb_define_virtual_variable("$'", postmatch_getter, 0);
- rb_define_virtual_variable("$+", last_paren_match_getter, 0);
-
- rb_define_virtual_variable("$=", ignorecase_getter, ignorecase_setter);
- rb_define_virtual_variable("$KCODE", kcode_getter, kcode_setter);
- rb_define_virtual_variable("$-K", kcode_getter, kcode_setter);
-
- rb_cRegexp = rb_define_class("Regexp", rb_cObject);
- rb_define_singleton_method(rb_cRegexp, "allocate", rb_reg_s_alloc, 0);
- rb_define_singleton_method(rb_cRegexp, "compile", rb_class_new_instance, -1);
- rb_define_singleton_method(rb_cRegexp, "quote", rb_reg_s_quote, -1);
- rb_define_singleton_method(rb_cRegexp, "escape", rb_reg_s_quote, -1);
- rb_define_singleton_method(rb_cRegexp, "last_match", rb_reg_s_last_match, -1);
-
- rb_define_method(rb_cRegexp, "initialize", rb_reg_initialize_m, -1);
- rb_define_method(rb_cRegexp, "clone", rb_reg_clone, 0);
- rb_define_method(rb_cRegexp, "==", rb_reg_equal, 1);
- rb_define_method(rb_cRegexp, "=~", rb_reg_match, 1);
- rb_define_method(rb_cRegexp, "===", rb_reg_match, 1);
- rb_define_method(rb_cRegexp, "~", rb_reg_match2, 0);
- rb_define_method(rb_cRegexp, "match", rb_reg_match_m, 1);
- rb_define_method(rb_cRegexp, "to_s", rb_reg_inspect, 0);
- rb_define_method(rb_cRegexp, "inspect", rb_reg_inspect, 0);
- rb_define_method(rb_cRegexp, "source", rb_reg_source, 0);
- rb_define_method(rb_cRegexp, "casefold?", rb_reg_casefold_p, 0);
- rb_define_method(rb_cRegexp, "options", rb_reg_options_m, 0);
- rb_define_method(rb_cRegexp, "kcode", rb_reg_kcode_m, 0);
-
- rb_define_const(rb_cRegexp, "IGNORECASE", INT2FIX(RE_OPTION_IGNORECASE));
- rb_define_const(rb_cRegexp, "EXTENDED", INT2FIX(RE_OPTION_EXTENDED));
- rb_define_const(rb_cRegexp, "MULTILINE", INT2FIX(RE_OPTION_MULTILINE));
-
- rb_global_variable(&reg_cache);
-
- rb_cMatch = rb_define_class("MatchData", rb_cObject);
- rb_define_global_const("MatchingData", rb_cMatch);
- rb_undef_method(CLASS_OF(rb_cMatch), "allocate");
- rb_undef_method(CLASS_OF(rb_cMatch), "new");
-
- rb_define_method(rb_cMatch, "clone", match_clone, 0);
- rb_define_method(rb_cMatch, "size", match_size, 0);
- rb_define_method(rb_cMatch, "length", match_size, 0);
- rb_define_method(rb_cMatch, "offset", match_offset, 1);
- rb_define_method(rb_cMatch, "begin", match_begin, 1);
- rb_define_method(rb_cMatch, "end", match_end, 1);
- rb_define_method(rb_cMatch, "to_a", match_to_a, 0);
- rb_define_method(rb_cMatch, "to_ary", match_to_a, 0);
- rb_define_method(rb_cMatch, "[]", match_aref, -1);
- rb_define_method(rb_cMatch, "select", match_select, -1);
- rb_define_method(rb_cMatch, "pre_match", rb_reg_match_pre, 0);
- rb_define_method(rb_cMatch, "post_match", rb_reg_match_post, 0);
- rb_define_method(rb_cMatch, "to_s", match_to_s, 0);
- rb_define_method(rb_cMatch, "inspect", rb_any_to_s, 0);
- rb_define_method(rb_cMatch, "string", match_string, 0);
-}
diff --git a/re.h b/re.h
deleted file mode 100644
index ec041f6b17..0000000000
--- a/re.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/**********************************************************************
-
- re.h -
-
- $Author$
- $Date$
- created at: Thu Sep 30 14:18:32 JST 1993
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
-
-**********************************************************************/
-
-#ifndef RE_H
-#define RE_H
-
-#include <sys/types.h>
-#include <stdio.h>
-
-#include "regex.h"
-
-typedef struct re_pattern_buffer Regexp;
-
-struct RMatch {
- struct RBasic basic;
- VALUE str;
- struct re_registers *regs;
-};
-
-#define RMATCH(obj) (R_CAST(RMatch)(obj))
-
-VALUE rb_reg_regcomp _((VALUE));
-int rb_reg_search _((VALUE, VALUE, int, int));
-VALUE rb_reg_regsub _((VALUE, VALUE, struct re_registers *));
-int rb_reg_adjust_startpos _((VALUE, VALUE, int, int));
-void rb_match_busy _((VALUE));
-
-EXTERN int ruby_ignorecase;
-
-int rb_reg_mbclen2 _((unsigned int, VALUE));
-#define mbclen2(c,re) rb_reg_mbclen2((c),(re))
-#endif
diff --git a/regex.c b/regex.c
deleted file mode 100644
index 3f38757656..0000000000
--- a/regex.c
+++ /dev/null
@@ -1,4587 +0,0 @@
-/* Extended regular expression matching and search library.
- Copyright (C) 1993, 94, 95, 96, 97, 98 Free Software Foundation, Inc.
-
- The GNU C Library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public License as
- published by the Free Software Foundation; either version 2 of the
- License, or (at your option) any later version.
-
- The GNU C Library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public
- License along with the GNU C Library; see the file LGPL. If not,
- write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
- Boston, MA 02111-1307, USA. */
-/* Multi-byte extension added May, 1993 by t^2 (Takahiro Tanimoto)
- Last change: May 21, 1993 by t^2 */
-/* removed gapped buffer support, multiple syntax support by matz <matz@nts.co.jp> */
-/* Perl5 extension added by matz <matz@caelum.co.jp> */
-/* UTF-8 extension added Jan 16 1999 by Yoshida Masato <yoshidam@tau.bekkoame.ne.jp> */
-
-#include "config.h"
-
-#ifdef HAVE_STRING_H
-# include <string.h>
-#else
-# include <strings.h>
-#endif
-
-/* We write fatal error messages on standard error. */
-#include <stdio.h>
-
-/* isalpha(3) etc. are used for the character classes. */
-#include <ctype.h>
-#include <sys/types.h>
-
-#ifndef PARAMS
-# if defined __GNUC__ || (defined __STDC__ && __STDC__)
-# define PARAMS(args) args
-# else
-# define PARAMS(args) ()
-# endif /* GCC. */
-#endif /* Not PARAMS. */
-
-#if defined(STDC_HEADERS)
-# include <stddef.h>
-#else
-/* We need this for `regex.h', and perhaps for the Emacs include files. */
-# include <sys/types.h>
-#endif
-
-#if !defined(__STDC__) && !defined(_MSC_VER)
-# define volatile
-#endif
-
-#ifdef HAVE_PROTOTYPES
-# define _(args) args
-#else
-# define _(args) ()
-#endif
-
-#ifdef RUBY_PLATFORM
-#include "defines.h"
-
-# define RUBY
-extern int rb_prohibit_interrupt;
-extern int rb_trap_pending;
-void rb_trap_exec _((void));
-
-# define CHECK_INTS if (!rb_prohibit_interrupt) {\
- if (rb_trap_pending) rb_trap_exec();\
-}
-#endif
-
-/* Make alloca work the best possible way. */
-#ifdef __GNUC__
-# ifndef atarist
-# ifndef alloca
-# define alloca __builtin_alloca
-# endif
-# endif /* atarist */
-#else
-# if defined(HAVE_ALLOCA_H)
-# include <alloca.h>
-# elif !defined(alloca)
-char *alloca();
-# endif
-#endif /* __GNUC__ */
-
-#ifdef _AIX
-#pragma alloca
-#endif
-
-#ifdef HAVE_STRING_H
-# include <string.h>
-#else
-# include <strings.h>
-#endif
-
-#ifdef C_ALLOCA
-#define FREE_VARIABLES() alloca(0)
-#else
-#define FREE_VARIABLES()
-#endif
-
-#define FREE_AND_RETURN_VOID(stackb) do { \
- FREE_VARIABLES(); \
- if (stackb != stacka) xfree(stackb); \
- return; \
-} while(0)
-
-#define FREE_AND_RETURN(stackb,val) do { \
- FREE_VARIABLES(); \
- if (stackb != stacka) xfree(stackb); \
- return(val); \
-} while(0)
-
-#define DOUBLE_STACK(type) do { \
- type *stackx; \
- unsigned int xlen = stacke - stackb; \
- if (stackb == stacka) { \
- stackx = (type*)xmalloc(2 * xlen * sizeof(type)); \
- memcpy(stackx, stackb, xlen * sizeof (type)); \
- } \
- else { \
- stackx = (type*)xrealloc(stackb, 2 * xlen * sizeof(type)); \
- } \
- /* Rearrange the pointers. */ \
- stackp = stackx + (stackp - stackb); \
- stackb = stackx; \
- stacke = stackb + 2 * xlen; \
-} while (0)
-
-#define RE_TALLOC(n,t) ((t*)alloca((n)*sizeof(t)))
-#define TMALLOC(n,t) ((t*)xmalloc((n)*sizeof(t)))
-#define TREALLOC(s,n,t) (s=((t*)xrealloc(s,(n)*sizeof(t))))
-
-#define EXPAND_FAIL_STACK() DOUBLE_STACK(unsigned char*)
-#define ENSURE_FAIL_STACK(n) \
- do { \
- if (stacke - stackp <= (n)) { \
- /* if (len > re_max_failures * MAX_NUM_FAILURE_ITEMS) \
- { \
- FREE_AND_RETURN(stackb,(-2)); \
- }*/ \
- \
- /* Roughly double the size of the stack. */ \
- EXPAND_FAIL_STACK(); \
- } \
- } while (0)
-
-/* Get the interface, including the syntax bits. */
-#include "regex.h"
-
-/* Subroutines for re_compile_pattern. */
-static void store_jump _((char*, int, char*));
-static void insert_jump _((int, char*, char*, char*));
-static void store_jump_n _((char*, int, char*, unsigned));
-static void insert_jump_n _((int, char*, char*, char*, unsigned));
-static void insert_op _((int, char*, char*));
-static void insert_op_2 _((int, char*, char*, int, int));
-static int memcmp_translate _((unsigned char*, unsigned char*, int));
-
-/* Define the syntax stuff, so we can do the \<, \>, etc. */
-
-/* This must be nonzero for the wordchar and notwordchar pattern
- commands in re_match. */
-#define Sword 1
-#define Sword2 2
-
-#define SYNTAX(c) re_syntax_table[c]
-
-static char re_syntax_table[256];
-static void init_syntax_once _((void));
-static const unsigned char *translate = 0;
-static void init_regs _((struct re_registers*, unsigned int));
-static void bm_init_skip _((int *, unsigned char*, int, const unsigned char*));
-static int current_mbctype = MBCTYPE_ASCII;
-
-#undef P
-
-#ifdef RUBY
-#include "util.h"
-#endif
-
-static void
-init_syntax_once()
-{
- register int c;
- static int done = 0;
-
- if (done)
- return;
-
- memset(re_syntax_table, 0, sizeof re_syntax_table);
-
- for (c=0; c<=0x7f; c++)
- if (isalnum(c))
- re_syntax_table[c] = Sword;
- re_syntax_table['_'] = Sword;
-
- for (c=0x80; c<=0xff; c++)
- if (isalnum(c))
- re_syntax_table[c] = Sword2;
- done = 1;
-}
-
-void
-re_set_casetable(table)
- const char *table;
-{
- translate = (const unsigned char*)table;
-}
-
-/* Jim Meyering writes:
-
- "... Some ctype macros are valid only for character codes that
- isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
- using /bin/cc or gcc but without giving an ansi option). So, all
- ctype uses should be through macros like ISPRINT... If
- STDC_HEADERS is defined, then autoconf has verified that the ctype
- macros don't need to be guarded with references to isascii. ...
- Defining isascii to 1 should let any compiler worth its salt
- eliminate the && through constant folding."
- Solaris defines some of these symbols so we must undefine them first. */
-
-#undef ISASCII
-#if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
-# define ISASCII(c) 1
-#else
-# define ISASCII(c) isascii(c)
-#endif
-
-#ifdef isblank
-# define ISBLANK(c) (ISASCII(c) && isblank(c))
-#else
-# define ISBLANK(c) ((c) == ' ' || (c) == '\t')
-#endif
-#ifdef isgraph
-# define ISGRAPH(c) (ISASCII(c) && isgraph(c))
-#else
-# define ISGRAPH(c) (ISASCII(c) && isprint(c) && !isspace(c))
-#endif
-
-#undef ISPRINT
-#define ISPRINT(c) (ISASCII(c) && isprint(c))
-#define ISDIGIT(c) (ISASCII(c) && isdigit(c))
-#define ISALNUM(c) (ISASCII(c) && isalnum(c))
-#define ISALPHA(c) (ISASCII(c) && isalpha(c))
-#define ISCNTRL(c) (ISASCII(c) && iscntrl(c))
-#define ISLOWER(c) (ISASCII(c) && islower(c))
-#define ISPUNCT(c) (ISASCII(c) && ispunct(c))
-#define ISSPACE(c) (ISASCII(c) && isspace(c))
-#define ISUPPER(c) (ISASCII(c) && isupper(c))
-#define ISXDIGIT(c) (ISASCII(c) && isxdigit(c))
-
-#ifndef NULL
-# define NULL (void *)0
-#endif
-
-/* We remove any previous definition of `SIGN_EXTEND_CHAR',
- since ours (we hope) works properly with all combinations of
- machines, compilers, `char' and `unsigned char' argument types.
- (Per Bothner suggested the basic approach.) */
-#undef SIGN_EXTEND_CHAR
-#if __STDC__
-# define SIGN_EXTEND_CHAR(c) ((signed char)(c))
-#else /* not __STDC__ */
-/* As in Harbison and Steele. */
-# define SIGN_EXTEND_CHAR(c) ((((unsigned char)(c)) ^ 128) - 128)
-#endif
-
-/* These are the command codes that appear in compiled regular
- expressions, one per byte. Some command codes are followed by
- argument bytes. A command code can specify any interpretation
- whatsoever for its arguments. Zero-bytes may appear in the compiled
- regular expression.
-
- The value of `exactn' is needed in search.c (search_buffer) in emacs.
- So regex.h defines a symbol `RE_EXACTN_VALUE' to be 1; the value of
- `exactn' we use here must also be 1. */
-
-enum regexpcode
- {
- unused=0,
- exactn=1, /* Followed by one byte giving n, then by n literal bytes. */
- begline, /* Fail unless at beginning of line. */
- endline, /* Fail unless at end of line. */
- begbuf, /* Succeeds if at beginning of buffer (if emacs) or at beginning
- of string to be matched (if not). */
- endbuf, /* Analogously, for end of buffer/string. */
- endbuf2, /* End of buffer/string, or newline just before it. */
- begpos, /* Matches where last scan//gsub left off. */
- jump, /* Followed by two bytes giving relative address to jump to. */
- jump_past_alt,/* Same as jump, but marks the end of an alternative. */
- on_failure_jump, /* Followed by two bytes giving relative address of
- place to resume at in case of failure. */
- finalize_jump, /* Throw away latest failure point and then jump to
- address. */
- maybe_finalize_jump, /* Like jump but finalize if safe to do so.
- This is used to jump back to the beginning
- of a repeat. If the command that follows
- this jump is clearly incompatible with the
- one at the beginning of the repeat, such that
- we can be sure that there is no use backtracking
- out of repetitions already completed,
- then we finalize. */
- dummy_failure_jump, /* Jump, and push a dummy failure point. This
- failure point will be thrown away if an attempt
- is made to use it for a failure. A + construct
- makes this before the first repeat. Also
- use it as an intermediary kind of jump when
- compiling an or construct. */
- push_dummy_failure, /* Push a dummy failure point and continue. Used at the end of
- alternatives. */
- succeed_n, /* Used like on_failure_jump except has to succeed n times;
- then gets turned into an on_failure_jump. The relative
- address following it is useless until then. The
- address is followed by two bytes containing n. */
- jump_n, /* Similar to jump, but jump n times only; also the relative
- address following is in turn followed by yet two more bytes
- containing n. */
- try_next, /* Jump to next pattern for the first time,
- leaving this pattern on the failure stack. */
- finalize_push, /* Finalize stack and push the beginning of the pattern
- on the stack to retry (used for non-greedy match) */
- finalize_push_n, /* Similar to finalize_push, buf finalize n time only */
- set_number_at, /* Set the following relative location to the
- subsequent number. */
- anychar, /* Matches any (more or less) one character excluding newlines. */
- anychar_repeat, /* Matches sequence of characters excluding newlines. */
- charset, /* Matches any one char belonging to specified set.
- First following byte is number of bitmap bytes.
- Then come bytes for a bitmap saying which chars are in.
- Bits in each byte are ordered low-bit-first.
- A character is in the set if its bit is 1.
- A character too large to have a bit in the map
- is automatically not in the set. */
- charset_not, /* Same parameters as charset, but match any character
- that is not one of those specified. */
- start_memory, /* Start remembering the text that is matched, for
- storing in a memory register. Followed by one
- byte containing the register number. Register numbers
- must be in the range 0 through RE_NREGS. */
- stop_memory, /* Stop remembering the text that is matched
- and store it in a memory register. Followed by
- one byte containing the register number. Register
- numbers must be in the range 0 through RE_NREGS. */
- start_paren, /* Place holder at the start of (?:..). */
- stop_paren, /* Place holder at the end of (?:..). */
- casefold_on, /* Turn on casefold flag. */
- casefold_off, /* Turn off casefold flag. */
- option_set, /* Turn on multi line match (match with newlines). */
- start_nowidth, /* Save string point to the stack. */
- stop_nowidth, /* Restore string place at the point start_nowidth. */
- pop_and_fail, /* Fail after popping nowidth entry from stack. */
- stop_backtrack, /* Restore backtrack stack at the point start_nowidth. */
- duplicate, /* Match a duplicate of something remembered.
- Followed by one byte containing the index of the memory
- register. */
- wordchar, /* Matches any word-constituent character. */
- notwordchar, /* Matches any char that is not a word-constituent. */
- wordbeg, /* Succeeds if at word beginning. */
- wordend, /* Succeeds if at word end. */
- wordbound, /* Succeeds if at a word boundary. */
- notwordbound /* Succeeds if not at a word boundary. */
- };
-
-
-/* Number of failure points to allocate space for initially,
- when matching. If this number is exceeded, more space is allocated,
- so it is not a hard limit. */
-
-#ifndef NFAILURES
-#define NFAILURES 160
-#endif
-
-/* Store NUMBER in two contiguous bytes starting at DESTINATION. */
-#define STORE_NUMBER(destination, number) \
- do { (destination)[0] = (number) & 0377; \
- (destination)[1] = (number) >> 8; } while (0)
-
-/* Same as STORE_NUMBER, except increment the destination pointer to
- the byte after where the number is stored. Watch out that values for
- DESTINATION such as p + 1 won't work, whereas p will. */
-#define STORE_NUMBER_AND_INCR(destination, number) \
- do { STORE_NUMBER(destination, number); \
- (destination) += 2; } while (0)
-
-
-/* Put into DESTINATION a number stored in two contingous bytes starting
- at SOURCE. */
-#define EXTRACT_NUMBER(destination, source) \
- do { (destination) = *(source) & 0377; \
- (destination) += SIGN_EXTEND_CHAR(*(char*)((source) + 1)) << 8; } while (0)
-
-/* Same as EXTRACT_NUMBER, except increment the pointer for source to
- point to second byte of SOURCE. Note that SOURCE has to be a value
- such as p, not, e.g., p + 1. */
-#define EXTRACT_NUMBER_AND_INCR(destination, source) \
- do { EXTRACT_NUMBER(destination, source); \
- (source) += 2; } while (0)
-
-
-/* Specify the precise syntax of regexps for compilation. This provides
- for compatibility for various utilities which historically have
- different, incompatible syntaxes.
-
- The argument SYNTAX is a bit-mask comprised of the various bits
- defined in regex.h. */
-
-long
-re_set_syntax(syntax)
- long syntax;
-{
- /* obsolete */
- return 0;
-}
-
-
-/* Macros for re_compile_pattern, which is found below these definitions. */
-
-#define TRANSLATE_P() ((options&RE_OPTION_IGNORECASE) && translate)
-#define MAY_TRANSLATE() ((bufp->options&(RE_OPTION_IGNORECASE|RE_MAY_IGNORECASE)) && translate)
-/* Fetch the next character in the uncompiled pattern---translating it
- if necessary. Also cast from a signed character in the constant
- string passed to us by the user to an unsigned char that we can use
- as an array index (in, e.g., `translate'). */
-#define PATFETCH(c) \
- do {if (p == pend) goto end_of_pattern; \
- c = (unsigned char) *p++; \
- if (TRANSLATE_P()) c = (unsigned char)translate[c]; \
- } while (0)
-
-/* Fetch the next character in the uncompiled pattern, with no
- translation. */
-#define PATFETCH_RAW(c) \
- do {if (p == pend) goto end_of_pattern; \
- c = (unsigned char)*p++; \
- } while (0)
-
-/* Go backwards one character in the pattern. */
-#define PATUNFETCH p--
-
-#define MBC2WC(c, p) \
- do { \
- if (current_mbctype == MBCTYPE_UTF8) { \
- int n = mbclen(c) - 1; \
- c &= (1<<(BYTEWIDTH-2-n)) - 1; \
- while (n--) { \
- c = c << 6 | (*p++ & ((1<<6)-1)); \
- } \
- } \
- else { \
- c <<= 8; \
- c |= (unsigned char)*(p)++; \
- } \
- } while (0)
-
-#define PATFETCH_MBC(c) \
- do { \
- if (p + mbclen(c) - 1 >= pend) goto end_of_pattern; \
- MBC2WC(c, p); \
- } while(0)
-
-#define WC2MBC1ST(c) \
- ((current_mbctype != MBCTYPE_UTF8) ? ((c<0x100) ? (c) : (((c)>>8)&0xff)) : utf8_firstbyte(c))
-
-typedef unsigned int (*mbc_startpos_func_t) _((const char *string, unsigned int pos));
-const mbc_startpos_func_t mbc_startpos_func[];
-#define mbc_startpos(start, pos) (*mbc_startpos_func[current_mbctype])((start), (pos))
-
-static unsigned int
-utf8_firstbyte(c)
- unsigned long c;
-{
- if (c < 0x80) return c;
- if (c <= 0x7ff) return ((c>>6)&0xff)|0xc0;
- if (c <= 0xffff) return ((c>>12)&0xff)|0xe0;
- if (c <= 0x1fffff) return ((c>>18)&0xff)|0xf0;
- if (c <= 0x3ffffff) return ((c>>24)&0xff)|0xf8;
- if (c <= 0x7fffffff) return ((c>>30)&0xff)|0xfc;
-#if SIZEOF_INT > 4
- if (c <= 0xfffffffff) return 0xfe;
-#else
- return 0xfe;
-#endif
-}
-
-static void
-print_mbc(c)
- unsigned int c;
-{
- if (current_mbctype == MBCTYPE_UTF8) {
- if (c < 0x80)
- printf("%c", (int)c);
- else if (c <= 0x7ff)
- printf("%c%c", (int)utf8_firstbyte(c), (int)(c & 0x3f));
- else if (c <= 0xffff)
- printf("%c%c%c", (int)utf8_firstbyte(c), (int)((c >> 6) & 0x3f),
- (int)(c & 0x3f));
- else if (c <= 0x1fffff)
- printf("%c%c%c%c", (int)utf8_firstbyte(c), (int)((c >> 12) & 0x3f),
- (int)((c >> 6) & 0x3f), (int)(c & 0x3f));
- else if (c <= 0x3ffffff)
- printf("%c%c%c%c%c", (int)utf8_firstbyte(c), (int)((c >> 18) & 0x3f),
- (int)((c >> 12) & 0x3f), (int)((c >> 6) & 0x3f), (int)(c & 0x3f));
- else if (c <= 0x7fffffff)
- printf("%c%c%c%c%c%c", (int)utf8_firstbyte(c), (int)((c >> 24) & 0x3f),
- (int)((c >> 18) & 0x3f), (int)((c >> 12) & 0x3f),
- (int)((c >> 6) & 0x3f), (int)(c & 0x3f));
- }
- else if (c < 0xff) {
- printf("\\%o", (int)c);
- }
- else {
- printf("%c%c", (int)(c >> BYTEWIDTH), (int)(c &0xff));
- }
-}
-
-/* If the buffer isn't allocated when it comes in, use this. */
-#define INIT_BUF_SIZE 28
-
-/* Make sure we have at least N more bytes of space in buffer. */
-#define GET_BUFFER_SPACE(n) \
- do { \
- while (b - bufp->buffer + (n) >= bufp->allocated) \
- EXTEND_BUFFER; \
- } while (0)
-
-/* Make sure we have one more byte of buffer space and then add CH to it. */
-#define BUFPUSH(ch) \
- do { \
- GET_BUFFER_SPACE(1); \
- *b++ = (char)(ch); \
- } while (0)
-
-/* Extend the buffer by twice its current size via reallociation and
- reset the pointers that pointed into the old allocation to point to
- the correct places in the new allocation. If extending the buffer
- results in it being larger than 1 << 16, then flag memory exhausted. */
-#define EXTEND_BUFFER \
- do { char *old_buffer = bufp->buffer; \
- if (bufp->allocated == (1L<<16)) goto too_big; \
- bufp->allocated *= 2; \
- if (bufp->allocated > (1L<<16)) bufp->allocated = (1L<<16); \
- bufp->buffer = (char*)xrealloc(bufp->buffer, bufp->allocated); \
- if (bufp->buffer == 0) \
- goto memory_exhausted; \
- b = (b - old_buffer) + bufp->buffer; \
- if (fixup_alt_jump) \
- fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer; \
- if (laststart) \
- laststart = (laststart - old_buffer) + bufp->buffer; \
- begalt = (begalt - old_buffer) + bufp->buffer; \
- if (pending_exact) \
- pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
- } while (0)
-
-
-/* Set the bit for character C in a character set list. */
-#define SET_LIST_BIT(c) \
- (b[(unsigned char)(c) / BYTEWIDTH] \
- |= 1 << ((unsigned char)(c) % BYTEWIDTH))
-
-/* Get the next unsigned number in the uncompiled pattern. */
-#define GET_UNSIGNED_NUMBER(num) \
- do { if (p != pend) { \
- PATFETCH(c); \
- while (ISDIGIT(c)) { \
- if (num < 0) \
- num = 0; \
- num = num * 10 + c - '0'; \
- if (p == pend) \
- break; \
- PATFETCH(c); \
- } \
- } \
- } while (0)
-
-#define STREQ(s1, s2) ((strcmp(s1, s2) == 0))
-
-#define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
-
-#define IS_CHAR_CLASS(string) \
- (STREQ(string, "alpha") || STREQ(string, "upper") \
- || STREQ(string, "lower") || STREQ(string, "digit") \
- || STREQ(string, "alnum") || STREQ(string, "xdigit") \
- || STREQ(string, "space") || STREQ(string, "print") \
- || STREQ(string, "punct") || STREQ(string, "graph") \
- || STREQ(string, "cntrl") || STREQ(string, "blank"))
-
-#define STORE_MBC(p, c) \
- do { \
- (p)[0] = (unsigned char)(((c) >>24) & 0xff); \
- (p)[1] = (unsigned char)(((c) >>16) & 0xff); \
- (p)[2] = (unsigned char)(((c) >> 8) & 0xff); \
- (p)[3] = (unsigned char)(((c) >> 0) & 0xff); \
- } while (0)
-
-#define STORE_MBC_AND_INCR(p, c) \
- do { \
- *(p)++ = (unsigned char)(((c) >>24) & 0xff); \
- *(p)++ = (unsigned char)(((c) >>16) & 0xff); \
- *(p)++ = (unsigned char)(((c) >> 8) & 0xff); \
- *(p)++ = (unsigned char)(((c) >> 0) & 0xff); \
- } while (0)
-
-#define EXTRACT_MBC(p) \
- ((unsigned int)((unsigned char)(p)[0] << 24 | \
- (unsigned char)(p)[1] << 16 | \
- (unsigned char)(p)[2] << 8 | \
- (unsigned char)(p)[3]))
-
-#define EXTRACT_MBC_AND_INCR(p) \
- ((unsigned int)((p) += 4, \
- (unsigned char)(p)[-4] << 24 | \
- (unsigned char)(p)[-3] << 16 | \
- (unsigned char)(p)[-2] << 8 | \
- (unsigned char)(p)[-1]))
-
-#define EXTRACT_UNSIGNED(p) \
- ((unsigned char)(p)[0] | (unsigned char)(p)[1] << 8)
-#define EXTRACT_UNSIGNED_AND_INCR(p) \
- ((p) += 2, (unsigned char)(p)[-2] | (unsigned char)(p)[-1] << 8)
-
-/* Handle (mb)?charset(_not)?.
-
- Structure of mbcharset(_not)? in compiled pattern.
-
- struct {
- unsinged char id; mbcharset(_not)?
- unsigned char sbc_size;
- unsigned char sbc_map[sbc_size]; same as charset(_not)? up to here.
- unsigned short mbc_size; number of intervals.
- struct {
- unsigned long beg; beginning of interval.
- unsigned long end; end of interval.
- } intervals[mbc_size];
- }; */
-
-static void
-set_list_bits(c1, c2, b)
- unsigned long c1, c2;
- unsigned char *b;
-{
- unsigned char sbc_size = b[-1];
- unsigned short mbc_size = EXTRACT_UNSIGNED(&b[sbc_size]);
- unsigned short beg, end, upb;
-
- if (c1 > c2)
- return;
- b = &b[sbc_size + 2];
-
- for (beg = 0, upb = mbc_size; beg < upb; ) {
- unsigned short mid = (unsigned short)(beg + upb) >> 1;
-
- if ((int)c1 - 1 > (int)EXTRACT_MBC(&b[mid*8+4]))
- beg = mid + 1;
- else
- upb = mid;
- }
-
- for (end = beg, upb = mbc_size; end < upb; ) {
- unsigned short mid = (unsigned short)(end + upb) >> 1;
-
- if ((int)c2 >= (int)EXTRACT_MBC(&b[mid*8]) - 1)
- end = mid + 1;
- else
- upb = mid;
- }
-
- if (beg != end) {
- if (c1 > EXTRACT_MBC(&b[beg*8]))
- c1 = EXTRACT_MBC(&b[beg*8]);
- if (c2 < EXTRACT_MBC(&b[(end - 1)*8+4]))
- c2 = EXTRACT_MBC(&b[(end - 1)*8+4]);
- }
- if (end < mbc_size && end != beg + 1)
- /* NOTE: memcpy() would not work here. */
- memmove(&b[(beg + 1)*8], &b[end*8], (mbc_size - end)*8);
- STORE_MBC(&b[beg*8 + 0], c1);
- STORE_MBC(&b[beg*8 + 4], c2);
- mbc_size += beg - end + 1;
- STORE_NUMBER(&b[-2], mbc_size);
-}
-
-static int
-is_in_list(c, b)
- unsigned long c;
- const unsigned char *b;
-{
- unsigned short size;
- unsigned short i, j;
-
- size = *b++;
- if ((int)c / BYTEWIDTH < (int)size && b[c / BYTEWIDTH] & 1 << c % BYTEWIDTH) {
- return 1;
- }
- b += size + 2;
- size = EXTRACT_UNSIGNED(&b[-2]);
- if (size == 0) return 0;
-
- for (i = 0, j = size; i < j; ) {
- unsigned short k = (unsigned short)(i + j) >> 1;
-
- if (c > EXTRACT_MBC(&b[k*8+4]))
- i = k + 1;
- else
- j = k;
- }
- if (i < size && EXTRACT_MBC(&b[i*8]) <= c
- && ((unsigned char)c != '\n' && (unsigned char)c != '\0'))
- return 1;
- return 0;
-}
-
-static void
-print_partial_compiled_pattern(start, end)
- unsigned char *start;
- unsigned char *end;
-{
- int mcnt, mcnt2;
- unsigned char *p = start;
- unsigned char *pend = end;
-
- if (start == NULL) {
- printf("(null)\n");
- return;
- }
-
- /* Loop over pattern commands. */
- while (p < pend) {
- switch ((enum regexpcode)*p++) {
- case unused:
- printf("/unused");
- break;
-
- case exactn:
- mcnt = *p++;
- printf("/exactn/%d", mcnt);
- do {
- putchar('/');
- printf("%c", *p++);
- }
- while (--mcnt);
- break;
-
- case start_memory:
- mcnt = *p++;
- printf("/start_memory/%d/%d", mcnt, *p++);
- break;
-
- case stop_memory:
- mcnt = *p++;
- printf("/stop_memory/%d/%d", mcnt, *p++);
- break;
-
- case start_paren:
- printf("/start_paren");
- break;
-
- case stop_paren:
- printf("/stop_paren");
- break;
-
- case casefold_on:
- printf("/casefold_on");
- break;
-
- case casefold_off:
- printf("/casefold_off");
- break;
-
- case option_set:
- printf("/option_set/%d", *p++);
- break;
-
- case start_nowidth:
- EXTRACT_NUMBER_AND_INCR(mcnt, p);
- printf("/start_nowidth//%d", mcnt);
- break;
-
- case stop_nowidth:
- printf("/stop_nowidth//");
- p += 2;
- break;
-
- case pop_and_fail:
- printf("/pop_and_fail");
- break;
-
- case stop_backtrack:
- printf("/stop_backtrack//");
- p += 2;
- break;
-
- case duplicate:
- printf("/duplicate/%d", *p++);
- break;
-
- case anychar:
- printf("/anychar");
- break;
-
- case anychar_repeat:
- printf("/anychar_repeat");
- break;
-
- case charset:
- case charset_not:
- {
- register int c;
-
- printf("/charset%s",
- (enum regexpcode)*(p - 1) == charset_not ? "_not" : "");
-
- mcnt = *p++;
- printf("/%d", mcnt);
- for (c = 0; c < mcnt; c++) {
- unsigned bit;
- unsigned char map_byte = p[c];
-
- putchar ('/');
-
- for (bit = 0; bit < BYTEWIDTH; bit++)
- if (map_byte & (1 << bit))
- printf("%c", c * BYTEWIDTH + bit);
- }
- p += mcnt;
- mcnt = EXTRACT_UNSIGNED_AND_INCR(p);
- printf("/");
- while (mcnt--) {
- print_mbc(EXTRACT_MBC_AND_INCR(p));
- printf("-");
- print_mbc(EXTRACT_MBC_AND_INCR(p));
- }
- break;
- }
-
- case begline:
- printf("/begline");
- break;
-
- case endline:
- printf("/endline");
- break;
-
- case on_failure_jump:
- EXTRACT_NUMBER_AND_INCR(mcnt, p);
- printf("/on_failure_jump//%d", mcnt);
- break;
-
- case dummy_failure_jump:
- EXTRACT_NUMBER_AND_INCR(mcnt, p);
- printf("/dummy_failure_jump//%d", mcnt);
- break;
-
- case push_dummy_failure:
- printf("/push_dummy_failure");
- break;
-
- case finalize_jump:
- EXTRACT_NUMBER_AND_INCR(mcnt, p);
- printf("/finalize_jump//%d", mcnt);
- break;
-
- case maybe_finalize_jump:
- EXTRACT_NUMBER_AND_INCR(mcnt, p);
- printf("/maybe_finalize_jump//%d", mcnt);
- break;
-
- case jump_past_alt:
- EXTRACT_NUMBER_AND_INCR(mcnt, p);
- printf("/jump_past_alt//%d", mcnt);
- break;
-
- case jump:
- EXTRACT_NUMBER_AND_INCR(mcnt, p);
- printf("/jump//%d", mcnt);
- break;
-
- case succeed_n:
- EXTRACT_NUMBER_AND_INCR(mcnt, p);
- EXTRACT_NUMBER_AND_INCR(mcnt2, p);
- printf("/succeed_n//%d//%d", mcnt, mcnt2);
- break;
-
- case jump_n:
- EXTRACT_NUMBER_AND_INCR(mcnt, p);
- EXTRACT_NUMBER_AND_INCR(mcnt2, p);
- printf("/jump_n//%d//%d", mcnt, mcnt2);
- break;
-
- case set_number_at:
- EXTRACT_NUMBER_AND_INCR(mcnt, p);
- EXTRACT_NUMBER_AND_INCR(mcnt2, p);
- printf("/set_number_at//%d//%d", mcnt, mcnt2);
- break;
-
- case try_next:
- EXTRACT_NUMBER_AND_INCR(mcnt, p);
- printf("/try_next//%d", mcnt);
- break;
-
- case finalize_push:
- EXTRACT_NUMBER_AND_INCR(mcnt, p);
- printf("/finalize_push//%d", mcnt);
- break;
-
- case finalize_push_n:
- EXTRACT_NUMBER_AND_INCR(mcnt, p);
- EXTRACT_NUMBER_AND_INCR(mcnt2, p);
- printf("/finalize_push_n//%d//%d", mcnt, mcnt2);
- break;
-
- case wordbound:
- printf("/wordbound");
- break;
-
- case notwordbound:
- printf("/notwordbound");
- break;
-
- case wordbeg:
- printf("/wordbeg");
- break;
-
- case wordend:
- printf("/wordend");
-
- case wordchar:
- printf("/wordchar");
- break;
-
- case notwordchar:
- printf("/notwordchar");
- break;
-
- case begbuf:
- printf("/begbuf");
- break;
-
- case endbuf:
- printf("/endbuf");
- break;
-
- case endbuf2:
- printf("/endbuf2");
- break;
-
- case begpos:
- printf("/begpos");
- break;
-
- default:
- printf("?%d", *(p-1));
- }
- }
- printf("/\n");
-}
-
-
-static void
-print_compiled_pattern(bufp)
- struct re_pattern_buffer *bufp;
-{
- unsigned char *buffer = (unsigned char*)bufp->buffer;
-
- print_partial_compiled_pattern(buffer, buffer + bufp->used);
-}
-
-static char*
-calculate_must_string(start, end)
- char *start;
- char *end;
-{
- int mcnt;
- int max = 0;
- char *p = start;
- char *pend = end;
- char *must = 0;
-
- if (start == NULL) return 0;
-
- /* Loop over pattern commands. */
- while (p < pend) {
- switch ((enum regexpcode)*p++) {
- case unused:
- break;
-
- case exactn:
- mcnt = *p;
- if (mcnt > max) {
- must = p;
- max = mcnt;
- }
- p += mcnt+1;
- break;
-
- case start_memory:
- case stop_memory:
- p += 2;
- break;
-
- case duplicate:
- p++;
- break;
-
- case casefold_on:
- case casefold_off:
- return 0; /* should not check must_string */
-
- case pop_and_fail:
- case anychar:
- case anychar_repeat:
- case begline:
- case endline:
- case wordbound:
- case notwordbound:
- case wordbeg:
- case wordend:
- case wordchar:
- case notwordchar:
- case begbuf:
- case endbuf:
- case endbuf2:
- case begpos:
- case push_dummy_failure:
- case start_paren:
- case stop_paren:
- case option_set:
- break;
-
- case charset:
- case charset_not:
- mcnt = *p++;
- p += mcnt;
- mcnt = EXTRACT_UNSIGNED_AND_INCR(p);
- while (mcnt--) {
- p += 4;
- }
- break;
-
- case on_failure_jump:
- EXTRACT_NUMBER_AND_INCR(mcnt, p);
- if (mcnt > 0) p += mcnt;
- if ((enum regexpcode)p[-3] == jump) {
- p -= 2;
- EXTRACT_NUMBER_AND_INCR(mcnt, p);
- if (mcnt > 0) p += mcnt;
- }
- break;
-
- case dummy_failure_jump:
- case succeed_n:
- case try_next:
- case jump:
- EXTRACT_NUMBER_AND_INCR(mcnt, p);
- if (mcnt > 0) p += mcnt;
- break;
-
- case start_nowidth:
- case stop_nowidth:
- case stop_backtrack:
- case finalize_jump:
- case maybe_finalize_jump:
- case finalize_push:
- p += 2;
- break;
-
- case jump_n:
- case set_number_at:
- case finalize_push_n:
- p += 4;
- break;
-
- default:
- break;
- }
- }
- return must;
-}
-
-static unsigned int
-read_backslash(c)
- int c;
-{
- switch (c) {
- case 'n':
- return '\n';
-
- case 't':
- return '\t';
-
- case 'r':
- return '\r';
-
- case 'f':
- return '\f';
-
- case 'v':
- return '\v';
-
- case 'a':
- return '\007';
-
- case 'b':
- return '\010';
-
- case 'e':
- return '\033';
- }
- return c;
-}
-
-static unsigned int
-read_special(p, pend, pp)
- const char *p, *pend, **pp;
-{
- int c;
-
- PATFETCH_RAW(c);
- switch (c) {
- case 'M':
- PATFETCH_RAW(c);
- if (c != '-') return -1;
- PATFETCH_RAW(c);
- *pp = p;
- if (c == '\\') {
- return read_special(p, pend, pp) | 0x80;
- }
- else if (c == -1) return ~0;
- else {
- return ((c & 0xff) | 0x80);
- }
-
- case 'C':
- PATFETCH_RAW(c);
- if (c != '-') return ~0;
- case 'c':
- PATFETCH_RAW(c);
- *pp = p;
- if (c == '\\') {
- c = read_special(p, pend, pp);
- }
- else if (c == '?') return 0177;
- else if (c == -1) return ~0;
- return c & 0x9f;
- default:
- return read_backslash(c);
- }
-
- end_of_pattern:
- return ~0;
-}
-
-/* re_compile_pattern takes a regular-expression string
- and converts it into a buffer full of byte commands for matching.
-
- PATTERN is the address of the pattern string
- SIZE is the length of it.
- BUFP is a struct re_pattern_buffer * which points to the info
- on where to store the byte commands.
- This structure contains a char * which points to the
- actual space, which should have been obtained with malloc.
- re_compile_pattern may use realloc to grow the buffer space.
-
- The number of bytes of commands can be found out by looking in
- the `struct re_pattern_buffer' that bufp pointed to, after
- re_compile_pattern returns. */
-
-char *
-re_compile_pattern(pattern, size, bufp)
- const char *pattern;
- int size;
- struct re_pattern_buffer *bufp;
-{
- register char *b = bufp->buffer;
- register const char *p = pattern;
- const char *nextp;
- const char *pend = pattern + size;
- register unsigned int c, c1 = 0;
- const char *p0;
- int numlen;
-#define ERROR_MSG_MAX_SIZE 200
- static char error_msg[ERROR_MSG_MAX_SIZE+1];
-
- /* Address of the count-byte of the most recently inserted `exactn'
- command. This makes it possible to tell whether a new exact-match
- character can be added to that command or requires a new `exactn'
- command. */
-
- char *pending_exact = 0;
-
- /* Address of the place where a forward-jump should go to the end of
- the containing expression. Each alternative of an `or', except the
- last, ends with a forward-jump of this sort. */
-
- char *fixup_alt_jump = 0;
-
- /* Address of start of the most recently finished expression.
- This tells postfix * where to find the start of its operand. */
-
- char *laststart = 0;
-
- /* In processing a repeat, 1 means zero matches is allowed. */
-
- char zero_times_ok;
-
- /* In processing a repeat, 1 means many matches is allowed. */
-
- char many_times_ok;
-
- /* In processing a repeat, 1 means non-greedy matches. */
-
- char greedy;
-
- /* Address of beginning of regexp, or inside of last (. */
-
- char *begalt = b;
-
- /* Place in the uncompiled pattern (i.e., the {) to
- which to go back if the interval is invalid. */
- const char *beg_interval;
-
- /* In processing an interval, at least this many matches must be made. */
- int lower_bound;
-
- /* In processing an interval, at most this many matches can be made. */
- int upper_bound;
-
- /* Stack of information saved by ( and restored by ).
- Five stack elements are pushed by each (:
- First, the value of b.
- Second, the value of fixup_alt_jump.
- Third, the value of begalt.
- Fourth, the value of regnum.
- Fifth, the type of the paren. */
-
- int stacka[40];
- int *stackb = stacka;
- int *stackp = stackb;
- int *stacke = stackb + 40;
-
- /* Counts ('s as they are encountered. Remembered for the matching ),
- where it becomes the register number to put in the stop_memory
- command. */
-
- int regnum = 1;
-
- int range = 0;
- int had_mbchar = 0;
- int had_num_literal = 0;
- int had_char_class = 0;
-
- int options = bufp->options;
-
- bufp->fastmap_accurate = 0;
- bufp->must = 0;
- bufp->must_skip = 0;
-
- /* Initialize the syntax table. */
- init_syntax_once();
-
- if (bufp->allocated == 0) {
- bufp->allocated = INIT_BUF_SIZE;
- /* EXTEND_BUFFER loses when bufp->allocated is 0. */
- bufp->buffer = (char*)xrealloc(bufp->buffer, INIT_BUF_SIZE);
- if (!bufp->buffer) goto memory_exhausted; /* this not happen */
- begalt = b = bufp->buffer;
- }
-
- while (p != pend) {
- PATFETCH(c);
-
- switch (c) {
- case '$':
- if (bufp->options & RE_OPTION_SINGLELINE) {
- BUFPUSH(endbuf);
- }
- else {
- p0 = p;
- /* When testing what follows the $,
- look past the \-constructs that don't consume anything. */
-
- while (p0 != pend) {
- if (*p0 == '\\' && p0 + 1 != pend
- && (p0[1] == 'b' || p0[1] == 'B'))
- p0 += 2;
- else
- break;
- }
- BUFPUSH(endline);
- }
- break;
-
- case '^':
- if (bufp->options & RE_OPTION_SINGLELINE)
- BUFPUSH(begbuf);
- else
- BUFPUSH(begline);
- break;
-
- case '+':
- case '?':
- case '*':
- /* If there is no previous pattern, char not special. */
- if (!laststart) {
- snprintf(error_msg, ERROR_MSG_MAX_SIZE,
- "invalid regular expression; there's no previous pattern, to which '%c' would define cardinality at %d",
- c, p-pattern);
- FREE_AND_RETURN(stackb, error_msg);
- }
- /* If there is a sequence of repetition chars,
- collapse it down to just one. */
- zero_times_ok = c != '+';
- many_times_ok = c != '?';
- greedy = 1;
- if (p != pend) {
- PATFETCH(c);
- switch (c) {
- case '?':
- greedy = 0;
- break;
- case '*':
- case '+':
- goto nested_meta;
- default:
- PATUNFETCH;
- break;
- }
- }
-
- repeat:
- /* Star, etc. applied to an empty pattern is equivalent
- to an empty pattern. */
- if (!laststart)
- break;
-
- if (greedy && many_times_ok && *laststart == anychar && b - laststart <= 2) {
- if (b[-1] == stop_paren)
- b--;
- if (zero_times_ok)
- *laststart = anychar_repeat;
- else {
- BUFPUSH(anychar_repeat);
- }
- break;
- }
- /* Now we know whether or not zero matches is allowed
- and also whether or not two or more matches is allowed. */
- if (many_times_ok) {
- /* If more than one repetition is allowed, put in at the
- end a backward relative jump from b to before the next
- jump we're going to put in below (which jumps from
- laststart to after this jump). */
- GET_BUFFER_SPACE(3);
- store_jump(b,greedy?maybe_finalize_jump:finalize_push,laststart-3);
- b += 3; /* Because store_jump put stuff here. */
- }
-
- /* On failure, jump from laststart to next pattern, which will be the
- end of the buffer after this jump is inserted. */
- GET_BUFFER_SPACE(3);
- insert_jump(on_failure_jump, laststart, b + 3, b);
- b += 3;
-
- if (zero_times_ok) {
- if (greedy == 0) {
- GET_BUFFER_SPACE(3);
- insert_jump(try_next, laststart, b + 3, b);
- b += 3;
- }
- }
- else {
- /* At least one repetition is required, so insert a
- `dummy_failure_jump' before the initial
- `on_failure_jump' instruction of the loop. This
- effects a skip over that instruction the first time
- we hit that loop. */
- GET_BUFFER_SPACE(3);
- insert_jump(dummy_failure_jump, laststart, laststart + 6, b);
- b += 3;
- }
- break;
-
- case '.':
- laststart = b;
- BUFPUSH(anychar);
- break;
-
- case '[':
- if (p == pend)
- FREE_AND_RETURN(stackb, "invalid regular expression; '[' can't be the last character ie. can't start range at the end of pattern");
- while ((b - bufp->buffer + 9 + (1 << BYTEWIDTH) / BYTEWIDTH)
- > bufp->allocated)
- EXTEND_BUFFER;
-
- laststart = b;
- if (*p == '^') {
- BUFPUSH(charset_not);
- p++;
- }
- else
- BUFPUSH(charset);
- p0 = p;
-
- BUFPUSH((1 << BYTEWIDTH) / BYTEWIDTH);
- /* Clear the whole map */
- memset(b, 0, (1 << BYTEWIDTH) / BYTEWIDTH + 2);
-
- had_mbchar = 0;
- had_num_literal = 0;
- had_char_class = 0;
-
- /* Read in characters and ranges, setting map bits. */
- for (;;) {
- int size;
- unsigned last = (unsigned)-1;
-
- if ((size = EXTRACT_UNSIGNED(&b[(1 << BYTEWIDTH) / BYTEWIDTH]))
- || current_mbctype) {
- /* Ensure the space is enough to hold another interval
- of multi-byte chars in charset(_not)?. */
- size = (1 << BYTEWIDTH) / BYTEWIDTH + 2 + size*8 + 8;
- while (b + size + 1 > bufp->buffer + bufp->allocated)
- EXTEND_BUFFER;
- }
- range_retry:
- if (range && had_char_class) {
- FREE_AND_RETURN(stackb, "invalid regular expression; can't use character class as an end value of range");
- }
- PATFETCH(c);
-
- if (c == ']') {
- if (p == p0 + 1) {
- if (p == pend)
- FREE_AND_RETURN(stackb, "invalid regular expression; empty character class");
- }
- else
- /* Stop if this isn't merely a ] inside a bracket
- expression, but rather the end of a bracket
- expression. */
- break;
- }
- /* Look ahead to see if it's a range when the last thing
- was a character class. */
- if (had_char_class && c == '-' && *p != ']')
- FREE_AND_RETURN(stackb, "invalid regular expression; can't use character class as a start value of range");
- if (ismbchar(c)) {
- PATFETCH_MBC(c);
- had_mbchar++;
- }
- had_char_class = 0;
-
- /* \ escapes characters when inside [...]. */
- if (c == '\\') {
- PATFETCH_RAW(c);
- switch (c) {
- case 'w':
- for (c = 0; c < (1 << BYTEWIDTH); c++) {
- if (SYNTAX(c) == Sword ||
- (!current_mbctype && SYNTAX(c) == Sword2))
- SET_LIST_BIT(c);
- }
- if (current_mbctype) {
- set_list_bits(0x80, 0xffffffff, b);
- }
- had_char_class = 1;
- last = -1;
- continue;
-
- case 'W':
- for (c = 0; c < (1 << BYTEWIDTH); c++) {
- if (SYNTAX(c) != Sword &&
- ((current_mbctype && !re_mbctab[c]) ||
- (!current_mbctype && SYNTAX(c) != Sword2)))
- SET_LIST_BIT(c);
- }
- had_char_class = 1;
- last = -1;
- continue;
-
- case 's':
- for (c = 0; c < 256; c++)
- if (ISSPACE(c))
- SET_LIST_BIT(c);
- had_char_class = 1;
- last = -1;
- continue;
-
- case 'S':
- for (c = 0; c < 256; c++)
- if (!ISSPACE(c))
- SET_LIST_BIT(c);
- if (current_mbctype)
- set_list_bits(0x80, 0xffffffff, b);
- had_char_class = 1;
- last = -1;
- continue;
-
- case 'd':
- for (c = '0'; c <= '9'; c++)
- SET_LIST_BIT(c);
- had_char_class = 1;
- last = -1;
- continue;
-
- case 'D':
- for (c = 0; c < 256; c++)
- if (!ISDIGIT(c))
- SET_LIST_BIT(c);
- if (current_mbctype)
- set_list_bits(0x80, 0xffffffff, b);
- had_char_class = 1;
- last = -1;
- continue;
-
- case 'x':
- c = scan_hex(p, 2, &numlen);
- p += numlen;
- had_num_literal = 1;
- break;
-
- case '0': case '1': case '2': case '3': case '4':
- case '5': case '6': case '7': case '8': case '9':
- PATUNFETCH;
- c = scan_oct(p, 3, &numlen);
- p += numlen;
- had_num_literal = 1;
- break;
-
- case 'M':
- case 'C':
- case 'c':
- {
- char *pp;
-
- --p;
- c = read_special(p, pend, &pp);
- if (c > 255) goto invalid_escape;
- p = pp;
- had_num_literal = 1;
- }
- break;
-
- default:
- c = read_backslash(c);
- if (ismbchar(c)) {
- PATFETCH_MBC(c);
- had_mbchar++;
- }
- break;
- }
- }
-
- /* Get a range. */
- if (range) {
- if (last > c)
- goto invalid_pattern;
-
- range = 0;
- if (had_mbchar == 0) {
- for (;last<=c;last++)
- SET_LIST_BIT(last);
- }
- else if (had_mbchar == 2) {
- set_list_bits(last, c, b);
- }
- else {
- /* restriction: range between sbc and mbc */
- goto invalid_pattern;
- }
- }
- else if (p[0] == '-' && p[1] != ']') {
- last = c;
- PATFETCH(c1);
- range = 1;
- goto range_retry;
- }
- else if (c == '[' && *p == ':') {
- /* Leave room for the null. */
- char str[CHAR_CLASS_MAX_LENGTH + 1];
-
- PATFETCH_RAW(c);
- c1 = 0;
-
- /* If pattern is `[[:'. */
- if (p == pend)
- FREE_AND_RETURN(stackb, "invalid regular expression; re can't end '[[:'");
-
- for (;;) {
- PATFETCH (c);
- if (c == ':' || c == ']' || p == pend
- || c1 == CHAR_CLASS_MAX_LENGTH)
- break;
- str[c1++] = c;
- }
- str[c1] = '\0';
-
- /* If isn't a word bracketed by `[:' and:`]':
- undo the ending character, the letters, and leave
- the leading `:' and `[' (but set bits for them). */
- if (c == ':' && *p == ']') {
- int ch;
- char is_alnum = STREQ(str, "alnum");
- char is_alpha = STREQ(str, "alpha");
- char is_blank = STREQ(str, "blank");
- char is_cntrl = STREQ(str, "cntrl");
- char is_digit = STREQ(str, "digit");
- char is_graph = STREQ(str, "graph");
- char is_lower = STREQ(str, "lower");
- char is_print = STREQ(str, "print");
- char is_punct = STREQ(str, "punct");
- char is_space = STREQ(str, "space");
- char is_upper = STREQ(str, "upper");
- char is_xdigit = STREQ(str, "xdigit");
-
- if (!IS_CHAR_CLASS(str)){
- snprintf(error_msg, ERROR_MSG_MAX_SIZE,
- "invalid regular expression; [:%s:] is not a character class", str);
- FREE_AND_RETURN(stackb, error_msg);
- }
-
- /* Throw away the ] at the end of the character class. */
- PATFETCH(c);
-
- if (p == pend)
- FREE_AND_RETURN(stackb, "invalid regular expression; range doesn't have ending ']' after a character class");
-
- for (ch = 0; ch < 1 << BYTEWIDTH; ch++) {
- if ( (is_alnum && ISALNUM(ch))
- || (is_alpha && ISALPHA(ch))
- || (is_blank && ISBLANK(ch))
- || (is_cntrl && ISCNTRL(ch))
- || (is_digit && ISDIGIT(ch))
- || (is_graph && ISGRAPH(ch))
- || (is_lower && ISLOWER(ch))
- || (is_print && ISPRINT(ch))
- || (is_punct && ISPUNCT(ch))
- || (is_space && ISSPACE(ch))
- || (is_upper && ISUPPER(ch))
- || (is_xdigit && ISXDIGIT(ch)))
- SET_LIST_BIT(ch);
- }
- had_char_class = 1;
- }
- else {
- c1++;
- while (c1--)
- PATUNFETCH;
- SET_LIST_BIT(TRANSLATE_P()?translate['[']:'[');
- SET_LIST_BIT(TRANSLATE_P()?translate[':']:':');
- had_char_class = 0;
- last = ':';
- }
- }
- else if (had_mbchar == 0 && (!current_mbctype || !had_num_literal)) {
- SET_LIST_BIT(c);
- had_num_literal = 0;
- }
- else
- set_list_bits(c, c, b);
- had_mbchar = 0;
- }
-
- /* Discard any character set/class bitmap bytes that are all
- 0 at the end of the map. Decrement the map-length byte too. */
- while ((int)b[-1] > 0 && b[b[-1] - 1] == 0)
- b[-1]--;
- if (b[-1] != (1 << BYTEWIDTH) / BYTEWIDTH)
- memmove(&b[b[-1]], &b[(1 << BYTEWIDTH) / BYTEWIDTH],
- 2 + EXTRACT_UNSIGNED(&b[(1 << BYTEWIDTH) / BYTEWIDTH])*8);
- b += b[-1] + 2 + EXTRACT_UNSIGNED(&b[b[-1]])*8;
- break;
-
- case '(':
- {
- int old_options = options;
- int push_option = 0;
- int casefold = 0;
-
- PATFETCH(c);
- if (c == '?') {
- int negative = 0;
-
- PATFETCH_RAW(c);
- switch (c) {
- case 'x': case 'p': case 'm': case 'i': case '-':
- for (;;) {
- switch (c) {
- case '-':
- negative = 1;
- break;
-
- case ':':
- case ')':
- break;
-
- case 'x':
- if (negative)
- options &= ~RE_OPTION_EXTENDED;
- else
- options |= RE_OPTION_EXTENDED;
- break;
-
- case 'p':
- if (negative) {
- if ((options&RE_OPTION_POSIXLINE) == RE_OPTION_POSIXLINE) {
- options &= ~RE_OPTION_POSIXLINE;
- }
- }
- else if ((options&RE_OPTION_POSIXLINE) != RE_OPTION_POSIXLINE) {
- options |= RE_OPTION_POSIXLINE;
- }
- push_option = 1;
- break;
-
- case 'm':
- if (negative) {
- if (options&RE_OPTION_MULTILINE) {
- options &= ~RE_OPTION_MULTILINE;
- }
- }
- else if (!(options&RE_OPTION_MULTILINE)) {
- options |= RE_OPTION_MULTILINE;
- }
- push_option = 1;
- break;
-
- case 'i':
- if (negative) {
- if (options&RE_OPTION_IGNORECASE) {
- options &= ~RE_OPTION_IGNORECASE;
- }
- }
- else if (!(options&RE_OPTION_IGNORECASE)) {
- options |= RE_OPTION_IGNORECASE;
- }
- casefold = 1;
- break;
-
- default:
- FREE_AND_RETURN(stackb, "undefined (?...) inline option");
- }
- if (c == ')') {
- c = '#'; /* read whole in-line options */
- break;
- }
- if (c == ':') break;
- PATFETCH_RAW(c);
- }
- break;
-
- case '#':
- for (;;) {
- PATFETCH(c);
- if (c == ')') break;
- }
- c = '#';
- break;
-
- case ':':
- case '=':
- case '!':
- case '>':
- break;
-
- default:
- FREE_AND_RETURN(stackb, "undefined (?...) sequence");
- }
- }
- else {
- PATUNFETCH;
- c = '(';
- }
- if (c == '#') {
- if (push_option) {
- BUFPUSH(option_set);
- BUFPUSH(options);
- }
- if (casefold) {
- if (options & RE_OPTION_IGNORECASE)
- BUFPUSH(casefold_on);
- else
- BUFPUSH(casefold_off);
- }
- break;
- }
- if (stackp+8 >= stacke) {
- DOUBLE_STACK(int);
- }
-
- /* Laststart should point to the start_memory that we are about
- to push (unless the pattern has RE_NREGS or more ('s). */
- /* obsolete: now RE_NREGS is just a default register size. */
- *stackp++ = b - bufp->buffer;
- *stackp++ = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
- *stackp++ = begalt - bufp->buffer;
- switch (c) {
- case '(':
- BUFPUSH(start_memory);
- BUFPUSH(regnum);
- *stackp++ = regnum++;
- *stackp++ = b - bufp->buffer;
- BUFPUSH(0);
- /* too many ()'s to fit in a byte. (max 254) */
- if (regnum >= RE_REG_MAX) goto too_big;
- break;
-
- case '=':
- case '!':
- case '>':
- BUFPUSH(start_nowidth);
- *stackp++ = b - bufp->buffer;
- BUFPUSH(0); /* temporary value */
- BUFPUSH(0);
- if (c != '!') break;
-
- BUFPUSH(on_failure_jump);
- *stackp++ = b - bufp->buffer;
- BUFPUSH(0); /* temporary value */
- BUFPUSH(0);
- break;
-
- case ':':
- BUFPUSH(start_paren);
- pending_exact = 0;
- default:
- break;
- }
- if (push_option) {
- BUFPUSH(option_set);
- BUFPUSH(options);
- }
- if (casefold) {
- if (options & RE_OPTION_IGNORECASE)
- BUFPUSH(casefold_on);
- else
- BUFPUSH(casefold_off);
- }
- *stackp++ = c;
- *stackp++ = old_options;
- fixup_alt_jump = 0;
- laststart = 0;
- begalt = b;
- }
- break;
-
- case ')':
- if (stackp == stackb)
- FREE_AND_RETURN(stackb, "unmatched )");
-
- pending_exact = 0;
- if (fixup_alt_jump) {
- /* Push a dummy failure point at the end of the
- alternative for a possible future
- `finalize_jump' to pop. See comments at
- `push_dummy_failure' in `re_match'. */
- BUFPUSH(push_dummy_failure);
-
- /* We allocated space for this jump when we assigned
- to `fixup_alt_jump', in the `handle_alt' case below. */
- store_jump(fixup_alt_jump, jump, b);
- }
- if (options != stackp[-1]) {
- if ((options ^ stackp[-1]) & RE_OPTION_IGNORECASE) {
- BUFPUSH((options&RE_OPTION_IGNORECASE)?casefold_off:casefold_on);
- }
- if ((options ^ stackp[-1]) != RE_OPTION_IGNORECASE) {
- BUFPUSH(option_set);
- BUFPUSH(stackp[-1]);
- }
- }
- p0 = b;
- options = *--stackp;
- switch (c = *--stackp) {
- case '(':
- {
- char *loc = bufp->buffer + *--stackp;
- *loc = regnum - stackp[-1];
- BUFPUSH(stop_memory);
- BUFPUSH(stackp[-1]);
- BUFPUSH(regnum - stackp[-1]);
- stackp--;
- }
- break;
-
- case '!':
- BUFPUSH(pop_and_fail);
- /* back patch */
- STORE_NUMBER(bufp->buffer+stackp[-1], b - bufp->buffer - stackp[-1] - 2);
- stackp--;
- /* fall through */
- case '=':
- BUFPUSH(stop_nowidth);
- /* tell stack-pos place to start_nowidth */
- STORE_NUMBER(bufp->buffer+stackp[-1], b - bufp->buffer - stackp[-1] - 2);
- BUFPUSH(0); /* space to hold stack pos */
- BUFPUSH(0);
- stackp--;
- break;
-
- case '>':
- BUFPUSH(stop_backtrack);
- /* tell stack-pos place to start_nowidth */
- STORE_NUMBER(bufp->buffer+stackp[-1], b - bufp->buffer - stackp[-1] - 2);
- BUFPUSH(0); /* space to hold stack pos */
- BUFPUSH(0);
- stackp--;
- break;
-
- case ':':
- BUFPUSH(stop_paren);
- break;
-
- default:
- break;
- }
- begalt = *--stackp + bufp->buffer;
- stackp--;
- fixup_alt_jump = *stackp ? *stackp + bufp->buffer - 1 : 0;
- laststart = *--stackp + bufp->buffer;
- if (c == '!' || c == '=') laststart = b;
- break;
-
- case '|':
- /* Insert before the previous alternative a jump which
- jumps to this alternative if the former fails. */
- GET_BUFFER_SPACE(3);
- insert_jump(on_failure_jump, begalt, b + 6, b);
- pending_exact = 0;
- b += 3;
- /* The alternative before this one has a jump after it
- which gets executed if it gets matched. Adjust that
- jump so it will jump to this alternative's analogous
- jump (put in below, which in turn will jump to the next
- (if any) alternative's such jump, etc.). The last such
- jump jumps to the correct final destination. A picture:
- _____ _____
- | | | |
- | v | v
- a | b | c
-
- If we are at `b', then fixup_alt_jump right now points to a
- three-byte space after `a'. We'll put in the jump, set
- fixup_alt_jump to right after `b', and leave behind three
- bytes which we'll fill in when we get to after `c'. */
-
- if (fixup_alt_jump)
- store_jump(fixup_alt_jump, jump_past_alt, b);
-
- /* Mark and leave space for a jump after this alternative,
- to be filled in later either by next alternative or
- when know we're at the end of a series of alternatives. */
- fixup_alt_jump = b;
- GET_BUFFER_SPACE(3);
- b += 3;
-
- laststart = 0;
- begalt = b;
- break;
-
- case '{':
- /* If there is no previous pattern, this is an invalid pattern. */
- if (!laststart) {
- snprintf(error_msg, ERROR_MSG_MAX_SIZE,
- "invalid regular expression; there's no previous pattern, to which '{' would define cardinality at %d",
- p-pattern);
- FREE_AND_RETURN(stackb, error_msg);
- }
- if( p == pend)
- FREE_AND_RETURN(stackb, "invalid regular expression; '{' can't be last character" );
-
- beg_interval = p - 1;
-
- lower_bound = -1; /* So can see if are set. */
- upper_bound = -1;
- GET_UNSIGNED_NUMBER(lower_bound);
- if (c == ',') {
- GET_UNSIGNED_NUMBER(upper_bound);
- }
- else
- /* Interval such as `{1}' => match exactly once. */
- upper_bound = lower_bound;
-
- if (lower_bound < 0 || c != '}')
- goto unfetch_interval;
-
- if (lower_bound >= RE_DUP_MAX || upper_bound >= RE_DUP_MAX)
- FREE_AND_RETURN(stackb, "too big quantifier in {,}");
- if (upper_bound < 0) upper_bound = RE_DUP_MAX;
- if (lower_bound > upper_bound)
- FREE_AND_RETURN(stackb, "can't do {n,m} with n > m");
-
- beg_interval = 0;
- pending_exact = 0;
-
- greedy = 1;
- if (p != pend) {
- PATFETCH(c);
- if (c == '?') greedy = 0;
- else PATUNFETCH;
- }
-
- if (lower_bound == 0) {
- zero_times_ok = 1;
- if (upper_bound == RE_DUP_MAX) {
- many_times_ok = 1;
- goto repeat;
- }
- if (upper_bound == 1) {
- many_times_ok = 0;
- goto repeat;
- }
- }
- if (lower_bound == 1) {
- if (upper_bound == 1) {
- /* No need to repeat */
- break;
- }
- if (upper_bound == RE_DUP_MAX) {
- many_times_ok = 1;
- zero_times_ok = 0;
- goto repeat;
- }
- }
-
- /* If upper_bound is zero, don't want to succeed at all;
- jump from laststart to b + 3, which will be the end of
- the buffer after this jump is inserted. */
-
- if (upper_bound == 0) {
- GET_BUFFER_SPACE(3);
- insert_jump(jump, laststart, b + 3, b);
- b += 3;
- break;
- }
-
- /* If lower_bound == upper_bound, repeat count can be removed */
- if (lower_bound == upper_bound) {
- int mcnt;
- int skip_stop_paren = 0;
-
- if (b[-1] == stop_paren) {
- skip_stop_paren = 1;
- b--;
- }
-
- if (*laststart == exactn && laststart[1]+2 == b - laststart
- && laststart[1]*lower_bound < 256) {
- mcnt = laststart[1];
- GET_BUFFER_SPACE((lower_bound-1)*mcnt);
- laststart[1] = lower_bound*mcnt;
- while (--lower_bound) {
- memcpy(b, laststart+2, mcnt);
- b += mcnt;
- }
- if (skip_stop_paren) BUFPUSH(stop_paren);
- break;
- }
-
- if (lower_bound < 5 && b - laststart < 10) {
- /* 5 and 10 are the magic numbers */
-
- mcnt = b - laststart;
- GET_BUFFER_SPACE((lower_bound-1)*mcnt);
- while (--lower_bound) {
- memcpy(b, laststart, mcnt);
- b += mcnt;
- }
- if (skip_stop_paren) BUFPUSH(stop_paren);
- break;
- }
- if (skip_stop_paren) b++; /* push back stop_paren */
- }
-
- /* Otherwise, we have a nontrivial interval. When
- we're all done, the pattern will look like:
- set_number_at <jump count> <upper bound>
- set_number_at <succeed_n count> <lower bound>
- succeed_n <after jump addr> <succed_n count>
- <body of loop>
- jump_n <succeed_n addr> <jump count>
- (The upper bound and `jump_n' are omitted if
- `upper_bound' is 1, though.) */
- { /* If the upper bound is > 1, we need to insert
- more at the end of the loop. */
- unsigned nbytes = upper_bound == 1 ? 10 : 20;
-
- GET_BUFFER_SPACE(nbytes);
- /* Initialize lower bound of the `succeed_n', even
- though it will be set during matching by its
- attendant `set_number_at' (inserted next),
- because `re_compile_fastmap' needs to know.
- Jump to the `jump_n' we might insert below. */
- insert_jump_n(succeed_n, laststart, b + (nbytes/2),
- b, lower_bound);
- b += 5; /* Just increment for the succeed_n here. */
-
- /* Code to initialize the lower bound. Insert
- before the `succeed_n'. The `5' is the last two
- bytes of this `set_number_at', plus 3 bytes of
- the following `succeed_n'. */
- insert_op_2(set_number_at, laststart, b, 5, lower_bound);
- b += 5;
-
- if (upper_bound > 1) {
- /* More than one repetition is allowed, so
- append a backward jump to the `succeed_n'
- that starts this interval.
-
- When we've reached this during matching,
- we'll have matched the interval once, so
- jump back only `upper_bound - 1' times. */
- GET_BUFFER_SPACE(5);
- store_jump_n(b, greedy?jump_n:finalize_push_n, laststart + 5,
- upper_bound - 1);
- b += 5;
-
- /* The location we want to set is the second
- parameter of the `jump_n'; that is `b-2' as
- an absolute address. `laststart' will be
- the `set_number_at' we're about to insert;
- `laststart+3' the number to set, the source
- for the relative address. But we are
- inserting into the middle of the pattern --
- so everything is getting moved up by 5.
- Conclusion: (b - 2) - (laststart + 3) + 5,
- i.e., b - laststart.
-
- We insert this at the beginning of the loop
- so that if we fail during matching, we'll
- reinitialize the bounds. */
- insert_op_2(set_number_at, laststart, b, b - laststart,
- upper_bound - 1);
- b += 5;
- }
- }
- break;
-
- unfetch_interval:
- /* If an invalid interval, match the characters as literals. */
- p = beg_interval;
- beg_interval = 0;
-
- /* normal_char and normal_backslash need `c'. */
- PATFETCH(c);
- goto normal_char;
-
- case '\\':
- if (p == pend)
- FREE_AND_RETURN(stackb, "invalid regular expression; '\\' can't be last character");
- /* Do not translate the character after the \, so that we can
- distinguish, e.g., \B from \b, even if we normally would
- translate, e.g., B to b. */
- PATFETCH_RAW(c);
- switch (c) {
- case 's':
- case 'S':
- case 'd':
- case 'D':
- while (b - bufp->buffer + 9 + (1 << BYTEWIDTH) / BYTEWIDTH
- > bufp->allocated)
- EXTEND_BUFFER;
-
- laststart = b;
- if (c == 's' || c == 'd') {
- BUFPUSH(charset);
- }
- else {
- BUFPUSH(charset_not);
- }
-
- BUFPUSH((1 << BYTEWIDTH) / BYTEWIDTH);
- memset(b, 0, (1 << BYTEWIDTH) / BYTEWIDTH + 2);
- if (c == 's' || c == 'S') {
- SET_LIST_BIT(' ');
- SET_LIST_BIT('\t');
- SET_LIST_BIT('\n');
- SET_LIST_BIT('\r');
- SET_LIST_BIT('\f');
- }
- else {
- char cc;
-
- for (cc = '0'; cc <= '9'; cc++) {
- SET_LIST_BIT(cc);
- }
- }
-
- while ((int)b[-1] > 0 && b[b[-1] - 1] == 0)
- b[-1]--;
- if (b[-1] != (1 << BYTEWIDTH) / BYTEWIDTH)
- memmove(&b[b[-1]], &b[(1 << BYTEWIDTH) / BYTEWIDTH],
- 2 + EXTRACT_UNSIGNED(&b[(1 << BYTEWIDTH) / BYTEWIDTH])*8);
- b += b[-1] + 2 + EXTRACT_UNSIGNED(&b[b[-1]])*8;
- break;
-
- case 'w':
- laststart = b;
- BUFPUSH(wordchar);
- break;
-
- case 'W':
- laststart = b;
- BUFPUSH(notwordchar);
- break;
-
-#ifndef RUBY
- case '<':
- BUFPUSH(wordbeg);
- break;
-
- case '>':
- BUFPUSH(wordend);
- break;
-#endif
-
- case 'b':
- BUFPUSH(wordbound);
- break;
-
- case 'B':
- BUFPUSH(notwordbound);
- break;
-
- case 'A':
- BUFPUSH(begbuf);
- break;
-
- case 'Z':
- if ((bufp->options & RE_OPTION_SINGLELINE) == 0) {
- BUFPUSH(endbuf2);
- break;
- }
- /* fall through */
- case 'z':
- BUFPUSH(endbuf);
- break;
-
- case 'G':
- BUFPUSH(begpos);
- break;
-
- /* hex */
- case 'x':
- had_mbchar = 0;
- c = scan_hex(p, 2, &numlen);
- p += numlen;
- had_num_literal = 1;
- goto numeric_char;
-
- /* octal */
- case '0':
- had_mbchar = 0;
- c = scan_oct(p, 2, &numlen);
- p += numlen;
- had_num_literal = 1;
- goto numeric_char;
-
- /* back-ref or octal */
- case '1': case '2': case '3':
- case '4': case '5': case '6':
- case '7': case '8': case '9':
- PATUNFETCH;
- p0 = p;
-
- had_mbchar = 0;
- c1 = 0;
- GET_UNSIGNED_NUMBER(c1);
- if (!ISDIGIT(c)) PATUNFETCH;
-
- if (9 < c1 && c1 >= regnum) {
- /* need to get octal */
- c = scan_oct(p0, 3, &numlen) & 0xff;
- p = p0 + numlen;
- c1 = 0;
- had_num_literal = 1;
- goto numeric_char;
- }
-
- laststart = b;
- BUFPUSH(duplicate);
- BUFPUSH(c1);
- break;
-
- case 'M':
- case 'C':
- case 'c':
- p0 = --p;
- c = read_special(p, pend, &p0);
- if (c > 255) goto invalid_escape;
- p = p0;
- had_num_literal = 1;
- goto numeric_char;
-
- default:
- c = read_backslash(c);
- goto normal_char;
- }
- break;
-
- case '#':
- if (options & RE_OPTION_EXTENDED) {
- while (p != pend) {
- PATFETCH(c);
- if (c == '\n') break;
- }
- break;
- }
- goto normal_char;
-
- case ' ':
- case '\t':
- case '\f':
- case '\r':
- case '\n':
- if (options & RE_OPTION_EXTENDED)
- break;
-
- default:
- normal_char: /* Expects the character in `c'. */
- had_mbchar = 0;
- if (ismbchar(c)) {
- had_mbchar = 1;
- c1 = p - pattern;
- }
- numeric_char:
- nextp = p + mbclen(c) - 1;
- if (!pending_exact || pending_exact + *pending_exact + 1 != b
- || *pending_exact >= (c1 ? 0176 : 0177)
- || *nextp == '+' || *nextp == '?'
- || *nextp == '*' || *nextp == '^'
- || *nextp == '{') {
- laststart = b;
- BUFPUSH(exactn);
- pending_exact = b;
- BUFPUSH(0);
- }
- if (had_num_literal || c == 0xff) {
- BUFPUSH(0xff);
- (*pending_exact)++;
- had_num_literal = 0;
- }
- BUFPUSH(c);
- (*pending_exact)++;
- if (had_mbchar) {
- int len = mbclen(c) - 1;
- while (len--) {
- PATFETCH_RAW(c);
- BUFPUSH(c);
- (*pending_exact)++;
- }
- }
- }
- }
-
- if (fixup_alt_jump)
- store_jump(fixup_alt_jump, jump, b);
-
- if (stackp != stackb)
- FREE_AND_RETURN(stackb, "unmatched (");
-
- /* set optimize flags */
- laststart = bufp->buffer;
- if (laststart != b) {
- if (*laststart == start_memory) laststart += 3;
- if (*laststart == dummy_failure_jump) laststart += 3;
- else if (*laststart == try_next) laststart += 3;
- if (*laststart == anychar_repeat) {
- bufp->options |= RE_OPTIMIZE_ANCHOR;
- }
- }
-
- bufp->used = b - bufp->buffer;
- bufp->re_nsub = regnum;
- laststart = bufp->buffer;
- if (laststart != b) {
- if (*laststart == start_memory) laststart += 3;
- if (*laststart == exactn) {
- bufp->options |= RE_OPTIMIZE_EXACTN;
- bufp->must = laststart+1;
- }
- }
- if (!bufp->must) {
- bufp->must = calculate_must_string(bufp->buffer, b);
- }
- if (current_mbctype == MBCTYPE_SJIS) bufp->options |= RE_OPTIMIZE_NO_BM;
- else if (bufp->must) {
- int i;
- int len = (unsigned char)bufp->must[0];
-
- for (i=1; i<len; i++) {
- if ((unsigned char)bufp->must[i] == 0xff ||
- (current_mbctype && ismbchar(bufp->must[i]))) {
- bufp->options |= RE_OPTIMIZE_NO_BM;
- break;
- }
- }
- if (!(bufp->options & RE_OPTIMIZE_NO_BM)) {
- bufp->must_skip = (int *) xmalloc((1 << BYTEWIDTH)*sizeof(int));
- bm_init_skip(bufp->must_skip, (unsigned char*)bufp->must+1,
- (unsigned char)bufp->must[0],
- (unsigned char*)(MAY_TRANSLATE()?translate:0));
- }
- }
-
- bufp->regstart = TMALLOC(regnum, unsigned char*);
- bufp->regend = TMALLOC(regnum, unsigned char*);
- bufp->old_regstart = TMALLOC(regnum, unsigned char*);
- bufp->old_regend = TMALLOC(regnum, unsigned char*);
- bufp->reg_info = TMALLOC(regnum, register_info_type);
- bufp->best_regstart = TMALLOC(regnum, unsigned char*);
- bufp->best_regend = TMALLOC(regnum, unsigned char*);
- FREE_AND_RETURN(stackb, 0);
-
- invalid_pattern:
- FREE_AND_RETURN(stackb, "invalid regular expression");
-
- end_of_pattern:
- FREE_AND_RETURN(stackb, "premature end of regular expression");
-
- too_big:
- FREE_AND_RETURN(stackb, "regular expression too big");
-
- memory_exhausted:
- FREE_AND_RETURN(stackb, "memory exhausted");
-
- nested_meta:
- FREE_AND_RETURN(stackb, "nested *?+ in regexp");
-
- invalid_escape:
- FREE_AND_RETURN(stackb, "Invalid escape character syntax");
-}
-
-void
-re_free_pattern(bufp)
- struct re_pattern_buffer *bufp;
-{
- xfree(bufp->buffer);
- xfree(bufp->fastmap);
- if (bufp->must_skip) xfree(bufp->must_skip);
-
- xfree(bufp->regstart);
- xfree(bufp->regend);
- xfree(bufp->old_regstart);
- xfree(bufp->old_regend);
- xfree(bufp->best_regstart);
- xfree(bufp->best_regend);
- xfree(bufp->reg_info);
- xfree(bufp);
-}
-
-/* Store a jump of the form <OPCODE> <relative address>.
- Store in the location FROM a jump operation to jump to relative
- address FROM - TO. OPCODE is the opcode to store. */
-
-static void
-store_jump(from, opcode, to)
- char *from, *to;
- int opcode;
-{
- from[0] = (char)opcode;
- STORE_NUMBER(from + 1, to - (from + 3));
-}
-
-
-/* Open up space before char FROM, and insert there a jump to TO.
- CURRENT_END gives the end of the storage not in use, so we know
- how much data to copy up. OP is the opcode of the jump to insert.
-
- If you call this function, you must zero out pending_exact. */
-
-static void
-insert_jump(op, from, to, current_end)
- int op;
- char *from, *to, *current_end;
-{
- register char *pfrom = current_end; /* Copy from here... */
- register char *pto = current_end + 3; /* ...to here. */
-
- while (pfrom != from)
- *--pto = *--pfrom;
- store_jump(from, op, to);
-}
-
-
-/* Store a jump of the form <opcode> <relative address> <n> .
-
- Store in the location FROM a jump operation to jump to relative
- address FROM - TO. OPCODE is the opcode to store, N is a number the
- jump uses, say, to decide how many times to jump.
-
- If you call this function, you must zero out pending_exact. */
-
-static void
-store_jump_n(from, opcode, to, n)
- char *from, *to;
- int opcode;
- unsigned n;
-{
- from[0] = (char)opcode;
- STORE_NUMBER(from + 1, to - (from + 3));
- STORE_NUMBER(from + 3, n);
-}
-
-
-/* Similar to insert_jump, but handles a jump which needs an extra
- number to handle minimum and maximum cases. Open up space at
- location FROM, and insert there a jump to TO. CURRENT_END gives the
- end of the storage in use, so we know how much data to copy up. OP is
- the opcode of the jump to insert.
-
- If you call this function, you must zero out pending_exact. */
-
-static void
-insert_jump_n(op, from, to, current_end, n)
- int op;
- char *from, *to, *current_end;
- unsigned n;
-{
- register char *pfrom = current_end; /* Copy from here... */
- register char *pto = current_end + 5; /* ...to here. */
-
- while (pfrom != from)
- *--pto = *--pfrom;
- store_jump_n(from, op, to, n);
-}
-
-
-/* Open up space at location THERE, and insert operation OP.
- CURRENT_END gives the end of the storage in use, so
- we know how much data to copy up.
-
- If you call this function, you must zero out pending_exact. */
-
-static void
-insert_op(op, there, current_end)
- int op;
- char *there, *current_end;
-{
- register char *pfrom = current_end; /* Copy from here... */
- register char *pto = current_end + 1; /* ...to here. */
-
- while (pfrom != there)
- *--pto = *--pfrom;
-
- there[0] = (char)op;
-}
-
-
-/* Open up space at location THERE, and insert operation OP followed by
- NUM_1 and NUM_2. CURRENT_END gives the end of the storage in use, so
- we know how much data to copy up.
-
- If you call this function, you must zero out pending_exact. */
-
-static void
-insert_op_2(op, there, current_end, num_1, num_2)
- int op;
- char *there, *current_end;
- int num_1, num_2;
-{
- register char *pfrom = current_end; /* Copy from here... */
- register char *pto = current_end + 5; /* ...to here. */
-
- while (pfrom != there)
- *--pto = *--pfrom;
-
- there[0] = (char)op;
- STORE_NUMBER(there + 1, num_1);
- STORE_NUMBER(there + 3, num_2);
-}
-
-
-#define trans_eq(c1, c2, translate) (translate?(translate[c1]==translate[c2]):((c1)==(c2)))
-static int
-slow_match(little, lend, big, bend, translate)
- unsigned char *little, *lend;
- unsigned char *big, *bend;
- unsigned char *translate;
-{
- int c;
-
- while (little < lend && big < bend) {
- c = *little++;
- if (c == 0xff)
- c = *little++;
- if (!trans_eq(*big++, c, translate)) break;
- }
- if (little == lend) return 1;
- return 0;
-}
-
-static int
-slow_search(little, llen, big, blen, translate)
- unsigned char *little;
- int llen;
- unsigned char *big;
- int blen;
- char *translate;
-{
- unsigned char *bsave = big;
- unsigned char *bend = big + blen;
- register int c;
- int fescape = 0;
-
- c = *little;
- if (c == 0xff) {
- c = little[1];
- fescape = 1;
- }
- else if (translate && !ismbchar(c)) {
- c = translate[c];
- }
-
- while (big < bend) {
- /* look for first character */
- if (fescape) {
- while (big < bend) {
- if (*big == c) break;
- big++;
- }
- }
- else if (translate && !ismbchar(c)) {
- while (big < bend) {
- if (ismbchar(*big)) big+=mbclen(*big)-1;
- else if (translate[*big] == c) break;
- big++;
- }
- }
- else {
- while (big < bend) {
- if (*big == c) break;
- if (ismbchar(*big)) big+=mbclen(*big)-1;
- big++;
- }
- }
-
- if (slow_match(little, little+llen, big, bend, translate))
- return big - bsave;
-
- big+=mbclen(*big);
- }
- return -1;
-}
-
-static void
-bm_init_skip(skip, pat, m, translate)
- int *skip;
- unsigned char *pat;
- int m;
- const unsigned char *translate;
-{
- int j, c;
-
- for (c=0; c<256; c++) {
- skip[c] = m;
- }
- if (translate) {
- for (j=0; j<m-1; j++) {
- skip[translate[pat[j]]] = m-1-j;
- }
- }
- else {
- for (j=0; j<m-1; j++) {
- skip[pat[j]] = m-1-j;
- }
- }
-}
-
-static int
-bm_search(little, llen, big, blen, skip, translate)
- unsigned char *little;
- int llen;
- unsigned char *big;
- int blen;
- int *skip;
- unsigned char *translate;
-{
- int i, j, k;
-
- i = llen-1;
- if (translate) {
- while (i < blen) {
- k = i;
- j = llen-1;
- while (j >= 0 && translate[big[k]] == translate[little[j]]) {
- k--;
- j--;
- }
- if (j < 0) return k+1;
-
- i += skip[translate[big[i]]];
- }
- return -1;
- }
- while (i < blen) {
- k = i;
- j = llen-1;
- while (j >= 0 && big[k] == little[j]) {
- k--;
- j--;
- }
- if (j < 0) return k+1;
-
- i += skip[big[i]];
- }
- return -1;
-}
-
-/* Given a pattern, compute a fastmap from it. The fastmap records
- which of the (1 << BYTEWIDTH) possible characters can start a string
- that matches the pattern. This fastmap is used by re_search to skip
- quickly over totally implausible text.
-
- The caller must supply the address of a (1 << BYTEWIDTH)-byte data
- area as bufp->fastmap.
- The other components of bufp describe the pattern to be used. */
-void
-re_compile_fastmap(bufp)
- struct re_pattern_buffer *bufp;
-{
- unsigned char *pattern = (unsigned char*)bufp->buffer;
- int size = bufp->used;
- register char *fastmap = bufp->fastmap;
- register unsigned char *p = pattern;
- register unsigned char *pend = pattern + size;
- register int j, k;
- unsigned is_a_succeed_n;
-
-
- unsigned char *stacka[NFAILURES];
- unsigned char **stackb = stacka;
- unsigned char **stackp = stackb;
- unsigned char **stacke = stackb + NFAILURES;
- int options = bufp->options;
-
- memset(fastmap, 0, (1 << BYTEWIDTH));
- bufp->fastmap_accurate = 1;
- bufp->can_be_null = 0;
-
- while (p) {
- is_a_succeed_n = 0;
- if (p == pend) {
- bufp->can_be_null = 1;
- break;
- }
-#ifdef SWITCH_ENUM_BUG
- switch ((int)((enum regexpcode)*p++))
-#else
- switch ((enum regexpcode)*p++)
-#endif
- {
- case exactn:
- if (p[1] == 0xff) {
- if (TRANSLATE_P())
- fastmap[translate[p[2]]] = 2;
- else
- fastmap[p[2]] = 2;
- bufp->options |= RE_OPTIMIZE_BMATCH;
- }
- else if (TRANSLATE_P())
- fastmap[translate[p[1]]] = 1;
- else
- fastmap[p[1]] = 1;
- break;
-
- case begline:
- case begbuf:
- case begpos:
- case endbuf:
- case endbuf2:
- case wordbound:
- case notwordbound:
- case wordbeg:
- case wordend:
- case pop_and_fail:
- case push_dummy_failure:
- case start_paren:
- case stop_paren:
- continue;
-
- case casefold_on:
- bufp->options |= RE_MAY_IGNORECASE;
- case casefold_off:
- options ^= RE_OPTION_IGNORECASE;
- continue;
-
- case option_set:
- options = *p++;
- continue;
-
- case endline:
- if (TRANSLATE_P())
- fastmap[translate['\n']] = 1;
- else
- fastmap['\n'] = 1;
- if ((options & RE_OPTION_SINGLELINE) == 0 && bufp->can_be_null == 0)
- bufp->can_be_null = 2;
- break;
-
- case jump_n:
- case finalize_jump:
- case maybe_finalize_jump:
- case jump:
- case jump_past_alt:
- case dummy_failure_jump:
- case finalize_push:
- case finalize_push_n:
- EXTRACT_NUMBER_AND_INCR(j, p);
- p += j;
- if (j > 0)
- continue;
- /* Jump backward reached implies we just went through
- the body of a loop and matched nothing.
- Opcode jumped to should be an on_failure_jump.
- Just treat it like an ordinary jump.
- For a * loop, it has pushed its failure point already;
- If so, discard that as redundant. */
-
- if ((enum regexpcode)*p != on_failure_jump
- && (enum regexpcode)*p != try_next
- && (enum regexpcode)*p != succeed_n)
- continue;
- p++;
- EXTRACT_NUMBER_AND_INCR(j, p);
- p += j;
- if (stackp != stackb && *stackp == p)
- stackp--; /* pop */
- continue;
-
- case try_next:
- case start_nowidth:
- case stop_nowidth:
- case stop_backtrack:
- p += 2;
- continue;
-
- case succeed_n:
- is_a_succeed_n = 1;
- /* Get to the number of times to succeed. */
- EXTRACT_NUMBER(k, p + 2);
- /* Increment p past the n for when k != 0. */
- if (k != 0) {
- p += 4;
- continue;
- }
- /* fall through */
-
- case on_failure_jump:
- EXTRACT_NUMBER_AND_INCR(j, p);
- if (p + j < pend) {
- if (stackp == stacke) {
- EXPAND_FAIL_STACK();
- }
- *++stackp = p + j; /* push */
- }
- else {
- bufp->can_be_null = 1;
- }
- if (is_a_succeed_n)
- EXTRACT_NUMBER_AND_INCR(k, p); /* Skip the n. */
- continue;
-
- case set_number_at:
- p += 4;
- continue;
-
- case start_memory:
- case stop_memory:
- p += 2;
- continue;
-
- case duplicate:
- bufp->can_be_null = 1;
- if (*p >= bufp->re_nsub) break;
- fastmap['\n'] = 1;
- case anychar_repeat:
- case anychar:
- for (j = 0; j < (1 << BYTEWIDTH); j++) {
- if (j != '\n' || (options & RE_OPTION_MULTILINE))
- fastmap[j] = 1;
- }
- if (bufp->can_be_null) {
- FREE_AND_RETURN_VOID(stackb);
- }
- /* Don't return; check the alternative paths
- so we can set can_be_null if appropriate. */
- if ((enum regexpcode)p[-1] == anychar_repeat) {
- continue;
- }
- break;
-
- case wordchar:
- for (j = 0; j < 0x80; j++) {
- if (SYNTAX(j) == Sword)
- fastmap[j] = 1;
- }
- switch (current_mbctype) {
- case MBCTYPE_ASCII:
- for (j = 0x80; j < (1 << BYTEWIDTH); j++) {
- if (SYNTAX(j) == Sword2)
- fastmap[j] = 1;
- }
- break;
- case MBCTYPE_EUC:
- case MBCTYPE_SJIS:
- case MBCTYPE_UTF8:
- for (j = 0x80; j < (1 << BYTEWIDTH); j++) {
- if (re_mbctab[j])
- fastmap[j] = 1;
- }
- break;
- }
- break;
-
- case notwordchar:
- for (j = 0; j < 0x80; j++)
- if (SYNTAX(j) != Sword)
- fastmap[j] = 1;
- switch (current_mbctype) {
- case MBCTYPE_ASCII:
- for (j = 0x80; j < (1 << BYTEWIDTH); j++) {
- if (SYNTAX(j) != Sword2)
- fastmap[j] = 1;
- }
- break;
- case MBCTYPE_EUC:
- case MBCTYPE_SJIS:
- case MBCTYPE_UTF8:
- for (j = 0x80; j < (1 << BYTEWIDTH); j++) {
- if (!re_mbctab[j])
- fastmap[j] = 1;
- }
- break;
- }
- break;
-
- case charset:
- /* NOTE: Charset for single-byte chars never contain
- multi-byte char. See set_list_bits(). */
- for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
- if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))) {
- int tmp = TRANSLATE_P()?translate[j]:j;
- fastmap[tmp] = 1;
- }
- {
- unsigned short size;
- unsigned long c, beg, end;
-
- p += p[-1] + 2;
- size = EXTRACT_UNSIGNED(&p[-2]);
- for (j = 0; j < (int)size; j++) {
- c = EXTRACT_MBC(&p[j*8]);
- beg = WC2MBC1ST(c);
- c = EXTRACT_MBC(&p[j*8+4]);
- end = WC2MBC1ST(c);
- /* set bits for 1st bytes of multi-byte chars. */
- while (beg <= end) {
- /* NOTE: Charset for multi-byte chars might contain
- single-byte chars. We must reject them. */
- if (c < 0x100) {
- fastmap[beg] = 2;
- bufp->options |= RE_OPTIMIZE_BMATCH;
- }
- else if (ismbchar(beg))
- fastmap[beg] = 1;
- beg++;
- }
- }
- }
- break;
-
- case charset_not:
- /* S: set of all single-byte chars.
- M: set of all first bytes that can start multi-byte chars.
- s: any set of single-byte chars.
- m: any set of first bytes that can start multi-byte chars.
-
- We assume S+M = U.
- ___ _ _
- s+m = (S*s+M*m). */
- /* Chars beyond end of map must be allowed */
- /* NOTE: Charset_not for single-byte chars might contain
- multi-byte chars. See set_list_bits(). */
- for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
- if (!ismbchar(j))
- fastmap[j] = 1;
-
- for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
- if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))) {
- if (!ismbchar(j))
- fastmap[j] = 1;
- }
- {
- unsigned short size;
- unsigned long c, beg;
- int num_literal = 0;
-
- p += p[-1] + 2;
- size = EXTRACT_UNSIGNED(&p[-2]);
- if (size == 0) {
- for (j = 0x80; j < (1 << BYTEWIDTH); j++)
- if (ismbchar(j))
- fastmap[j] = 1;
- break;
- }
- for (j = 0,c = 0;j < (int)size; j++) {
- unsigned int cc = EXTRACT_MBC(&p[j*8]);
- beg = WC2MBC1ST(cc);
- while (c <= beg) {
- if (ismbchar(c))
- fastmap[c] = 1;
- c++;
- }
-
- cc = EXTRACT_MBC(&p[j*8+4]);
- if (cc < 0xff) {
- num_literal = 1;
- while (c <= cc) {
- if (ismbchar(c))
- fastmap[c] = 1;
- c++;
- }
- }
- c = WC2MBC1ST(cc);
- }
-
- for (j = c; j < (1 << BYTEWIDTH); j++) {
- if (num_literal)
- fastmap[j] = 1;
- if (ismbchar(j))
- fastmap[j] = 1;
- }
- }
- break;
-
- case unused: /* pacify gcc -Wall */
- break;
- }
-
- /* Get here means we have successfully found the possible starting
- characters of one path of the pattern. We need not follow this
- path any farther. Instead, look at the next alternative
- remembered in the stack. */
- if (stackp != stackb)
- p = *stackp--; /* pop */
- else
- break;
- }
- FREE_AND_RETURN_VOID(stackb);
-}
-
-/* adjust startpos value to the position between characters. */
-int
-re_adjust_startpos(bufp, string, size, startpos, range)
- struct re_pattern_buffer *bufp;
- const char *string;
- int size, startpos, range;
-{
- /* Update the fastmap now if not correct already. */
- if (!bufp->fastmap_accurate) {
- re_compile_fastmap(bufp);
- }
-
- /* Adjust startpos for mbc string */
- if (current_mbctype && startpos>0 && !(bufp->options&RE_OPTIMIZE_BMATCH)) {
- int i = mbc_startpos(string, startpos);
-
- if (i < startpos) {
- if (range > 0) {
- startpos = i + mbclen(string[i]);
- }
- else {
- int len = mbclen(string[i]);
- if (i + len <= startpos)
- startpos = i + len;
- else
- startpos = i;
- }
- }
- }
- return startpos;
-}
-
-
-/* Using the compiled pattern in BUFP->buffer, first tries to match
- STRING, starting first at index STARTPOS, then at STARTPOS + 1, and
- so on. RANGE is the number of places to try before giving up. If
- RANGE is negative, it searches backwards, i.e., the starting
- positions tried are STARTPOS, STARTPOS - 1, etc. STRING is of SIZE.
- In REGS, return the indices of STRING that matched the entire
- BUFP->buffer and its contained subexpressions.
-
- The value returned is the position in the strings at which the match
- was found, or -1 if no match was found, or -2 if error (such as
- failure stack overflow). */
-
-int
-re_search(bufp, string, size, startpos, range, regs)
- struct re_pattern_buffer *bufp;
- const char *string;
- int size, startpos, range;
- struct re_registers *regs;
-{
- register char *fastmap = bufp->fastmap;
- int val, anchor = 0;
-
- /* Check for out-of-range starting position. */
- if (startpos < 0 || startpos > size)
- return -1;
-
- /* Update the fastmap now if not correct already. */
- if (fastmap && !bufp->fastmap_accurate) {
- re_compile_fastmap(bufp);
- }
-
-
- /* If the search isn't to be a backwards one, don't waste time in a
- search for a pattern that must be anchored. */
- if (bufp->used > 0) {
- switch ((enum regexpcode)bufp->buffer[0]) {
- case begbuf:
- begbuf_match:
- if (range > 0) {
- if (startpos > 0) return -1;
- else {
- val = re_match(bufp, string, size, 0, regs);
- if (val >= 0) return 0;
- return val;
- }
- }
- break;
-
- case begline:
- anchor = 1;
- break;
-
- case begpos:
- val = re_match(bufp, string, size, startpos, regs);
- if (val >= 0) return startpos;
- return val;
-
- default:
- break;
- }
- }
- if (bufp->options & RE_OPTIMIZE_ANCHOR) {
- if (bufp->options&RE_OPTION_SINGLELINE) {
- goto begbuf_match;
- }
- anchor = 1;
- }
-
- if (bufp->must) {
- int len = ((unsigned char*)bufp->must)[0];
- int pos, pbeg, pend;
-
- pbeg = startpos;
- pend = startpos + range;
- if (pbeg > pend) { /* swap pbeg,pend */
- pos = pend; pend = pbeg; pbeg = pos;
- }
- pend = size;
- if (bufp->options & RE_OPTIMIZE_NO_BM) {
- pos = slow_search(bufp->must+1, len,
- string+pbeg, pend-pbeg,
- MAY_TRANSLATE()?translate:0);
- }
- else {
- pos = bm_search(bufp->must+1, len,
- string+pbeg, pend-pbeg,
- bufp->must_skip,
- MAY_TRANSLATE()?translate:0);
- }
- if (pos == -1) return -1;
- if (range > 0 && (bufp->options & RE_OPTIMIZE_EXACTN)) {
- startpos += pos;
- range -= pos;
- if (range < 0) return -1;
- }
- }
-
- for (;;) {
- /* If a fastmap is supplied, skip quickly over characters that
- cannot possibly be the start of a match. Note, however, that
- if the pattern can possibly match the null string, we must
- test it at each starting point so that we take the first null
- string we get. */
-
- if (fastmap && startpos < size
- && bufp->can_be_null != 1 && !(anchor && startpos == 0)) {
- if (range > 0) { /* Searching forwards. */
- register unsigned char *p, c;
- int irange = range;
-
- p = (unsigned char*)string+startpos;
-
- while (range > 0) {
- c = *p++;
- if (ismbchar(c)) {
- int len;
-
- if (fastmap[c])
- break;
- len = mbclen(c) - 1;
- while (len--) {
- c = *p++;
- range--;
- if (fastmap[c] == 2)
- goto startpos_adjust;
- }
- }
- else {
- if (fastmap[MAY_TRANSLATE() ? translate[c] : c])
- break;
- }
- range--;
- }
- startpos_adjust:
- startpos += irange - range;
- }
- else { /* Searching backwards. */
- register unsigned char c;
-
- c = string[startpos];
- c &= 0xff;
- if (MAY_TRANSLATE() ? !fastmap[translate[c]] : !fastmap[c])
- goto advance;
- }
- }
-
- if (startpos > size) return -1;
- if ((anchor || !bufp->can_be_null) && range > 0 && size > 0 && startpos == size)
- return -1;
- val = re_match(bufp, string, size, startpos, regs);
- if (val >= 0) return startpos;
- if (val == -2) return -2;
-
-#ifndef NO_ALLOCA
-#ifdef C_ALLOCA
- alloca(0);
-#endif /* C_ALLOCA */
-#endif /* NO_ALLOCA */
-
- if (range > 0) {
- if (anchor && startpos < size &&
- (startpos < 1 || string[startpos-1] != '\n')) {
- while (range > 0 && string[startpos] != '\n') {
- range--;
- startpos++;
- }
- }
- }
-
- advance:
- if (!range)
- break;
- else if (range > 0) {
- const char *d = string + startpos;
-
- if (ismbchar(*d)) {
- int len = mbclen(*d) - 1;
- range-=len, startpos+=len;
- if (!range)
- break;
- }
- range--, startpos++;
- }
- else {
- range++, startpos--;
- {
- const char *s, *d, *p;
-
- s = string; d = string + startpos;
- for (p = d; p-- > s && ismbchar(*p); )
- /* --p >= s would not work on 80[12]?86.
- (when the offset of s equals 0 other than huge model.) */
- ;
- if (!((d - p) & 1)) {
- if (!range)
- break;
- range++, startpos--;
- }
- }
- }
- }
- return -1;
-}
-
-
-
-
-/* The following are used for re_match, defined below: */
-
-/* Accessing macros used in re_match: */
-
-#define IS_ACTIVE(R) ((R).bits.is_active)
-#define MATCHED_SOMETHING(R) ((R).bits.matched_something)
-
-
-/* Macros used by re_match: */
-
-/* I.e., regstart, regend, and reg_info. */
-#define NUM_REG_ITEMS 3
-
-/* I.e., ptr and count. */
-#define NUM_COUNT_ITEMS 2
-
-/* Individual items aside from the registers. */
-#define NUM_NONREG_ITEMS 4
-
-/* We push at most this many things on the stack whenever we
- fail. The `+ 2' refers to PATTERN_PLACE and STRING_PLACE, which are
- arguments to the PUSH_FAILURE_POINT macro. */
-#define MAX_NUM_FAILURE_ITEMS (num_regs * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
-
-/* We push this many things on the stack whenever we fail. */
-#define NUM_FAILURE_ITEMS (last_used_reg * NUM_REG_ITEMS + NUM_NONREG_ITEMS + 1)
-
-/* This pushes counter information for succeed_n and jump_n */
-#define PUSH_FAILURE_COUNT(ptr) \
- do { \
- int c; \
- EXTRACT_NUMBER(c, ptr); \
- ENSURE_FAIL_STACK(NUM_COUNT_ITEMS); \
- *stackp++ = (unsigned char*)(long)c; \
- *stackp++ = (ptr); \
- num_failure_counts++; \
- } while (0)
-
-/* This pushes most of the information about the current state we will want
- if we ever fail back to it. */
-
-#define PUSH_FAILURE_POINT(pattern_place, string_place) \
- do { \
- long last_used_reg, this_reg; \
- \
- /* Find out how many registers are active or have been matched. \
- (Aside from register zero, which is only set at the end.) */ \
- for (last_used_reg = num_regs-1; last_used_reg > 0; last_used_reg--)\
- if (!REG_UNSET(regstart[last_used_reg])) \
- break; \
- \
- ENSURE_FAIL_STACK(NUM_FAILURE_ITEMS); \
- *stackp++ = (unsigned char*)(long)num_failure_counts; \
- num_failure_counts = 0; \
- \
- /* Now push the info for each of those registers. */ \
- for (this_reg = 1; this_reg <= last_used_reg; this_reg++) { \
- *stackp++ = regstart[this_reg]; \
- *stackp++ = regend[this_reg]; \
- *stackp++ = reg_info[this_reg].word; \
- } \
- \
- /* Push how many registers we saved. */ \
- *stackp++ = (unsigned char*)last_used_reg; \
- \
- *stackp++ = pattern_place; \
- *stackp++ = string_place; \
- *stackp++ = (unsigned char*)(long)options; /* current option status */ \
- *stackp++ = (unsigned char*)0; /* non-greedy flag */ \
- } while(0)
-
-#define NON_GREEDY ((unsigned char*)1)
-
-#define POP_FAILURE_COUNT() \
- do { \
- unsigned char *ptr = *--stackp; \
- int count = (long)*--stackp; \
- STORE_NUMBER(ptr, count); \
- } while (0)
-
-/* This pops what PUSH_FAILURE_POINT pushes. */
-
-#define POP_FAILURE_POINT() \
- do { \
- long temp; \
- stackp -= NUM_NONREG_ITEMS; /* Remove failure points (and flag). */ \
- temp = (long)*--stackp; /* How many regs pushed. */ \
- temp *= NUM_REG_ITEMS; /* How much to take off the stack. */ \
- stackp -= temp; /* Remove the register info. */ \
- temp = (long)*--stackp; /* How many counters pushed. */ \
- while (temp--) { \
- POP_FAILURE_COUNT(); /* Remove the counter info. */ \
- } \
- num_failure_counts = 0; /* Reset num_failure_counts. */ \
- } while(0)
-
- /* Registers are set to a sentinel when they haven't yet matched. */
-#define REG_UNSET_VALUE ((unsigned char*)-1)
-#define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
-
-#define PREFETCH if (d == dend) goto fail
-
- /* Call this when have matched something; it sets `matched' flags for the
- registers corresponding to the subexpressions of which we currently
- are inside. */
-#define SET_REGS_MATCHED \
- do { unsigned this_reg; \
- for (this_reg = 0; this_reg < num_regs; this_reg++) { \
- if (IS_ACTIVE(reg_info[this_reg])) \
- MATCHED_SOMETHING(reg_info[this_reg]) = 1; \
- else \
- MATCHED_SOMETHING(reg_info[this_reg]) = 0; \
- } \
- } while(0)
-
-#define AT_STRINGS_BEG(d) ((d) == string)
-#define AT_STRINGS_END(d) ((d) == dend)
-
-#define IS_A_LETTER(d) (SYNTAX(*(d)) == Sword || \
- (current_mbctype ? \
- (re_mbctab[*(d)] && ((d)+mbclen(*(d)))<=dend): \
- SYNTAX(*(d)) == Sword2))
-
-#define PREV_IS_A_LETTER(d) ((current_mbctype == MBCTYPE_SJIS)? \
- IS_A_LETTER((d)-(!AT_STRINGS_BEG((d)-1)&& \
- ismbchar((d)[-2])?2:1)): \
- ((current_mbctype && ((d)[-1] >= 0x80)) || \
- IS_A_LETTER((d)-1)))
-
-static void
-init_regs(regs, num_regs)
- struct re_registers *regs;
- unsigned int num_regs;
-{
- int i;
-
- regs->num_regs = num_regs;
- if (num_regs < RE_NREGS)
- num_regs = RE_NREGS;
-
- if (regs->allocated == 0) {
- regs->beg = TMALLOC(num_regs, int);
- regs->end = TMALLOC(num_regs, int);
- regs->allocated = num_regs;
- }
- else if (regs->allocated < num_regs) {
- TREALLOC(regs->beg, num_regs, int);
- TREALLOC(regs->end, num_regs, int);
- regs->allocated = num_regs;
- }
- for (i=0; i<num_regs; i++) {
- regs->beg[i] = regs->end[i] = -1;
- }
-}
-
-/* Match the pattern described by BUFP against STRING, which is of
- SIZE. Start the match at index POS in STRING. In REGS, return the
- indices of STRING that matched the entire BUFP->buffer and its
- contained subexpressions.
-
- If bufp->fastmap is nonzero, then it had better be up to date.
-
- The reason that the data to match are specified as two components
- which are to be regarded as concatenated is so this function can be
- used directly on the contents of an Emacs buffer.
-
- -1 is returned if there is no match. -2 is returned if there is an
- error (such as match stack overflow). Otherwise the value is the
- length of the substring which was matched. */
-
-int
-re_match(bufp, string_arg, size, pos, regs)
- struct re_pattern_buffer *bufp;
- const char *string_arg;
- int size, pos;
- struct re_registers *regs;
-{
- register unsigned char *p = (unsigned char*)bufp->buffer;
- unsigned char *p1;
-
- /* Pointer to beyond end of buffer. */
- register unsigned char *pend = p + bufp->used;
-
- unsigned num_regs = bufp->re_nsub;
-
- unsigned char *string = (unsigned char*)string_arg;
-
- register unsigned char *d, *dend;
- register int mcnt; /* Multipurpose. */
- int options = bufp->options;
-
- /* Failure point stack. Each place that can handle a failure further
- down the line pushes a failure point on this stack. It consists of
- restart, regend, and reg_info for all registers corresponding to the
- subexpressions we're currently inside, plus the number of such
- registers, and, finally, two char *'s. The first char * is where to
- resume scanning the pattern; the second one is where to resume
- scanning the strings. If the latter is zero, the failure point is a
- ``dummy''; if a failure happens and the failure point is a dummy, it
- gets discarded and the next next one is tried. */
-
- unsigned char **stacka;
- unsigned char **stackb;
- unsigned char **stackp;
- unsigned char **stacke;
-
- /* Information on the contents of registers. These are pointers into
- the input strings; they record just what was matched (on this
- attempt) by a subexpression part of the pattern, that is, the
- regnum-th regstart pointer points to where in the pattern we began
- matching and the regnum-th regend points to right after where we
- stopped matching the regnum-th subexpression. (The zeroth register
- keeps track of what the whole pattern matches.) */
-
- unsigned char **regstart = bufp->regstart;
- unsigned char **regend = bufp->regend;
-
- /* If a group that's operated upon by a repetition operator fails to
- match anything, then the register for its start will need to be
- restored because it will have been set to wherever in the string we
- are when we last see its open-group operator. Similarly for a
- register's end. */
- unsigned char **old_regstart = bufp->old_regstart;
- unsigned char **old_regend = bufp->old_regend;
-
- /* The is_active field of reg_info helps us keep track of which (possibly
- nested) subexpressions we are currently in. The matched_something
- field of reg_info[reg_num] helps us tell whether or not we have
- matched any of the pattern so far this time through the reg_num-th
- subexpression. These two fields get reset each time through any
- loop their register is in. */
-
- register_info_type *reg_info = bufp->reg_info;
-
- /* The following record the register info as found in the above
- variables when we find a match better than any we've seen before.
- This happens as we backtrack through the failure points, which in
- turn happens only if we have not yet matched the entire string. */
-
- unsigned best_regs_set = 0;
- unsigned char **best_regstart = bufp->best_regstart;
- unsigned char **best_regend = bufp->best_regend;
-
- int num_failure_counts = 0;
-
- if (regs) {
- init_regs(regs, num_regs);
- }
-
- /* Initialize the stack. */
- stacka = RE_TALLOC(MAX_NUM_FAILURE_ITEMS * NFAILURES, unsigned char*);
- stackb = stacka;
- stackp = stackb;
- stacke = &stackb[MAX_NUM_FAILURE_ITEMS * NFAILURES];
-
-#ifdef DEBUG_REGEX
- fprintf(stderr, "Entering re_match(%s)\n", string_arg);
-#endif
-
- /* Initialize subexpression text positions to -1 to mark ones that no
- ( or ( and ) or ) has been seen for. Also set all registers to
- inactive and mark them as not having matched anything or ever
- failed. */
- for (mcnt = 0; mcnt < num_regs; mcnt++) {
- regstart[mcnt] = regend[mcnt]
- = old_regstart[mcnt] = old_regend[mcnt]
- = best_regstart[mcnt] = best_regend[mcnt] = REG_UNSET_VALUE;
-#ifdef __CHECKER__
- reg_info[mcnt].word = 0;
-#endif
- IS_ACTIVE (reg_info[mcnt]) = 0;
- MATCHED_SOMETHING (reg_info[mcnt]) = 0;
- }
-
- /* Set up pointers to ends of strings.
- Don't allow the second string to be empty unless both are empty. */
-
-
- /* `p' scans through the pattern as `d' scans through the data. `dend'
- is the end of the input string that `d' points within. `d' is
- advanced into the following input string whenever necessary, but
- this happens before fetching; therefore, at the beginning of the
- loop, `d' can be pointing at the end of a string, but it cannot
- equal string2. */
-
- d = string + pos, dend = string + size;
-
- /* This loops over pattern commands. It exits by returning from the
- function if match is complete, or it drops through if match fails
- at this starting point in the input data. */
-
- for (;;) {
-#ifdef DEBUG_REGEX
- fprintf(stderr,
- "regex loop(%d): matching 0x%02d\n",
- p - (unsigned char*)bufp->buffer,
- *p);
-#endif
- /* End of pattern means we might have succeeded. */
- if (p == pend) {
- /* If not end of string, try backtracking. Otherwise done. */
- if ((bufp->options & RE_OPTION_LONGEST) && d != dend) {
- if (best_regs_set) /* non-greedy, no need to backtrack */
- goto restore_best_regs;
- while (stackp != stackb && stackp[-1] == NON_GREEDY) {
- if (best_regs_set) /* non-greedy, no need to backtrack */
- goto restore_best_regs;
- POP_FAILURE_POINT();
- }
- if (stackp != stackb) {
- /* More failure points to try. */
-
- /* If exceeds best match so far, save it. */
- if (! best_regs_set || (d > best_regend[0])) {
- best_regs_set = 1;
- best_regend[0] = d; /* Never use regstart[0]. */
-
- for (mcnt = 1; mcnt < num_regs; mcnt++) {
- best_regstart[mcnt] = regstart[mcnt];
- best_regend[mcnt] = regend[mcnt];
- }
- }
- goto fail;
- }
- /* If no failure points, don't restore garbage. */
- else if (best_regs_set) {
- restore_best_regs:
- /* Restore best match. */
- d = best_regend[0];
-
- for (mcnt = 0; mcnt < num_regs; mcnt++) {
- regstart[mcnt] = best_regstart[mcnt];
- regend[mcnt] = best_regend[mcnt];
- }
- }
- }
-
- /* If caller wants register contents data back, convert it
- to indices. */
- if (regs) {
- regs->beg[0] = pos;
- regs->end[0] = d - string;
- for (mcnt = 1; mcnt < num_regs; mcnt++) {
- if (REG_UNSET(regend[mcnt])) {
- regs->beg[mcnt] = -1;
- regs->end[mcnt] = -1;
- continue;
- }
- regs->beg[mcnt] = regstart[mcnt] - string;
- regs->end[mcnt] = regend[mcnt] - string;
- }
- }
- FREE_AND_RETURN(stackb, (d - pos - string));
- }
-
- /* Otherwise match next pattern command. */
-#ifdef SWITCH_ENUM_BUG
- switch ((int)((enum regexpcode)*p++))
-#else
- switch ((enum regexpcode)*p++)
-#endif
- {
- /* ( [or `(', as appropriate] is represented by start_memory,
- ) by stop_memory. Both of those commands are followed by
- a register number in the next byte. The text matched
- within the ( and ) is recorded under that number. */
- case start_memory:
- old_regstart[*p] = regstart[*p];
- regstart[*p] = d;
- IS_ACTIVE(reg_info[*p]) = 1;
- MATCHED_SOMETHING(reg_info[*p]) = 0;
- p += 2;
- continue;
-
- case stop_memory:
- old_regend[*p] = regend[*p];
- regend[*p] = d;
- IS_ACTIVE(reg_info[*p]) = 0;
- p += 2;
- continue;
-
- case start_paren:
- case stop_paren:
- break;
-
- /* \<digit> has been turned into a `duplicate' command which is
- followed by the numeric value of <digit> as the register number. */
- case duplicate:
- {
- int regno = *p++; /* Get which register to match against */
- register unsigned char *d2, *dend2;
-
- /* Check if there's corresponding group */
- if (regno >= num_regs) goto fail;
- /* Check if corresponding group is still open */
- if (IS_ACTIVE(reg_info[regno])) goto fail;
-
- /* Where in input to try to start matching. */
- d2 = regstart[regno];
- if (REG_UNSET(d2)) goto fail;
-
- /* Where to stop matching; if both the place to start and
- the place to stop matching are in the same string, then
- set to the place to stop, otherwise, for now have to use
- the end of the first string. */
-
- dend2 = regend[regno];
- if (REG_UNSET(dend2)) goto fail;
- for (;;) {
- /* At end of register contents => success */
- if (d2 == dend2) break;
-
- /* If necessary, advance to next segment in data. */
- PREFETCH;
-
- /* How many characters left in this segment to match. */
- mcnt = dend - d;
-
- /* Want how many consecutive characters we can match in
- one shot, so, if necessary, adjust the count. */
- if (mcnt > dend2 - d2)
- mcnt = dend2 - d2;
-
- /* Compare that many; failure if mismatch, else move
- past them. */
- if ((options & RE_OPTION_IGNORECASE)
- ? memcmp_translate(d, d2, mcnt)
- : memcmp((char*)d, (char*)d2, mcnt))
- goto fail;
- d += mcnt, d2 += mcnt;
- }
- }
- break;
-
- case start_nowidth:
- PUSH_FAILURE_POINT(0, d);
- if (stackp - stackb > RE_DUP_MAX) {
- FREE_AND_RETURN(stackb,(-2));
- }
- EXTRACT_NUMBER_AND_INCR(mcnt, p);
- STORE_NUMBER(p+mcnt, stackp - stackb);
- continue;
-
- case stop_nowidth:
- EXTRACT_NUMBER_AND_INCR(mcnt, p);
- stackp = stackb + mcnt;
- d = stackp[-3];
- POP_FAILURE_POINT();
- continue;
-
- case stop_backtrack:
- EXTRACT_NUMBER_AND_INCR(mcnt, p);
- stackp = stackb + mcnt;
- POP_FAILURE_POINT();
- continue;
-
- case pop_and_fail:
- EXTRACT_NUMBER(mcnt, p+1);
- stackp = stackb + mcnt;
- POP_FAILURE_POINT();
- goto fail;
-
- case anychar:
- PREFETCH;
- if (ismbchar(*d)) {
- if (d + mbclen(*d) > dend)
- goto fail;
- SET_REGS_MATCHED;
- d += mbclen(*d);
- break;
- }
- if (!(options&RE_OPTION_MULTILINE)
- && (TRANSLATE_P() ? translate[*d] : *d) == '\n')
- goto fail;
- SET_REGS_MATCHED;
- d++;
- break;
-
- case anychar_repeat:
- for (;;) {
- PUSH_FAILURE_POINT(p, d);
- PREFETCH;
- if (ismbchar(*d)) {
- if (d + mbclen(*d) > dend)
- goto fail;
- SET_REGS_MATCHED;
- d += mbclen(*d);
- continue;
- }
- if (!(options&RE_OPTION_MULTILINE) &&
- (TRANSLATE_P() ? translate[*d] : *d) == '\n')
- goto fail;
- SET_REGS_MATCHED;
- d++;
- }
- break;
-
- case charset:
- case charset_not:
- {
- int not; /* Nonzero for charset_not. */
- int part = 0; /* true if matched part of mbc */
- unsigned char *dsave = d + 1;
- int cc, c;
-
- PREFETCH;
- cc = c = (unsigned char)*d++;
- if (ismbchar(c)) {
- if (d + mbclen(c) - 1 <= dend) {
- MBC2WC(c, d);
- }
- }
- else if (TRANSLATE_P())
- cc = c = (unsigned char)translate[c];
-
- not = is_in_list(c, p);
- if (!not && cc != c) {
- part = not = is_in_list(cc, p);
- }
- if (*(p - 1) == (unsigned char)charset_not) {
- not = !not;
- }
- if (!not) goto fail;
-
- p += 1 + *p + 2 + EXTRACT_UNSIGNED(&p[1 + *p])*8;
- SET_REGS_MATCHED;
-
- if (part) d = dsave;
- break;
- }
-
- case begline:
- if (size == 0 || AT_STRINGS_BEG(d))
- break;
- if (d[-1] == '\n' && !AT_STRINGS_END(d))
- break;
- goto fail;
-
- case endline:
- if (AT_STRINGS_END(d)) {
- if (size == 0 || d[-1] != '\n')
- break;
- }
- else if (*d == '\n')
- break;
- goto fail;
-
- /* Match at the very beginning of the string. */
- case begbuf:
- if (AT_STRINGS_BEG(d))
- break;
- goto fail;
-
- /* Match at the very end of the data. */
- case endbuf:
- if (AT_STRINGS_END(d))
- break;
- goto fail;
-
- /* Match at the very end of the data. */
- case endbuf2:
- if (AT_STRINGS_END(d)) {
- if (size == 0 || d[-1] != '\n')
- break;
- }
- /* .. or newline just before the end of the data. */
- if (*d == '\n' && AT_STRINGS_END(d+1))
- break;
- goto fail;
-
- /* `or' constructs are handled by starting each alternative with
- an on_failure_jump that points to the start of the next
- alternative. Each alternative except the last ends with a
- jump to the joining point. (Actually, each jump except for
- the last one really jumps to the following jump, because
- tensioning the jumps is a hassle.) */
-
- /* The start of a stupid repeat has an on_failure_jump that points
- past the end of the repeat text. This makes a failure point so
- that on failure to match a repetition, matching restarts past
- as many repetitions have been found with no way to fail and
- look for another one. */
-
- /* A smart repeat is similar but loops back to the on_failure_jump
- so that each repetition makes another failure point. */
-
- /* Match at the starting position. */
- case begpos:
- if (d - string == pos)
- break;
- goto fail;
-
- case on_failure_jump:
- on_failure:
- EXTRACT_NUMBER_AND_INCR(mcnt, p);
- PUSH_FAILURE_POINT(p + mcnt, d);
- continue;
-
- /* The end of a smart repeat has a maybe_finalize_jump back.
- Change it either to a finalize_jump or an ordinary jump. */
- case maybe_finalize_jump:
- EXTRACT_NUMBER_AND_INCR(mcnt, p);
- p1 = p;
-
- /* Compare the beginning of the repeat with what in the
- pattern follows its end. If we can establish that there
- is nothing that they would both match, i.e., that we
- would have to backtrack because of (as in, e.g., `a*a')
- then we can change to finalize_jump, because we'll
- never have to backtrack.
-
- This is not true in the case of alternatives: in
- `(a|ab)*' we do need to backtrack to the `ab' alternative
- (e.g., if the string was `ab'). But instead of trying to
- detect that here, the alternative has put on a dummy
- failure point which is what we will end up popping. */
-
- /* Skip over open/close-group commands. */
- while (p1 + 2 < pend) {
- if ((enum regexpcode)*p1 == stop_memory ||
- (enum regexpcode)*p1 == start_memory)
- p1 += 3; /* Skip over args, too. */
- else if (/*(enum regexpcode)*p1 == start_paren ||*/
- (enum regexpcode)*p1 == stop_paren)
- p1 += 1;
- else
- break;
- }
-
- if (p1 == pend)
- p[-3] = (unsigned char)finalize_jump;
- else if (*p1 == (unsigned char)exactn ||
- *p1 == (unsigned char)endline) {
- register int c = *p1 == (unsigned char)endline ? '\n' : p1[2];
- register unsigned char *p2 = p + mcnt;
- /* p2[0] ... p2[2] are an on_failure_jump.
- Examine what follows that. */
- if (p2[3] == (unsigned char)exactn && p2[5] != c)
- p[-3] = (unsigned char)finalize_jump;
- else if (p2[3] == (unsigned char)charset ||
- p2[3] == (unsigned char)charset_not) {
- int not;
- if (ismbchar(c)) {
- unsigned char *pp = p1+3;
- MBC2WC(c, pp);
- }
- /* `is_in_list()' is TRUE if c would match */
- /* That means it is not safe to finalize. */
- not = is_in_list(c, p2 + 4);
- if (p2[3] == (unsigned char)charset_not)
- not = !not;
- if (!not)
- p[-3] = (unsigned char)finalize_jump;
- }
- }
- p -= 2; /* Point at relative address again. */
- if (p[-1] != (unsigned char)finalize_jump) {
- p[-1] = (unsigned char)jump;
- goto nofinalize;
- }
- /* Note fall through. */
-
- /* The end of a stupid repeat has a finalize_jump back to the
- start, where another failure point will be made which will
- point to after all the repetitions found so far. */
-
- /* Take off failure points put on by matching on_failure_jump
- because didn't fail. Also remove the register information
- put on by the on_failure_jump. */
- case finalize_jump:
- if (stackp > stackb && stackp[-3] == d) {
- p = stackp[-4];
- POP_FAILURE_POINT();
- continue;
- }
- POP_FAILURE_POINT();
- /* Note fall through. */
-
- /* We need this opcode so we can detect where alternatives end
- in `group_match_null_string_p' et al. */
- case jump_past_alt:
- /* fall through */
-
- /* Jump without taking off any failure points. */
- case jump:
- nofinalize:
- EXTRACT_NUMBER_AND_INCR(mcnt, p);
- if (mcnt < 0 && stackp > stackb && stackp[-3] == d) /* avoid infinite loop */
- goto fail;
- p += mcnt;
- continue;
-
- case dummy_failure_jump:
- /* Normally, the on_failure_jump pushes a failure point, which
- then gets popped at finalize_jump. We will end up at
- finalize_jump, also, and with a pattern of, say, `a+', we
- are skipping over the on_failure_jump, so we have to push
- something meaningless for finalize_jump to pop. */
- PUSH_FAILURE_POINT(0, 0);
- goto nofinalize;
-
- /* At the end of an alternative, we need to push a dummy failure
- point in case we are followed by a `finalize_jump', because
- we don't want the failure point for the alternative to be
- popped. For example, matching `(a|ab)*' against `aab'
- requires that we match the `ab' alternative. */
- case push_dummy_failure:
- /* See comments just above at `dummy_failure_jump' about the
- two zeroes. */
- p1 = p;
- /* Skip over open/close-group commands. */
- while (p1 + 2 < pend) {
- if ((enum regexpcode)*p1 == stop_memory ||
- (enum regexpcode)*p1 == start_memory)
- p1 += 3; /* Skip over args, too. */
- else if (/*(enum regexpcode)*p1 == start_paren ||*/
- (enum regexpcode)*p1 == stop_paren)
- p1 += 1;
- else
- break;
- }
- if ((enum regexpcode)*p1 == jump)
- p[-1] = unused;
- else
- PUSH_FAILURE_POINT(0, 0);
- break;
-
- /* Have to succeed matching what follows at least n times. Then
- just handle like an on_failure_jump. */
- case succeed_n:
- EXTRACT_NUMBER(mcnt, p + 2);
- /* Originally, this is how many times we HAVE to succeed. */
- if (mcnt != 0) {
- mcnt--;
- p += 2;
- PUSH_FAILURE_COUNT(p);
- STORE_NUMBER_AND_INCR(p, mcnt);
- PUSH_FAILURE_POINT(0, 0);
- }
- else {
- goto on_failure;
- }
- continue;
-
- case jump_n:
- EXTRACT_NUMBER(mcnt, p + 2);
- /* Originally, this is how many times we CAN jump. */
- if (mcnt) {
- mcnt--;
- PUSH_FAILURE_COUNT(p + 2);
- STORE_NUMBER(p + 2, mcnt);
- goto nofinalize; /* Do the jump without taking off
- any failure points. */
- }
- /* If don't have to jump any more, skip over the rest of command. */
- else
- p += 4;
- continue;
-
- case set_number_at:
- EXTRACT_NUMBER_AND_INCR(mcnt, p);
- p1 = p + mcnt;
- EXTRACT_NUMBER_AND_INCR(mcnt, p);
- STORE_NUMBER(p1, mcnt);
- continue;
-
- case try_next:
- EXTRACT_NUMBER_AND_INCR(mcnt, p);
- if (p + mcnt < pend) {
- PUSH_FAILURE_POINT(p, d);
- stackp[-1] = NON_GREEDY;
- }
- p += mcnt;
- continue;
-
- case finalize_push:
- POP_FAILURE_POINT();
- EXTRACT_NUMBER_AND_INCR(mcnt, p);
- if (mcnt < 0 && stackp > stackb && stackp[-3] == d) /* avoid infinite loop */
- goto fail;
- PUSH_FAILURE_POINT(p + mcnt, d);
- stackp[-1] = NON_GREEDY;
- continue;
-
- case finalize_push_n:
- EXTRACT_NUMBER(mcnt, p + 2);
- /* Originally, this is how many times we CAN jump. */
- if (mcnt) {
- int pos, i;
-
- mcnt--;
- STORE_NUMBER(p + 2, mcnt);
- EXTRACT_NUMBER(pos, p);
- EXTRACT_NUMBER(i, p+pos+5);
- if (i > 0) goto nofinalize;
- POP_FAILURE_POINT();
- EXTRACT_NUMBER_AND_INCR(mcnt, p);
- PUSH_FAILURE_POINT(p + mcnt, d);
- stackp[-1] = NON_GREEDY;
- p += 2; /* skip n */
- }
- /* If don't have to push any more, skip over the rest of command. */
- else
- p += 4;
- continue;
-
- /* Ignore these. Used to ignore the n of succeed_n's which
- currently have n == 0. */
- case unused:
- continue;
-
- case casefold_on:
- options |= RE_OPTION_IGNORECASE;
- continue;
-
- case casefold_off:
- options &= ~RE_OPTION_IGNORECASE;
- continue;
-
- case option_set:
- options = *p++;
- continue;
-
- case wordbound:
- if (AT_STRINGS_BEG(d)) {
- if (IS_A_LETTER(d)) break;
- else goto fail;
- }
- if (AT_STRINGS_END(d)) {
- if (PREV_IS_A_LETTER(d)) break;
- else goto fail;
- }
- if (PREV_IS_A_LETTER(d) != IS_A_LETTER(d))
- break;
- goto fail;
-
- case notwordbound:
- if (AT_STRINGS_BEG(d)) {
- if (IS_A_LETTER(d)) goto fail;
- else break;
- }
- if (AT_STRINGS_END(d)) {
- if (PREV_IS_A_LETTER(d)) goto fail;
- else break;
- }
- if (PREV_IS_A_LETTER(d) != IS_A_LETTER(d))
- goto fail;
- break;
-
- case wordbeg:
- if (IS_A_LETTER(d) && (AT_STRINGS_BEG(d) || !PREV_IS_A_LETTER(d)))
- break;
- goto fail;
-
- case wordend:
- if (!AT_STRINGS_BEG(d) && PREV_IS_A_LETTER(d)
- && (!IS_A_LETTER(d) || AT_STRINGS_END(d)))
- break;
- goto fail;
-
- case wordchar:
- PREFETCH;
- if (!IS_A_LETTER(d))
- goto fail;
- if (ismbchar(*d) && d + mbclen(*d) - 1 < dend)
- d += mbclen(*d) - 1;
- d++;
- SET_REGS_MATCHED;
- break;
-
- case notwordchar:
- PREFETCH;
- if (IS_A_LETTER(d))
- goto fail;
- if (ismbchar(*d) && d + mbclen(*d) - 1 < dend)
- d += mbclen(*d) - 1;
- d++;
- SET_REGS_MATCHED;
- break;
-
- case exactn:
- /* Match the next few pattern characters exactly.
- mcnt is how many characters to match. */
- mcnt = *p++;
- /* This is written out as an if-else so we don't waste time
- testing `translate' inside the loop. */
- if (TRANSLATE_P()) {
- do {
- unsigned char c;
-
- PREFETCH;
- if (*p == 0xff) {
- p++;
- if (!--mcnt
- || AT_STRINGS_END(d)
- || (unsigned char)*d++ != (unsigned char)*p++)
- goto fail;
- continue;
- }
- c = *d++;
- if (ismbchar(c)) {
- int n;
-
- if (c != (unsigned char)*p++)
- goto fail;
- for (n = mbclen(c) - 1; n > 0; n--)
- if (!--mcnt /* redundant check if pattern was
- compiled properly. */
- || AT_STRINGS_END(d)
- || (unsigned char)*d++ != (unsigned char)*p++)
- goto fail;
- continue;
- }
- /* compiled code translation needed for ruby */
- if ((unsigned char)translate[c] != (unsigned char)translate[*p++])
- goto fail;
- }
- while (--mcnt);
- }
- else {
- do {
- PREFETCH;
- if (*p == 0xff) {p++; mcnt--;}
- if (*d++ != *p++) goto fail;
- }
- while (--mcnt);
- }
- SET_REGS_MATCHED;
- break;
- }
-#ifdef RUBY
- CHECK_INTS;
-#endif
- continue; /* Successfully executed one pattern command; keep going. */
-
- /* Jump here if any matching operation fails. */
- fail:
- if (stackp != stackb) {
- /* A restart point is known. Restart there and pop it. */
- short last_used_reg, this_reg;
-
- /* If this failure point is from a dummy_failure_point, just
- skip it. */
- if (stackp[-4] == 0 || (best_regs_set && stackp[-1] == NON_GREEDY)) {
- POP_FAILURE_POINT();
- goto fail;
- }
- stackp--; /* discard greedy flag */
- options = (long)*--stackp;
- d = *--stackp;
- p = *--stackp;
- /* Restore register info. */
- last_used_reg = (long)*--stackp;
-
- /* Make the ones that weren't saved -1 or 0 again. */
- for (this_reg = num_regs - 1; this_reg > last_used_reg; this_reg--) {
- regend[this_reg] = REG_UNSET_VALUE;
- regstart[this_reg] = REG_UNSET_VALUE;
- IS_ACTIVE(reg_info[this_reg]) = 0;
- MATCHED_SOMETHING(reg_info[this_reg]) = 0;
- }
-
- /* And restore the rest from the stack. */
- for ( ; this_reg > 0; this_reg--) {
- reg_info[this_reg].word = *--stackp;
- regend[this_reg] = *--stackp;
- regstart[this_reg] = *--stackp;
- }
- mcnt = (long)*--stackp;
- while (mcnt--) {
- POP_FAILURE_COUNT();
- }
- if (p < pend) {
- int is_a_jump_n = 0;
- int failed_paren = 0;
-
- p1 = p;
- /* If failed to a backwards jump that's part of a repetition
- loop, need to pop this failure point and use the next one. */
- switch ((enum regexpcode)*p1) {
- case jump_n:
- case finalize_push_n:
- is_a_jump_n = 1;
- case maybe_finalize_jump:
- case finalize_jump:
- case finalize_push:
- case jump:
- p1++;
- EXTRACT_NUMBER_AND_INCR(mcnt, p1);
-
- if (mcnt >= 0) break; /* should be backward jump */
- p1 += mcnt;
-
- if (( is_a_jump_n && (enum regexpcode)*p1 == succeed_n) ||
- (!is_a_jump_n && (enum regexpcode)*p1 == on_failure_jump)) {
- if (failed_paren) {
- p1++;
- EXTRACT_NUMBER_AND_INCR(mcnt, p1);
- PUSH_FAILURE_POINT(p1 + mcnt, d);
- }
- goto fail;
- }
- break;
- default:
- /* do nothing */;
- }
- }
- }
- else
- break; /* Matching at this starting point really fails. */
- }
-
- if (best_regs_set)
- goto restore_best_regs;
-
- FREE_AND_RETURN(stackb,(-1)); /* Failure to match. */
-}
-
-
-static int
-memcmp_translate(s1, s2, len)
- unsigned char *s1, *s2;
- register int len;
-{
- register unsigned char *p1 = s1, *p2 = s2, c;
- while (len) {
- c = *p1++;
- if (ismbchar(c)) {
- int n;
-
- if (c != *p2++) return 1;
- for (n = mbclen(c) - 1; n > 0; n--)
- if (!--len || *p1++ != *p2++)
- return 1;
- }
- else
- if (translate[c] != translate[*p2++])
- return 1;
- len--;
- }
- return 0;
-}
-
-void
-re_copy_registers(regs1, regs2)
- struct re_registers *regs1, *regs2;
-{
- int i;
-
- if (regs1 == regs2) return;
- if (regs1->allocated == 0) {
- regs1->beg = TMALLOC(regs2->num_regs, int);
- regs1->end = TMALLOC(regs2->num_regs, int);
- regs1->allocated = regs2->num_regs;
- }
- else if (regs1->allocated < regs2->num_regs) {
- TREALLOC(regs1->beg, regs2->num_regs, int);
- TREALLOC(regs1->end, regs2->num_regs, int);
- regs1->allocated = regs2->num_regs;
- }
- for (i=0; i<regs2->num_regs; i++) {
- regs1->beg[i] = regs2->beg[i];
- regs1->end[i] = regs2->end[i];
- }
- regs1->num_regs = regs2->num_regs;
-}
-
-void
-re_free_registers(regs)
- struct re_registers *regs;
-{
- if (regs->allocated == 0) return;
- if (regs->beg) xfree(regs->beg);
- if (regs->end) xfree(regs->end);
-}
-
-/* Functions for multi-byte support.
- Created for grep multi-byte extension Jul., 1993 by t^2 (Takahiro Tanimoto)
- Last change: Jul. 9, 1993 by t^2 */
-static const unsigned char mbctab_ascii[] = {
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-};
-
-static const unsigned char mbctab_euc[] = { /* 0xA1-0xFE */
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
-};
-
-static const unsigned char mbctab_sjis[] = { /* 0x80-0x9f,0xE0-0xFC */
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0
-};
-
-static const unsigned char mbctab_sjis_trail[] = { /* 0x40-0x7E,0x80-0xFC */
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0
-};
-
-static const unsigned char mbctab_utf8[] = {
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 0, 0,
-};
-
-const unsigned char *re_mbctab = mbctab_ascii;
-
-void
-re_mbcinit(mbctype)
- int mbctype;
-{
- switch (mbctype) {
- case MBCTYPE_ASCII:
- re_mbctab = mbctab_ascii;
- current_mbctype = MBCTYPE_ASCII;
- break;
- case MBCTYPE_EUC:
- re_mbctab = mbctab_euc;
- current_mbctype = MBCTYPE_EUC;
- break;
- case MBCTYPE_SJIS:
- re_mbctab = mbctab_sjis;
- current_mbctype = MBCTYPE_SJIS;
- break;
- case MBCTYPE_UTF8:
- re_mbctab = mbctab_utf8;
- current_mbctype = MBCTYPE_UTF8;
- break;
- }
-}
-
-#define mbc_isfirst(t, c) (t)[(unsigned char)(c)]
-#define mbc_len(t, c) ((t)[(unsigned char)(c)]+1)
-
-static unsigned int asc_startpos _((const char *string, unsigned int pos));
-static unsigned int
-asc_startpos(string, pos)
- const char *string;
- unsigned int pos;
-{
- return pos;
-}
-
-#define euc_islead(c) ((unsigned char)((c) - 0xa1) > 0xfe - 0xa1)
-#define euc_mbclen(c) mbc_len(mbctab_euc, (c))
-static unsigned int euc_startpos _((const char *string, unsigned int pos));
-static unsigned int
-euc_startpos(string, pos)
- const char *string;
- unsigned int pos;
-{
- unsigned int i = pos, w;
-
- while (i > 0 && !euc_islead(string[i])) {
- --i;
- }
- if (i == pos || i + (w = euc_mbclen(string[i])) > pos) {
- return i;
- }
- i += w;
- return i + ((pos - i) & ~1);
-}
-
-#define sjis_isfirst(c) mbc_isfirst(mbctab_sjis, (c))
-#define sjis_istrail(c) mbctab_sjis_trail[(unsigned char)(c)]
-#define sjis_mbclen(c) mbc_len(mbctab_sjis, (c))
-static unsigned int sjis_startpos _((const char *string, unsigned int pos));
-static unsigned int
-sjis_startpos(string, pos)
- const char *string;
- unsigned int pos;
-{
- unsigned int i = pos, w;
-
- if (i > 0 && sjis_istrail(string[i])) {
- do {
- if (!sjis_isfirst(string[--i])) {
- ++i;
- break;
- }
- } while (i > 0);
- }
- if (i == pos || i + (w = sjis_mbclen(string[i])) > pos) {
- return i;
- }
- i += w;
- return i + ((pos - i) & ~1);
-}
-
-#define utf8_islead(c) ((unsigned char)((c) & 0xc0) != 0x80)
-#define utf8_mbclen(c) mbc_len(mbctab_utf8, (c))
-static unsigned int utf8_startpos _((const char *string, unsigned int pos));
-static unsigned int
-utf8_startpos(string, pos)
- const char *string;
- unsigned int pos;
-{
- unsigned int i = pos, w;
-
- while (i > 0 && !utf8_islead(string[i])) {
- --i;
- }
- if (i == pos || i + (w = utf8_mbclen(string[i])) > pos) {
- return i;
- }
- return i + w;
-}
-
-const mbc_startpos_func_t mbc_startpos_func[4] = {
- asc_startpos, euc_startpos, sjis_startpos, utf8_startpos
-};
-
-/*
- vi: sw=2 ts=8
- Local variables:
- mode : C
- c-file-style : "gnu"
- tab-width : 8
- End :
-*/
diff --git a/regex.h b/regex.h
deleted file mode 100644
index d5eb01d235..0000000000
--- a/regex.h
+++ /dev/null
@@ -1,227 +0,0 @@
-/* Definitions for data structures and routines for the regular
- expression library, version 0.12.
- Copyright (C) 1985,89,90,91,92,93,95,96,97,98 Free Software Foundation, Inc.
-
- This file is part of the GNU C Library. Its master source is NOT part of
- the C library, however. The master source lives in /gd/gnu/lib.
-
- The GNU C Library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public License as
- published by the Free Software Foundation; either version 2 of the
- License, or (at your option) any later version.
-
- The GNU C Library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public
- License along with the GNU C Library; see the file LGPL. If not,
- write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
- Boston, MA 02111-1307, USA. */
-/* Multi-byte extension added May, 1993 by t^2 (Takahiro Tanimoto)
- Last change: May 21, 1993 by t^2 */
-/* modified for Ruby by matz@netlab.co.jp */
-
-#ifndef __REGEXP_LIBRARY
-#define __REGEXP_LIBRARY
-
-/* symbol mangling for ruby */
-#ifdef RUBY
-# define re_adjust_startpos ruby_re_adjust_startpos
-# define re_compile_fastmap ruby_re_compile_fastmap
-# define re_compile_pattern ruby_re_compile_pattern
-# define re_copy_registers ruby_re_copy_registers
-# define re_free_pattern ruby_re_free_pattern
-# define re_free_registers ruby_re_free_registers
-# define re_match ruby_re_match
-# define re_mbcinit ruby_re_mbcinit
-# define re_search ruby_re_search
-# define re_set_casetable ruby_re_set_casetable
-# define register_info_type ruby_register_info_type
-#endif
-
-#include <stddef.h>
-
-/* Define number of parens for which we record the beginnings and ends.
- This affects how much space the `struct re_registers' type takes up. */
-#ifndef RE_NREGS
-#define RE_NREGS 10
-#endif
-
-#define BYTEWIDTH 8
-
-#define RE_REG_MAX ((1<<BYTEWIDTH)-1)
-
-/* Maximum number of duplicates an interval can allow. */
-#ifndef RE_DUP_MAX
-#define RE_DUP_MAX ((1 << 15) - 1)
-#endif
-
-
-/* If this bit is set, then character classes are supported; they are:
- [:alpha:], [:upper:], [:lower:], [:digit:], [:alnum:], [:xdigit:],
- [:space:], [:print:], [:punct:], [:graph:], and [:cntrl:].
- If not set, then character classes are not supported. */
-#define RE_CHAR_CLASSES (1L << 9)
-
-/* match will be done case insensetively */
-#define RE_OPTION_IGNORECASE (1L)
-/* perl-style extended pattern available */
-#define RE_OPTION_EXTENDED (RE_OPTION_IGNORECASE<<1)
-/* newline will be included for . */
-#define RE_OPTION_MULTILINE (RE_OPTION_EXTENDED<<1)
-/* ^ and $ ignore newline */
-#define RE_OPTION_SINGLELINE (RE_OPTION_MULTILINE<<1)
-/* works line Perl's /s; it's called POSIX for wrong reason */
-#define RE_OPTION_POSIXLINE (RE_OPTION_MULTILINE|RE_OPTION_SINGLELINE)
-/* search for longest match, in accord with POSIX regexp */
-#define RE_OPTION_LONGEST (RE_OPTION_SINGLELINE<<1)
-
-#define RE_MAY_IGNORECASE (RE_OPTION_LONGEST<<1)
-#define RE_OPTIMIZE_ANCHOR (RE_MAY_IGNORECASE<<1)
-#define RE_OPTIMIZE_EXACTN (RE_OPTIMIZE_ANCHOR<<1)
-#define RE_OPTIMIZE_NO_BM (RE_OPTIMIZE_EXACTN<<1)
-#define RE_OPTIMIZE_BMATCH (RE_OPTIMIZE_NO_BM<<1)
-
-/* For multi-byte char support */
-#define MBCTYPE_ASCII 0
-#define MBCTYPE_EUC 1
-#define MBCTYPE_SJIS 2
-#define MBCTYPE_UTF8 3
-
-#if defined IMPORT || defined USEIMPORTLIB
-extern __declspec(dllimport)
-#elif defined EXPORT
-extern __declspec(dllexport)
-#else
-extern
-#endif
-const unsigned char *re_mbctab;
-#if defined(__STDC__)
-void re_mbcinit (int);
-#else
-void re_mbcinit ();
-#endif
-
-#undef ismbchar
-#define ismbchar(c) re_mbctab[(unsigned char)(c)]
-#define mbclen(c) (re_mbctab[(unsigned char)(c)]+1)
-
-/* Structure used in re_match() */
-
-typedef union
-{
- unsigned char *word;
- struct {
- unsigned is_active : 1;
- unsigned matched_something : 1;
- } bits;
-} register_info_type;
-
-/* This data structure is used to represent a compiled pattern. */
-
-struct re_pattern_buffer
- {
- char *buffer; /* Space holding the compiled pattern commands. */
- int allocated; /* Size of space that `buffer' points to. */
- int used; /* Length of portion of buffer actually occupied */
- char *fastmap; /* Pointer to fastmap, if any, or zero if none. */
- /* re_search uses the fastmap, if there is one,
- to skip over totally implausible characters. */
- char *must; /* Pointer to exact pattern which strings should have
- to be matched. */
- int *must_skip; /* Pointer to exact pattern skip table for bm_search */
- long options; /* Flags for options such as extended_pattern. */
- long re_nsub; /* Number of subexpressions found by the compiler. */
- char fastmap_accurate;
- /* Set to zero when a new pattern is stored,
- set to one when the fastmap is updated from it. */
- char can_be_null; /* Set to one by compiling fastmap
- if this pattern might match the null string.
- It does not necessarily match the null string
- in that case, but if this is zero, it cannot.
- 2 as value means can match null string
- but at end of range or before a character
- listed in the fastmap. */
-
- /* stack & working area for re_match() */
- unsigned char **regstart;
- unsigned char **regend;
- unsigned char **old_regstart;
- unsigned char **old_regend;
- register_info_type *reg_info;
- unsigned char **best_regstart;
- unsigned char **best_regend;
- };
-
-typedef struct re_pattern_buffer regex_t;
-
-/* Structure to store register contents data in.
-
- Pass the address of such a structure as an argument to re_match, etc.,
- if you want this information back.
-
- For i from 1 to RE_NREGS - 1, start[i] records the starting index in
- the string of where the ith subexpression matched, and end[i] records
- one after the ending index. start[0] and end[0] are analogous, for
- the entire pattern. */
-
-struct re_registers
- {
- int allocated;
- int num_regs;
- int *beg;
- int *end;
- };
-
-/* Type for byte offsets within the string. POSIX mandates this. */
-typedef size_t regoff_t;
-
-/* POSIX specification for registers. Aside from the different names than
- `re_registers', POSIX uses an array of structures, instead of a
- structure of arrays. */
-typedef struct
-{
- regoff_t rm_so; /* Byte offset from string's start to substring's start. */
- regoff_t rm_eo; /* Byte offset from string's start to substring's end. */
-} regmatch_t;
-
-
-#ifdef __STDC__
-
-extern char *re_compile_pattern (const char *, int, struct re_pattern_buffer *);
-void re_free_pattern (struct re_pattern_buffer *);
-/* Is this really advertised? */
-extern int re_adjust_startpos (struct re_pattern_buffer *, const char*, int, int, int);
-extern void re_compile_fastmap (struct re_pattern_buffer *);
-extern int re_search (struct re_pattern_buffer *, const char*, int, int, int,
- struct re_registers *);
-extern int re_match (struct re_pattern_buffer *, const char *, int, int,
- struct re_registers *);
-extern void re_set_casetable (const char *table);
-extern void re_copy_registers (struct re_registers*, struct re_registers*);
-extern void re_free_registers (struct re_registers*);
-
-#ifndef RUBY
-/* 4.2 bsd compatibility. */
-extern char *re_comp (const char *);
-extern int re_exec (const char *);
-#endif
-
-#else /* !__STDC__ */
-
-extern char *re_compile_pattern ();
-void re_free_regexp ();
-/* Is this really advertised? */
-extern int re_adjust_startpos ();
-extern void re_compile_fastmap ();
-extern int re_search ();
-extern int re_match ();
-extern void re_set_casetable ();
-extern void re_copy_registers ();
-extern void re_free_registers ();
-
-#endif /* __STDC__ */
-
-#endif /* !__REGEXP_LIBRARY */
diff --git a/ruby.1 b/ruby.1
deleted file mode 100644
index 6d6bebf1ae..0000000000
--- a/ruby.1
+++ /dev/null
@@ -1,291 +0,0 @@
-.\"Ruby is copyrighted by Yukihiro Matsumoto <matz@netlab.jp>.
-.na
-.TH RUBY 1 "ruby 1.6" "2000-09-11" "Ruby Programmers Reference Guide"
-.SH NAME
-ruby - Interpreted object-oriented scripting language
-.SH SYNOPSIS
-.B ruby \c
- [ \c
-.BI --version \c
- ] [ \c
-.BI -c \c
- ] [ \c
-.BI -w \c
- ] [ \c
-.BI -d \c
- ] [ \c
-.BI -l \c
- ]
- [ \c
-.BI -p \c
- ] [ \c
-.BI -n \c
- ] [ \c
-.BI -a \c
- ] [ \c
-.BI -s \c
- ] [ \c
-.BI -0 "[octal]"\c
- ]
- [ \c
-.BI -K "c"\c
- ] [ \c
-.BI -e "command"\c
- ] [ \c
-.BI -F "pattern"\c
- ]
- [ \c
-.BI -i "[extension]"\c
- ] [ \c
-.BI -I "dir"\c
- ] [ \c
-.BI -r "library"\c
- ]
- [ \c
-.BI -S \c
- ] [ \c
-.BI -v \c
- ] [ \c
-.BI -x "[directory]"\c
- ] [ \c
-.BI -C "directory"\c
- ]
- [ \c
-.BI -y \c
-] [ \c
-.BI -- \c
- ] [ programfile ] [ argument ] ...
-
-.SH PREFACE
-Ruby is an interpreted scripting language for quick and easy
-object-oriented programming. It has many features to process text
-files and to do system management tasks (as in Perl). It is simple,
-straight-forward, and extensible.
-.PP
-If you want a language for easy object-oriented programming, or you
-don't like the Perl ugliness, or you do like the concept of lisp, but
-don't like too much parentheses, Ruby may be the language of your
-choice.
-.SH DESCRIPTION
-Ruby's features are as follows:
-.TP
-.B "\(bu Interpretive"
-Ruby is an interpreted language, so you don't have to recompile
-programs written in Ruby to execute them.
-.TP
-.B "\(bu Variables have no type (dynamic typing)"
-Variables in Ruby can contain data of any type. You don't have to
-worry about variable typing. Consequently, it has a weaker compile
-time check.
-.TP
-.B "\(bu No declaration needed"
-You can use variables in your Ruby programs without any declarations.
-Variable names denote their scope, local, global, instance, etc.
-.TP
-.B "\(bu Simple syntax"
-Ruby has a simple syntax influenced slightly from Eiffel.
-.TP
-.B "\(bu No user-level memory management"
-Ruby has automatic memory management. Objects no longer
-referenced from anywhere are automatically collected by the
-garbage collector built into the interpreter.
-.TP
-.B "\(bu Everything is an object"
-Ruby is the purely object-oriented language, and was so since its
-creation. Even such basic data as integers are seen as objects.
-.TP
-.B "\(bu Class, inheritance, methods"
-Of course, as an object-oriented language, Ruby has such basic
-features like classes, inheritance, and methods.
-.TP
-.B "\(bu Singleton methods"
-Ruby has the ability to define methods for certain objects. For
-example, you can define a press-button action for certain widget by
-defining a singleton method for the button. Or, you can make up your
-own prototype based object system using singleton methods, if you want
-to.
-.TP
-.B "\(bu Mix-in by modules"
-Ruby intentionally does not have the multiple inheritance as it is a
-source of confusion. Instead, Ruby has the ability to share
-implementations across the inheritance tree. This is often called
-`Mix-in'.
-.TP
-.B "\(bu Iterators"
-Ruby has iterators for loop abstraction.
-.TP
-.B "\(bu Closures"
-In Ruby, you can objectify the procedure.
-.TP
-.B "\(bu Text processing and regular expression"
-Ruby has a bunch of text processing features like in Perl.
-.TP
-.B "\(bu Bignums"
-With built-in bignums, you can for example calculate factorial(400).
-.TP
-.B "\(bu Exception handling"
-As in Java(tm).
-.TP
-.B "\(bu Direct access to the OS"
-Ruby can use most UNIX system calls, often used in system programming.
-.TP
-.B "\(bu Dynamic loading"
-On most UNIX systems, you can load object files into the Ruby
-interpreter on-the-fly.
-.PP
-.SH COMMAND LINE OPTIONS
-Ruby interpreter accepts following command-line options (switches).
-They are quite similar to those of Perl.
-.TP
-.B -0[octal]
-specifies the input record separator ($/) as an octal number. If no
-digit is given, the null character is taken as the separator. Other
-switches may follow the digits. -00 turns Ruby into paragraph mode. -
-0777 makes Ruby read whole file at once as a single string since there
-is no legal character with that value.
-.TP
-.B -a
-turns on auto-split mode when used with -n or -p. In auto-split
-mode, Ruby executes
-.nf
-.ne 1
-\& $F = $_.split
-at beginning of each loop.
-.fi
-.TP
-.B -c
-causes Ruby to check the syntax of the script and exit without
-executing. If there are no syntax errors, Ruby will print "Syntax
-OK" to the standard output.
-.TP
-.B --copyright
-prints the copyright notice.
-.TP
-.B -d --debug
-turns on debug mode. $DEBUG will set true.
-.TP
-.B -e command
-specifies script from command-line while telling Ruby to not
-search argv for script filenames.
-.TP
-.B -F pattern
-specifies input field separator ($;).
-.TP
-.B -h --help
-prints a summary of the options.
-.TP
-.B -i extension
-specifies in-place-edit mode. The extension, if specified, is
-added to old filename to make a backup copy.
-example:
-.nf
-.ne 8
-\& % echo matz > /tmp/junk
-\& % cat /tmp/junk
-\& matz
-\& % ruby -p -i.bak -e '$_.upcase!' /tmp/junk
-\& % cat /tmp/junk
-\& MATZ
-\& % cat /tmp/junk.bak
-\& matz
-.fi
-.TP
-.B -I directory
-used to tell Ruby where to load the library scripts. Directory path
-will be added to the load-path variable ($:').
-.TP
-.B -Kkcode
-specifies KANJI (Japanese) encoding.
-.TP
-.B -l
-enables automatic line-ending processing, which means to firstly set
-$\e to the value of $/, and secondly chops every line read using chop!.
-.TP
-.B -n
-causes Ruby to assume the following loop around your script,
-which makes it iterate over filename arguments somewhat like
-sed -n or awk.
-.nf
-.ne 3
-\& while gets
-\& ...
-\& end
-.fi
-.TP
-.B -p
-acts mostly same as -n switch, but print the value of variable
-$_ at the each end of the loop.
-example:
-.nf
-.ne 2
-\& % echo matz | ruby -p -e '$_.tr! "a-z", "A-Z"'
-\& MATZ
-.fi
-.TP
-.B -r library
-causes Ruby to load the library using require. It is useful
-with switches -n or -p.
-.TP
-.B -s
-enables some switch parsing for switches after script name but before
-any filename arguments (or before a --). Any switches found there are
-removed from ARGV and set the corresponding variable in the script.
-example:
-.nf
-.ne 3
-\& #! /usr/local/bin/ruby -s
-\& # prints "true" if invoked with `-xyz' switch.
-\& print "true\en" if $xyz
-.fi
-.TP
-.B -S
-makes Ruby use the PATH environment variable to search for
-script, unless if its name begins with a slash. This is used to
-emulate #! on machines that don't support it, in the following
-manner:
-.nf
-.ne 2
-\& #! /usr/local/bin/ruby
-\& # This line makes the next one a comment in ruby \e
-\& exec /usr/local/bin/ruby -S $0 $*
-.fi
-On some systems $0 does not always contain the full pathname, so you
-need -S switch to tell Ruby to search for the script if necessary. To
-handle embedded spaces or such. A better construct than $* would be
-${1+"$@"}, but it does not work if the script is being interpreted by
-csh.
-.TP
-.B -v --verbose
-enables verbose mode. Ruby will print its version at the beginning,
-and set the variable `$VERBOSE' to true. Some methods print extra
-messages if this variable is true. If this switch is given, and no
-other switches are present, Ruby quits after printing its version.
-.TP
-.B -T[level]
-turns on taint checks at the specified level (default 1).
-.TP
-.B --version
-prints the version of Ruby interpreter.
-.TP
-.B -w
-enables verbose mode without printing version message at the
-beginning. It set the `$VERBOSE' variable to true.
-.TP
-.B -x[directory]
-tells Ruby that the script is embedded in a message. Leading garbage
-will be discarded until the first that starts with "#!" and contains
-the string, "ruby". Any meaningful switches on that line will applied.
-The end of script must be specified with either EOF, ^D (control-D),
-^Z (control-Z), or reserved word __END__.If the directory name is
-specified, Ruby will switch to that directory before executing script.
-.TP
-.B -C directory
-causes Ruby to switch to the directory.
-.TP
-.B -y --yydebug
-turns on compiler debug mode. Ruby will print a bunch of internal
-state messages during compiling scripts. You don't have to specify
-this switch, unless you are going to debug the Ruby interpreter.
-.PP
-.SH AUTHOR
- Ruby is designed and implemented by Yukihiro Matsumoto <matz@netlab.jp>.
diff --git a/ruby.c b/ruby.c
deleted file mode 100644
index 155a6fa0ad..0000000000
--- a/ruby.c
+++ /dev/null
@@ -1,1061 +0,0 @@
-/**********************************************************************
-
- ruby.c -
-
- $Author$
- $Date$
- created at: Tue Aug 10 12:47:31 JST 1993
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
- Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
- Copyright (C) 2000 Information-technology Promotion Agency, Japan
-
-**********************************************************************/
-
-#if defined _WIN32 || defined __CYGWIN__
-#include <windows.h>
-#endif
-#include "ruby.h"
-#include "dln.h"
-#include "node.h"
-#include <stdio.h>
-#include <sys/types.h>
-#include <ctype.h>
-
-#ifdef __hpux
-#include <sys/pstat.h>
-#endif
-
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-
-#ifndef HAVE_STRING_H
-char *strchr _((const char*,const char));
-char *strrchr _((const char*,const char));
-char *strstr _((const char*,const char*));
-#endif
-
-#include "util.h"
-
-#ifndef HAVE_STDLIB_H
-char *getenv();
-#endif
-
-VALUE ruby_debug = Qfalse;
-VALUE ruby_verbose = Qfalse;
-static int sflag = 0;
-static int xflag = 0;
-extern int yydebug;
-
-char *ruby_inplace_mode = Qfalse;
-
-static void load_stdin _((void));
-static void load_file _((char *, int));
-static void forbid_setid _((const char *));
-
-static VALUE do_loop = Qfalse, do_print = Qfalse;
-static VALUE do_check = Qfalse, do_line = Qfalse;
-static VALUE do_split = Qfalse;
-
-static char *script;
-
-static int origargc;
-static char **origargv;
-
-static void
-usage(name)
- const char *name;
-{
- /* This message really ought to be max 23 lines.
- * Removed -h because the user already knows that option. Others? */
-
- static char *usage_msg[] = {
-"-0[octal] specify record separator (\\0, if no argument)",
-"-a autosplit mode with -n or -p (splits $_ into $F)",
-"-c check syntax only",
-"-Cdirectory cd to directory, before executing your script",
-"-d set debugging flags (set $DEBUG to true)",
-"-e 'command' one line of script. Several -e's allowed. Omit [programfile]",
-"-Fpattern split() pattern for autosplit (-a)",
-"-i[extension] edit ARGV files in place (make backup if extension supplied)",
-"-Idirectory specify $LOAD_PATH directory (may be used more than once)",
-"-Kkcode specifies KANJI (Japanese) code-set",
-"-l enable line ending processing",
-"-n assume 'while gets(); ... end' loop around your script",
-"-p assume loop like -n but print line also like sed",
-"-rlibrary require the library, before executing your script",
-"-s enable some switch parsing for switches after script name",
-"-S look for the script using PATH environment variable",
-"-T[level] turn on tainting checks",
-"-v print version number, then turn on verbose mode",
-"-w turn warnings on for your script",
-"-x[directory] strip off text before #!ruby line and perhaps cd to directory",
-"--copyright print the copyright",
-"--version print the version",
-NULL
-};
- char **p = usage_msg;
-
- printf("Usage: %s [switches] [--] [programfile] [arguments]\n", name);
- while (*p)
- printf(" %s\n", *p++);
-}
-
-extern VALUE rb_load_path;
-
-#define STATIC_FILE_LENGTH 255
-
-#if defined _WIN32 || defined __CYGWIN__ || defined __DJGPP__
-static char *
-rubylib_mangle(s, l)
- char *s;
- unsigned int l;
-{
- static char *newp, *oldp;
- static int newl, oldl, notfound;
- static char newsub[STATIC_FILE_LENGTH+1];
-
- if (!newp && !notfound) {
- newp = getenv("RUBYLIB_PREFIX");
- if (newp) {
- char *s;
-
- oldp = newp;
- while (*newp && !ISSPACE(*newp) && *newp != ';') {
- newp++; oldl++; /* Skip digits. */
- }
- while (*newp && (ISSPACE(*newp) || *newp == ';')) {
- newp++; /* Skip whitespace. */
- }
- newl = strlen(newp);
- if (newl == 0 || oldl == 0 || newl > STATIC_FILE_LENGTH) {
- rb_fatal("malformed RUBYLIB_PREFIX");
- }
- strcpy(newsub, newp);
- s = newsub;
- while (*s) {
- if (*s == '\\') *s = '/';
- s++;
- }
- }
- else {
- notfound = 1;
- }
- }
- if (l == 0) {
- l = strlen(s);
- }
- if (!newp || l < oldl || strncasecmp(oldp, s, oldl) != 0) {
- static char ret[STATIC_FILE_LENGTH+1];
- strncpy(ret, s, l);
- ret[l] = 0;
- return ret;
- }
- if (l + newl - oldl > STATIC_FILE_LENGTH || newl > STATIC_FILE_LENGTH) {
- rb_fatal("malformed RUBYLIB_PREFIX");
- }
- strcpy(newsub + newl, s + oldl);
- newsub[l + newl - oldl] = 0;
- return newsub;
-}
-#define rubylib_mangled_path(s, l) rb_str_new2(rubylib_mangle((s), (l)))
-#define rubylib_mangled_path2(s) rb_str_new2(rubylib_mangle((s), 0))
-#else
-#define rubylib_mangled_path(s, l) rb_str_new((s), (l))
-#define rubylib_mangled_path2(s) rb_str_new2(s)
-#endif
-
-void
-ruby_incpush(path)
- const char *path;
-{
- const char sep = PATH_SEP_CHAR;
-
- if (path == 0) return;
-#if defined(__CYGWIN__)
- {
- char rubylib[FILENAME_MAX];
- conv_to_posix_path(path, rubylib, FILENAME_MAX);
- path = rubylib;
- }
-#endif
- if (strchr(path, sep)) {
- const char *p, *s;
- VALUE ary = rb_ary_new();
-
- p = path;
- while (*p) {
- while (*p == sep) p++;
- if (s = strchr(p, sep)) {
- rb_ary_push(ary, rubylib_mangled_path(p, (int)(s-p)));
- p = s + 1;
- }
- else {
- rb_ary_push(ary, rubylib_mangled_path2(p));
- break;
- }
- }
- rb_ary_concat(rb_load_path, ary);
- }
- else {
- rb_ary_push(rb_load_path, rubylib_mangled_path2(path));
- }
-}
-
-#if defined _WIN32 || defined __CYGWIN__ || defined __DJGPP__ || defined __EMX__
-#define LOAD_RELATIVE 1
-#endif
-
-void
-ruby_init_loadpath()
-{
-#if defined LOAD_RELATIVE
- char libpath[FILENAME_MAX+1];
- char *p;
- int rest;
-#if defined _WIN32 || defined __CYGWIN__
-# if defined LIBRUBY_SO
- HMODULE libruby = GetModuleHandle(LIBRUBY_SO);
-# else
- HMODULE libruby = NULL;
-# endif
- GetModuleFileName(libruby, libpath, sizeof libpath);
-#elif defined(DJGPP)
- extern char *__dos_argv0;
- strncpy(libpath, __dos_argv0, FILENAME_MAX);
-#define CharNext(p) ((p) + mblen(p, MB_CUR_MAX))
-#elif defined(__EMX__)
- _execname(libpath, FILENAME_MAX);
-#endif
-
-#ifndef CharNext /* defined as CharNext[AW] on Windows. */
-#define CharNext(p) ((p) + 1)
-#endif
-
- for (p = libpath; *p; p = CharNext(p))
- if (*p == '\\')
- *p = '/';
-
- p = strrchr(libpath, '/');
- if (p) {
- *p = 0;
- if (p-libpath > 3 && !strcasecmp(p-4, "/bin")) {
- p -= 4;
- *p = 0;
- }
- }
- else {
- strcpy(libpath, ".");
- p = libpath + 1;
- }
-
- rest = FILENAME_MAX - (p - libpath);
-
-#define RUBY_RELATIVE(path) (strncpy(p, (path), rest), libpath)
-#else
-#define RUBY_RELATIVE(path) (path)
-#endif
-
- if (rb_safe_level() == 0) {
- ruby_incpush(getenv("RUBYLIB"));
- }
-
-#ifdef RUBY_SEARCH_PATH
- ruby_incpush(RUBY_RELATIVE(RUBY_SEARCH_PATH));
-#endif
-
- ruby_incpush(RUBY_RELATIVE(RUBY_SITE_LIB2));
-#ifdef RUBY_SITE_THIN_ARCHLIB
- ruby_incpush(RUBY_RELATIVE(RUBY_SITE_THIN_ARCHLIB));
-#endif
- ruby_incpush(RUBY_RELATIVE(RUBY_SITE_ARCHLIB));
- ruby_incpush(RUBY_RELATIVE(RUBY_SITE_LIB));
-
- ruby_incpush(RUBY_RELATIVE(RUBY_LIB));
-#ifdef RUBY_THIN_ARCHLIB
- ruby_incpush(RUBY_RELATIVE(RUBY_THIN_ARCHLIB));
-#endif
- ruby_incpush(RUBY_RELATIVE(RUBY_ARCHLIB));
-
- if (rb_safe_level() == 0) {
- ruby_incpush(".");
- }
-}
-
-struct req_list {
- char *name;
- struct req_list *next;
-};
-static struct req_list req_list_head, *req_list_last = &req_list_head;
-
-static void
-add_modules(mod)
- const char *mod;
-{
- struct req_list *list;
-
- list = ALLOC(struct req_list);
- list->name = ALLOC_N(char, strlen(mod)+1);
- strcpy(list->name, mod);
- list->next = 0;
- req_list_last->next = list;
- req_list_last = list;
-}
-
-extern void Init_ext _((void));
-
-static void
-require_libraries()
-{
- extern NODE *ruby_eval_tree;
- extern NODE *ruby_eval_tree_begin;
- char *orig_sourcefile = ruby_sourcefile;
- NODE *save[2];
- struct req_list *list = req_list_head.next;
- struct req_list *tmp;
-
- Init_ext(); /* should be called here for some reason :-( */
- ruby_sourcefile = 0;
- save[0] = ruby_eval_tree;
- save[1] = ruby_eval_tree_begin;
- ruby_eval_tree = ruby_eval_tree_begin = 0;
- req_list_last = 0;
- while (list) {
- rb_require(list->name);
- tmp = list->next;
- free(list->name);
- free(list);
- list = tmp;
- }
- req_list_head.next = 0;
- ruby_eval_tree = save[0];
- ruby_eval_tree_begin = save[1];
- ruby_sourcefile = orig_sourcefile;
-}
-
-static void
-process_sflag()
-{
- if (sflag) {
- int n;
- VALUE *args;
-
- n = RARRAY(rb_argv)->len;
- args = RARRAY(rb_argv)->ptr;
- while (n > 0) {
- VALUE v = *args++;
- char *s = StringValuePtr(v);
- char *p;
-
- if (s[0] != '-') break;
- n--;
- if (s[1] == '-' && s[2] == '\0') break;
-
- s[0] = '$';
- if (p = strchr(s, '=')) {
- *p++ = '\0';
- rb_gv_set(s, rb_str_new2(p));
- }
- else {
- rb_gv_set(s, Qtrue);
- }
- s[0] = '-';
- }
- n = RARRAY(rb_argv)->len - n;
- while (n--) {
- rb_ary_shift(rb_argv);
- }
- }
- sflag = 0;
-}
-
-static void proc_options _((int argc, char **argv));
-
-static char*
-moreswitches(s)
- char *s;
-{
- int argc; char *argv[3];
- char *p = s;
-
- argc = 2; argv[0] = argv[2] = 0;
- while (*s && !ISSPACE(*s))
- s++;
- argv[1] = ALLOCA_N(char, s-p+2);
- argv[1][0] = '-';
- strncpy(argv[1]+1, p, s-p);
- argv[1][s-p+1] = '\0';
- proc_options(argc, argv);
- while (*s && ISSPACE(*s))
- s++;
- return s;
-}
-
-static void
-proc_options(argc, argv)
- int argc;
- char **argv;
-{
- char *argv0 = argv[0];
- int do_search;
- char *s;
-
- int version = 0;
- int copyright = 0;
- int verbose = 0;
- VALUE e_script = Qfalse;
-
- if (argc == 0) return;
-
- do_search = Qfalse;
-
- for (argc--,argv++; argc > 0; argc--,argv++) {
- if (argv[0][0] != '-' || !argv[0][1]) break;
-
- s = argv[0]+1;
- reswitch:
- switch (*s) {
- case 'a':
- do_split = Qtrue;
- s++;
- goto reswitch;
-
- case 'p':
- do_print = Qtrue;
- /* through */
- case 'n':
- do_loop = Qtrue;
- s++;
- goto reswitch;
-
- case 'd':
- ruby_debug = Qtrue;
- ruby_verbose = Qtrue;
- s++;
- goto reswitch;
-
- case 'y':
- yydebug = 1;
- s++;
- goto reswitch;
-
- case 'v':
- if (argv0 == 0 || verbose) {
- s++;
- goto reswitch;
- }
- ruby_show_version();
- verbose = 1;
- case 'w':
- ruby_verbose = Qtrue;
- s++;
- goto reswitch;
-
- case 'c':
- do_check = Qtrue;
- s++;
- goto reswitch;
-
- case 's':
- forbid_setid("-s");
- sflag = 1;
- s++;
- goto reswitch;
-
- case 'h':
- usage(origargv[0]);
- exit(0);
-
- case 'l':
- do_line = Qtrue;
- rb_output_rs = rb_rs;
- s++;
- goto reswitch;
-
- case 'S':
- forbid_setid("-S");
- do_search = Qtrue;
- s++;
- goto reswitch;
-
- case 'e':
- forbid_setid("-e");
- if (!*++s) {
- s = argv[1];
- argc--,argv++;
- }
- if (!s) {
- fprintf(stderr, "%s: no code specified for -e\n", origargv[0]);
- exit(2);
- }
- if (!e_script) {
- e_script = rb_str_new(0,0);
- if (script == 0) script = "-e";
- }
- rb_str_cat2(e_script, s);
- rb_str_cat2(e_script, "\n");
- break;
-
- case 'r':
- forbid_setid("-r");
- if (*++s) {
- add_modules(s);
- }
- else if (argv[1]) {
- add_modules(argv[1]);
- argc--,argv++;
- }
- break;
-
- case 'i':
- forbid_setid("-i");
- if (ruby_inplace_mode) free(ruby_inplace_mode);
- ruby_inplace_mode = strdup(s+1);
- break;
-
- case 'x':
- xflag = Qtrue;
- s++;
- if (*s && chdir(s) < 0) {
- rb_fatal("Can't chdir to %s", s);
- }
- break;
-
- case 'C':
- case 'X':
- s++;
- if (!*s) {
- s = argv[1];
- argc--,argv++;
- }
- if (!s || !*s) {
- rb_fatal("Can't chdir");
- }
- if (chdir(s) < 0) {
- rb_fatal("Can't chdir to %s", s);
- }
- break;
-
- case 'F':
- if (*++s) {
- rb_fs = rb_str_new2(s);
- }
- break;
-
- case 'K':
- if (*++s) {
- rb_set_kcode(s);
- s++;
- }
- goto reswitch;
-
- case 'T':
- {
- int numlen;
- int v = 1;
-
- if (*++s) {
- v = scan_oct(s, 2, &numlen);
- if (numlen == 0) v = 1;
- }
- rb_set_safe_level(v);
- }
- break;
-
- case 'I':
- forbid_setid("-I");
- if (*++s)
- ruby_incpush(s);
- else if (argv[1]) {
- ruby_incpush(argv[1]);
- argc--,argv++;
- }
- break;
-
- case '0':
- {
- int numlen;
- int v;
- char c;
-
- v = scan_oct(s, 4, &numlen);
- s += numlen;
- if (v > 0377) rb_rs = Qnil;
- else if (v == 0 && numlen >= 2) {
- rb_rs = rb_str_new2("\n\n");
- }
- else {
- c = v & 0xff;
- rb_rs = rb_str_new(&c, 1);
- }
- }
- goto reswitch;
-
- case '-':
- if (!s[1] || s[1] == '\r' && !s[2]) {
- argc--,argv++;
- goto switch_end;
- }
- s++;
- if (strcmp("copyright", s) == 0)
- copyright = 1;
- else if (strcmp("debug", s) == 0) {
- ruby_debug = Qtrue;
- ruby_verbose = Qtrue;
- }
- else if (strcmp("version", s) == 0)
- version = 1;
- else if (strcmp("verbose", s) == 0) {
- verbose = 1;
- ruby_verbose = Qtrue;
- }
- else if (strcmp("yydebug", s) == 0)
- yydebug = 1;
- else if (strcmp("help", s) == 0) {
- usage(origargv[0]);
- exit(0);
- }
- else {
- fprintf(stderr, "%s: invalid option --%s (-h will show valid options)\n",
- origargv[0], s);
- exit(2);
- }
- break;
-
- case '*':
- case ' ':
- if (s[1] == '-') s+=2;
- break;
-
- default:
- fprintf(stderr, "%s: invalid option -%c (-h will show valid options)\n",
- origargv[0], *s);
- exit(2);
-
- case 0:
- break;
- }
- }
-
- switch_end:
- if (argv0 == 0) return;
-
- if (rb_safe_level() == 0 && (s = getenv("RUBYOPT"))) {
- while (ISSPACE(*s)) s++;
- if (*s == '-' && *(s+1) == 'T') {
- int numlen;
- int v = 1;
-
- s += 2;
- if (*++s) {
- v = scan_oct(s, 2, &numlen);
- if (numlen == 0) v = 1;
- }
- rb_set_safe_level(v);
- }
- else {
- while (s && *s) {
- while (ISSPACE(*s)) s++;
- if (*s == '-') {
- s++;
- if (ISSPACE(*s)) continue;
- }
- if (!*s) break;
- if (!strchr("IdvwrK", *s))
- rb_raise(rb_eRuntimeError, "Illegal switch in RUBYOPT: -%c", *s);
- s = moreswitches(s);
- }
- }
- }
-
- if (version) {
- ruby_show_version();
- exit(0);
- }
- if (copyright) {
- ruby_show_copyright();
- }
-
- if (rb_safe_level() >= 4) {
- OBJ_TAINT(rb_argv);
- OBJ_TAINT(rb_load_path);
- }
-
- if (!e_script && argc == 0) { /* no more args */
- if (verbose) exit(0);
- script = "-";
- }
- else {
- if (!e_script) {
- script = argv[0];
- }
- if (script[0] == '\0') {
- script = "-";
- }
- else {
- if (do_search) {
- char *path = getenv("RUBYPATH");
-
- script = 0;
- if (path) {
- script = dln_find_file(argv[0], path);
- }
- if (!script) {
- script = dln_find_file(argv[0], getenv("PATH"));
- }
- if (!script) script = argv[0];
- }
- }
- if (!e_script) {
- argc--; argv++;
- }
- }
-
- ruby_script(script);
- ruby_set_argv(argc, argv);
- process_sflag();
-
- ruby_init_loadpath();
- ruby_sourcefile = rb_source_filename(argv0);
- if (e_script) {
- require_libraries();
- rb_compile_string(script, e_script, 1);
- }
- else if (strlen(script) == 1 && script[0] == '-') {
- load_stdin();
- }
- else {
- load_file(script, 1);
- }
-
- process_sflag();
- xflag = 0;
-
- if (rb_safe_level() >= 4) {
- FL_UNSET(rb_argv, FL_TAINT);
- FL_UNSET(rb_load_path, FL_TAINT);
- }
-}
-
-extern int ruby__end__seen;
-
-static void
-load_file(fname, script)
- char *fname;
- int script;
-{
- extern VALUE rb_stdin;
- VALUE f;
- int line_start = 1;
-
- if (strcmp(fname, "-") == 0) {
- f = rb_stdin;
- }
- else {
- FILE *fp = fopen(fname, "r");
-
- if (fp == NULL) {
- rb_load_fail(fname);
- }
- fclose(fp);
-
- f = rb_file_open(fname, "r");
-#if defined DOSISH || defined __CYGWIN__
- {
- char *ext = strrchr(fname, '.');
- if (ext && strcasecmp(ext, ".exe") == 0)
- rb_io_binmode(f);
- }
-#endif
- }
-
- if (script) {
- VALUE c = 1; /* something not nil */
- VALUE line;
- char *p;
-
- if (xflag) {
- forbid_setid("-x");
- xflag = Qfalse;
- while (!NIL_P(line = rb_io_gets(f))) {
- line_start++;
- if (RSTRING(line)->len > 2
- && RSTRING(line)->ptr[0] == '#'
- && RSTRING(line)->ptr[1] == '!') {
- if (p = strstr(RSTRING(line)->ptr, "ruby")) {
- goto start_read;
- }
- }
- }
- rb_raise(rb_eLoadError, "No Ruby script found in input");
- }
-
- c = rb_io_getc(f);
- if (c == INT2FIX('#')) {
- line = rb_io_gets(f);
- if (NIL_P(line)) return;
- line_start++;
-
- if (RSTRING(line)->len > 2 && RSTRING(line)->ptr[0] == '!') {
- if ((p = strstr(RSTRING(line)->ptr, "ruby")) == 0) {
- /* not ruby script, kick the program */
- char **argv;
- char *path;
- char *pend = RSTRING(line)->ptr + RSTRING(line)->len;
-
- p = RSTRING(line)->ptr + 1; /* skip `#!' */
- if (pend[-1] == '\n') pend--; /* chomp line */
- if (pend[-1] == '\r') pend--;
- *pend = '\0';
- while (p < pend && ISSPACE(*p))
- p++;
- path = p; /* interpreter path */
- while (p < pend && !ISSPACE(*p))
- p++;
- *p++ = '\0';
- if (p < pend) {
- argv = ALLOCA_N(char*, origargc+3);
- argv[1] = p;
- MEMCPY(argv+2, origargv+1, char*, origargc);
- }
- else {
- argv = origargv;
- }
- argv[0] = path;
- execv(path, argv);
-
- ruby_sourcefile = rb_source_filename(fname);
- ruby_sourceline = 1;
- rb_fatal("Can't exec %s", path);
- }
-
- start_read:
- p += 4;
- RSTRING(line)->ptr[RSTRING(line)->len-1] = '\0';
- if (RSTRING(line)->ptr[RSTRING(line)->len-2] == '\r')
- RSTRING(line)->ptr[RSTRING(line)->len-2] = '\0';
- if (p = strstr(p, " -")) {
- p++; /* skip space before `-' */
- while (*p == '-') {
- p = moreswitches(p+1);
- }
- }
- }
- }
- else if (!NIL_P(c)) {
- rb_io_ungetc(f, c);
- }
- require_libraries(); /* Why here? unnatural */
- if (NIL_P(c)) return;
- }
- rb_compile_file(fname, f, line_start);
- if (script && ruby__end__seen) {
- rb_define_global_const("DATA", f);
- }
- else if (f != rb_stdin) {
- rb_io_close(f);
- }
- rb_gc();
-}
-
-void
-rb_load_file(fname)
- char *fname;
-{
- load_file(fname, 0);
-}
-
-static void
-load_stdin()
-{
- forbid_setid("program input from stdin");
- load_file("-", 1);
-}
-
-VALUE rb_progname;
-VALUE rb_argv;
-VALUE rb_argv0;
-
-static void
-set_arg0(val, id)
- VALUE val;
- ID id;
-{
- char *s;
- int i;
- static int len;
-
- if (origargv == 0) rb_raise(rb_eRuntimeError, "$0 not initialized");
- StringValue(val);
- s = RSTRING(val)->ptr;
- i = RSTRING(val)->len;
-#ifdef __hpux
- if (i >= PST_CLEN) {
- union pstun j;
- j.pst_command = s;
- i = PST_CLEN;
- RSTRING(val)->len = i;
- *(s + i) = '\0';
- pstat(PSTAT_SETCMD, j, PST_CLEN, 0, 0);
- }
- else {
- union pstun j;
- j.pst_command = s;
- pstat(PSTAT_SETCMD, j, i, 0, 0);
- }
- rb_progname = rb_tainted_str_new(s, i);
-#elif defined(HAVE_SETPROCTITLE)
- setproctitle("%.*s", i, s);
- rb_progname = rb_tainted_str_new(s, i);
-#else
- if (len == 0) {
- char *s = origargv[0];
- int i;
-
- s += strlen(s);
- /* See if all the arguments are contiguous in memory */
- for (i = 1; i < origargc; i++) {
- if (origargv[i] == s + 1) {
- s++;
- s += strlen(s); /* this one is ok too */
- }
- else {
- break;
- }
- }
- len = s - origargv[0];
- }
-
- if (i >= len) {
- i = len;
- memcpy(origargv[0], s, i);
- origargv[0][i] = '\0';
- }
- else {
- memcpy(origargv[0], s, i);
- s = origargv[0]+i;
- *s++ = '\0';
- while (++i < len)
- *s++ = ' ';
- for (i = 1; i < origargc; i++)
- origargv[i] = 0;
- }
-#endif
- rb_progname = rb_tainted_str_new2(origargv[0]);
-}
-
-void
-ruby_script(name)
- char *name;
-{
- if (name) {
- rb_progname = rb_tainted_str_new2(name);
- ruby_sourcefile = rb_source_filename(name);
- }
-}
-
-static int uid, euid, gid, egid;
-
-static void
-init_ids()
-{
- uid = (int)getuid();
- euid = (int)geteuid();
- gid = (int)getgid();
- egid = (int)getegid();
-#ifdef VMS
- uid |= gid << 16;
- euid |= egid << 16;
-#endif
- if (uid && (euid != uid || egid != gid)) {
- rb_set_safe_level(1);
- }
-}
-
-static void
-forbid_setid(s)
- const char *s;
-{
- if (euid != uid)
- rb_raise(rb_eSecurityError, "No %s allowed while running setuid", s);
- if (egid != gid)
- rb_raise(rb_eSecurityError, "No %s allowed while running setgid", s);
- if (rb_safe_level() > 0)
- rb_raise(rb_eSecurityError, "No %s allowed in tainted mode", s);
-}
-
-void
-ruby_prog_init()
-{
- init_ids();
-
- ruby_sourcefile = rb_source_filename("ruby");
- rb_define_variable("$VERBOSE", &ruby_verbose);
- rb_define_variable("$-v", &ruby_verbose);
- rb_define_variable("$-w", &ruby_verbose);
- rb_define_variable("$DEBUG", &ruby_debug);
- rb_define_variable("$-d", &ruby_debug);
- rb_define_readonly_variable("$-p", &do_print);
- rb_define_readonly_variable("$-l", &do_line);
-
- rb_define_hooked_variable("$0", &rb_progname, 0, set_arg0);
-
- rb_argv = rb_ary_new();
- rb_define_readonly_variable("$*", &rb_argv);
- rb_define_global_const("ARGV", rb_argv);
- rb_define_readonly_variable("$-a", &do_split);
- rb_global_variable(&rb_argv0);
-
-#ifdef MSDOS
- /*
- * There is no way we can refer to them from ruby, so close them to save
- * space.
- */
- (void)fclose(stdaux);
- (void)fclose(stdprn);
-#endif
-}
-
-void
-ruby_set_argv(argc, argv)
- int argc;
- char **argv;
-{
- int i;
-
-#if defined(USE_DLN_A_OUT)
- if (origargv) dln_argv0 = origargv[0];
- else dln_argv0 = argv[0];
-#endif
- rb_ary_clear(rb_argv);
- for (i=0; i < argc; i++) {
- rb_ary_push(rb_argv, rb_tainted_str_new2(argv[i]));
- }
-}
-
-void
-ruby_process_options(argc, argv)
- int argc;
- char **argv;
-{
- origargc = argc; origargv = argv;
-
- ruby_script(argv[0]); /* for the time being */
- rb_argv0 = rb_progname;
-#if defined(USE_DLN_A_OUT)
- dln_argv0 = argv[0];
-#endif
- proc_options(argc, argv);
-
- if (do_check && ruby_nerrs == 0) {
- printf("Syntax OK\n");
- exit(0);
- }
- if (do_print) {
- rb_parser_append_print();
- }
- if (do_loop) {
- rb_parser_while_loop(do_line, do_split);
- }
-}
diff --git a/ruby.h b/ruby.h
deleted file mode 100644
index 12b373948b..0000000000
--- a/ruby.h
+++ /dev/null
@@ -1,658 +0,0 @@
-/**********************************************************************
-
- ruby.h -
-
- $Author$
- created at: Thu Jun 10 14:26:32 JST 1993
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
- Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
- Copyright (C) 2000 Information-technology Promotion Agency, Japan
-
-**********************************************************************/
-
-#ifndef RUBY_H
-#define RUBY_H
-
-#if defined(__cplusplus)
-extern "C" {
-#endif
-
-#include "config.h"
-#include "defines.h"
-
-#ifdef HAVE_STDLIB_H
-# include <stdlib.h>
-#endif
-
-#ifdef HAVE_STRING_H
-# include <string.h>
-#else
-# include <strings.h>
-#endif
-
-#include <stddef.h>
-#include <stdio.h>
-
-/* need to include <ctype.h> to use these macros */
-#ifndef ISPRINT
-#define ISASCII(c) isascii((unsigned char)(c))
-#undef ISPRINT
-#define ISPRINT(c) (ISASCII(c) && isprint((unsigned char)(c)))
-#define ISSPACE(c) (ISASCII(c) && isspace((unsigned char)(c)))
-#define ISUPPER(c) (ISASCII(c) && isupper((unsigned char)(c)))
-#define ISLOWER(c) (ISASCII(c) && islower((unsigned char)(c)))
-#define ISALNUM(c) (ISASCII(c) && isalnum((unsigned char)(c)))
-#define ISALPHA(c) (ISASCII(c) && isalpha((unsigned char)(c)))
-#define ISDIGIT(c) (ISASCII(c) && isdigit((unsigned char)(c)))
-#define ISXDIGIT(c) (ISASCII(c) && isxdigit((unsigned char)(c)))
-#endif
-
-#ifndef NORETURN
-# define NORETURN(x) x
-#endif
-
-#if defined(HAVE_ALLOCA_H) && !defined(__GNUC__)
-#include <alloca.h>
-#endif
-
-#ifdef _AIX
-#pragma alloca
-#endif
-
-#if SIZEOF_LONG != SIZEOF_VOIDP
----->> ruby requires sizeof(void*) == sizeof(long) to be compiled. <<----
-#endif
-typedef unsigned long VALUE;
-typedef unsigned long ID;
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# ifndef LONG_MAX
-# ifdef HAVE_LIMITS_H
-# include <limits.h>
-# else
- /* assuming 32bit(2's compliment) long */
-# define LONG_MAX 2147483647
-# endif
-# endif
-# ifndef LONG_MIN
-# define LONG_MIN (-LONG_MAX-1)
-# endif
-# ifndef CHAR_BIT
-# define CHAR_BIT 8
-# endif
-#endif
-
-#if HAVE_LONG_LONG
-# ifndef LLONG_MAX
-# ifdef LONG_LONG_MAX
-# define LLONG_MAX LONG_LONG_MAX
-# else
-# ifdef _I64_MAX
-# define LLONG_MAX _I64_MAX
-# else
- /* assuming 64bit(2's complement) long long */
-# define LLONG_MAX 9223372036854775807LL
-# endif
-# endif
-# endif
-# ifndef LLONG_MIN
-# ifdef LONG_LONG_MIN
-# define LLONG_MIN LONG_LONG_MIN
-# else
-# ifdef _I64_MIN
-# define LLONG_MIN _I64_MAX
-# else
-# define LLONG_MIN (-LLONG_MAX-1)
-# endif
-# endif
-# endif
-#endif
-
-#define FIXNUM_MAX (LONG_MAX>>1)
-#define FIXNUM_MIN RSHIFT((long)LONG_MIN,1)
-
-#define FIXNUM_FLAG 0x01
-#define INT2FIX(i) ((VALUE)(((long)(i))<<1 | FIXNUM_FLAG))
-#define LONG2FIX(i) INT2FIX(i)
-#define rb_fix_new(v) INT2FIX(v)
-VALUE rb_int2inum _((long));
-#define INT2NUM(v) rb_int2inum(v)
-#define LONG2NUM(v) INT2NUM(v)
-#define rb_int_new(v) rb_int2inum(v)
-VALUE rb_uint2inum _((unsigned long));
-#define UINT2NUM(v) rb_uint2inum(v)
-#define ULONG2NUM(v) UINT2NUM(v)
-#define rb_uint_new(v) rb_uint2inum(v)
-
-#if HAVE_LONG_LONG
-VALUE rb_ll2inum _((LONG_LONG));
-#define LL2NUM(v) rb_ll2inum(v)
-VALUE rb_ull2inum _((unsigned LONG_LONG));
-#define ULL2NUM(v) rb_ull2inum(v)
-#endif
-
-#if SIZEOF_OFF_T > SIZEOF_LONG && HAVE_LONG_LONG
-# define OFFT2NUM(v) LL2NUM(v)
-#else
-# define OFFT2NUM(v) INT2NUM(v)
-#endif
-
-#define FIX2LONG(x) RSHIFT((long)x,1)
-#define FIX2ULONG(x) (((unsigned long)(x))>>1)
-#define FIXNUM_P(f) (((long)(f))&FIXNUM_FLAG)
-#define POSFIXABLE(f) ((f) <= FIXNUM_MAX)
-#define NEGFIXABLE(f) ((f) >= FIXNUM_MIN)
-#define FIXABLE(f) (POSFIXABLE(f) && NEGFIXABLE(f))
-
-#define IMMEDIATE_MASK 0x03
-#define IMMEDIATE_P(x) ((VALUE)(x) & IMMEDIATE_MASK)
-
-#define SYMBOL_FLAG 0x0e
-#define SYMBOL_P(x) (((VALUE)(x)&0xff)==SYMBOL_FLAG)
-#define ID2SYM(x) ((VALUE)(((long)(x))<<8|SYMBOL_FLAG))
-#define SYM2ID(x) RSHIFT((long)x,8)
-
-/* special contants - i.e. non-zero and non-fixnum constants */
-#define Qfalse 0
-#define Qtrue 2
-#define Qnil 4
-#define Qundef 6 /* undefined value for placeholder */
-
-#define RTEST(v) (((VALUE)(v) & ~Qnil) != 0)
-#define NIL_P(v) ((VALUE)(v) == Qnil)
-
-#define CLASS_OF(v) rb_class_of((VALUE)(v))
-
-#define T_NONE 0x00
-
-#define T_NIL 0x01
-#define T_OBJECT 0x02
-#define T_CLASS 0x03
-#define T_ICLASS 0x04
-#define T_MODULE 0x05
-#define T_FLOAT 0x06
-#define T_STRING 0x07
-#define T_REGEXP 0x08
-#define T_ARRAY 0x09
-#define T_FIXNUM 0x0a
-#define T_HASH 0x0b
-#define T_STRUCT 0x0c
-#define T_BIGNUM 0x0d
-#define T_FILE 0x0e
-
-#define T_TRUE 0x20
-#define T_FALSE 0x21
-#define T_DATA 0x22
-#define T_MATCH 0x23
-#define T_SYMBOL 0x24
-
-#define T_BLKTAG 0x3b
-#define T_UNDEF 0x3c
-#define T_VARMAP 0x3d
-#define T_SCOPE 0x3e
-#define T_NODE 0x3f
-
-#define T_MASK 0x3f
-
-#define BUILTIN_TYPE(x) (((struct RBasic*)(x))->flags & T_MASK)
-
-#define TYPE(x) rb_type((VALUE)(x))
-
-void rb_check_type _((VALUE,int));
-#define Check_Type(v,t) rb_check_type((VALUE)(v),t)
-
-VALUE rb_str_to_str _((VALUE));
-VALUE rb_string_value _((volatile VALUE*));
-
-#define StringValue(v) if (TYPE(v) != T_STRING) rb_string_value(&(v))
-void rb_check_safe_str _((VALUE));
-#define SafeStringValue(v) do {\
- StringValue(v);\
- rb_check_safe_str(v);\
-} while (0)
-#define StringValuePtr(v) RSTRING((TYPE(v) == T_STRING) ? (v) : rb_string_value(&(v)))->ptr
-/* obsolete macro - use SafeStringValue(v) */
-#define Check_SafeStr(v) rb_check_safe_str((VALUE)(v))
-
-void rb_secure _((int));
-EXTERN int ruby_safe_level;
-#define rb_safe_level() (ruby_safe_level)
-void rb_set_safe_level _((int));
-
-long rb_num2long _((VALUE));
-unsigned long rb_num2ulong _((VALUE));
-#define NUM2LONG(x) (FIXNUM_P(x)?FIX2LONG(x):rb_num2long((VALUE)x))
-#define NUM2ULONG(x) rb_num2ulong((VALUE)x)
-#if SIZEOF_INT < SIZEOF_LONG
-int rb_num2int _((VALUE));
-#define NUM2INT(x) (FIXNUM_P(x)?FIX2INT(x):rb_num2int((VALUE)x))
-int rb_fix2int _((VALUE));
-#define FIX2INT(x) rb_fix2int((VALUE)x)
-#define NUM2UINT(x) ((unsigned int)NUM2INT(x))
-#define FIX2UINT(x) ((unsigned int)FIX2INT(x))
-#else
-#define NUM2INT(x) NUM2LONG(x)
-#define NUM2UINT(x) NUM2ULONG(x)
-#define FIX2INT(x) FIX2LONG(x)
-#define FIX2UINT(x) FIX2ULONG(x)
-#endif
-
-#if HAVE_LONG_LONG
-LONG_LONG rb_num2ll _((VALUE));
-unsigned LONG_LONG rb_num2ull _((VALUE));
-# define NUM2LL(x) (FIXNUM_P(x)?FIX2LONG(x):rb_num2ll((VALUE)x))
-#endif
-
-#if HAVE_LONG_LONG && SIZEOF_OFF_T > SIZEOF_LONG
-# define NUM2OFFT(x) ((off_t)NUM2LL(x))
-#else
-# define NUM2OFFT(x) NUM2LONG(x)
-#endif
-
-double rb_num2dbl _((VALUE));
-#define NUM2DBL(x) rb_num2dbl((VALUE)(x))
-
-/* obsolete API - use StringValue() */
-char *rb_str2cstr _((VALUE,int*));
-/* obsolete API - use StringValuePtr() */
-#define STR2CSTR(x) rb_str2cstr((VALUE)(x),0)
-
-#define NUM2CHR(x) (((TYPE(x) == T_STRING)&&(RSTRING(x)->len>=1))?\
- RSTRING(x)->ptr[0]:(char)(NUM2INT(x)&0xff))
-#define CHR2FIX(x) INT2FIX((long)((x)&0xff))
-
-VALUE rb_newobj _((void));
-#define NEWOBJ(obj,type) type *obj = (type*)rb_newobj()
-#define OBJSETUP(obj,c,t) {\
- RBASIC(obj)->flags = (t);\
- RBASIC(obj)->klass = (c);\
- if (rb_safe_level() >= 3) FL_SET(obj, FL_TAINT);\
-}
-#define CLONESETUP(clone,obj) do {\
- OBJSETUP(clone,rb_singleton_class_clone(RBASIC(obj)->klass),RBASIC(obj)->flags);\
- rb_singleton_class_attached(RBASIC(clone)->klass, (VALUE)clone);\
- if (FL_TEST(obj, FL_EXIVAR)) rb_copy_generic_ivar((VALUE)clone,(VALUE)obj);\
-} while (0)
-#define DUPSETUP(dup,obj) do {\
- OBJSETUP(dup,rb_obj_class(obj),(RBASIC(obj)->flags)&(T_MASK|FL_EXIVAR|FL_TAINT));\
- if (FL_TEST(obj, FL_EXIVAR)) rb_copy_generic_ivar((VALUE)dup,(VALUE)obj);\
-} while (0)
-
-struct RBasic {
- unsigned long flags;
- VALUE klass;
-};
-
-struct RObject {
- struct RBasic basic;
- struct st_table *iv_tbl;
-};
-
-struct RClass {
- struct RBasic basic;
- struct st_table *iv_tbl;
- struct st_table *m_tbl;
- VALUE super;
-};
-
-struct RFloat {
- struct RBasic basic;
- double value;
-};
-
-#define ELTS_SHARED FL_USER2
-
-struct RString {
- struct RBasic basic;
- long len;
- char *ptr;
- union {
- int capa;
- VALUE shared;
- } aux;
-};
-
-struct RArray {
- struct RBasic basic;
- long len;
- union {
- int capa;
- VALUE shared;
- } aux;
- VALUE *ptr;
-};
-
-struct RRegexp {
- struct RBasic basic;
- struct re_pattern_buffer *ptr;
- long len;
- char *str;
-};
-
-struct RHash {
- struct RBasic basic;
- struct st_table *tbl;
- int iter_lev;
- VALUE ifnone;
-};
-
-struct RFile {
- struct RBasic basic;
- struct OpenFile *fptr;
-};
-
-struct RData {
- struct RBasic basic;
- void (*dmark) _((void*));
- void (*dfree) _((void*));
- void *data;
-};
-
-#define DATA_PTR(dta) (RDATA(dta)->data)
-
-/*
-#define RUBY_DATA_FUNC(func) ((void (*)_((void*)))func)
-*/
-typedef void (*RUBY_DATA_FUNC) _((void*));
-
-VALUE rb_data_object_alloc _((VALUE,void*,RUBY_DATA_FUNC,RUBY_DATA_FUNC));
-
-#define Data_Wrap_Struct(klass,mark,free,sval) (\
- rb_data_object_alloc(klass,sval,(RUBY_DATA_FUNC)mark,(RUBY_DATA_FUNC)free)\
-)
-
-#define Data_Make_Struct(klass,type,mark,free,sval) (\
- sval = ALLOC(type),\
- memset(sval, 0, sizeof(type)),\
- Data_Wrap_Struct(klass,mark,free,sval)\
-)
-
-#define Data_Get_Struct(obj,type,sval) {\
- Check_Type(obj, T_DATA); \
- sval = (type*)DATA_PTR(obj);\
-}
-
-struct RStruct {
- struct RBasic basic;
- long len;
- VALUE *ptr;
-};
-
-struct RBignum {
- struct RBasic basic;
- char sign;
- long len;
- void *digits;
-};
-
-#define R_CAST(st) (struct st*)
-#define RBASIC(obj) (R_CAST(RBasic)(obj))
-#define ROBJECT(obj) (R_CAST(RObject)(obj))
-#define RCLASS(obj) (R_CAST(RClass)(obj))
-#define RMODULE(obj) RCLASS(obj)
-#define RFLOAT(obj) (R_CAST(RFloat)(obj))
-#define RSTRING(obj) (R_CAST(RString)(obj))
-#define RREGEXP(obj) (R_CAST(RRegexp)(obj))
-#define RARRAY(obj) (R_CAST(RArray)(obj))
-#define RHASH(obj) (R_CAST(RHash)(obj))
-#define RDATA(obj) (R_CAST(RData)(obj))
-#define RSTRUCT(obj) (R_CAST(RStruct)(obj))
-#define RBIGNUM(obj) (R_CAST(RBignum)(obj))
-#define RFILE(obj) (R_CAST(RFile)(obj))
-
-#define FL_SINGLETON FL_USER0
-#define FL_MARK (1<<6)
-#define FL_FINALIZE (1<<7)
-#define FL_TAINT (1<<8)
-#define FL_EXIVAR (1<<9)
-#define FL_FREEZE (1<<10)
-
-#define FL_USHIFT 11
-
-#define FL_USER0 (1<<(FL_USHIFT+0))
-#define FL_USER1 (1<<(FL_USHIFT+1))
-#define FL_USER2 (1<<(FL_USHIFT+2))
-#define FL_USER3 (1<<(FL_USHIFT+3))
-#define FL_USER4 (1<<(FL_USHIFT+4))
-#define FL_USER5 (1<<(FL_USHIFT+5))
-#define FL_USER6 (1<<(FL_USHIFT+6))
-#define FL_USER7 (1<<(FL_USHIFT+7))
-
-#define FL_UMASK (0xff<<FL_USHIFT)
-
-#define SPECIAL_CONST_P(x) (IMMEDIATE_P(x) || !RTEST(x))
-
-#define FL_ABLE(x) (!SPECIAL_CONST_P(x))
-#define FL_TEST(x,f) (FL_ABLE(x)?(RBASIC(x)->flags&(f)):0)
-#define FL_SET(x,f) do {if (FL_ABLE(x)) RBASIC(x)->flags |= (f);} while (0)
-#define FL_UNSET(x,f) do {if (FL_ABLE(x)) RBASIC(x)->flags &= ~(f);} while (0)
-#define FL_REVERSE(x,f) do {if (FL_ABLE(x)) RBASIC(x)->flags ^= (f);} while (0)
-
-#define OBJ_TAINTED(x) FL_TEST((x), FL_TAINT)
-#define OBJ_TAINT(x) FL_SET((x), FL_TAINT)
-#define OBJ_INFECT(x,s) do {if (FL_ABLE(x) && FL_ABLE(s)) RBASIC(x)->flags |= RBASIC(s)->flags & FL_TAINT;} while (0)
-
-#define OBJ_FROZEN(x) FL_TEST((x), FL_FREEZE)
-#define OBJ_FREEZE(x) FL_SET((x), FL_FREEZE)
-
-#define ALLOC_N(type,n) (type*)xmalloc(sizeof(type)*(n))
-#define ALLOC(type) (type*)xmalloc(sizeof(type))
-#define REALLOC_N(var,type,n) (var)=(type*)xrealloc((char*)(var),sizeof(type)*(n))
-
-#define ALLOCA_N(type,n) (type*)alloca(sizeof(type)*(n))
-
-#define MEMZERO(p,type,n) memset((p), 0, sizeof(type)*(n))
-#define MEMCPY(p1,p2,type,n) memcpy((p1), (p2), sizeof(type)*(n))
-#define MEMMOVE(p1,p2,type,n) memmove((p1), (p2), sizeof(type)*(n))
-#define MEMCMP(p1,p2,type,n) memcmp((p1), (p2), sizeof(type)*(n))
-
-void rb_glob _((char*,void(*)(const char*,VALUE),VALUE));
-void rb_globi _((char*,void(*)(const char*,VALUE),VALUE));
-
-VALUE rb_define_class _((const char*,VALUE));
-VALUE rb_define_module _((const char*));
-VALUE rb_define_class_under _((VALUE, const char*, VALUE));
-VALUE rb_define_module_under _((VALUE, const char*));
-
-void rb_include_module _((VALUE,VALUE));
-void rb_extend_object _((VALUE,VALUE));
-
-void rb_define_variable _((const char*,VALUE*));
-void rb_define_virtual_variable _((const char*,VALUE(*)(ANYARGS),void(*)(ANYARGS)));
-void rb_define_hooked_variable _((const char*,VALUE*,VALUE(*)(ANYARGS),void(*)(ANYARGS)));
-void rb_define_readonly_variable _((const char*,VALUE*));
-void rb_define_const _((VALUE,const char*,VALUE));
-void rb_define_global_const _((const char*,VALUE));
-
-#define RUBY_METHOD_FUNC(func) ((VALUE (*)(ANYARGS))func)
-void rb_define_method _((VALUE,const char*,VALUE(*)(ANYARGS),int));
-void rb_define_module_function _((VALUE,const char*,VALUE(*)(ANYARGS),int));
-void rb_define_global_function _((const char*,VALUE(*)(ANYARGS),int));
-
-void rb_undef_method _((VALUE,const char*));
-void rb_define_alias _((VALUE,const char*,const char*));
-void rb_define_attr _((VALUE,const char*,int,int));
-
-void rb_global_variable _((VALUE*));
-void rb_gc_register_address _((VALUE*));
-void rb_gc_unregister_address _((VALUE*));
-
-ID rb_intern _((const char*));
-char *rb_id2name _((ID));
-ID rb_to_id _((VALUE));
-
-char *rb_class2name _((VALUE));
-
-void rb_p _((VALUE));
-
-VALUE rb_eval_string _((const char*));
-VALUE rb_eval_string_protect _((const char*, int*));
-VALUE rb_eval_string_wrap _((const char*, int*));
-VALUE rb_funcall __((VALUE, ID, int, ...));
-VALUE rb_funcall2 _((VALUE, ID, int, VALUE*));
-VALUE rb_funcall3 _((VALUE, ID, int, VALUE*));
-int rb_scan_args __((int, VALUE*, const char*, ...));
-VALUE rb_call_super _((int, VALUE*));
-
-VALUE rb_gv_set _((const char*, VALUE));
-VALUE rb_gv_get _((const char*));
-VALUE rb_iv_get _((VALUE, const char*));
-VALUE rb_iv_set _((VALUE, const char*, VALUE));
-
-VALUE rb_equal _((VALUE,VALUE));
-
-EXTERN VALUE ruby_verbose, ruby_debug;
-
-NORETURN(void rb_raise __((VALUE, const char*, ...)));
-NORETURN(void rb_fatal __((const char*, ...)));
-NORETURN(void rb_bug __((const char*, ...)));
-NORETURN(void rb_sys_fail _((const char*)));
-NORETURN(void rb_iter_break _((void)));
-NORETURN(void rb_exit _((int)));
-NORETURN(void rb_notimplement _((void)));
-
-void rb_warning __((const char*, ...)); /* reports if `-w' specified */
-void rb_sys_warning __((const char*, ...)); /* reports if `-w' specified */
-void rb_warn __((const char*, ...)); /* reports always */
-
-VALUE rb_each _((VALUE));
-VALUE rb_yield _((VALUE));
-int rb_block_given_p _((void));
-VALUE rb_iterate _((VALUE(*)(VALUE),VALUE,VALUE(*)(ANYARGS),VALUE));
-VALUE rb_rescue _((VALUE(*)(ANYARGS),VALUE,VALUE(*)(ANYARGS),VALUE));
-VALUE rb_rescue2 __((VALUE(*)(ANYARGS),VALUE,VALUE(*)(ANYARGS),VALUE,...));
-VALUE rb_ensure _((VALUE(*)(ANYARGS),VALUE,VALUE(*)(ANYARGS),VALUE));
-VALUE rb_catch _((const char*,VALUE(*)(ANYARGS),VALUE));
-NORETURN(void rb_throw _((const char*,VALUE)));
-
-VALUE rb_require _((const char*));
-
-void ruby_init _((void));
-void ruby_options _((int, char**));
-void ruby_run _((void));
-
-EXTERN VALUE rb_mKernel;
-EXTERN VALUE rb_mComparable;
-EXTERN VALUE rb_mEnumerable;
-EXTERN VALUE rb_mPrecision;
-EXTERN VALUE rb_mErrno;
-EXTERN VALUE rb_mFileTest;
-EXTERN VALUE rb_mGC;
-EXTERN VALUE rb_mMath;
-EXTERN VALUE rb_mProcess;
-
-EXTERN VALUE rb_cObject;
-EXTERN VALUE rb_cArray;
-EXTERN VALUE rb_cBignum;
-EXTERN VALUE rb_cClass;
-EXTERN VALUE rb_cDir;
-EXTERN VALUE rb_cData;
-EXTERN VALUE rb_cFalseClass;
-EXTERN VALUE rb_cFile;
-EXTERN VALUE rb_cFixnum;
-EXTERN VALUE rb_cFloat;
-EXTERN VALUE rb_cHash;
-EXTERN VALUE rb_cInteger;
-EXTERN VALUE rb_cIO;
-EXTERN VALUE rb_cModule;
-EXTERN VALUE rb_cNilClass;
-EXTERN VALUE rb_cNumeric;
-EXTERN VALUE rb_cProc;
-EXTERN VALUE rb_cRange;
-EXTERN VALUE rb_cRegexp;
-EXTERN VALUE rb_cString;
-EXTERN VALUE rb_cSymbol;
-EXTERN VALUE rb_cThread;
-EXTERN VALUE rb_cTime;
-EXTERN VALUE rb_cTrueClass;
-EXTERN VALUE rb_cStruct;
-
-EXTERN VALUE rb_eException;
-EXTERN VALUE rb_eStandardError;
-EXTERN VALUE rb_eSystemExit;
-EXTERN VALUE rb_eInterrupt;
-EXTERN VALUE rb_eSignal;
-EXTERN VALUE rb_eFatal;
-EXTERN VALUE rb_eArgError;
-EXTERN VALUE rb_eEOFError;
-EXTERN VALUE rb_eIndexError;
-EXTERN VALUE rb_eRangeError;
-EXTERN VALUE rb_eIOError;
-EXTERN VALUE rb_eRuntimeError;
-EXTERN VALUE rb_eSecurityError;
-EXTERN VALUE rb_eSystemCallError;
-EXTERN VALUE rb_eTypeError;
-EXTERN VALUE rb_eZeroDivError;
-EXTERN VALUE rb_eNotImpError;
-EXTERN VALUE rb_eNoMemError;
-EXTERN VALUE rb_eNoMethodError;
-EXTERN VALUE rb_eFloatDomainError;
-
-EXTERN VALUE rb_eScriptError;
-EXTERN VALUE rb_eNameError;
-EXTERN VALUE rb_eSyntaxError;
-EXTERN VALUE rb_eLoadError;
-
-EXTERN VALUE rb_defout, rb_stdin, rb_stdout, rb_stderr, ruby_errinfo;
-
-static inline VALUE
-#if defined(HAVE_PROTOTYPES)
-rb_class_of(VALUE obj)
-#else
-rb_class_of(obj)
- VALUE obj;
-#endif
-{
- if (FIXNUM_P(obj)) return rb_cFixnum;
- if (obj == Qnil) return rb_cNilClass;
- if (obj == Qfalse) return rb_cFalseClass;
- if (obj == Qtrue) return rb_cTrueClass;
- if (SYMBOL_P(obj)) return rb_cSymbol;
-
- return RBASIC(obj)->klass;
-}
-
-static inline int
-#if defined(HAVE_PROTOTYPES)
-rb_type(VALUE obj)
-#else
-rb_type(obj)
- VALUE obj;
-#endif
-{
- if (FIXNUM_P(obj)) return T_FIXNUM;
- if (obj == Qnil) return T_NIL;
- if (obj == Qfalse) return T_FALSE;
- if (obj == Qtrue) return T_TRUE;
- if (obj == Qundef) return T_UNDEF;
- if (SYMBOL_P(obj)) return T_SYMBOL;
- return BUILTIN_TYPE(obj);
-}
-
-static inline int
-#if defined(HAVE_PROTOTYPES)
-rb_special_const_p(VALUE obj)
-#else
-rb_special_const_p(obj)
- VALUE obj;
-#endif
-{
- if (SPECIAL_CONST_P(obj)) return Qtrue;
- return Qfalse;
-}
-
-#include "intern.h"
-
-#if defined(EXTLIB) && defined(USE_DLN_A_OUT)
-/* hook for external modules */
-static char *dln_libs_to_be_linked[] = { EXTLIB, 0 };
-#endif
-
-#if defined(__cplusplus)
-} /* extern "C" { */
-#endif
-
-#endif /* ifndef RUBY_H */
diff --git a/rubyio.h b/rubyio.h
deleted file mode 100644
index 214128449f..0000000000
--- a/rubyio.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/**********************************************************************
-
- rubyio.h -
-
- $Author$
- $Date$
- created at: Fri Nov 12 16:47:09 JST 1993
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
-
-**********************************************************************/
-
-#ifndef RUBYIO_H
-#define RUBYIO_H
-
-#include <stdio.h>
-#include <errno.h>
-
-typedef struct OpenFile {
- FILE *f; /* stdio ptr for read/write */
- FILE *f2; /* additional ptr for rw pipes */
- int mode; /* mode flags */
- int pid; /* child's pid (for pipes) */
- int lineno; /* number of lines read */
- char *path; /* pathname for file */
- void (*finalize) _((struct OpenFile*)); /* finalize proc */
-} OpenFile;
-
-#define FMODE_READABLE 1
-#define FMODE_WRITABLE 2
-#define FMODE_READWRITE 3
-#define FMODE_BINMODE 4
-#define FMODE_SYNC 8
-#define FMODE_WBUF 16
-
-#define GetOpenFile(obj,fp) rb_io_check_closed((fp) = RFILE(rb_io_taint_check(obj))->fptr)
-
-#define MakeOpenFile(obj, fp) do {\
- if (RFILE(obj)->fptr) {\
- rb_io_close(obj);\
- free(RFILE(obj)->fptr);\
- RFILE(obj)->fptr = 0;\
- }\
- fp = 0;\
- fp = RFILE(obj)->fptr = ALLOC(OpenFile);\
- fp->f = fp->f2 = NULL;\
- fp->mode = 0;\
- fp->pid = 0;\
- fp->lineno = 0;\
- fp->path = NULL;\
- fp->finalize = 0;\
-} while (0)
-
-#define GetReadFile(fptr) ((fptr)->f)
-#define GetWriteFile(fptr) (((fptr)->f2) ? (fptr)->f2 : (fptr)->f)
-
-FILE *rb_fopen _((const char*, const char*));
-FILE *rb_fdopen _((int, const char*));
-int rb_getc _((FILE*));
-int rb_io_mode_flags _((const char*));
-void rb_io_check_writable _((OpenFile*));
-void rb_io_check_readable _((OpenFile*));
-void rb_io_fptr_finalize _((OpenFile*));
-void rb_io_synchronized _((OpenFile*));
-void rb_io_check_closed _((OpenFile*));
-
-VALUE rb_io_taint_check _((VALUE));
-void rb_eof_error _((void));
-
-void rb_read_check _((FILE*));
-int rb_read_pending _((FILE*));
-#endif
diff --git a/rubysig.h b/rubysig.h
deleted file mode 100644
index 7b8e71a62e..0000000000
--- a/rubysig.h
+++ /dev/null
@@ -1,90 +0,0 @@
-/**********************************************************************
-
- rubysig.h -
-
- $Author$
- $Date$
- created at: Wed Aug 16 01:15:38 JST 1995
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
-
-**********************************************************************/
-
-#ifndef SIG_H
-#define SIG_H
-
-#ifdef NT
-typedef LONG rb_atomic_t;
-
-# define ATOMIC_TEST(var) InterlockedExchange(&(var), 0)
-# define ATOMIC_SET(var, val) InterlockedExchange(&(var), (val))
-# define ATOMIC_INC(var) InterlockedIncrement(&(var))
-# define ATOMIC_DEC(var) InterlockedDecrement(&(var))
-
-/* Windows doesn't allow interrupt while system calls */
-# define TRAP_BEG do {\
- rb_atomic_t trap_immediate = ATOMIC_SET(rb_trap_immediate, 1);
-# define TRAP_END ATOMIC_SET(rb_trap_immediate, trap_immediate);\
-} while (0)
-# define RUBY_CRITICAL(statements) do {\
- win32_enter_critical();\
- statements;\
- win32_leave_critical();\
-} while (0)
-#else
-typedef int rb_atomic_t;
-
-# define ATOMIC_TEST(var) ((var) ? ((var) = 0, 1) : 0)
-# define ATOMIC_SET(var, val) ((var) = (val))
-# define ATOMIC_INC(var) (++(var))
-# define ATOMIC_DEC(var) (--(var))
-
-# define TRAP_BEG do {\
- int trap_immediate = rb_trap_immediate;\
- rb_trap_immediate = 1;
-# define TRAP_END rb_trap_immediate = trap_immediate;\
-} while (0)
-
-# define RUBY_CRITICAL(statements) do {\
- int trap_immediate = rb_trap_immediate;\
- rb_trap_immediate = 0;\
- statements;\
- rb_trap_immediate = trap_immediate;\
-} while (0)
-#endif
-EXTERN rb_atomic_t rb_trap_immediate;
-
-EXTERN int rb_prohibit_interrupt;
-#define DEFER_INTS {rb_prohibit_interrupt++;}
-#define ALLOW_INTS {rb_prohibit_interrupt--; CHECK_INTS;}
-#define ENABLE_INTS {rb_prohibit_interrupt--;}
-
-VALUE rb_with_disable_interrupt _((VALUE(*)(ANYARGS),VALUE));
-
-EXTERN rb_atomic_t rb_trap_pending;
-void rb_trap_restore_mask _((void));
-
-EXTERN int rb_thread_critical;
-void rb_thread_schedule _((void));
-#if defined(HAVE_SETITIMER) && !defined(__BOW__)
-EXTERN int rb_thread_pending;
-# define CHECK_INTS if (!rb_prohibit_interrupt) {\
- if (rb_trap_pending) rb_trap_exec();\
- if (rb_thread_pending && !rb_thread_critical) rb_thread_schedule();\
-}
-#else
-/* pseudo preemptive thread switching */
-EXTERN int rb_thread_tick;
-#define THREAD_TICK 500
-#define CHECK_INTS if (!rb_prohibit_interrupt) {\
- if (rb_trap_pending) rb_trap_exec();\
- if (!rb_thread_critical) {\
- if (rb_thread_tick-- <= 0) {\
- rb_thread_tick = THREAD_TICK;\
- rb_thread_schedule();\
- }\
- }\
-}
-#endif
-
-#endif
diff --git a/rubytest.rb b/rubytest.rb
deleted file mode 100644
index 05705dacf5..0000000000
--- a/rubytest.rb
+++ /dev/null
@@ -1,44 +0,0 @@
-#! ./miniruby
-
-load './rbconfig.rb'
-include Config
-
-unless File.exist? "./#{CONFIG['ruby_install_name']}#{CONFIG['EXEEXT']}"
- print "./#{CONFIG['ruby_install_name']} is not found.\n"
- print "Try `make' first, then `make test', please.\n"
- exit 1
-end
-
-if File.exist? CONFIG['LIBRUBY_SO']
- case RUBY_PLATFORM
- when /-hpux/
- dldpath = "SHLIB_PATH"
- when /-aix/
- dldpath = "LIBPATH"
- when /-beos/
- dldpath = "LIBRARY_PATH"
- else
- dldpath = "LD_LIBRARY_PATH"
- end
- x = ENV[dldpath]
- x = x ? ".:"+x : "."
- ENV[dldpath] = x
-end
-
-if /linux/ =~ RUBY_PLATFORM and File.exist? CONFIG['LIBRUBY_SO']
- ENV["LD_PRELOAD"] = "./#{CONFIG['LIBRUBY_SO']}"
-end
-
-$stderr.reopen($stdout)
-error = ''
-
-`./#{CONFIG["ruby_install_name"]}#{CONFIG["EXEEXT"]} #{CONFIG["srcdir"]}/sample/test.rb`.each do |line|
- if line =~ /^end of test/
- print "test succeeded\n"
- exit 0
- end
- error << line if line =~ %r:^(sample/test.rb|not):
-end
-print error
-print "test failed\n"
-exit 1
diff --git a/sample/README b/sample/README
deleted file mode 100644
index 82db05eec9..0000000000
--- a/sample/README
+++ /dev/null
@@ -1,52 +0,0 @@
-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
-dualstack-fetch.rb IPv6 demo
-dualstack-httpd.rb IPv6 demo
-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.
-io.rb io test
-irb.rb interactive ruby
-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
-rcs.awk random character stereogram (AWK)
-rcs.rb random character stereogram (Ruby)
-rcs.dat data for random character stereogram
-rd2html.rb rd (Ruby Document) to HTML translator
-regx.rb regular expression tester
-sieve.rb sieve of Eratosthenes
-svr.rb socket server
-test.rb test suite used by `make test'
-time.rb /usr/bin/time clone
-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/biorhythm.rb b/sample/biorhythm.rb
deleted file mode 100644
index a139eed6c0..0000000000
--- a/sample/biorhythm.rb
+++ /dev/null
@@ -1,161 +0,0 @@
-#!/usr/local/bin/ruby
-#
-# biorhythm.rb -
-# $Release Version: $
-# $Revision$
-# $Date$
-# by Yasuo OHBA(STAFS Development Room)
-#
-# --
-#
-#
-#
-
-# probably based on:
-#
-# Newsgroups: comp.sources.misc,de.comp.sources.os9
-# From: fkk@stasys.sta.sub.org (Frank Kaefer)
-# Subject: v41i126: br - Biorhythm v3.0, Part01/01
-# Message-ID: <1994Feb1.070616.15982@sparky.sterling.com>
-# Sender: kent@sparky.sterling.com (Kent Landfield)
-# Organization: Sterling Software
-# Date: Tue, 1 Feb 1994 07:06:16 GMT
-#
-# Posting-number: Volume 41, Issue 126
-# Archive-name: br/part01
-# Environment: basic, dos, os9
-
-include Math
-require "date.rb"
-require "parsearg.rb"
-require "parsedate.rb"
-
-def usage()
- print "Usage:\n"
- print "biorhythm.rb [options]\n"
- print " options...\n"
- print " -D YYYYMMDD(birthday) : use default values.\n"
- print " --sdate | --date YYYYMMDD : use system date; use specified date.\n"
- print " --birthday YYYYMMDD : specifies your birthday.\n"
- print " -v | -g : show values or graph.\n"
- print " --days DAYS : graph range (only in effect for graphs).\n"
- print " --help : help\n"
-end
-$USAGE = 'usage'
-
-def printHeader(y, m, d, p, w)
- print "\n>>> Biorhythm <<<\n"
- printf "The birthday %04d.%02d.%02d is a %s\n", y, m, d, w
- printf "Age in days: [%d]\n\n", p
-end
-
-def getPosition(z)
- pi = Math::PI
- phys = (50.0 * (1.0 + sin((z / 23.0 - (z / 23)) * 360.0 * pi / 180.0))).to_i
- emot = (50.0 * (1.0 + sin((z / 28.0 - (z / 28)) * 360.0 * pi / 180.0))).to_i
- geist =(50.0 * (1.0 + sin((z / 33.0 - (z / 33)) * 360.0 * pi / 180.0))).to_i
- return phys, emot, geist
-end
-
-def parsedate(s)
- ParseDate::parsedate(s).indexes(0, 1, 2)
-end
-
-def name_of_week(date)
- Date::DAYNAMES[date.wday]
-end
-
-#
-# main program
-#
-parseArgs(0, nil, "vg", "D:", "sdate", "date:", "birthday:", "days:")
-
-if $OPT_D
- dd = Date.today
- bd = Date.new(*parsedate($OPT_D))
- ausgabeart = "g"
-else
- if $OPT_birthday
- bd = Date.new(*parsedate($OPT_birthday))
- else
- printf(STDERR, "Birthday (YYYYMMDD) : ")
- if (si = STDIN.gets.chop) != ""
- bd = Date.new(*parsedate(si))
- end
- end
- if !bd
- printf STDERR, "BAD Input Birthday!!\n"
- exit()
- end
-
- if $OPT_sdate
- dd = Date.today
- elsif $OPT_date
- dd = Date.new(*parsedate($OPT_date))
- else
- printf(STDERR, "Date [<RETURN> for Systemdate] (YYYYMMDD) : ")
- if (si = STDIN.gets.chop) != ""
- dd = Date.new(*parsedate(si))
- end
- end
- if !dd
- dd = Date.today
- end
-
- if $OPT_v
- ausgabeart = "v"
- elsif $OPT_g
- ausgabeart = "g"
- else
- printf(STDERR, "Values for today or Graph (v/g) [default g] : ")
- ausgabeart = STDIN.gets.chop
- end
-end
-if (ausgabeart == "v")
- printHeader(bd.year, bd.month, bd.day, dd - bd, name_of_week(bd))
- print "\n"
-
- phys, emot, geist = getPosition(dd - bd)
- printf "Biorhythm: %04d.%02d.%02d\n", dd.year, dd.month, dd.day
- printf "Physical: %d%%\n", phys
- printf "Emotional: %d%%\n", emot
- printf "Mental: %d%%\n", geist
- print "\n"
-else
- if $OPT_days
- display_period = $OPT_days.to_i
- elsif $OPT_D
- display_period = 9
- else
- printf(STDERR, "Graph for how many days [default 10] : ")
- display_period = STDIN.gets.chop
- if (display_period == "")
- display_period = 9
- else
- display_period = display_period.to_i - 1
- end
- end
-
- printHeader(bd.year, bd.month, bd.day, dd - bd, name_of_week(bd))
- print " P=physical, E=emotional, M=mental\n"
- print " -------------------------+-------------------------\n"
- print " Bad Condition | Good Condition\n"
- print " -------------------------+-------------------------\n"
-
- for z in (dd - bd)..(dd - bd + display_period)
- phys, emot, geist = getPosition(z)
-
- printf "%04d.%02d.%02d : ", dd.year, dd.month, dd.day
- p = (phys / 2.0 + 0.5).to_i
- e = (emot / 2.0 + 0.5).to_i
- g = (geist / 2.0 + 0.5).to_i
- graph = "." * 51
- graph[25] = ?|
- graph[p] = ?P
- graph[e] = ?E
- graph[g] = ?M
- print graph, "\n"
- dd = dd + 1
- end
- print " -------------------------+-------------------------\n\n"
-end
diff --git a/sample/cal.rb b/sample/cal.rb
deleted file mode 100644
index 4e0d416f06..0000000000
--- a/sample/cal.rb
+++ /dev/null
@@ -1,111 +0,0 @@
-#! /usr/bin/env ruby
-
-# cal.rb: Written by Tadayoshi Funaba 1998-2000
-# $Id: cal.rb,v 1.11 2000-07-16 10:28:50+09 tadf Exp $
-
-require 'date2'
-require 'getopts'
-
-$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] [-jmty] [[month] year]'
- exit 1
-end
-
-def pict(y, m, sg)
- d = (1..31).detect{|d| Date.exist?(y, m, d, sg)}
- fi = Date.new(y, m, d, sg)
- fi -= (fi.jd - $k + 1) % 7
-
- ve = (fi..fi + 6).collect{|cu|
- %w(S M Tu W Th F S)[cu.wday]
- }
- ve += (fi..fi + 41).collect{|cu|
- if cu.mon == m then cu.send($da) end.to_s
- }
-
- ve = ve.collect{|e| e.rjust($dw)}
-
- gr = group(ve, 7)
- gr = trans(gr) if $OPT_t
- ta = gr.collect{|xs| xs.join(' ')}
-
- ca = %w(January February March April May June July
- August September October November December)[m - 1]
- ca = ca + ' ' + y.to_s if not $OPT_y
- ca = ca.center($mw)
-
- ta.unshift(ca)
-end
-
-def group(xs, n)
- (0..xs.size / n - 1).collect{|i| xs[i * n, n]}
-end
-
-def trans(xs)
- (0..xs[0].size - 1).collect{|i| xs.collect{|x| x[i]}}
-end
-
-def unite(xs)
- if xs.empty? then [] else xs[0] + unite(xs[1..-1]) end
-end
-
-def block(xs, n)
- unite(group(xs, n).collect{|ys| trans(ys).collect{|zs| zs.join(' ')}})
-end
-
-def unlines(xs)
- xs.collect{|x| x + "\n"}.join
-end
-
-usage unless getopts('jmty', "c:#{$cc}")
-
-y, m = ARGV.indexes(1, 0).compact.collect{|x| x.to_i}
-$OPT_y ||= (y and not m)
-
-to = Date.today
-y ||= to.year
-m ||= to.mon
-
-usage unless m >= 1 and m <= 12
-usage unless y >= -4712
-usage unless sg = $tab[$OPT_c]
-
-$dw = if $OPT_j then 3 else 2 end
-$mw = ($dw + 1) * 7 - 1
-$mn = if $OPT_j then 2 else 3 end
-$tw = ($mw + 2) * $mn - 2
-
-$k = if $OPT_m then 1 else 0 end
-$da = if $OPT_j then :yday else :mday end
-
-print (if not $OPT_y
- unlines(pict(y, m, sg))
- else
- y.to_s.center($tw) + "\n\n" +
- unlines(block((1..12).collect{|m| pict(y, m, sg)}, $mn)) + "\n"
- end)
diff --git a/sample/cbreak.rb b/sample/cbreak.rb
deleted file mode 100644
index cbb15d2f41..0000000000
--- a/sample/cbreak.rb
+++ /dev/null
@@ -1,36 +0,0 @@
-# ioctl example works on Sun
-
-CBREAK = 0x00000002
-ECHO = 0x00000008
-TIOCGETP = 0x40067408
-TIOCSETP = 0x80067409
-
-def cbreak ()
- set_cbreak(TRUE)
-end
-
-def cooked ()
- set_cbreak(FALSE)
-end
-
-def set_cbreak (on)
- tty = "\0" * 256
- STDIN.ioctl(TIOCGETP, tty)
- ttys = tty.unpack("C4 S")
- if on
- ttys[4] |= CBREAK
- ttys[4] &= ~ECHO
- else
- ttys[4] &= ~CBREAK
- ttys[4] |= ECHO
- end
- tty = ttys.pack("C4 S")
- STDIN.ioctl(TIOCSETP, tty)
-end
-cbreak();
-
-print("this is no-echo line: ");
-readline().print
-cooked();
-print("this is echo line: ");
-readline()
diff --git a/sample/clnt.rb b/sample/clnt.rb
deleted file mode 100644
index 7998379aa2..0000000000
--- a/sample/clnt.rb
+++ /dev/null
@@ -1,17 +0,0 @@
-# socket example - client side
-# usage: ruby clnt.rb [host] port
-
-require "socket"
-
-host=(if ARGV.length == 2; ARGV.shift; else "localhost"; end)
-print("Trying ", host, " ...")
-STDOUT.flush
-s = TCPsocket.open(host, ARGV.shift)
-print(" done\n")
-print("addr: ", s.addr.join(":"), "\n")
-print("peer: ", s.peeraddr.join(":"), "\n")
-while gets()
- s.write($_)
- print(s.readline)
-end
-s.close
diff --git a/sample/dbmtest.rb b/sample/dbmtest.rb
deleted file mode 100644
index c77cc2065b..0000000000
--- a/sample/dbmtest.rb
+++ /dev/null
@@ -1,14 +0,0 @@
-# ruby dbm acess
-require "dbm"
-
-d = DBM.open("test")
-keys = d.keys
-if keys.length > 0 then
- for k in keys; print k, "\n"; end
- for v in d.values; print v, "\n"; end
-else
- d['foobar'] = 'FB'
- d['baz'] = 'BZ'
- d['quux'] = 'QX'
-end
-
diff --git a/sample/dir.rb b/sample/dir.rb
deleted file mode 100644
index 2465c4d68e..0000000000
--- a/sample/dir.rb
+++ /dev/null
@@ -1,10 +0,0 @@
-# directory access
-# list all files but .*/*~/*.o
-dirp = Dir.open(".")
-for f in dirp
- $_ = f
- unless (~/^\./ || ~/~$/ || ~/\.o/)
- print f, "\n"
- end
-end
-dirp.close
diff --git a/sample/dualstack-fetch.rb b/sample/dualstack-fetch.rb
deleted file mode 100644
index ab8d0914f2..0000000000
--- a/sample/dualstack-fetch.rb
+++ /dev/null
@@ -1,48 +0,0 @@
-# simple webpage fetcher
-
-# The code demonstrates how a multi-protocol client should be written.
-# TCPsocket is using getaddrinfo() internally, so there should be no problem.
-
-require "socket"
-
-if ARGV.size != 1
- STDERR.print "requires URL\n"
- exit
-end
-
-url = ARGV[0]
-if url !~ /^http:\/\/([^\/]+)(\/.*)$/
- STDERR.print "only http with full hostname is supported\n"
- exit
-end
-
-# split URL into host, port and path
-hostport = $1
-path = $2
-if (hostport =~ /^(.*):([0-9]+)$/)
- host = $1
- port = $2
-else
- host = hostport
- port = 80
-end
-if host =~ /^\[(.*)\]$/
- host = $1
-end
-
-#STDERR.print "url=<#{ARGV[0]}>\n"
-#STDERR.print "host=<#{host}>\n"
-#STDERR.print "port=<#{port}>\n"
-#STDERR.print "path=<#{path}>\n"
-
-STDERR.print "conntecting to #{host} port #{port}\n"
-c = TCPsocket.new(host, port)
-dest = Socket.getnameinfo(c.getpeername,
- Socket::NI_NUMERICHOST|Socket::NI_NUMERICSERV)
-STDERR.print "conntected to #{dest[0]} port #{dest[1]}\n"
-c.print "GET #{path} HTTP/1.0\n"
-c.print "Host: #{host}\n"
-c.print "\n"
-while c.gets
- print
-end
diff --git a/sample/dualstack-httpd.rb b/sample/dualstack-httpd.rb
deleted file mode 100644
index 893b29feba..0000000000
--- a/sample/dualstack-httpd.rb
+++ /dev/null
@@ -1,55 +0,0 @@
-# simple httpd
-
-# The code demonstrates how a multi-protocol daemon should be written.
-
-require "socket"
-require "thread"
-
-port = 8888
-res = Socket.getaddrinfo(nil, port, nil, Socket::SOCK_STREAM, nil, Socket::AI_PASSIVE)
-sockpool = []
-names = []
-threads = []
-
-res.each do |i|
- s = TCPserver.new(i[3], i[1])
- n = Socket.getnameinfo(s.getsockname, Socket::NI_NUMERICHOST|Socket::NI_NUMERICSERV).join(" port ")
- sockpool.push s
- names.push n
-end
-
-(0 .. sockpool.size - 1).each do |i|
- mysock = sockpool[i]
- myname = names[i]
- STDERR.print "socket #{mysock} started, address #{myname}\n"
- threads[i] = Thread.start do # Thread.start cannot be used here!
- ls = mysock # copy to dynamic variable
- t = Thread.current
- STDERR.print "socket #{myname} listener started, pid #{$$} thread #{t}\n"
- while TRUE
- as = ls.accept
- Thread.start do
- STDERR.print "socket #{myname} accepted, thread ", Thread.current, "\n"
- s = as # copy to dynamic variable
- str = ''
- while line = s.gets
- break if line == "\r\n" or line == "\n"
- str << line
- end
- STDERR.print "socket #{myname} got string\n"
- s.write("HTTP/1.0 200 OK\n")
- s.write("Content-type: text/plain\n\n")
- s.write("this is test: my name is #{myname}, you sent:\n")
- s.write("---start\n")
- s.write(str)
- s.write("---end\n")
- s.close
- STDERR.print "socket #{myname} processed, thread ", Thread.current, " terminating\n"
- end
- end
- end
-end
-
-for t in threads
- t.join
-end
diff --git a/sample/eval.rb b/sample/eval.rb
deleted file mode 100644
index 8b582b0fdc..0000000000
--- a/sample/eval.rb
+++ /dev/null
@@ -1,42 +0,0 @@
-line = ''
-indent=0
-$stdout.sync = TRUE
-print "ruby> "
-while TRUE
- l = gets
- unless l
- break if line == ''
- else
- line = line + l
- if l =~ /,\s*$/
- print "ruby| "
- next
- end
- if l =~ /^\s*(class|module|def|if|unless|case|while|until|for|begin)\b[^_]/
- indent += 1
- end
- if l =~ /^\s*end\b[^_]/
- indent -= 1
- end
- if l =~ /\{\s*(\|.*\|)?\s*$/
- indent += 1
- end
- if l =~ /^\s*\}/
- indent -= 1
- end
- if indent > 0
- print "ruby| "
- next
- end
- end
- begin
- print eval(line).inspect, "\n"
- rescue ScriptError, StandardError
- $! = 'exception raised' unless $!
- print "ERR: ", $!, "\n"
- end
- break if not l
- line = ''
- print "ruby> "
-end
-print "\n"
diff --git a/sample/export.rb b/sample/export.rb
deleted file mode 100644
index 949e5b10bf..0000000000
--- a/sample/export.rb
+++ /dev/null
@@ -1,40 +0,0 @@
-# method access permission
-# output:
-# foobar
-# Foo
-
-class Foo
- public :printf
- def baz
- print "baz\n"
- end
- private :baz
-
- def quux
- print "in QUUX "
- baz()
- end
-end
-
-def foobar
- print "foobar\n"
-end
-
-f = Foo.new
-#Foo.private :printf
-class Foo # redefines foobar's scope
- public :foobar
-end
-f.foobar
-f.printf "%s\n", Foo
-
-f.quux
-
-class Bar<Foo
- def quux
- super
- baz()
- end
-end
-
-Bar.new.quux
diff --git a/sample/exyacc.rb b/sample/exyacc.rb
deleted file mode 100644
index 908ba6c501..0000000000
--- a/sample/exyacc.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-#! /usr/local/bin/ruby -Kn
-# usage: exyacc.rb [yaccfiles]
-# this is coverted from exyacc.pl in the camel book
-
-$/ = nil
-
-while gets()
- sbeg = $_.index("\n%%") + 1
- send = $_.rindex("\n%%") + 1
- $_ = $_[sbeg, send-sbeg]
- sub!(/.*\n/, "")
- gsub!(/'\{'/, "'\001'")
- gsub!(/'}'/, "'\002'")
- gsub!('\*/', "\003\003")
- gsub!("/\\*[^\003]*\003\003", '')
- while gsub!(/\{[^{}]*}/, ''); end
- gsub!(/'\001'/, "'{'")
- gsub!(/'\002'/, "'}'")
- while gsub!(/^[ \t]*\n(\s)/, '\1'); end
- gsub!(/([:|])[ \t\n]+(\w)/, '\1 \2')
- print $_
-end
diff --git a/sample/fact.rb b/sample/fact.rb
deleted file mode 100644
index 1462a6923a..0000000000
--- a/sample/fact.rb
+++ /dev/null
@@ -1,10 +0,0 @@
-def fact(n)
- return 1 if n == 0
- f = 1
- while n>0
- f *= n
- n -= 1
- end
- return f
-end
-print fact(ARGV[0].to_i), "\n"
diff --git a/sample/fib.awk b/sample/fib.awk
deleted file mode 100644
index 7ebe8930f5..0000000000
--- a/sample/fib.awk
+++ /dev/null
@@ -1,5 +0,0 @@
- function fib(n) {
- if ( n<2 ) return n; else return fib(n-2) + fib(n-1)
- }
-
- BEGIN { print fib(20); }
diff --git a/sample/fib.pl b/sample/fib.pl
deleted file mode 100644
index 945a4929a7..0000000000
--- a/sample/fib.pl
+++ /dev/null
@@ -1,11 +0,0 @@
-sub fib {
- my($n)=@_;
- if ($n<2) {
- return $n;
- }
- else {
- return fib($n-2)+fib($n-1);
- }
-}
-
-print fib(20), "\n";
diff --git a/sample/fib.py b/sample/fib.py
deleted file mode 100644
index 8318021d24..0000000000
--- a/sample/fib.py
+++ /dev/null
@@ -1,10 +0,0 @@
-# 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.rb b/sample/fib.rb
deleted file mode 100644
index cde4fba082..0000000000
--- a/sample/fib.rb
+++ /dev/null
@@ -1,10 +0,0 @@
-# calculate Fibonacci(20)
-# for benchmark
-def fib(n)
- if n<2
- n
- else
- fib(n-2)+fib(n-1)
- end
-end
-print(fib(20), "\n");
diff --git a/sample/fib.scm b/sample/fib.scm
deleted file mode 100644
index b246ca50ac..0000000000
--- a/sample/fib.scm
+++ /dev/null
@@ -1,8 +0,0 @@
-(define (fib n)
- (if (< n 2)
- n
- (+ (fib (- n 2)) (fib (- n 1)))))
-
-(display (fib 20))
-(newline)
-(quit)
diff --git a/sample/freq.rb b/sample/freq.rb
deleted file mode 100644
index 362753f71f..0000000000
--- a/sample/freq.rb
+++ /dev/null
@@ -1,12 +0,0 @@
-# word occurrence listing
-# usege: ruby freq.rb file..
-freq = Hash.new(0)
-while line = gets()
- line.scan(/\w+/) do |word|
- freq[word] += 1
- end
-end
-
-for word in freq.keys.sort!
- print word, " -- ", freq[word], "\n"
-end
diff --git a/sample/from.rb b/sample/from.rb
deleted file mode 100644
index 59cc387792..0000000000
--- a/sample/from.rb
+++ /dev/null
@@ -1,98 +0,0 @@
-#! /usr/local/bin/ruby
-
-require "parsedate"
-require "kconv"
-require "mailread"
-
-include ParseDate
-include Kconv
-
-class String
-
- def kconv(code = Kconv::EUC)
- Kconv.kconv(self, code, Kconv::AUTO)
- end
-
- def kjust(len)
- len += 1
- me = self[0, len].ljust(len)
- if me =~ /.$/ and $&.size == 2
- me[-2..-1] = ' '
- me[-2, 2] = ' '
- end
- me.chop!
- end
-
-end
-
-if ARGV[0] == '-w'
- wait = TRUE
- ARGV.shift
-end
-
-if ARGV.length == 0
- file = ENV['MAIL']
- user = ENV['USER'] || ENV['USERNAME'] || ENV['LOGNAME']
-else
- file = user = ARGV[0]
- ARGV.clear
-end
-
-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;
-def fromout(date, from, subj)
- return if !date
- y, m, d = parsedate(date) if date
- y ||= 0; m ||= 0; d ||= 0
- if from
- from.gsub! /\n/, ""
- else
- from = "sombody@somewhere"
- end
- if subj
- subj.gsub! /\n/, ""
- else
- subj = "(nil)"
- end
- if ENV['LANG'] =~ /sjis/i
- lang = Kconv::SJIS
- else
- lang = Kconv::EUC
- end
- from = from.kconv(lang).kjust(28)
- subj = subj.kconv(lang).kjust(40)
- printf "%02d/%02d/%02d [%s] %s\n",y%100,m,d,from,subj
- $outcount += 1
-end
-
-if File.exist?(file)
- atime = File.atime(file)
- mtime = File.mtime(file)
- f = open(file, "r")
- 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
-end
-
-if $outcount == 0
- print "You have no mail.\n"
- sleep 2 if wait
-elsif wait
- system "stty cbreak -echo"
- getc()
- system "stty cooked echo"
-end
diff --git a/sample/fullpath.rb b/sample/fullpath.rb
deleted file mode 100644
index 252e7dc217..0000000000
--- a/sample/fullpath.rb
+++ /dev/null
@@ -1,23 +0,0 @@
-#! /usr/local/bin/ruby
-# convert ls-lR filename into fullpath.
-
-if ARGV[0] =~ /-p/
- ARGV.shift
- path = ARGV.shift
-end
-
-if path == nil
- path = ""
-elsif path !~ %r|/$|
- path += "/"
-end
-
-while line = gets()
- case line
- when /:$/
- path = $_.chop.chop + "/"
- when /^total/, /^d/
- when /^(.*\d )(.+)$/
- print($1, path, $2, "\n")
- end
-end
diff --git a/sample/getopts.test b/sample/getopts.test
deleted file mode 100644
index 2866bccea8..0000000000
--- a/sample/getopts.test
+++ /dev/null
@@ -1,36 +0,0 @@
-#! /usr/local/bin/ruby
-
-load("parsearg.rb")
-
-def usage()
- printf "Usage:\n"
- printf "%s -d [-x x] [-y y] [--geometry geom] [--version] [string ...]\n", $0
-end
-
-$USAGE = 'usage'
-parseArgs(0, "d&(x|y)", "dfg", "x:", "y:", "geometry:800x600", "version")
-if ($OPT_d)
- if $OPT_version
- printf "version 1.0\n"
- end
- if ($OPT_x)
- printf("x = %d\n", $OPT_x.to_i)
- end
- if ($OPT_y)
- printf("y = %d\n", $OPT_y.to_i)
- end
- if ($OPT_geometry)
- printf("geometry = %s\n", $OPT_geometry)
- end
- if $OPT_f
- printf "f = TRUE\n"
- end
- if $OPT_g
- printf "g = TRUE\n"
- end
-end
-
-while (ARGV.length != 0)
- print "other = ", ARGV[0], "\n"
- ARGV.shift
-end
diff --git a/sample/goodfriday.rb b/sample/goodfriday.rb
deleted file mode 100644
index 1c48f55d96..0000000000
--- a/sample/goodfriday.rb
+++ /dev/null
@@ -1,48 +0,0 @@
-#! /usr/bin/env ruby
-
-# goodfriday.rb: Written by Tadayoshi Funaba 1998, 2000
-# $Id: goodfriday.rb,v 1.1.1.1 2000-07-16 10:25:30+09 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.new(*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/irb.rb b/sample/irb.rb
deleted file mode 100644
index 58f3699139..0000000000
--- a/sample/irb.rb
+++ /dev/null
@@ -1,21 +0,0 @@
-#!/usr/bin/env ruby
-#
-# irb.rb - intaractive ruby
-# $Release Version: 0.7.3 $
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-#
-
-require "irb"
-
-if __FILE__ == $0
- IRB.start(__FILE__)
-else
- # check -e option
- if /^-e$/ =~ $0
- IRB.start(__FILE__)
- else
- IRB.initialize(__FILE__)
- end
-end
diff --git a/sample/less.rb b/sample/less.rb
deleted file mode 100644
index 8be359108f..0000000000
--- a/sample/less.rb
+++ /dev/null
@@ -1,17 +0,0 @@
-#! /usr/local/bin/ruby
-
-ZCAT = "/usr/local/bin/zcat"
-LESS = "/usr/local/bin/less"
-
-FILE = ARGV.pop
-OPTION = (if ARGV.length == 0; "" else ARGV.join(" "); end)
-
-if FILE =~ /\.(Z|gz)$/
- exec(format("%s %s | %s %s", ZCAT, FILE, LESS, OPTION))
-elsif FILE == nil
- exec(format("%s %s", LESS, OPTION))
-else
- print(format("%s %s %s", LESS, OPTION, FILE), "\n")
- exec(format("%s %s %s", LESS, OPTION, FILE))
-end
-exit()
diff --git a/sample/list.rb b/sample/list.rb
deleted file mode 100644
index 221f7edb16..0000000000
--- a/sample/list.rb
+++ /dev/null
@@ -1,80 +0,0 @@
-# Linked list example
-class MyElem
- # object initializer called from Class#new
- def initialize(item)
- # @variables are instance variable, no declaration needed
- @data = item
- @succ = nil
- end
-
- def data
- @data
- end
-
- def succ
- @succ
- end
-
- # the method invoked by ``obj.data = val''
- def succ=(new)
- @succ = new
- end
-end
-
-class MyList
- def add_to_list(obj)
- elt = MyElem.new(obj)
- if @head
- @tail.succ = elt
- else
- @head = elt
- end
- @tail = elt
- end
-
- def each
- elt = @head
- while elt
- yield elt
- elt = elt.succ
- end
- end
-
- # the method to convert object into string.
- # redefining this will affect print.
- def to_s
- str = "<MyList:\n";
- for elt in self
- # short form of ``str = str + elt.data.to_s + "\n"''
- str += elt.data.to_s + "\n"
- end
- str += ">"
- str
- end
-end
-
-class Point
- def initialize(x, y)
- @x = x; @y = y
- self
- end
-
- def to_s
- sprintf("%d@%d", @x, @y)
- end
-end
-
-# global variable name starts with `$'.
-$list1 = MyList.new
-$list1.add_to_list(10)
-$list1.add_to_list(20)
-$list1.add_to_list(Point.new(2, 3))
-$list1.add_to_list(Point.new(4, 5))
-$list2 = MyList.new
-$list2.add_to_list(20)
-$list2.add_to_list(Point.new(4, 5))
-$list2.add_to_list($list1)
-
-# parenthesises around method arguments can be ommitted unless ambiguous.
-print "list1:\n", $list1, "\n"
-print "list2:\n", $list2, "\n"
diff --git a/sample/list2.rb b/sample/list2.rb
deleted file mode 100644
index 914cb8996e..0000000000
--- a/sample/list2.rb
+++ /dev/null
@@ -1,16 +0,0 @@
-# Linked list example -- short version
-class Point
- def initialize(x, y)
- @x = x; @y = y
- self
- end
-
- def to_s
- sprintf("%d@%d", @x, @y)
- end
-end
-
-list1 = [10, 20, Point.new(2, 3), Point.new(4, 5)]
-list2 = [20, Point.new(4, 5), list1]
-print("list1:\n", list1.join("\n"), "\n")
-print("list2:\n", list2.join("\n"), "\n")
diff --git a/sample/list3.rb b/sample/list3.rb
deleted file mode 100644
index 1d756fdff0..0000000000
--- a/sample/list3.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-# Linked list example -- short version
-# using inspect
-
-class Point
- def initialize(x, y)
- @x = x; @y = y
- self
- end
-
- def to_s
- sprintf("%d@%d", @x, @y)
- end
-end
-
-list1 = [10, 20, Point.new(2, 3), Point.new(4, 5)]
-list2 = [20, Point.new(4, 5), list1]
-print("list1: ", list1.inspect, "\n")
-print("list2: ", list2.inspect, "\n")
diff --git a/sample/mine.rb b/sample/mine.rb
deleted file mode 100644
index 8fc27e0c6d..0000000000
--- a/sample/mine.rb
+++ /dev/null
@@ -1,175 +0,0 @@
-#! /usr/bin/ruby -Ke
-
-class Board
- def clr
- print "\e[2J"
- end
- def pos(x,y)
- printf "\e[%d;%dH", y+1, x*2+1
- end
- def colorstr(id,s)
- printf "\e[%dm%s\e[0m", id, s
- end
- def put(x, y, col, str)
- pos(x,y); colorstr(43,str)
- pos(0,@hi); print "残り:",@mc,"/",@total," "
- pos(x,y)
- end
- private :clr, :pos, :colorstr, :put
- CHR=["・","1","2","3","4","5","6","7","8","★","●","@@"]
- COL=[46,43,45] # default,opened,over
- def initialize(h,w,m)
- # ゲーム盤の生成(h:縦,w:横,m:爆弾の数)
- @hi=h; @wi=w; @m=m
- reset
- end
- def reset
- # ゲーム盤を(再)初期化する
- srand()
- @cx=0; @cy=0; @mc=@m
- @over=false
- @data=Array.new(@hi*@wi)
- @state=Array.new(@hi*@wi)
- @total=@hi*@wi
- @total.times {|i| @data[i]=0}
- @m.times do
- loop do
- j=rand(@total-1)
- if @data[j] == 0 then
- @data[j]=1
- break
- end
- end
- end
- clr; pos(0,0)
- @hi.times{|y| pos(0,y); colorstr(COL[0],CHR[0]*@wi)}
- pos(@cx,@cy)
- end
- def mark
- # 現在のカーソル位置にマークをつける
- if @state[@wi*@cy+@cx] != nil then return end
- @state[@wi*@cy+@cx] = "MARK"
- @mc=@mc-1;
- @total=@total-1;
- put(@cx, @cy, COL[1], CHR[9])
- end
- def open(x=@cx,y=@cy)
- # 現在のカーソル位置をオープンにする
- # 爆弾があればゲームオーバー
- if @state[@wi*y+x] =="OPEN" then return 0 end
- if @state[@wi*y+x] == nil then @total=@total-1 end
- if @state[@wi*y+x] =="MARK" then @mc=@mc+1 end
- @state[@wi*y+x]="OPEN"
- if fetch(x,y) == 1 then @over = 1; return end
- c = count(x,y)
- put(x, y, COL[1], CHR[c])
- return 0 if c != 0
- if x > 0 && y > 0 then open(x-1,y-1) end
- if y > 0 then open(x, y-1) end
- if x < @wi-1 && y > 0 then open(x+1,y-1) end
- if x > 0 then open(x-1,y) end
- if x < @wi-1 then open(x+1,y) end
- if x > 0 && y < @hi-1 then open(x-1,y+1) end
- if y < @hi -1 then open(x,y+1) end
- if x < @wi-1 && y < @hi-1 then open(x+1,y+1) end
- pos(@cx,@cy)
- end
- def fetch(x,y)
- # (x,y)の位置の爆弾の数(0 or 1)を返す
- if x < 0 then 0
- elsif x >= @wi then 0
- elsif y < 0 then 0
- elsif y >= @hi then 0
- else
- @data[y*@wi+x]
- end
- end
- def count(x,y)
- # (x,y)に隣接する爆弾の数を返す
- fetch(x-1,y-1)+fetch(x,y-1)+fetch(x+1,y-1)+
- fetch(x-1,y) + fetch(x+1,y)+
- fetch(x-1,y+1)+fetch(x,y+1)+fetch(x+1,y+1)
- end
- def over(win)
- # ゲームの終了
- quit
- unless win
- pos(@cx,@cy); print CHR[11]
- end
- pos(0,@hi)
- if win then print "*** YOU WIN !! ***"
- else print "*** GAME OVER ***"
- end
- end
- def over?
- # ゲームの終了チェック
- # 終了処理も呼び出す
- remain = (@mc+@total == 0)
- if @over || remain
- over(remain)
- true
- else
- false
- end
- end
- def quit
- # ゲームの中断(または終了)
- # 盤面を全て見せる
- @hi.times do|y|
- pos(0,y)
- @wi.times do|x|
- colorstr(if @state[y*@wi+x] == "MARK" then COL[1] else COL[2] end,
- if fetch(x,y)==1 then CHR[10] else CHR[count(x,y)] end)
- end
- end
- end
- def down
- # カーソルを下に
- if @cy < @hi-1 then @cy=@cy+1; pos(@cx, @cy) end
- end
- def up
- # カーソルを上に
- if @cy > 0 then @cy=@cy-1; pos(@cx, @cy) end
- end
- def left
- # カーソルを左に
- if @cx > 0 then @cx=@cx-1; pos(@cx, @cy) end
- end
- def right
- # カーソルを右に
- if @cx < @wi-1 then @cx=@cx+1; pos(@cx, @cy) end
- end
-end
-
-bd=Board.new(10,10,10)
-system("stty raw -echo")
-begin
- loop do
- case STDIN.getc
- when ?n # new game
- bd.reset
- when ?m # mark
- bd.mark
- when ?j
- bd.down
- when ?k
- bd.up
- when ?h
- bd.left
- when ?l
- bd.right
- when ?\s
- bd.open
- when ?q,?\C-c # quit game
- bd.quit
- break
- end
- if bd.over?
- if STDIN.getc == ?q then break end
- bd.reset
- end
- end
-ensure
- system("stty -raw echo")
-end
-print "\n"
diff --git a/sample/mkproto.rb b/sample/mkproto.rb
deleted file mode 100644
index e1d49be3e3..0000000000
--- a/sample/mkproto.rb
+++ /dev/null
@@ -1,27 +0,0 @@
-$/ = nil
-while line = gets()
- if /^((void|VALUE|int|char *\*|ID|struct [\w_]+ *\*|st_table *\*) *)?\n([\w\d_]+)\(.*\)\n\s*((.+;\n)*)\{/ =~ line
- $_ = $'
- printf "%s %s(", $2, $3
- args = []
- for arg in $4.split(/;\n\s*/)
- arg.gsub! ' +', ' '
- if arg =~ /,/
- if arg =~ /(([^*]+) *\** *[\w\d_]+),/
- type = $2.strip
- args.push $1.strip
- arg = $'
- else
- type = ""
- end
- while arg.sub!(/(\** *[\w\d_]+)(,|$)/, "") && $~
- args.push type + " " + $1.strip
- end
- else
- args.push arg.strip
- end
- end
- printf "%s);\n", args.join(', ')
- redo
- end
-end
diff --git a/sample/mpart.rb b/sample/mpart.rb
deleted file mode 100644
index a88eba0ef6..0000000000
--- a/sample/mpart.rb
+++ /dev/null
@@ -1,44 +0,0 @@
-#! ./ruby
-# split into multi part
-# usage: mpart.rb [-nnn] file..
-
-lines = 1000
-
-if (ARGV[0] =~ /^-(\d+)$/ )
- lines = $1.to_i;
- ARGV.shift;
-end
-
-basename = ARGV[0]
-extname = "part"
-
-part = 1
-line = 0
-
-fline = 0
-for i in ifp = open(basename)
- fline = fline + 1
-end
-ifp.close
-
-parts = fline / lines + 1
-
-for i in ifp = open(basename)
- if line == 0
- ofp = open(sprintf("%s.%s%02d", basename, extname, part), "w")
- printf(ofp, "%s part%02d/%02d\n", basename, part, parts)
- ofp.write("BEGIN--cut here--cut here\n")
- end
- ofp.write(i)
- line = line + 1
- if line >= lines and !ifp.eof?
- ofp.write("END--cut here--cut here\n")
- ofp.close
- part = part + 1
- line = 0
- end
-end
-ofp.write("END--cut here--cut here\n")
-ofp.close
-
-ifp.close
diff --git a/sample/mrshtest.rb b/sample/mrshtest.rb
deleted file mode 100644
index 8d2dc9936b..0000000000
--- a/sample/mrshtest.rb
+++ /dev/null
@@ -1,13 +0,0 @@
-include Marshal
-a = 25.6;
-pt = Struct.new('Point', :x,:y);
-x = pt.new(10, 10)
-y = pt.new(20, 20)
-rt = Struct.new('Rectangle', :origin,:corner);
-z = rt.new(x, y)
-c = Object.new
-s = [a, x, z, c, c, "fff"];
-p s
-d = dump(s);
-p d
-p load(d)
diff --git a/sample/observ.rb b/sample/observ.rb
deleted file mode 100644
index 72e5178b38..0000000000
--- a/sample/observ.rb
+++ /dev/null
@@ -1,32 +0,0 @@
-#! /usr/local/bin/ruby
-
-require "thread"
-require "observer"
-
-class Tick
- include Observable
- def initialize
- Thread.start do
- loop do
- sleep 0.999
- now = Time.now
- changed
- notify_observers(now.hour, now.min, now.sec)
- end
- end
- end
-end
-
-class Clock
- def initialize(tick)
- @tick = tick
- @tick.add_observer(self)
- end
- def update(h, m, s)
- printf "\e[8D%02d:%02d:%02d", h, m, s
- STDOUT.flush
- end
-end
-
-clock = Clock.new(Tick.new)
-sleep
diff --git a/sample/occur.pl b/sample/occur.pl
deleted file mode 100644
index 1f5fcf27a4..0000000000
--- a/sample/occur.pl
+++ /dev/null
@@ -1,9 +0,0 @@
-while (<>) {
- for (split(/\W+/)) {
- $freq{$_}++;
- }
-}
-
-for (sort keys %freq) {
- print "$_ -- $freq{$_}\n";
-}
diff --git a/sample/occur.rb b/sample/occur.rb
deleted file mode 100644
index f489beee17..0000000000
--- a/sample/occur.rb
+++ /dev/null
@@ -1,12 +0,0 @@
-# word occurrence listing
-# usege: ruby occur.rb file..
-freq = Hash.new(0)
-while gets()
- for word in $_.split(/\W+/)
- freq[word] += 1
- end
-end
-
-for word in freq.keys.sort!
- print word, " -- ", freq[word], "\n"
-end
diff --git a/sample/occur2.rb b/sample/occur2.rb
deleted file mode 100644
index b8ecf70904..0000000000
--- a/sample/occur2.rb
+++ /dev/null
@@ -1,16 +0,0 @@
-# word occurrence listing
-# usege: ruby occur2.rb file..
-freq = {}
-while gets()
- for word in $_.split(/\W+/)
- begin
- freq[word] = freq[word] + 1
- rescue NameError
- freq[word] = 1
- end
- end
-end
-
-for word in freq.keys.sort
- printf("%s -- %d\n", word, freq[word])
-end
diff --git a/sample/philos.rb b/sample/philos.rb
deleted file mode 100644
index 119e7c36b9..0000000000
--- a/sample/philos.rb
+++ /dev/null
@@ -1,54 +0,0 @@
-#
-# The Dining Philosophers - thread example
-#
-require "thread"
-
-srand
-#srand
-N=9 # number of philosophers
-$forks = []
-for i in 0..N-1
- $forks[i] = Mutex.new
-end
-$state = "-o"*N
-
-def wait
- sleep rand(20)/10.0
-end
-
-def think(n)
- wait
-end
-
-def eat(n)
- wait
-end
-
-def philosopher(n)
- while TRUE
- think n
- $forks[n].lock
- if not $forks[(n+1)%N].try_lock
- $forks[n].unlock # avoid deadlock
- next
- end
- $state[n*2] = ?|;
- $state[(n+1)%N*2] = ?|;
- $state[n*2+1] = ?*;
- print $state, "\n"
- eat(n)
- $state[n*2] = ?-;
- $state[(n+1)%N*2] = ?-;
- $state[n*2+1] = ?o;
- print $state, "\n"
- $forks[n].unlock
- $forks[(n+1)%N].unlock
- end
-end
-
-for n in 0..N-1
- Thread.start(n){|i| philosopher(i)}
- sleep 0.1
-end
-
-sleep
diff --git a/sample/pi.rb b/sample/pi.rb
deleted file mode 100644
index 49067cc347..0000000000
--- a/sample/pi.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-#!/usr/local/bin/ruby
-
-k, a, b, a1, b1 = 2, 4, 1, 12, 4
-
-while TRUE
- # Next approximation
- p, q, k = k*k, 2*k+1, k+1
- a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
- # Print common digits
- d = a / b
- d1 = a1 / b1
- while d == d1
- print d
- $stdout.flush
- a, a1 = 10*(a%b), 10*(a1%b1)
- d, d1 = a/b, a1/b1
- end
-end
diff --git a/sample/rcs.awk b/sample/rcs.awk
deleted file mode 100644
index 08979285c9..0000000000
--- a/sample/rcs.awk
+++ /dev/null
@@ -1,33 +0,0 @@
-BEGIN {
- sw = 40.0;
- dw = 78.0;
- hdw = dw / 2.0;
- w = 20.0;
- h =1.0;
- d = 0.2;
- ss="abcdefghijklmnopqrstuvwxyz0123456789!#$%^&*()-=\\[];'`,./";
- rnd = srand();
-}
-
-{
- xr = -hdw; y = h * 1.0; maxxl = -999;
- s = "";
- while (xr < hdw) {
- x = xr * (1 + y) - y * w / 2;
- i = (x / (1 + h) + sw /2);
- c = (0 < i && i < length($0)) ? substr($0, i, 1) : "0";
- y = h - d * c;
- xl = xr - w * y / (1 + y);
- if (xl < -hdw || xl >= hdw || xl <= maxxl) {
- t = rand() * length(ss);
- c = substr(ss, t, 1);
- }
- else {
- c = substr(s, xl + hdw, 1);
- maxxl = xl;
- }
- s = s c;
- xr = xr + 1;
- }
- print s;
-}
diff --git a/sample/rcs.dat b/sample/rcs.dat
deleted file mode 100644
index 61c88bff89..0000000000
--- a/sample/rcs.dat
+++ /dev/null
@@ -1,17 +0,0 @@
-0000000000000000220000000000000000
-0000000000000111221110000000000000
-0000000000111112222111110000000000
-0000000111111112222111111110000000
-0000111111111122222211111111110000
-0111111111111222222221111111111110
-2222222222222222222222222222222222
-1122222222222222222222222222222211
-0111122222222222222222222222211110
-0011111122222222222222222211111100
-0001111111222222222222221111111000
-0000111112222222222222222111110000
-0000011122222222112222222211100000
-0000001122222221111222222211000000
-0000000122221111111111222210000000
-0000000221111111111111111220000000
-0000000000000000000000000000000000
diff --git a/sample/rcs.rb b/sample/rcs.rb
deleted file mode 100644
index 7c091936f3..0000000000
--- a/sample/rcs.rb
+++ /dev/null
@@ -1,49 +0,0 @@
-# random dot steraogram
-# usage: rcs.rb rcs.dat
-
-sw = 40.0 # width of original pattern
-dw = 78.0 # width of generating Random Character Streogram
-hdw = dw / 2.0
-w = 20.0 # distance between eyes
-h =1.0 # distance from screen and base plane
-d = 0.2 # z value unit
-ss="abcdefghijklmnopqrstuvwxyz0123456789#!$%^&*()-=\\[];'`,./"
-rnd = srand()
-
-while gets()
-# print($_)
- xr = -hdw; y = h * 1.0; maxxl = -999
- s = "";
- while xr < hdw
- x = xr * (1 + y) - y * w / 2
- i = (x / (1 + h) + sw / 2)
- if (1 < i && i < $_.length);
- c = $_[i, 1].to_i
- else
- c = 0
- end
- y = h - d * c
- xl = xr - w * y / (1 + y);
- if xl < -hdw || xl >= hdw || xl <= maxxl
- tt = rand(ss.length)
- c = ss[tt, 1]
- else
- c = s[xl + hdw, 1]
- maxxl = xl
- end
- s += c
- xr += 1
- end
- print(s, "\n")
-end
-
-
-
-
-
-
-
-
-
-
-
diff --git a/sample/regx.rb b/sample/regx.rb
deleted file mode 100644
index aaf4b5f1ee..0000000000
--- a/sample/regx.rb
+++ /dev/null
@@ -1,23 +0,0 @@
-st = "\033[7m"
-en = "\033[m"
-#st = "<<"
-#en = ">>"
-
-while TRUE
- print "str> "
- STDOUT.flush
- input = gets
- break if not input
- if input != ""
- str = input
- str.chop!
- end
- print "pat> "
- STDOUT.flush
- re = gets
- break if not re
- re.chop!
- str.gsub! re, "#{st}\\&#{en}"
- print str, "\n"
-end
-print "\n"
diff --git a/sample/sieve.rb b/sample/sieve.rb
deleted file mode 100644
index 359c185f20..0000000000
--- a/sample/sieve.rb
+++ /dev/null
@@ -1,14 +0,0 @@
-# sieve of Eratosthenes
-max = Integer(ARGV.shift || 100)
-sieve = []
-for i in 2 .. max
- sieve[i] = i
-end
-
-for i in 2 .. Math.sqrt(max)
- next unless sieve[i]
- (i*i).step(max, i) do |j|
- sieve[j] = nil
- end
-end
-puts sieve.compact.join ", "
diff --git a/sample/svr.rb b/sample/svr.rb
deleted file mode 100644
index af566056b7..0000000000
--- a/sample/svr.rb
+++ /dev/null
@@ -1,32 +0,0 @@
-# socket example - server side
-# usage: ruby svr.rb
-
-require "socket"
-
-gs = TCPserver.open(0)
-addr = gs.addr
-addr.shift
-printf("server is on %s\n", addr.join(":"))
-socks = [gs]
-
-while TRUE
- nsock = select(socks);
- next if nsock == nil
- for s in nsock[0]
- if s == gs
- ns = s.accept
- socks.push(ns)
- print(s, " is accepted\n")
- else
- if s.eof?
- print(s, " is gone\n")
- s.close
- socks.delete(s)
- else
- if str = s.gets;
- s.write(str)
- end
- end
- end
- end
-end
diff --git a/sample/test.rb b/sample/test.rb
deleted file mode 100644
index b20712019d..0000000000
--- a/sample/test.rb
+++ /dev/null
@@ -1,1485 +0,0 @@
-#! /usr/bin/env ruby
-
-$testnum=0
-$ntest=0
-$failed = 0
-
-def test_check(what)
- printf "%s\n", what
- $what = what
- $testnum = 0
-end
-
-def test_ok(cond)
- $testnum+=1
- $ntest+=1
- if cond
- printf "ok %d\n", $testnum
- else
- where = caller[0]
- printf "not ok %s %d -- %s\n", $what, $testnum, where
- $failed+=1
- end
-end
-
-# make sure conditional operators work
-
-test_check "assignment"
-
-a=[]; a[0] ||= "bar";
-test_ok(a[0] == "bar")
-h={}; h["foo"] ||= "bar";
-test_ok(h["foo"] == "bar")
-
-aa = 5
-aa ||= 25
-test_ok(aa == 5)
-bb ||= 25
-test_ok(bb == 25)
-cc &&=33
-test_ok(cc == nil)
-cc = 5
-cc &&=44
-test_ok(cc == 44)
-
-a = nil; test_ok(a == nil)
-a = 1; test_ok(a == 1)
-a = []; test_ok(a == [])
-a = [1]; test_ok(a == [1])
-a = [nil]; test_ok(a == [nil])
-a = [[]]; test_ok(a == [[]])
-a = [*[]]; test_ok(a == [])
-a = [*[1]]; test_ok(a == [1])
-a = [*[1,2]]; test_ok(a == [1,2])
-
-a = *nil; test_ok(a == nil)
-a = *1; test_ok(a == 1)
-a = *[]; test_ok(a == nil)
-a = *[1]; test_ok(a == 1)
-a = *[nil]; test_ok(a == nil)
-a = *[[]]; test_ok(a == [])
-a = *[*[]]; test_ok(a == nil)
-a = *[*[1]]; test_ok(a == 1)
-a = *[*[1,2]]; test_ok(a == [1,2])
-
-*a = nil; test_ok(a == [])
-*a = 1; test_ok(a == [1])
-*a = []; test_ok(a == [])
-*a = [1]; test_ok(a == [1])
-*a = [nil]; test_ok(a == [nil])
-*a = [[]]; test_ok(a == [[]])
-*a = [*[]]; test_ok(a == [])
-*a = [*[1]]; test_ok(a == [1])
-*a = [*[1,2]]; test_ok(a == [1,2])
-
-*a = *nil; test_ok(a == [])
-*a = *1; test_ok(a == [1])
-*a = *[]; test_ok(a == [])
-*a = *[1]; test_ok(a == [1])
-*a = *[nil]; test_ok(a == [])
-*a = *[[]]; test_ok(a == [])
-*a = *[*[]]; test_ok(a == [])
-*a = *[*[1]]; test_ok(a == [1])
-*a = *[*[1,2]]; test_ok(a == [1,2])
-
-a,b,*c = nil; test_ok([a,b,c] == [nil, nil, []])
-a,b,*c = 1; test_ok([a,b,c] == [1, nil, []])
-a,b,*c = []; test_ok([a,b,c] == [nil, nil, []])
-a,b,*c = [1]; test_ok([a,b,c] == [1, nil, []])
-a,b,*c = [nil]; test_ok([a,b,c] == [nil, nil, []])
-a,b,*c = [[]]; test_ok([a,b,c] == [[], nil, []])
-a,b,*c = [*[]]; test_ok([a,b,c] == [nil, nil, []])
-a,b,*c = [*[1]]; test_ok([a,b,c] == [1, nil, []])
-a,b,*c = [*[1,2]]; test_ok([a,b,c] == [1, 2, []])
-
-a,b,*c = *nil; test_ok([a,b,c] == [nil, nil, []])
-a,b,*c = *1; test_ok([a,b,c] == [1, nil, []])
-a,b,*c = *[]; test_ok([a,b,c] == [nil, nil, []])
-a,b,*c = *[1]; test_ok([a,b,c] == [1, nil, []])
-a,b,*c = *[nil]; test_ok([a,b,c] == [nil, nil, []])
-a,b,*c = *[[]]; test_ok([a,b,c] == [nil, nil, []])
-a,b,*c = *[*[]]; test_ok([a,b,c] == [nil, nil, []])
-a,b,*c = *[*[1]]; test_ok([a,b,c] == [1, nil, []])
-a,b,*c = *[*[1,2]]; test_ok([a,b,c] == [1, 2, []])
-
-def f; yield nil; end; f {|a| test_ok(a == nil)}
-def f; yield 1; end; f {|a| test_ok(a == 1)}
-def f; yield []; end; f {|a| test_ok(a == [])}
-def f; yield [1]; end; f {|a| test_ok(a == [1])}
-def f; yield [nil]; end; f {|a| test_ok(a == [nil])}
-def f; yield [[]]; end; f {|a| test_ok(a == [[]])}
-def f; yield [*[]]; end; f {|a| test_ok(a == [])}
-def f; yield [*[1]]; end; f {|a| test_ok(a == [1])}
-def f; yield [*[1,2]]; end; f {|a| test_ok(a == [1,2])}
-
-def f; yield *nil; end; f {|a| test_ok(a == nil)}
-def f; yield *1; end; f {|a| test_ok(a == 1)}
-def f; yield *[]; end; f {|a| test_ok(a == nil)}
-def f; yield *[1]; end; f {|a| test_ok(a == 1)}
-def f; yield *[nil]; end; f {|a| test_ok(a == nil)}
-def f; yield *[[]]; end; f {|a| test_ok(a == [])}
-def f; yield *[*[]]; end; f {|a| test_ok(a == nil)}
-def f; yield *[*[1]]; end; f {|a| test_ok(a == 1)}
-def f; yield *[*[1,2]]; end; f {|a| test_ok(a == [1,2])}
-
-def f; yield nil; end; f {|*a| test_ok(a == [])}
-def f; yield 1; end; f {|*a| test_ok(a == [1])}
-def f; yield []; end; f {|*a| test_ok(a == [])}
-def f; yield [1]; end; f {|*a| test_ok(a == [1])}
-def f; yield [nil]; end; f {|*a| test_ok(a == [nil])}
-def f; yield [[]]; end; f {|*a| test_ok(a == [[]])}
-def f; yield [*[]]; end; f {|*a| test_ok(a == [])}
-def f; yield [*[1]]; end; f {|*a| test_ok(a == [1])}
-def f; yield [*[1,2]]; end; f {|*a| test_ok(a == [1,2])}
-
-def f; yield *nil; end; f {|*a| test_ok(a == [])}
-def f; yield *1; end; f {|*a| test_ok(a == [1])}
-def f; yield *[]; end; f {|*a| test_ok(a == [])}
-def f; yield *[1]; end; f {|*a| test_ok(a == [1])}
-def f; yield *[nil]; end; f {|*a| test_ok(a == [])}
-def f; yield *[[]]; end; f {|*a| test_ok(a == [])}
-def f; yield *[*[]]; end; f {|*a| test_ok(a == [])}
-def f; yield *[*[1]]; end; f {|*a| test_ok(a == [1])}
-def f; yield *[*[1,2]]; end; f {|*a| test_ok(a == [1,2])}
-
-def f; yield nil; end; f {|a,b,*c| test_ok([a,b,c] == [nil, nil, []])}
-def f; yield 1; end; f {|a,b,*c| test_ok([a,b,c] == [1, nil, []])}
-def f; yield []; end; f {|a,b,*c| test_ok([a,b,c] == [nil, nil, []])}
-def f; yield [1]; end; f {|a,b,*c| test_ok([a,b,c] == [1, nil, []])}
-def f; yield [nil]; end; f {|a,b,*c| test_ok([a,b,c] == [nil, nil, []])}
-def f; yield [[]]; end; f {|a,b,*c| test_ok([a,b,c] == [[], nil, []])}
-def f; yield [*[]]; end; f {|a,b,*c| test_ok([a,b,c] == [nil, nil, []])}
-def f; yield [*[1]]; end; f {|a,b,*c| test_ok([a,b,c] == [1, nil, []])}
-def f; yield [*[1,2]]; end; f {|a,b,*c| test_ok([a,b,c] == [1, 2, []])}
-
-def f; yield *nil; end; f {|a,b,*c| test_ok([a,b,c] == [nil, nil, []])}
-def f; yield *1; end; f {|a,b,*c| test_ok([a,b,c] == [1, nil, []])}
-def f; yield *[]; end; f {|a,b,*c| test_ok([a,b,c] == [nil, nil, []])}
-def f; yield *[1]; end; f {|a,b,*c| test_ok([a,b,c] == [1, nil, []])}
-def f; yield *[nil]; end; f {|a,b,*c| test_ok([a,b,c] == [nil, nil, []])}
-def f; yield *[[]]; end; f {|a,b,*c| test_ok([a,b,c] == [nil, nil, []])}
-def f; yield *[*[]]; end; f {|a,b,*c| test_ok([a,b,c] == [nil, nil, []])}
-def f; yield *[*[1]]; end; f {|a,b,*c| test_ok([a,b,c] == [1, nil, []])}
-def f; yield *[*[1,2]]; end; f {|a,b,*c| test_ok([a,b,c] == [1, 2, []])}
-
-test_check "condition"
-
-$x = '0';
-
-$x == $x && test_ok(true)
-$x != $x && test_ok(false)
-$x == $x || test_ok(false)
-$x != $x || test_ok(true)
-
-# first test to see if we can run the tests.
-
-test_check "if/unless";
-
-$x = 'test';
-test_ok(if $x == $x then true else false end)
-$bad = false
-unless $x == $x
- $bad = true
-end
-test_ok(!$bad)
-test_ok(unless $x != $x then true else false end)
-
-test_check "case"
-
-case 5
-when 1, 2, 3, 4, 6, 7, 8
- test_ok(false)
-when 5
- test_ok(true)
-end
-
-case 5
-when 5
- test_ok(true)
-when 1..10
- test_ok(false)
-end
-
-case 5
-when 1..10
- test_ok(true)
-else
- test_ok(false)
-end
-
-case 5
-when 5
- test_ok(true)
-else
- test_ok(false)
-end
-
-case "foobar"
-when /^f.*r$/
- test_ok(true)
-else
- test_ok(false)
-end
-
-test_check "while/until";
-
-tmp = open("while_tmp", "w")
-tmp.print "tvi925\n";
-tmp.print "tvi920\n";
-tmp.print "vt100\n";
-tmp.print "Amiga\n";
-tmp.print "paper\n";
-tmp.close
-
-# test break
-
-tmp = open("while_tmp", "r")
-test_ok(tmp.kind_of?(File))
-
-while line = tmp.gets()
- break if /vt100/ =~ line
-end
-
-test_ok(!tmp.eof? && /vt100/ =~ line)
-tmp.close
-
-# test next
-$bad = false
-tmp = open("while_tmp", "r")
-while line = tmp.gets()
- next if /vt100/ =~ line
- $bad = 1 if /vt100/ =~ line
-end
-test_ok(!(!tmp.eof? || /vt100/ =~ line || $bad))
-tmp.close
-
-# test redo
-$bad = false
-tmp = open("while_tmp", "r")
-while tmp.gets()
- line = $_
- gsub(/vt100/, 'VT100')
- if $_ != line
- $_.gsub!('VT100', 'Vt100')
- redo
- end
- $bad = 1 if /vt100/ =~ $_
- $bad = 1 if /VT100/ =~ $_
-end
-test_ok(tmp.eof? && !$bad)
-tmp.close
-
-sum=0
-for i in 1..10
- sum += i
- i -= 1
- if i > 0
- redo
- end
-end
-test_ok(sum == 220)
-
-# test interval
-$bad = false
-tmp = open("while_tmp", "r")
-while line = tmp.gets()
- break if 3
- case line
- when /vt100/, /Amiga/, /paper/
- $bad = true
- end
-end
-test_ok(!$bad)
-tmp.close
-
-File.unlink "while_tmp" or `/bin/rm -f "while_tmp"`
-test_ok(!File.exist?("while_tmp"))
-
-i = 0
-until i>4
- i+=1
-end
-test_ok(i>4)
-
-
-# exception handling
-test_check "exception";
-
-begin
- raise "this must be handled"
- test_ok(false)
-rescue
- test_ok(true)
-end
-
-$bad = true
-begin
- raise "this must be handled no.2"
-rescue
- if $bad
- $bad = false
- retry
- test_ok(false)
- end
-end
-test_ok(true)
-
-# exception in rescue clause
-$string = "this must be handled no.3"
-begin
- begin
- raise "exception in rescue clause"
- rescue
- raise $string
- end
- test_ok(false)
-rescue
- test_ok(true) if $! == $string
-end
-
-# exception in ensure clause
-begin
- begin
- raise "this must be handled no.4"
- ensure
- raise "exception in ensure clause"
- end
- test_ok(false)
-rescue
- test_ok(true)
-end
-
-$bad = true
-begin
- begin
- raise "this must be handled no.5"
- ensure
- $bad = false
- end
-rescue
-end
-test_ok(!$bad)
-
-$bad = true
-begin
- begin
- raise "this must be handled no.6"
- ensure
- $bad = false
- end
-rescue
-end
-test_ok(!$bad)
-
-$bad = true
-while true
- begin
- break
- ensure
- $bad = false
- end
-end
-test_ok(!$bad)
-
-test_ok(catch(:foo) {
- loop do
- loop do
- throw :foo, true
- break
- end
- break
- test_ok(false) # should no reach here
- end
- false
- })
-
-test_check "array"
-test_ok([1, 2] + [3, 4] == [1, 2, 3, 4])
-test_ok([1, 2] * 2 == [1, 2, 1, 2])
-test_ok([1, 2] * ":" == "1:2")
-
-test_ok([1, 2].hash == [1, 2].hash)
-
-test_ok([1,2,3] & [2,3,4] == [2,3])
-test_ok([1,2,3] | [2,3,4] == [1,2,3,4])
-test_ok([1,2,3] - [2,3] == [1])
-
-$x = [0, 1, 2, 3, 4, 5]
-test_ok($x[2] == 2)
-test_ok($x[1..3] == [1, 2, 3])
-test_ok($x[1,3] == [1, 2, 3])
-
-$x[0, 2] = 10
-test_ok($x[0] == 10 && $x[1] == 2)
-
-$x[0, 0] = -1
-test_ok($x[0] == -1 && $x[1] == 10)
-
-$x[-1, 1] = 20
-test_ok($x[-1] == 20 && $x.pop == 20)
-
-# array and/or
-test_ok(([1,2,3]&[2,4,6]) == [2])
-test_ok(([1,2,3]|[2,4,6]) == [1,2,3,4,6])
-
-# compact
-$x = [nil, 1, nil, nil, 5, nil, nil]
-$x.compact!
-test_ok($x == [1, 5])
-
-# uniq
-$x = [1, 1, 4, 2, 5, 4, 5, 1, 2]
-$x.uniq!
-test_ok($x == [1, 4, 2, 5])
-
-# empty?
-test_ok(!$x.empty?)
-$x = []
-test_ok($x.empty?)
-
-# sort
-$x = ["it", "came", "to", "pass", "that", "..."]
-$x = $x.sort.join(" ")
-test_ok($x == "... came it pass that to")
-$x = [2,5,3,1,7]
-$x.sort!{|a,b| a<=>b} # sort with condition
-test_ok($x == [1,2,3,5,7])
-$x.sort!{|a,b| b-a} # reverse sort
-test_ok($x == [7,5,3,2,1])
-
-# split test
-$x = "The Botest_ok of Mormon"
-test_ok($x.split(//).reverse!.join == $x.reverse)
-test_ok($x.reverse == $x.reverse!)
-test_ok("1 byte string".split(//).reverse.join(":") == "g:n:i:r:t:s: :e:t:y:b: :1")
-$x = "a b c d"
-test_ok($x.split == ['a', 'b', 'c', 'd'])
-test_ok($x.split(' ') == ['a', 'b', 'c', 'd'])
-test_ok(defined? "a".chomp)
-test_ok("abc".scan(/./) == ["a", "b", "c"])
-test_ok("1a2b3c".scan(/(\d.)/) == [["1a"], ["2b"], ["3c"]])
-# non-greedy match
-test_ok("a=12;b=22".scan(/(.*?)=(\d*);?/) == [["a", "12"], ["b", "22"]])
-
-$x = [1]
-test_ok(($x * 5).join(":") == '1:1:1:1:1')
-test_ok(($x * 1).join(":") == '1')
-test_ok(($x * 0).join(":") == '')
-
-*$x = (1..7).to_a
-test_ok($x.size == 7)
-test_ok($x == [1, 2, 3, 4, 5, 6, 7])
-
-$x = [1,2,3]
-$x[1,0] = $x
-test_ok($x == [1,1,2,3,2,3])
-
-$x = [1,2,3]
-$x[-1,0] = $x
-test_ok($x == [1,2,1,2,3,3])
-
-$x = [1,2,3]
-$x.concat($x)
-test_ok($x == [1,2,3,1,2,3])
-
-test_check "hash"
-$x = {1=>2, 2=>4, 3=>6}
-$y = {1, 2, 2, 4, 3, 6}
-
-test_ok($x[1] == 2)
-
-test_ok(begin
- for k,v in $y
- raise if k*2 != v
- end
- true
- rescue
- false
- end)
-
-test_ok($x.length == 3)
-test_ok($x.has_key?(1))
-test_ok($x.has_value?(4))
-test_ok($x.select(2,3) == [4,6])
-test_ok($x == {1=>2, 2=>4, 3=>6})
-
-$z = $y.keys.join(":")
-test_ok($z == "1:2:3")
-
-$z = $y.values.join(":")
-test_ok($z == "2:4:6")
-test_ok($x == $y)
-
-$y.shift
-test_ok($y.length == 2)
-
-$z = [1,2]
-$y[$z] = 256
-test_ok($y[$z] == 256)
-
-$x = Hash.new(0)
-$x[1] = 1
-test_ok($x[1] == 1)
-test_ok($x[2] == 0)
-
-$x = Hash.new([])
-test_ok($x[22] == [])
-test_ok($x[22].equal?($x[22]))
-
-$x = Hash.new{[]}
-test_ok($x[22] == [])
-test_ok(!$x[22].equal?($x[22]))
-
-$x = Hash.new{|h,k| $z = k; h[k] = k*2}
-$z = 0
-test_ok($x[22] == 44)
-test_ok($z == 22)
-$z = 0
-test_ok($x[22] == 44)
-test_ok($z == 0)
-$x.default = 5
-test_ok($x[23] == 5)
-
-$x = Hash.new
-def $x.default(k)
- $z = k
- self[k] = k*2
-end
-$z = 0
-test_ok($x[22] == 44)
-test_ok($z == 22)
-$z = 0
-test_ok($x[22] == 44)
-test_ok($z == 0)
-
-test_check "iterator"
-
-test_ok(!iterator?)
-
-def ttt
- test_ok(iterator?)
-end
-ttt{}
-
-# yield at top level
-test_ok(!defined?(yield))
-
-$x = [1, 2, 3, 4]
-$y = []
-
-# iterator over array
-for i in $x
- $y.push i
-end
-test_ok($x == $y)
-
-# nested iterator
-def tt
- 1.upto(10) {|i|
- yield i
- }
-end
-
-tt{|i| break if i == 5}
-test_ok(i == 5)
-
-def tt2(dummy)
- yield 1
-end
-
-def tt3(&block)
- tt2(raise(ArgumentError,""),&block)
-end
-
-$x = false
-begin
- tt3{}
-rescue ArgumentError
- $x = true
-rescue Exception
-end
-test_ok($x)
-
-# iterator break/redo/next/retry
-done = true
-loop{
- break
- done = false # should not reach here
-}
-test_ok(done)
-
-done = false
-$bad = false
-loop {
- break if done
- done = true
- next
- $bad = true # should not reach here
-}
-test_ok(!$bad)
-
-done = false
-$bad = false
-loop {
- break if done
- done = true
- redo
- $bad = true # should not reach here
-}
-test_ok(!$bad)
-
-$x = []
-for i in 1 .. 7
- $x.push i
-end
-test_ok($x.size == 7)
-test_ok($x == [1, 2, 3, 4, 5, 6, 7])
-
-$done = false
-$x = []
-for i in 1 .. 7 # see how retry works in iterator loop
- if i == 4 and not $done
- $done = true
- retry
- end
- $x.push(i)
-end
-test_ok($x.size == 10)
-test_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]]
-test_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
-
- def f(a)
- test_ok(a == [1])
- end
-end
-IterTest.new(nil).method(:f).to_proc.call([1])
-
-IterTest.new([0]).each0 { |x| $x = x }
-test_ok($x == 0)
-IterTest.new([1]).each1 { |x| $x = x }
-test_ok($x == 1)
-IterTest.new([2]).each2 { |x| $x = x }
-test_ok($x == [2])
-IterTest.new([3]).each3 { |x| $x = x }
-test_ok($x == 3)
-IterTest.new([4]).each4 { |x| $x = x }
-test_ok($x == 4)
-IterTest.new([5]).each5 { |x| $x = x }
-test_ok($x == 5)
-IterTest.new([6]).each6 { |x| $x = x }
-test_ok($x == [6])
-IterTest.new([7]).each7 { |x| $x = x }
-test_ok($x == 7)
-IterTest.new([8]).each8 { |x| $x = x }
-test_ok($x == 8)
-
-IterTest.new([[0]]).each0 { |x| $x = x }
-test_ok($x == [0])
-IterTest.new([[1]]).each1 { |x| $x = x }
-test_ok($x == 1)
-IterTest.new([[2]]).each2 { |x| $x = x }
-test_ok($x == [2])
-IterTest.new([[3]]).each3 { |x| $x = x }
-test_ok($x == 3)
-IterTest.new([[4]]).each4 { |x| $x = x }
-test_ok($x == [4])
-IterTest.new([[5]]).each5 { |x| $x = x }
-test_ok($x == 5)
-IterTest.new([[6]]).each6 { |x| $x = x }
-test_ok($x == [6])
-IterTest.new([[7]]).each7 { |x| $x = x }
-test_ok($x == 7)
-IterTest.new([[8]]).each8 { |x| $x = x }
-test_ok($x == [8])
-
-IterTest.new([[0,0]]).each0 { |x| $x = x }
-test_ok($x == [0,0])
-IterTest.new([[8,8]]).each8 { |x| $x = x }
-test_ok($x == [8,8])
-
-test_check "float"
-test_ok(2.6.floor == 2)
-test_ok(-2.6.floor == -3)
-test_ok(2.6.ceil == 3)
-test_ok(-2.6.ceil == -2)
-test_ok(2.6.truncate == 2)
-test_ok(-2.6.truncate == -2)
-test_ok(2.6.round == 3)
-test_ok(-2.4.truncate == -2)
-test_ok((13.4 % 1 - 0.4).abs < 0.0001)
-
-test_check "bignum"
-def fact(n)
- return 1 if n == 0
- f = 1
- while n>0
- f *= n
- n -= 1
- end
- return f
-end
-$x = fact(40)
-test_ok($x == $x)
-test_ok($x == fact(40))
-test_ok($x < $x+2)
-test_ok($x > $x-2)
-test_ok($x == 815915283247897734345611269596115894272000000000)
-test_ok($x != 815915283247897734345611269596115894272000000001)
-test_ok($x+1 == 815915283247897734345611269596115894272000000001)
-test_ok($x/fact(20) == 335367096786357081410764800000)
-$x = -$x
-test_ok($x == -815915283247897734345611269596115894272000000000)
-test_ok(2-(2**32) == -(2**32-2))
-test_ok(2**32 - 5 == (2**32-3)-2)
-
-$good = true;
-for i in 1000..1014
- $good = false if ((1<<i) != (2**i))
-end
-test_ok($good)
-
-$good = true;
-n1=1<<1000
-for i in 1000..1014
- $good = false if ((1<<i) != n1)
- n1 *= 2
-end
-test_ok($good)
-
-$good = true;
-n2=n1
-for i in 1..10
- n1 = n1 / 2
- n2 = n2 >> 1
- $good = false if (n1 != n2)
-end
-test_ok($good)
-
-$good = true;
-for i in 4000..4096
- n1 = 1 << i;
- if (n1**2-1) / (n1+1) != (n1-1)
- p i
- $good = false
- end
-end
-test_ok($good)
-
-b = 10**80
-a = b * 9 + 7
-test_ok(7 == a.modulo(b))
-test_ok(-b + 7 == a.modulo(-b))
-test_ok(b + -7 == (-a).modulo(b))
-test_ok(-7 == (-a).modulo(-b))
-test_ok(7 == a.remainder(b))
-test_ok(7 == a.remainder(-b))
-test_ok(-7 == (-a).remainder(b))
-test_ok(-7 == (-a).remainder(-b))
-
-test_ok(10**40+10**20 == 10000000000000000000100000000000000000000)
-test_ok(10**40/10**20 == 100000000000000000000)
-
-a = 677330545177305025495135714080
-b = 14269972710765292560
-test_ok(a % b == 0)
-test_ok(-a % b == 0)
-
-def shift_test(a)
- b = a / (2 ** 32)
- c = a >> 32
- test_ok(b == c)
-
- b = a * (2 ** 32)
- c = a << 32
- test_ok(b == c)
-end
-
-shift_test(-4518325415524767873)
-shift_test(-0xfffffffffffffffff)
-
-test_check "string & char"
-
-test_ok("abcd" == "abcd")
-test_ok("abcd" =~ "abcd")
-test_ok("abcd" === "abcd")
-# compile time string concatenation
-test_ok("ab" "cd" == "abcd")
-test_ok("#{22}aa" "cd#{44}" == "22aacd44")
-test_ok("#{22}aa" "cd#{44}" "55" "#{66}" == "22aacd445566")
-test_ok("abc" !~ /^$/)
-test_ok("abc\n" !~ /^$/)
-test_ok("abc" !~ /^d*$/)
-test_ok(("abc" =~ /d*$/) == 3)
-test_ok("" =~ /^$/)
-test_ok("\n" =~ /^$/)
-test_ok("a\n\n" =~ /^$/)
-test_ok("abcabc" =~ /.*a/ && $& == "abca")
-test_ok("abcabc" =~ /.*c/ && $& == "abcabc")
-test_ok("abcabc" =~ /.*?a/ && $& == "a")
-test_ok("abcabc" =~ /.*?c/ && $& == "abc")
-test_ok(/(.|\n)*?\n(b|\n)/ =~ "a\nb\n\n" && $& == "a\nb")
-
-test_ok(/^(ab+)+b/ =~ "ababb" && $& == "ababb")
-test_ok(/^(?:ab+)+b/ =~ "ababb" && $& == "ababb")
-test_ok(/^(ab+)+/ =~ "ababb" && $& == "ababb")
-test_ok(/^(?:ab+)+/ =~ "ababb" && $& == "ababb")
-
-test_ok(/(\s+\d+){2}/ =~ " 1 2" && $& == " 1 2")
-test_ok(/(?:\s+\d+){2}/ =~ " 1 2" && $& == " 1 2")
-
-$x = <<END;
-ABCD
-ABCD
-END
-$x.gsub!(/((.|\n)*?)B((.|\n)*?)D/){$1+$3}
-test_ok($x == "AC\nAC\n")
-
-test_ok("foobar" =~ /foo(?=(bar)|(baz))/)
-test_ok("foobaz" =~ /foo(?=(bar)|(baz))/)
-
-$foo = "abc"
-test_ok("#$foo = abc" == "abc = abc")
-test_ok("#{$foo} = abc" == "abc = abc")
-
-foo = "abc"
-test_ok("#{foo} = abc" == "abc = abc")
-
-test_ok('-' * 5 == '-----')
-test_ok('-' * 1 == '-')
-test_ok('-' * 0 == '')
-
-foo = '-'
-test_ok(foo * 5 == '-----')
-test_ok(foo * 1 == '-')
-test_ok(foo * 0 == '')
-
-$x = "a.gif"
-test_ok($x.sub(/.*\.([^\.]+)$/, '\1') == "gif")
-test_ok($x.sub(/.*\.([^\.]+)$/, 'b.\1') == "b.gif")
-test_ok($x.sub(/.*\.([^\.]+)$/, '\2') == "")
-test_ok($x.sub(/.*\.([^\.]+)$/, 'a\2b') == "ab")
-test_ok($x.sub(/.*\.([^\.]+)$/, '<\&>') == "<a.gif>")
-
-# character constants(assumes ASCII)
-test_ok("a"[0] == ?a)
-test_ok(?a == ?a)
-test_ok(?\C-a == 1)
-test_ok(?\M-a == 225)
-test_ok(?\M-\C-a == 129)
-test_ok("a".upcase![0] == ?A)
-test_ok("A".downcase![0] == ?a)
-test_ok("abc".tr!("a-z", "A-Z") == "ABC")
-test_ok("aabbcccc".tr_s!("a-z", "A-Z") == "ABC")
-test_ok("abcc".squeeze!("a-z") == "abc")
-test_ok("abcd".delete!("bc") == "ad")
-
-$x = "abcdef"
-$y = [ ?a, ?b, ?c, ?d, ?e, ?f ]
-$bad = false
-$x.each_byte {|i|
- if i != $y.shift
- $bad = true
- break
- end
-}
-test_ok(!$bad)
-
-s = "a string"
-s[0..s.size]="another string"
-test_ok(s == "another string")
-
-s = <<EOS
-#{
-[1,2,3].join(",")
-}
-EOS
-test_ok(s == "1,2,3\n")
-
-test_check "assignment"
-a = nil
-test_ok(defined?(a))
-test_ok(a == nil)
-
-# multiple asignment
-a, b = 1, 2
-test_ok(a == 1 && b == 2)
-
-a, b = b, a
-test_ok(a == 2 && b == 1)
-
-a, = 1,2
-test_ok(a == 1)
-
-a, *b = 1, 2, 3
-test_ok(a == 1 && b == [2, 3])
-
-a, (b, c), d = 1, [2, 3], 4
-test_ok(a == 1 && b == 2 && c == 3 && d == 4)
-
-*a = 1, 2, 3
-test_ok(a == [1, 2, 3])
-
-*a = 4
-test_ok(a == [4])
-
-*a = nil
-test_ok(a == [])
-
-test_check "call"
-def aaa(a, b=100, *rest)
- res = [a, b]
- res += rest if rest
- return res
-end
-
-# not enough argument
-begin
- aaa() # need at least 1 arg
- test_ok(false)
-rescue
- test_ok(true)
-end
-
-begin
- aaa # no arg given (exception raised)
- test_ok(false)
-rescue
- test_ok(true)
-end
-
-test_ok(aaa(1) == [1, 100])
-test_ok(aaa(1, 2) == [1, 2])
-test_ok(aaa(1, 2, 3, 4) == [1, 2, 3, 4])
-test_ok(aaa(1, *[2, 3, 4]) == [1, 2, 3, 4])
-
-test_check "proc"
-$proc = proc{|i| i}
-test_ok($proc.call(2) == 2)
-test_ok($proc.call(3) == 3)
-
-$proc = proc{|i| i*2}
-test_ok($proc.call(2) == 4)
-test_ok($proc.call(3) == 6)
-
-proc{
- iii=5 # nested local variable
- $proc = proc{|i|
- iii = i
- }
- $proc2 = proc {
- $x = iii # nested variables shared by procs
- }
- # scope of nested variables
- test_ok(defined?(iii))
-}.call
-test_ok(!defined?(iii)) # out of scope
-
-loop{iii=5; test_ok(eval("defined? iii")); break}
-loop {|iii|
- iii = 10
- def dyna_var_check
- loop {
- test_ok(!defined?(iii))
- break
- }
- end
- dyna_var_check
- break
-}
-$x=0
-$proc.call(5)
-$proc2.call
-test_ok($x == 5)
-
-if defined? Process.kill
- test_check "signal"
-
- $x = 0
- trap "SIGINT", proc{|sig| $x = 2}
- Process.kill "SIGINT", $$
- sleep 0.1
- test_ok($x == 2)
-
- trap "SIGINT", proc{raise "Interrupt"}
-
- x = false
- begin
- Process.kill "SIGINT", $$
- sleep 0.1
- rescue
- x = $!
- end
- test_ok(x && /Interrupt/ =~ x)
-end
-
-test_check "eval"
-test_ok(eval("") == nil)
-$bad=false
-eval 'while false; $bad = true; print "foo\n" end'
-test_ok(!$bad)
-
-test_ok(eval('TRUE'))
-test_ok(eval('true'))
-test_ok(!eval('NIL'))
-test_ok(!eval('nil'))
-test_ok(!eval('FALSE'))
-test_ok(!eval('false'))
-
-$foo = 'test_ok(true)'
-begin
- eval $foo
-rescue
- test_ok(false)
-end
-
-test_ok(eval("$foo") == 'test_ok(true)')
-test_ok(eval("true") == true)
-i = 5
-test_ok(eval("i == 5"))
-test_ok(eval("i") == 5)
-test_ok(eval("defined? i"))
-
-# eval with binding
-def test_ev
- local1 = "local1"
- lambda {
- local2 = "local2"
- return binding
- }.call
-end
-
-$x = test_ev
-test_ok(eval("local1", $x) == "local1") # normal local var
-test_ok(eval("local2", $x) == "local2") # nested local var
-$bad = true
-begin
- p eval("local1")
-rescue NameError # must raise error
- $bad = false
-end
-test_ok(!$bad)
-
-module EvTest
- EVTEST1 = 25
- evtest2 = 125
- $x = binding
-end
-test_ok(eval("EVTEST1", $x) == 25) # constant in module
-test_ok(eval("evtest2", $x) == 125) # local var in module
-$bad = true
-begin
- eval("EVTEST1")
-rescue NameError # must raise error
- $bad = false
-end
-test_ok(!$bad)
-
-x = proc{}
-eval "i4 = 1", x
-test_ok(eval("i4", x) == 1)
-x = proc{proc{}}.call
-eval "i4 = 22", x
-test_ok(eval("i4", x) == 22)
-$x = []
-x = proc{proc{}}.call
-eval "(0..9).each{|i5| $x[i5] = proc{i5*2}}", x
-test_ok($x[4].call == 8)
-
-x = binding
-eval "i = 1", x
-test_ok(eval("i", x) == 1)
-x = proc{binding}.call
-eval "i = 22", x
-test_ok(eval("i", x) == 22)
-$x = []
-x = proc{binding}.call
-eval "(0..9).each{|i5| $x[i5] = proc{i5*2}}", x
-test_ok($x[4].call == 8)
-x = proc{binding}.call
-eval "for i6 in 1..1; j6=i6; end", x
-test_ok(eval("defined? i6", x))
-test_ok(eval("defined? j6", x))
-
-proc {
- p = binding
- eval "foo11 = 1", p
- foo22 = 5
- proc{foo11=22}.call
- proc{foo22=55}.call
- test_ok(eval("foo11", p) == eval("foo11"))
- test_ok(eval("foo11") == 1)
- test_ok(eval("foo22", p) == eval("foo22"))
- test_ok(eval("foo22") == 55)
-}.call
-
-p1 = proc{i7 = 0; proc{i7}}.call
-test_ok(p1.call == 0)
-eval "i7=5", p1
-test_ok(p1.call == 5)
-test_ok(!defined?(i7))
-
-p1 = proc{i7 = 0; proc{i7}}.call
-i7 = nil
-test_ok(p1.call == 0)
-eval "i7=1", p1
-test_ok(p1.call == 1)
-eval "i7=5", p1
-test_ok(p1.call == 5)
-test_ok(i7 == nil)
-
-test_check "system"
-test_ok(`echo foobar` == "foobar\n")
-test_ok(`./miniruby -e 'print "foobar"'` == 'foobar')
-
-tmp = open("script_tmp", "w")
-tmp.print "print $zzz\n";
-tmp.close
-
-test_ok(`./miniruby -s script_tmp -zzz` == 'true')
-test_ok(`./miniruby -s script_tmp -zzz=555` == '555')
-
-tmp = open("script_tmp", "w")
-tmp.print "#! /usr/local/bin/ruby -s\n";
-tmp.print "print $zzz\n";
-tmp.close
-
-test_ok(`./miniruby script_tmp -zzz=678` == '678')
-
-tmp = open("script_tmp", "w")
-tmp.print "this is a leading junk\n";
-tmp.print "#! /usr/local/bin/ruby -s\n";
-tmp.print "print $zzz\n";
-tmp.print "__END__\n";
-tmp.print "this is a trailing junk\n";
-tmp.close
-
-test_ok(`./miniruby -x script_tmp` == 'nil')
-test_ok(`./miniruby -x script_tmp -zzz=555` == '555')
-
-tmp = open("script_tmp", "w")
-for i in 1..5
- tmp.print i, "\n"
-end
-tmp.close
-
-`./miniruby -i.bak -pe 'sub(/^[0-9]+$/){$&.to_i * 5}' script_tmp`
-done = true
-tmp = open("script_tmp", "r")
-while tmp.gets
- if $_.to_i % 5 != 0
- done = false
- break
- end
-end
-tmp.close
-test_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
-if (dir = File.dirname(File.dirname($0))) == '.'
- dir = ""
-else
- dir << "/"
-end
-for script in Dir["#{dir}{lib,sample,ext}/**/*.rb"]
- `./miniruby -c #{script}`
- unless $?
- $bad = true
- end
-end
-test_ok(!$bad)
-
-test_check "const"
-TEST1 = 1
-TEST2 = 2
-
-module Const
- TEST3 = 3
- TEST4 = 4
-end
-
-module Const2
- TEST3 = 6
- TEST4 = 8
-end
-
-include Const
-
-test_ok([TEST1,TEST2,TEST3,TEST4] == [1,2,3,4])
-
-include Const2
-STDERR.print "intentionally redefines TEST3, TEST4\n" if $VERBOSE
-test_ok([TEST1,TEST2,TEST3,TEST4] == [1,2,6,8])
-
-test_check "clone"
-foo = Object.new
-def foo.test
- "test"
-end
-bar = foo.clone
-def bar.test2
- "test2"
-end
-
-test_ok(bar.test2 == "test2")
-test_ok(bar.test == "test")
-test_ok(foo.test == "test")
-
-begin
- foo.test2
- test_ok false
-rescue NoMethodError
- test_ok true
-end
-
-module M001; end
-module M002; end
-module M003; include M002; end
-module M002; include M001; end
-module M003; include M002; end
-
-test_ok(M003.ancestors == [M003, M002, M001])
-
-test_check "marshal"
-$x = [1,2,3,[4,5,"foo"],{1=>"bar"},2.5,fact(30)]
-$y = Marshal.dump($x)
-test_ok($x == Marshal.load($y))
-
-StrClone=String.clone;
-test_ok(Marshal.load(Marshal.dump(StrClone.new("abc"))).type == StrClone)
-
-test_check "pack"
-
-$format = "c2x5CCxsdils_l_a6";
-# Need the expression in here to force ary[5] to be numeric. This avoids
-# test2 failing because ary2 goes str->numeric->str and ary does not.
-ary = [1,-100,127,128,32767,987.654321098 / 100.0,12345,123456,-32767,-123456,"abcdef"]
-$x = ary.pack($format)
-ary2 = $x.unpack($format)
-
-test_ok(ary.length == ary2.length)
-test_ok(ary.join(':') == ary2.join(':'))
-test_ok($x =~ /def/)
-
-test_check "math"
-test_ok(Math.sqrt(4) == 2)
-
-include Math
-test_ok(sqrt(4) == 2)
-
-test_check "struct"
-struct_test = Struct.new("Test", :foo, :bar)
-test_ok(struct_test == Struct::Test)
-
-test = struct_test.new(1, 2)
-test_ok(test.foo == 1 && test.bar == 2)
-test_ok(test[0] == 1 && test[1] == 2)
-
-a, b = test.to_a
-test_ok(a == 1 && b == 2)
-
-test[0] = 22
-test_ok(test.foo == 22)
-
-test.bar = 47
-test_ok(test.bar == 47)
-
-test_check "variable"
-test_ok($$.instance_of?(Fixnum))
-
-# read-only variable
-begin
- $$ = 5
- test_ok false
-rescue NameError
- test_ok true
-end
-
-foobar = "foobar"
-$_ = foobar
-test_ok($_ == foobar)
-
-class Gods
- @@rule = "Uranus"
- def ruler0
- @@rule
- end
-
- def self.ruler1 # <= per method definition style
- @@rule
- end
- class << self # <= multiple method definition style
- def ruler2
- @@rule
- end
- end
-end
-
-module Olympians
- @@rule ="Zeus"
- def ruler3
- @@rule
- end
-end
-
-class Titans < Gods
- @@rule = "Cronus"
- include Olympians # OK to cause warning (intentional)
-end
-
-test_ok(Gods.new.ruler0 == "Cronus")
-test_ok(Gods.ruler1 == "Cronus")
-test_ok(Gods.ruler2 == "Cronus")
-test_ok(Titans.ruler1 == "Cronus")
-test_ok(Titans.ruler2 == "Cronus")
-atlas = Titans.new
-test_ok(atlas.ruler0 == "Cronus")
-test_ok(atlas.ruler3 == "Zeus")
-
-test_check "trace"
-$x = 1234
-$y = 0
-trace_var :$x, proc{$y = $x}
-$x = 40414
-test_ok($y == $x)
-
-untrace_var :$x
-$x = 19660208
-test_ok($y != $x)
-
-trace_var :$x, proc{$x *= 2}
-$x = 5
-test_ok($x == 10)
-
-untrace_var :$x
-
-test_check "defined?"
-
-test_ok(defined?($x)) # global variable
-test_ok(defined?($x) == 'global-variable')# returns description
-
-foo=5
-test_ok(defined?(foo)) # local variable
-
-test_ok(defined?(Array)) # constant
-test_ok(defined?(Object.new)) # method
-test_ok(!defined?(Object.print))# private method
-test_ok(defined?(1 == 2)) # operator expression
-
-class Foo
- def foo
- p :foo
- end
- protected :foo
- def bar(f)
- test_ok(defined?(self.foo))
- test_ok(defined?(f.foo))
- end
-end
-f = Foo.new
-test_ok(defined?(f.foo) == nil)
-f.bar(f)
-
-def defined_test
- return !defined?(yield)
-end
-
-test_ok(defined_test) # not iterator
-test_ok(!defined_test{}) # called as iterator
-
-test_check "alias"
-class Alias0
- def foo; "foo" end
-end
-class Alias1<Alias0
- alias bar foo
- def foo; "foo+" + super end
-end
-class Alias2<Alias1
- alias baz foo
- undef foo
-end
-
-x = Alias2.new
-test_ok(x.bar == "foo")
-test_ok(x.baz == "foo+foo")
-
-# test_check for cache
-test_ok(x.baz == "foo+foo")
-
-class Alias3<Alias2
- def foo
- defined? super
- end
- def bar
- defined? super
- end
- def quux
- defined? super
- end
-end
-x = Alias3.new
-test_ok(!x.foo)
-test_ok(x.bar)
-test_ok(!x.quux)
-
-test_check "gc"
-begin
- 1.upto(10000) {
- tmp = [0,1,2,3,4,5,6,7,8,9]
- }
- tmp = nil
- test_ok true
-rescue
- test_ok false
-end
-class S
- def initialize(a)
- @a = a
- end
-end
-l=nil
-100000.times {
- l = S.new(l)
-}
-GC.start
-test_ok true # reach here or dumps core
-l = []
-100000.times {
- l.push([l])
-}
-GC.start
-test_ok true # reach here or dumps core
-
-if $failed > 0
- printf "test: %d failed %d\n", $ntest, $failed
-else
- printf "end of test(test: %d)\n", $ntest
-end
diff --git a/sample/time.rb b/sample/time.rb
deleted file mode 100644
index 1624fdf992..0000000000
--- a/sample/time.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-#! /usr/local/bin/ruby
-cmd = ARGV.join(" ")
-b = Time.now
-system(cmd)
-e = Time.now
-ut, st, cut, cst = Time.times.to_a
-total = (e - b).to_f
-printf STDERR, "%11.1f real %11.1f user %11.1f sys\n", total, cut, cst
diff --git a/sample/trojan.rb b/sample/trojan.rb
deleted file mode 100644
index 6e9b18f502..0000000000
--- a/sample/trojan.rb
+++ /dev/null
@@ -1,15 +0,0 @@
-#! /usr/local/bin/ruby
-
-path = ENV['PATH'].split(File::PATH_SEPARATOR)
-
-for dir in path
- if File.directory?(dir)
- for f in d = Dir.open(dir)
- fpath = dir+"/"+f
- if File.file?(fpath) && (File.stat(fpath).mode & 022) != 0
- printf("file %s is writable from other users\n", fpath)
- end
- end
- d.close
- end
-end
diff --git a/sample/tsvr.rb b/sample/tsvr.rb
deleted file mode 100644
index 8b019bdb71..0000000000
--- a/sample/tsvr.rb
+++ /dev/null
@@ -1,20 +0,0 @@
-# socket example - server side using thread
-# usage: ruby tsvr.rb
-
-require "socket"
-
-gs = TCPserver.open(0)
-addr = gs.addr
-addr.shift
-printf("server is on %s\n", addr.join(":"))
-
-while TRUE
- Thread.start(gs.accept) do |s|
- print(s, " is accepted\n")
- while s.gets
- s.write($_)
- end
- print(s, " is gone\n")
- s.close
- end
-end
diff --git a/sample/uumerge.rb b/sample/uumerge.rb
deleted file mode 100644
index 2576bcb864..0000000000
--- a/sample/uumerge.rb
+++ /dev/null
@@ -1,43 +0,0 @@
-#!/usr/bin/env ruby
-
-if ARGV[0] == "-c"
- out_stdout = 1
- ARGV.shift
-end
-
-$sawbegin = 0
-$sawend = 0
-
-while line = gets()
- if /^begin\s*(\d*)\s*(\S*)/ =~ line
- $mode, $file = $1, $2
- $sawbegin+=1
- if out_stdout
- out = STDOUT
- else
- out = open($file, "w") if $file != ""
- end
- out.binmode
- break
- end
-end
-
-raise "missing begin" unless $sawbegin
-
-out.binmode
-while line = gets()
- if /^end/ =~ line
- $sawend+=1
- out.close unless out_stdout
- File.chmod $mode.oct, $file unless out_stdout
- next
- end
- line.sub!(/[a-z]+$/, "") # handle stupid trailing lowercase letters
- next if /[a-z]/ =~ line
- next if !(((($_[0] - 32) & 077) + 2) / 3 == $_.length / 4)
- out << $_.unpack("u") if $sawbegin > $sawend
-end
-
-raise "missing end" if $sawbegin > $sawend
-raise "missing begin" if ! $sawbegin
-exit 0
diff --git a/signal.c b/signal.c
deleted file mode 100644
index c643fd48c2..0000000000
--- a/signal.c
+++ /dev/null
@@ -1,733 +0,0 @@
-/**********************************************************************
-
- signal.c -
-
- $Author$
- $Date$
- created at: Tue Dec 20 10:13:44 JST 1994
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
- Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
- Copyright (C) 2000 Information-technology Promotion Agency, Japan
-
-**********************************************************************/
-
-#include "ruby.h"
-#include "rubysig.h"
-#include <signal.h>
-#include <stdio.h>
-
-#ifdef __BEOS__
-#undef SIGBUS
-#endif
-
-#ifndef NSIG
-# ifdef DJGPP
-# define NSIG SIGMAX
-# else
-# define NSIG (_SIGMAX + 1) /* For QNX */
-# endif
-#endif
-
-static struct signals {
- char *signm;
- int signo;
-} siglist [] = {
-#ifdef SIGHUP
- "HUP", SIGHUP,
-#endif
-#ifdef SIGINT
- "INT", SIGINT,
-#endif
-#ifdef SIGQUIT
- "QUIT", SIGQUIT,
-#endif
-#ifdef SIGILL
- "ILL", SIGILL,
-#endif
-#ifdef SIGTRAP
- "TRAP", SIGTRAP,
-#endif
-#ifdef SIGIOT
- "IOT", SIGIOT,
-#endif
-#ifdef SIGABRT
- "ABRT", SIGABRT,
-#endif
-#ifdef SIGEMT
- "EMT", SIGEMT,
-#endif
-#ifdef SIGFPE
- "FPE", SIGFPE,
-#endif
-#ifdef SIGKILL
- "KILL", SIGKILL,
-#endif
-#ifdef SIGBUS
- "BUS", SIGBUS,
-#endif
-#ifdef SIGSEGV
- "SEGV", SIGSEGV,
-#endif
-#ifdef SIGSYS
- "SYS", SIGSYS,
-#endif
-#ifdef SIGPIPE
- "PIPE", SIGPIPE,
-#endif
-#ifdef SIGALRM
- "ALRM", SIGALRM,
-#endif
-#ifdef SIGTERM
- "TERM", SIGTERM,
-#endif
-#ifdef SIGURG
- "URG", SIGURG,
-#endif
-#ifdef SIGSTOP
- "STOP", SIGSTOP,
-#endif
-#ifdef SIGTSTP
- "TSTP", SIGTSTP,
-#endif
-#ifdef SIGCONT
- "CONT", SIGCONT,
-#endif
-#ifdef SIGCHLD
- "CHLD", SIGCHLD,
-#endif
-#ifdef SIGCLD
- "CLD", SIGCLD,
-#else
-# ifdef SIGCHLD
- "CLD", SIGCHLD,
-# endif
-#endif
-#ifdef SIGTTIN
- "TTIN", SIGTTIN,
-#endif
-#ifdef SIGTTOU
- "TTOU", SIGTTOU,
-#endif
-#ifdef SIGIO
- "IO", SIGIO,
-#endif
-#ifdef SIGXCPU
- "XCPU", SIGXCPU,
-#endif
-#ifdef SIGXFSZ
- "XFSZ", SIGXFSZ,
-#endif
-#ifdef SIGVTALRM
- "VTALRM", SIGVTALRM,
-#endif
-#ifdef SIGPROF
- "PROF", SIGPROF,
-#endif
-#ifdef SIGWINCH
- "WINCH", SIGWINCH,
-#endif
-#ifdef SIGUSR1
- "USR1", SIGUSR1,
-#endif
-#ifdef SIGUSR2
- "USR2", SIGUSR2,
-#endif
-#ifdef SIGLOST
- "LOST", SIGLOST,
-#endif
-#ifdef SIGMSG
- "MSG", SIGMSG,
-#endif
-#ifdef SIGPWR
- "PWR", SIGPWR,
-#endif
-#ifdef SIGPOLL
- "POLL", SIGPOLL,
-#endif
-#ifdef SIGDANGER
- "DANGER", SIGDANGER,
-#endif
-#ifdef SIGMIGRATE
- "MIGRATE", SIGMIGRATE,
-#endif
-#ifdef SIGPRE
- "PRE", SIGPRE,
-#endif
-#ifdef SIGGRANT
- "GRANT", SIGGRANT,
-#endif
-#ifdef SIGRETRACT
- "RETRACT", SIGRETRACT,
-#endif
-#ifdef SIGSOUND
- "SOUND", SIGSOUND,
-#endif
-#ifdef SIGINFO
- "INFO", SIGINFO,
-#endif
- NULL, 0,
-};
-
-static int
-signm2signo(nm)
- char *nm;
-{
- struct signals *sigs;
-
- for (sigs = siglist; sigs->signm; sigs++)
- if (strcmp(sigs->signm, nm) == 0)
- return sigs->signo;
- return 0;
-}
-
-static char*
-signo2signm(no)
- int no;
-{
- struct signals *sigs;
-
- for (sigs = siglist; sigs->signm; sigs++)
- if (sigs->signo == no)
- return sigs->signm;
- return 0;
-}
-
-VALUE
-rb_f_kill(argc, argv)
- int argc;
- VALUE *argv;
-{
- int negative = 0;
- int sig;
- int i;
- char *s;
-
- rb_secure(2);
- if (argc < 2)
- rb_raise(rb_eArgError, "wrong number of arguments -- kill(sig, pid...)");
- switch (TYPE(argv[0])) {
- case T_FIXNUM:
- sig = FIX2INT(argv[0]);
- break;
-
- case T_SYMBOL:
- s = rb_id2name(SYM2ID(argv[0]));
- if (!s) rb_raise(rb_eArgError, "bad signal");
- goto str_signal;
-
- case T_STRING:
- s = RSTRING(argv[0])->ptr;
- if (s[0] == '-') {
- negative++;
- s++;
- }
- str_signal:
- if (strncmp("SIG", s, 3) == 0)
- s += 3;
- if((sig = signm2signo(s)) == 0)
- rb_raise(rb_eArgError, "unsupported name `SIG%s'", s);
-
- if (negative)
- sig = -sig;
- break;
-
- default:
- {
- VALUE str;
-
- str = rb_check_convert_type(argv[0], T_STRING, "String", "to_str");
- if (!NIL_P(str)) {
- s = RSTRING(str)->ptr;
- goto str_signal;
- }
- rb_raise(rb_eArgError, "bad signal type %s",
- rb_class2name(CLASS_OF(argv[0])));
- }
- break;
- }
-
- if (sig < 0) {
- sig = -sig;
- for (i=1; i<argc; i++) {
- int pid = NUM2INT(argv[i]);
-#ifdef HAS_KILLPG
- if (killpg(pid, sig) < 0)
-#else
- if (kill(-pid, sig) < 0)
-#endif
- rb_sys_fail(0);
- }
- }
- else {
- for (i=1; i<argc; i++) {
- Check_Type(argv[i], T_FIXNUM);
- if (kill(FIX2INT(argv[i]), sig) < 0)
- rb_sys_fail(0);
- }
- }
- return INT2FIX(i-1);
-}
-
-static VALUE trap_list[NSIG];
-static rb_atomic_t trap_pending_list[NSIG];
-rb_atomic_t rb_trap_pending;
-rb_atomic_t rb_trap_immediate;
-int rb_prohibit_interrupt;
-
-void
-rb_gc_mark_trap_list()
-{
-#ifndef MACOS_UNUSE_SIGNAL
- int i;
-
- for (i=0; i<NSIG; i++) {
- if (trap_list[i])
- rb_gc_mark(trap_list[i]);
- }
-#endif /* MACOS_UNUSE_SIGNAL */
-}
-
-typedef RETSIGTYPE (*sighandler_t)_((int));
-
-#ifdef POSIX_SIGNAL
-static sighandler_t
-ruby_signal(signum, handler)
- int signum;
- sighandler_t handler;
-{
- struct sigaction sigact, old;
-
- sigact.sa_handler = handler;
- sigemptyset(&sigact.sa_mask);
- sigact.sa_flags = 0;
-#if defined(SA_RESTART)
- /* All other signals but VTALRM shall restart restartable syscall
- VTALRM will cause EINTR to syscall if interrupted.
- */
- if (signum != SIGVTALRM) {
- sigact.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
- }
-#endif
-#ifdef SA_NOCLDWAIT
- if (signum == SIGCHLD && handler == SIG_IGN)
- sigact.sa_flags |= SA_NOCLDWAIT;
-#endif
- sigaction(signum, &sigact, &old);
- return old.sa_handler;
-}
-
-void
-posix_signal(signum, handler)
- int signum;
- sighandler_t handler;
-{
- ruby_signal(signum, handler);
-}
-#else
-#define ruby_signal(sig,handler) signal((sig),(handler))
-#endif
-
-static void signal_exec _((int sig));
-static void
-signal_exec(sig)
- int sig;
-{
- if (trap_list[sig] == 0) {
- switch (sig) {
- case SIGINT:
- rb_thread_interrupt();
- break;
-#ifdef SIGHUP
- case SIGHUP:
-#endif
-#ifdef SIGQUIT
- case SIGQUIT:
-#endif
-#ifdef SIGALRM
- case SIGALRM:
-#endif
-#ifdef SIGUSR1
- case SIGUSR1:
-#endif
-#ifdef SIGUSR2
- case SIGUSR2:
-#endif
- rb_thread_signal_raise(signo2signm(sig));
- break;
- }
- }
- else {
- rb_thread_trap_eval(trap_list[sig], sig);
- }
-}
-
-static RETSIGTYPE sighandler _((int));
-static RETSIGTYPE
-sighandler(sig)
- int sig;
-{
-#ifdef NT
-#define IN_MAIN_CONTEXT(f, a) (win32_main_context(a, f) ? (void)0 : f(a))
-#else
-#define IN_MAIN_CONTEXT(f, a) f(a)
-#endif
-
- if (sig >= NSIG) {
- rb_bug("trap_handler: Bad signal %d", sig);
- }
-
-#if !defined(BSD_SIGNAL) && !defined(POSIX_SIGNAL)
- ruby_signal(sig, sighandler);
-#endif
-
- if (ATOMIC_TEST(rb_trap_immediate)) {
- IN_MAIN_CONTEXT(signal_exec, sig);
- ATOMIC_SET(rb_trap_immediate, 1);
- }
- else {
- ATOMIC_INC(rb_trap_pending);
- ATOMIC_INC(trap_pending_list[sig]);
- }
-}
-
-#ifdef SIGBUS
-static RETSIGTYPE sigbus _((int));
-static RETSIGTYPE
-sigbus(sig)
- int sig;
-{
- rb_bug("Bus Error");
-}
-#endif
-
-#ifdef SIGSEGV
-static RETSIGTYPE sigsegv _((int));
-static RETSIGTYPE
-sigsegv(sig)
- int sig;
-{
- rb_bug("Segmentation fault");
-}
-#endif
-
-#ifdef SIGPIPE
-static RETSIGTYPE sigpipe _((int));
-static RETSIGTYPE
-sigpipe(sig)
- int sig;
-{
- /* do nothing */
-}
-#endif
-
-void
-rb_trap_exit()
-{
-#ifndef MACOS_UNUSE_SIGNAL
- if (trap_list[0]) {
- VALUE trap_exit = trap_list[0];
-
- trap_list[0] = 0;
- rb_eval_cmd(trap_exit, rb_ary_new3(1, INT2FIX(0)), 0);
- }
-#endif
-}
-
-void
-rb_trap_exec()
-{
-#ifndef MACOS_UNUSE_SIGNAL
- int i;
-
- for (i=0; i<NSIG; i++) {
- if (trap_pending_list[i]) {
- trap_pending_list[i] = 0;
- signal_exec(i);
- }
- }
-#endif /* MACOS_UNUSE_SIGNAL */
- rb_trap_pending = 0;
-}
-
-struct trap_arg {
-#if !defined(NT)
-# ifdef HAVE_SIGPROCMASK
- sigset_t mask;
-# else
- int mask;
-# endif
-#endif
- VALUE sig, cmd;
-};
-
-# ifdef HAVE_SIGPROCMASK
-static sigset_t trap_last_mask;
-# else
-static int trap_last_mask;
-# endif
-
-static RETSIGTYPE sigexit _((int));
-static RETSIGTYPE
-sigexit(sig)
- int sig;
-{
- rb_exit(0);
-}
-
-static VALUE
-trap(arg)
- struct trap_arg *arg;
-{
- sighandler_t func;
- VALUE command, old;
- int sig;
- char *s;
-
- func = sighandler;
- command = arg->cmd;
- if (NIL_P(command)) {
- func = SIG_IGN;
- }
- else if (TYPE(command) == T_STRING) {
- SafeStringValue(command); /* taint check */
- if (RSTRING(command)->len == 0) {
- func = SIG_IGN;
- }
- else if (RSTRING(command)->len == 7) {
- if (strncmp(RSTRING(command)->ptr, "SIG_IGN", 7) == 0) {
- func = SIG_IGN;
- }
- else if (strncmp(RSTRING(command)->ptr, "SIG_DFL", 7) == 0) {
- func = SIG_DFL;
- }
- else if (strncmp(RSTRING(command)->ptr, "DEFAULT", 7) == 0) {
- func = SIG_DFL;
- }
- }
- else if (RSTRING(command)->len == 6) {
- if (strncmp(RSTRING(command)->ptr, "IGNORE", 6) == 0) {
- func = SIG_IGN;
- }
- }
- else if (RSTRING(command)->len == 4) {
- if (strncmp(RSTRING(command)->ptr, "EXIT", 4) == 0) {
- func = sigexit;
- }
- }
- }
- if (func == SIG_IGN || func == SIG_DFL) {
- command = 0;
- }
-
- switch (TYPE(arg->sig)) {
- case T_FIXNUM:
- sig = NUM2INT(arg->sig);
- break;
-
- case T_SYMBOL:
- s = rb_id2name(SYM2ID(arg->sig));
- if (!s) rb_raise(rb_eArgError, "bad signal");
- goto str_signal;
-
- case T_STRING:
- s = RSTRING(arg->sig)->ptr;
-
- str_signal:
- if (strncmp("SIG", s, 3) == 0)
- s += 3;
- sig = signm2signo(s);
- if (sig == 0 && strcmp(s, "EXIT") != 0)
- rb_raise(rb_eArgError, "unsupported signal SIG%s", s);
- }
-
- if (sig < 0 || sig > NSIG) {
- rb_raise(rb_eArgError, "invalid signal number (%d)", sig);
- }
-#if defined(HAVE_SETITIMER) && !defined(__BOW__)
- if (sig == SIGVTALRM) {
- rb_raise(rb_eArgError, "SIGVTALRM reserved for Thread; cannot set handler");
- }
-#endif
- if (func == SIG_DFL) {
- switch (sig) {
- case SIGINT:
-#ifdef SIGHUP
- case SIGHUP:
-#endif
-#ifdef SIGQUIT
- case SIGQUIT:
-#endif
-#ifdef SIGALRM
- case SIGALRM:
-#endif
-#ifdef SIGUSR1
- case SIGUSR1:
-#endif
-#ifdef SIGUSR2
- case SIGUSR2:
-#endif
- func = sighandler;
- break;
-#ifdef SIGBUS
- case SIGBUS:
- func = sigbus;
- break;
-#endif
-#ifdef SIGSEGV
- case SIGSEGV:
- func = sigsegv;
- break;
-#endif
-#ifdef SIGPIPE
- case SIGPIPE:
- func = sigpipe;
- break;
-#endif
- }
- }
- ruby_signal(sig, func);
- old = trap_list[sig];
- if (!old) old = Qnil;
-
- trap_list[sig] = command;
- /* enable at least specified signal. */
-#if !defined(NT)
-#ifdef HAVE_SIGPROCMASK
- sigdelset(&arg->mask, sig);
-#else
- arg->mask &= ~sigmask(sig);
-#endif
-#endif
- return old;
-}
-
-#if !defined(NT)
-static VALUE
-trap_ensure(arg)
- struct trap_arg *arg;
-{
- /* enable interrupt */
-#ifdef HAVE_SIGPROCMASK
- sigprocmask(SIG_SETMASK, &arg->mask, NULL);
-#else
- sigsetmask(arg->mask);
-#endif
- trap_last_mask = arg->mask;
- return 0;
-}
-#endif
-
-void
-rb_trap_restore_mask()
-{
-#if !defined(NT)
-# ifdef HAVE_SIGPROCMASK
- sigprocmask(SIG_SETMASK, &trap_last_mask, NULL);
-# else
- sigsetmask(trap_last_mask);
-# endif
-#endif
-}
-
-static VALUE
-sig_trap(argc, argv)
- int argc;
- VALUE *argv;
-{
- struct trap_arg arg;
-
- rb_secure(2);
- if (argc == 0 || argc > 2) {
- rb_raise(rb_eArgError, "wrong number of arguments -- trap(sig, cmd)/trap(sig){...}");
- }
-
- arg.sig = argv[0];
- if (argc == 1) {
- arg.cmd = rb_f_lambda();
- }
- else if (argc == 2) {
- arg.cmd = argv[1];
- }
-
- if (OBJ_TAINTED(arg.cmd)) {
- rb_raise(rb_eSecurityError, "Insecure: tainted signal trap");
- }
-#if !defined(NT)
- /* disable interrupt */
-# ifdef HAVE_SIGPROCMASK
- sigfillset(&arg.mask);
- sigprocmask(SIG_BLOCK, &arg.mask, &arg.mask);
-# else
- arg.mask = sigblock(~0);
-# endif
-
- return rb_ensure(trap, (VALUE)&arg, trap_ensure, (VALUE)&arg);
-#else
- return trap(&arg);
-#endif
-}
-
-static VALUE
-sig_list()
-{
- VALUE h = rb_hash_new();
- struct signals *sigs;
-
- for (sigs = siglist; sigs->signm; sigs++) {
- rb_hash_aset(h, rb_str_new2(sigs->signm), INT2FIX(sigs->signo));
- }
- return h;
-}
-
-static void
-install_sighandler(signum, handler)
- int signum;
- sighandler_t handler;
-{
- sighandler_t old;
-
- old = ruby_signal(signum, handler);
- if (old != SIG_DFL) {
- ruby_signal(signum, old);
- }
-}
-
-void
-Init_signal()
-{
-#ifndef MACOS_UNUSE_SIGNAL
- VALUE mSignal = rb_define_module("Signal");
-
- rb_define_global_function("trap", sig_trap, -1);
- rb_define_module_function(mSignal, "trap", sig_trap, -1);
- rb_define_module_function(mSignal, "list", sig_list, 0);
-
- install_sighandler(SIGINT, sighandler);
-#ifdef SIGHUP
- install_sighandler(SIGHUP, sighandler);
-#endif
-#ifdef SIGQUIT
- install_sighandler(SIGQUIT, sighandler);
-#endif
-#ifdef SIGALRM
- install_sighandler(SIGALRM, sighandler);
-#endif
-#ifdef SIGUSR1
- install_sighandler(SIGUSR1, sighandler);
-#endif
-#ifdef SIGUSR2
- install_sighandler(SIGUSR2, sighandler);
-#endif
-
-#ifdef SIGBUS
- install_sighandler(SIGBUS, sigbus);
-#endif
-#ifdef SIGSEGV
- install_sighandler(SIGSEGV, sigsegv);
-#endif
-#ifdef SIGPIPE
- install_sighandler(SIGPIPE, sigpipe);
-#endif
-#endif /* MACOS_UNUSE_SIGNAL */
-}
diff --git a/sprintf.c b/sprintf.c
deleted file mode 100644
index 2355a65f9c..0000000000
--- a/sprintf.c
+++ /dev/null
@@ -1,655 +0,0 @@
-/**********************************************************************
-
- sprintf.c -
-
- $Author$
- $Date$
- created at: Fri Oct 15 10:39:26 JST 1993
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
- Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
- Copyright (C) 2000 Information-technology Promotion Agency, Japan
-
-**********************************************************************/
-
-#include "ruby.h"
-#include <ctype.h>
-#include <math.h>
-
-#define BIT_DIGITS(N) (((N)*146)/485 + 1) /* log2(10) =~ 146/485 */
-
-static void fmt_setup _((char*,int,int,int,int));
-
-static char*
-remove_sign_bits(str, base)
- char *str;
- int base;
-{
- char *s, *t, *end;
-
- s = t = str;
- end = str + strlen(str);
-
- if (base == 16) {
- x_retry:
- switch (*t) {
- case 'c': case 'C':
- *t = '4';
- break;
- case 'd': case 'D':
- *t = '5';
- break;
- case 'e': case 'E':
- *t = '2';
- break;
- case 'f': case 'F':
- if (t[1] > '8') {
- t++;
- goto x_retry;
- }
- *t = '1';
- break;
- case '1':
- case '3':
- case '7':
- if (t[1] > '8') {
- t++;
- goto x_retry;
- }
- break;
- }
- switch (*t) {
- case '1': *t = 'f'; break;
- case '2': *t = 'e'; break;
- case '3': *t = 'f'; break;
- case '4': *t = 'c'; break;
- case '5': *t = 'd'; break;
- case '6': *t = 'e'; break;
- case '7': *t = 'f'; break;
- }
- }
- else if (base == 8) {
- o_retry:
- switch (*t) {
- case '6':
- *t = '2';
- break;
- case '7':
- if (t[1] > '3') {
- t++;
- goto o_retry;
- }
- *t = '1';
- break;
- case '1':
- case '3':
- if (t[1] > '3') {
- t++;
- goto o_retry;
- }
- break;
- }
- switch (*t) {
- case '1': *t = '7'; break;
- case '2': *t = '6'; break;
- case '3': *t = '7'; break;
- }
- }
- else if (base == 2) {
- while (t<end && *t == '1') t++;
- t--;
- }
- while (*t) *s++ = *t++;
- *s = '\0';
-
- return str;
-}
-
-#define FNONE 0
-#define FSHARP 1
-#define FMINUS 2
-#define FPLUS 4
-#define FZERO 8
-#define FSPACE 16
-#define FWIDTH 32
-#define FPREC 64
-
-#define CHECK(l) {\
- while (blen + (l) >= bsiz) {\
- REALLOC_N(buf, char, bsiz*2);\
- bsiz*=2;\
- }\
-}
-
-#define PUSH(s, l) { \
- CHECK(l);\
- memcpy(&buf[blen], s, l);\
- blen += (l);\
-}
-
-#define GETARG() \
- ((nextarg >= argc) ? (rb_raise(rb_eArgError, "too few argument."), 0) : argv[nextarg++])
-
-#define GETASTER(val) { \
- t = p++; \
- n = 0; \
- for (; p < end && ISDIGIT(*p); p++) { \
- n = 10 * n + (*p - '0'); \
- } \
- if (p >= end) { \
- rb_raise(rb_eArgError, "malformed format string - %%*[0-9]"); \
- } \
- if (*p == '$') { \
- int curarg = nextarg; \
- nextarg = n; \
- tmp = GETARG(); \
- nextarg = curarg; \
- } \
- else { \
- tmp = GETARG(); \
- p = t; \
- } \
- val = NUM2INT(tmp); \
-}
-
-VALUE
-rb_f_sprintf(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE fmt;
- char *buf, *p, *end;
- int blen, bsiz;
- VALUE result;
-
- int width, prec, flags = FNONE;
- int nextarg = 0;
- int tainted = 0;
- VALUE tmp;
- VALUE str;
-
- fmt = GETARG();
- if (OBJ_TAINTED(fmt)) tainted = 1;
- StringValue(fmt);
- p = RSTRING(fmt)->ptr;
- end = p + RSTRING(fmt)->len;
- blen = 0;
- bsiz = 120;
- buf = ALLOC_N(char, bsiz);
-
- for (; p < end; p++) {
- char *t;
- int n;
-
- for (t = p; t < end && *t != '%'; t++) ;
- PUSH(p, t - p);
- if (t >= end) {
- /* end of fmt string */
- goto sprint_exit;
- }
- p = t + 1; /* skip `%' */
-
- width = prec = -1;
- retry:
- switch (*p) {
- default:
- if (ISPRINT(*p))
- rb_raise(rb_eArgError, "malformed format string - %%%c", *p);
- else
- rb_raise(rb_eArgError, "malformed format string");
- break;
-
- case ' ':
- flags |= FSPACE;
- p++;
- goto retry;
-
- case '#':
- flags |= FSHARP;
- p++;
- goto retry;
-
- case '+':
- flags |= FPLUS;
- p++;
- goto retry;
-
- case '-':
- flags |= FMINUS;
- p++;
- goto retry;
-
- case '0':
- flags |= FZERO;
- p++;
- goto retry;
-
- case '1': case '2': case '3': case '4':
- case '5': case '6': case '7': case '8': case '9':
- n = 0;
- for (; p < end && ISDIGIT(*p); p++) {
- n = 10 * n + (*p - '0');
- }
- if (p >= end) {
- rb_raise(rb_eArgError, "malformed format string - %%[0-9]");
- }
- if (*p == '$') {
- nextarg = n;
- p++;
- goto retry;
- }
- width = n;
- flags |= FWIDTH;
- goto retry;
-
- case '*':
- if (flags & FWIDTH) {
- rb_raise(rb_eArgError, "width given twice");
- }
-
- flags |= FWIDTH;
- GETASTER(width);
- if (width < 0) {
- flags |= FMINUS;
- width = -width;
- }
- p++;
- goto retry;
-
- case '.':
- if (flags & FPREC) {
- rb_raise(rb_eArgError, "precision given twice");
- }
- flags |= FPREC;
-
- prec = 0;
- p++;
- if (*p == '*') {
- GETASTER(prec);
- if (prec < 0) { /* ignore negative precision */
- flags &= ~FPREC;
- }
- p++;
- goto retry;
- }
-
- for (; p < end && ISDIGIT(*p); p++) {
- prec = 10 * prec + (*p - '0');
- }
- if (p >= end) {
- rb_raise(rb_eArgError, "malformed format string - %%.[0-9]");
- }
- goto retry;
-
- case '\n':
- p--;
- case '\0':
- case '%':
- if (flags != FNONE) {
- rb_raise(rb_eArgError, "illegal format character - %%");
- }
- PUSH("%", 1);
- break;
-
- case 'c':
- {
- VALUE val = GETARG();
- char c;
-
- if (!(flags & FMINUS))
- while (--width > 0)
- PUSH(" ", 1);
- c = NUM2INT(val) & 0xff;
- PUSH(&c, 1);
- while (--width > 0)
- PUSH(" ", 1);
- }
- break;
-
- case 's':
- {
- VALUE arg = GETARG();
- int len;
-
- str = rb_obj_as_string(arg);
- if (OBJ_TAINTED(str)) tainted = 1;
- len = RSTRING(str)->len;
- if (flags&FPREC) {
- if (prec < len) {
- len = prec;
- }
- }
- if (flags&FWIDTH) {
- if (width > len) {
- CHECK(width);
- width -= len;
- if (!(flags&FMINUS)) {
- while (width--) {
- buf[blen++] = ' ';
- }
- }
- memcpy(&buf[blen], RSTRING(str)->ptr, len);
- blen += len;
- if (flags&FMINUS) {
- while (width--) {
- buf[blen++] = ' ';
- }
- }
- break;
- }
- }
- PUSH(RSTRING(str)->ptr, len);
- }
- break;
-
- case 'd':
- case 'i':
- case 'o':
- case 'x':
- case 'X':
- case 'b':
- case 'B':
- case 'u':
- {
- volatile VALUE val = GETARG();
- char fbuf[32], nbuf[64], *s, *t;
- char *prefix = 0;
- int sign = 0;
- char sc = 0;
- long v;
- int base, bignum = 0;
- int len, pos;
-
- switch (*p) {
- case 'd':
- case 'i':
- sign = 1; break;
- case 'o':
- case 'x':
- case 'X':
- case 'b':
- case 'B':
- case 'u':
- default:
- if (flags&(FPLUS|FSPACE)) sign = 1;
- break;
- }
- if (flags & FSHARP) {
- if (*p == 'o') prefix = "0";
- else if (*p == 'x') prefix = "0x";
- else if (*p == 'X') prefix = "0X";
- else if (*p == 'b') prefix = "0b";
- else if (*p == 'B') prefix = "0B";
- if (prefix) {
- width -= strlen(prefix);
- }
- }
-
- bin_retry:
- switch (TYPE(val)) {
- case T_FLOAT:
- val = rb_dbl2big(RFLOAT(val)->value);
- if (FIXNUM_P(val)) goto bin_retry;
- bignum = 1;
- break;
- case T_STRING:
- val = rb_str_to_inum(val, 0, Qtrue);
- goto bin_retry;
- case T_BIGNUM:
- bignum = 1;
- break;
- default:
- v = NUM2LONG(val);
- break;
- case T_FIXNUM:
- v = FIX2LONG(val);
- break;
- }
-
- if (*p == 'u' || *p == 'd' || *p == 'i') base = 10;
- else if (*p == 'x' || *p == 'X') base = 16;
- else if (*p == 'o') base = 8;
- else if (*p == 'b' || *p == 'B') base = 2;
- if (!bignum) {
- if (base == 2) {
- val = rb_int2big(v);
- goto bin_retry;
- }
- if (sign) {
- char c = *p;
- if (c == 'i') c = 'd'; /* %d and %i are identical */
- if (v < 0) {
- v = -v;
- sc = '-';
- width--;
- }
- else if (flags & FPLUS) {
- sc = '+';
- width--;
- }
- else if (flags & FSPACE) {
- sc = ' ';
- width--;
- }
- sprintf(fbuf, "%%l%c", c);
- sprintf(nbuf, fbuf, v);
- s = nbuf;
- goto format_integer;
- }
- s = nbuf;
- if (v < 0) {
- strcpy(s, "..");
- s += 2;
- }
- sprintf(fbuf, "%%l%c", *p);
- sprintf(s, fbuf, v);
- if (v < 0) {
- char d = 0;
-
- remove_sign_bits(s, base);
- switch (base) {
- case 16:
- d = 'f';
- break;
- case 8:
- d = '7'; break;
- }
- if (d && *s != d) {
- memmove(s+1, s, strlen(s)+1);
- *s = d;
- }
- }
- s = nbuf;
- goto format_integer;
- }
-
- if (sign) {
- val = rb_big2str(val, base);
- s = RSTRING(val)->ptr;
- if (s[0] == '-') {
- s++;
- sc = '-';
- width--;
- }
- else if (flags & FPLUS) {
- sc = '+';
- width--;
- }
- else if (flags & FSPACE) {
- sc = ' ';
- width--;
- }
- goto format_integer;
- }
- if (!RBIGNUM(val)->sign) {
- val = rb_big_clone(val);
- rb_big_2comp(val);
- }
- val = rb_big2str(val, base);
- s = RSTRING(val)->ptr;
- if (*s == '-') {
- remove_sign_bits(++s, base);
- val = rb_str_new(0, 3+strlen(s));
- t = RSTRING(val)->ptr;
- strcpy(t, "..");
- t += 2;
- switch (base) {
- case 16:
- if (s[0] != 'f') strcpy(t++, "f"); break;
- case 8:
- if (s[0] != '7') strcpy(t++, "7"); break;
- }
- strcpy(t, s);
- bignum = 2;
- }
- s = RSTRING(val)->ptr;
-
- format_integer:
- pos = -1;
- len = strlen(s);
-
- if (*p == 'X') {
- char *pp = s;
- while (*pp) {
- *pp = toupper(*pp);
- pp++;
- }
- }
- if (prec < len) prec = len;
- width -= prec;
- if (!(flags&(FZERO|FMINUS)) && s[0] != '.') {
- CHECK(width);
- while (width-->0) {
- buf[blen++] = ' ';
- }
- }
- if (sc) PUSH(&sc, 1);
- if (prefix) {
- int plen = strlen(prefix);
- PUSH(prefix, plen);
- if (pos) pos += plen;
- }
- if (!(flags & FMINUS)) {
- char c = ' ';
-
- if (s[0] == '.') {
- c = '.';
- if ((flags & FPREC) && prec > len) {
- pos = blen;
- }
- else {
- pos = blen + 2;
- }
- }
- else if (flags & FZERO) c = '0';
- CHECK(width);
- while (width-->0) {
- buf[blen++] = c;
- }
- }
- CHECK(prec - len);
- while (len < prec--) {
- buf[blen++] = s[0]=='.'?'.':'0';
- }
- PUSH(s, len);
- CHECK(width);
- while (width-->0) {
- buf[blen++] = ' ';
- }
- if (pos >= 0 && buf[pos] == '.') {
- char c = '.';
-
- switch (base) {
- case 16:
- if (*p == 'X') c = 'F';
- else c = 'f';
- break;
- case 8:
- c = '7'; break;
- case 2:
- c = '1'; break;
- }
- s = &buf[pos];
- while (*s && *s == '.') {
- *s++ = c;
- }
- }
- }
- break;
-
- case 'f':
- case 'g':
- case 'G':
- case 'e':
- case 'E':
- {
- VALUE val = GETARG();
- double fval;
- int i, need = 6;
- char fbuf[32];
-
- fval = RFLOAT(rb_Float(val))->value;
- fmt_setup(fbuf, *p, flags, width, prec);
- need = 0;
- if (*p != 'e' && *p != 'E') {
- i = INT_MIN;
- frexp(fval, &i);
- if (i > 0)
- need = BIT_DIGITS(i);
- }
- need += (flags&FPREC) ? prec : 6;
- if ((flags&FWIDTH) && need < width)
- need = width;
- need += 20;
-
- CHECK(need);
- sprintf(&buf[blen], fbuf, fval);
- blen += strlen(&buf[blen]);
- }
- break;
- }
- flags = FNONE;
- }
-
- sprint_exit:
-#if 0
- /* XXX - We cannot validiate the number of arguments because
- * the format string may contain `n$'-style argument selector.
- */
- if (RTEST(ruby_verbose) && nextarg < argc) {
- rb_raise(rb_eArgError, "too many argument for format string");
- }
-#endif
- result = rb_str_new(buf, blen);
- free(buf);
-
- if (tainted) OBJ_TAINT(result);
- return result;
-}
-
-static void
-fmt_setup(buf, c, flags, width, prec)
- char *buf;
- int c;
- int flags, width, prec;
-{
- *buf++ = '%';
- if (flags & FSHARP) *buf++ = '#';
- if (flags & FPLUS) *buf++ = '+';
- if (flags & FMINUS) *buf++ = '-';
- if (flags & FZERO) *buf++ = '0';
- if (flags & FSPACE) *buf++ = ' ';
-
- if (flags & FWIDTH) {
- sprintf(buf, "%d", width);
- buf += strlen(buf);
- }
-
- if (flags & FPREC) {
- sprintf(buf, ".%d", prec);
- buf += strlen(buf);
- }
-
- *buf++ = c;
- *buf = '\0';
-}
diff --git a/st.c b/st.c
deleted file mode 100644
index ebf398fd79..0000000000
--- a/st.c
+++ /dev/null
@@ -1,563 +0,0 @@
-/* This is a public domain general purpose hash table package written by Peter Moore @ UCB. */
-
-static char sccsid[] = "@(#) st.c 5.1 89/12/14 Crucible";
-
-#include "config.h"
-#include <stdio.h>
-#include "st.h"
-
-#ifdef NT
-#include <malloc.h>
-#endif
-
-typedef struct st_table_entry st_table_entry;
-
-struct st_table_entry {
- unsigned int hash;
- char *key;
- char *record;
- st_table_entry *next;
-};
-
-#define ST_DEFAULT_MAX_DENSITY 5
-#define ST_DEFAULT_INIT_TABLE_SIZE 11
-
- /*
- * DEFAULT_MAX_DENSITY is the default for the largest we allow the
- * average number of items per bin before increasing the number of
- * bins
- *
- * DEFAULT_INIT_TABLE_SIZE is the default for the number of bins
- * allocated initially
- *
- */
-static int numcmp();
-static int numhash();
-static struct st_hash_type type_numhash = {
- numcmp,
- numhash,
-};
-
-extern int strcmp();
-static int strhash();
-static struct st_hash_type type_strhash = {
- strcmp,
- strhash,
-};
-
-#ifdef RUBY_PLATFORM
-#define xmalloc ruby_xmalloc
-#define xcalloc ruby_xcalloc
-#define xrealloc ruby_xrealloc
-#define xfree ruby_xfree
-
-void *xmalloc();
-void *xcalloc();
-void *xrealloc();
-void xfree();
-#endif
-
-static void rehash();
-
-#define alloc(type) (type*)xmalloc((unsigned)sizeof(type))
-#define Calloc(n,s) (char*)xcalloc((n),(s))
-
-#define EQUAL(table,x,y) ((x)==(y) || (*table->type->compare)((x),(y)) == 0)
-
-#define do_hash(key,table) (unsigned int)(*(table)->type->hash)((key))
-#define do_hash_bin(key,table) (do_hash(key, table)%(table)->num_bins)
-
-/*
- * MINSIZE is the minimum size of a dictionary.
- */
-
-#define MINSIZE 8
-
-/*
-Table of prime numbers 2^n+a, 2<=n<=30.
-*/
-static long primes[] = {
- 8 + 3,
- 16 + 3,
- 32 + 5,
- 64 + 3,
- 128 + 3,
- 256 + 27,
- 512 + 9,
- 1024 + 9,
- 2048 + 5,
- 4096 + 3,
- 8192 + 27,
- 16384 + 43,
- 32768 + 3,
- 65536 + 45,
- 131072 + 29,
- 262144 + 3,
- 524288 + 21,
- 1048576 + 7,
- 2097152 + 17,
- 4194304 + 15,
- 8388608 + 9,
- 16777216 + 43,
- 33554432 + 35,
- 67108864 + 15,
- 134217728 + 29,
- 268435456 + 3,
- 536870912 + 11,
- 1073741824 + 85,
- 0
-};
-
-static int
-new_size(size)
- int size;
-{
- int i;
-
-#if 0
- for (i=3; i<31; i++) {
- if ((1<<i) > size) return 1<<i;
- }
- return -1;
-#else
- int newsize;
-
- for (i = 0, newsize = MINSIZE;
- i < sizeof(primes)/sizeof(primes[0]);
- i++, newsize <<= 1)
- {
- if (newsize > size) return primes[i];
- }
- /* Ran out of polynomials */
- return -1; /* should raise exception */
-#endif
-}
-
-#ifdef HASH_LOG
-static int collision = 0;
-static int init_st = 0;
-
-static void
-stat_col()
-{
- FILE *f = fopen("/tmp/col", "w");
- fprintf(f, "collision: %d\n", collision);
- fclose(f);
-}
-#endif
-
-st_table*
-st_init_table_with_size(type, size)
- struct st_hash_type *type;
- int size;
-{
- st_table *tbl;
-
-#ifdef HASH_LOG
- if (init_st == 0) {
- init_st = 1;
- atexit(stat_col);
- }
-#endif
-
- size = new_size(size); /* round up to prime number */
-
- tbl = alloc(st_table);
- tbl->type = type;
- tbl->num_entries = 0;
- tbl->num_bins = size;
- tbl->bins = (st_table_entry **)Calloc(size, sizeof(st_table_entry*));
-
- return tbl;
-}
-
-st_table*
-st_init_table(type)
- struct st_hash_type *type;
-{
- return st_init_table_with_size(type, 0);
-}
-
-st_table*
-st_init_numtable()
-{
- return st_init_table(&type_numhash);
-}
-
-st_table*
-st_init_numtable_with_size(size)
- int size;
-{
- return st_init_table_with_size(&type_numhash, size);
-}
-
-st_table*
-st_init_strtable()
-{
- return st_init_table(&type_strhash);
-}
-
-st_table*
-st_init_strtable_with_size(size)
- int size;
-{
- return st_init_table_with_size(&type_strhash, size);
-}
-
-void
-st_free_table(table)
- st_table *table;
-{
- register st_table_entry *ptr, *next;
- int i;
-
- for(i = 0; i < table->num_bins; i++) {
- ptr = table->bins[i];
- while (ptr != 0) {
- next = ptr->next;
- free(ptr);
- ptr = next;
- }
- }
- free(table->bins);
- free(table);
-}
-
-#define PTR_NOT_EQUAL(table, ptr, hash_val, key) \
-((ptr) != 0 && (ptr->hash != (hash_val) || !EQUAL((table), (key), (ptr)->key)))
-
-#ifdef HASH_LOG
-#define COLLISION collision++
-#else
-#define COLLISION
-#endif
-
-#define FIND_ENTRY(table, ptr, hash_val, bin_pos) \
-bin_pos = hash_val%(table)->num_bins;\
-ptr = (table)->bins[bin_pos];\
-if (PTR_NOT_EQUAL(table, ptr, hash_val, key)) {\
- COLLISION;\
- while (PTR_NOT_EQUAL(table, ptr->next, hash_val, key)) {\
- ptr = ptr->next;\
- }\
- ptr = ptr->next;\
-}
-
-int
-st_lookup(table, key, value)
- st_table *table;
- register char *key;
- char **value;
-{
- unsigned int hash_val, bin_pos;
- register st_table_entry *ptr;
-
- hash_val = do_hash(key, table);
- FIND_ENTRY(table, ptr, hash_val, bin_pos);
-
- if (ptr == 0) {
- return 0;
- }
- else {
- if (value != 0) *value = ptr->record;
- return 1;
- }
-}
-
-#define ADD_DIRECT(table, key, value, hash_val, bin_pos)\
-{\
- st_table_entry *entry;\
- if (table->num_entries/(table->num_bins) > ST_DEFAULT_MAX_DENSITY) {\
- rehash(table);\
- bin_pos = hash_val % table->num_bins;\
- }\
- \
- entry = alloc(st_table_entry);\
- \
- entry->hash = hash_val;\
- entry->key = key;\
- entry->record = value;\
- entry->next = table->bins[bin_pos];\
- table->bins[bin_pos] = entry;\
- table->num_entries++;\
-}
-
-int
-st_insert(table, key, value)
- register st_table *table;
- register char *key;
- char *value;
-{
- unsigned int hash_val, bin_pos;
- register st_table_entry *ptr;
-
- hash_val = do_hash(key, table);
- FIND_ENTRY(table, ptr, hash_val, bin_pos);
-
- if (ptr == 0) {
- ADD_DIRECT(table, key, value, hash_val, bin_pos);
- return 0;
- }
- else {
- ptr->record = value;
- return 1;
- }
-}
-
-void
-st_add_direct(table, key, value)
- st_table *table;
- char *key;
- char *value;
-{
- unsigned int hash_val, bin_pos;
-
- hash_val = do_hash(key, table);
- bin_pos = hash_val % table->num_bins;
- ADD_DIRECT(table, key, value, hash_val, bin_pos);
-}
-
-static void
-rehash(table)
- register st_table *table;
-{
- register st_table_entry *ptr, *next, **new_bins;
- int i, old_num_bins = table->num_bins, new_num_bins;
- unsigned int hash_val;
-
- new_num_bins = new_size(old_num_bins+1);
- new_bins = (st_table_entry**)Calloc(new_num_bins, sizeof(st_table_entry*));
-
- for(i = 0; i < old_num_bins; i++) {
- ptr = table->bins[i];
- while (ptr != 0) {
- next = ptr->next;
- hash_val = ptr->hash % new_num_bins;
- ptr->next = new_bins[hash_val];
- new_bins[hash_val] = ptr;
- ptr = next;
- }
- }
- free(table->bins);
- table->num_bins = new_num_bins;
- table->bins = new_bins;
-}
-
-st_table*
-st_copy(old_table)
- st_table *old_table;
-{
- st_table *new_table;
- st_table_entry *ptr, *entry;
- int i, num_bins = old_table->num_bins;
-
- new_table = alloc(st_table);
- if (new_table == 0) {
- return 0;
- }
-
- *new_table = *old_table;
- new_table->bins = (st_table_entry**)
- Calloc((unsigned)num_bins, sizeof(st_table_entry*));
-
- if (new_table->bins == 0) {
- free(new_table);
- return 0;
- }
-
- for(i = 0; i < num_bins; i++) {
- new_table->bins[i] = 0;
- ptr = old_table->bins[i];
- while (ptr != 0) {
- entry = alloc(st_table_entry);
- if (entry == 0) {
- free(new_table->bins);
- free(new_table);
- return 0;
- }
- *entry = *ptr;
- entry->next = new_table->bins[i];
- new_table->bins[i] = entry;
- ptr = ptr->next;
- }
- }
- return new_table;
-}
-
-int
-st_delete(table, key, value)
- register st_table *table;
- register char **key;
- char **value;
-{
- unsigned int hash_val;
- st_table_entry *tmp;
- register st_table_entry *ptr;
-
- hash_val = do_hash_bin(*key, table);
- ptr = table->bins[hash_val];
-
- if (ptr == 0) {
- if (value != 0) *value = 0;
- return 0;
- }
-
- if (EQUAL(table, *key, ptr->key)) {
- table->bins[hash_val] = ptr->next;
- table->num_entries--;
- if (value != 0) *value = ptr->record;
- *key = ptr->key;
- free(ptr);
- return 1;
- }
-
- for(; ptr->next != 0; ptr = ptr->next) {
- if (EQUAL(table, ptr->next->key, *key)) {
- tmp = ptr->next;
- ptr->next = ptr->next->next;
- table->num_entries--;
- if (value != 0) *value = tmp->record;
- *key = tmp->key;
- free(tmp);
- return 1;
- }
- }
-
- return 0;
-}
-
-int
-st_delete_safe(table, key, value, never)
- register st_table *table;
- register char **key;
- char **value;
- char *never;
-{
- unsigned int hash_val;
- register st_table_entry *ptr;
-
- hash_val = do_hash_bin(*key, table);
- ptr = table->bins[hash_val];
-
- if (ptr == 0) {
- if (value != 0) *value = 0;
- return 0;
- }
-
- for(; ptr != 0; ptr = ptr->next) {
- if ((ptr->key != never) && EQUAL(table, ptr->key, *key)) {
- table->num_entries--;
- *key = ptr->key;
- if (value != 0) *value = ptr->record;
- ptr->key = ptr->record = never;
- return 1;
- }
- }
-
- return 0;
-}
-
-static int
-delete_never(key, value, never)
- char *key, *value, *never;
-{
- if (value == never) return ST_DELETE;
- return ST_CONTINUE;
-}
-
-void
-st_cleanup_safe(table, never)
- st_table *table;
- char *never;
-{
- int num_entries = table->num_entries;
-
- st_foreach(table, delete_never, never);
- table->num_entries = num_entries;
-}
-
-void
-st_foreach(table, func, arg)
- st_table *table;
- enum st_retval (*func)();
- char *arg;
-{
- st_table_entry *ptr, *last, *tmp;
- enum st_retval retval;
- int i;
-
- for(i = 0; i < table->num_bins; i++) {
- last = 0;
- for(ptr = table->bins[i]; ptr != 0;) {
- retval = (*func)(ptr->key, ptr->record, arg);
- switch (retval) {
- case ST_CONTINUE:
- last = ptr;
- ptr = ptr->next;
- break;
- case ST_STOP:
- return;
- case ST_DELETE:
- tmp = ptr;
- if (last == 0) {
- table->bins[i] = ptr->next;
- }
- else {
- last->next = ptr->next;
- }
- ptr = ptr->next;
- free(tmp);
- table->num_entries--;
- }
- }
- }
-}
-
-static int
-strhash(string)
- register char *string;
-{
- register int c;
-
-#ifdef HASH_ELFHASH
- register unsigned int h = 0, g;
-
- while ((c = *string++) != '\0') {
- h = ( h << 4 ) + c;
- if ( g = h & 0xF0000000 )
- h ^= g >> 24;
- h &= ~g;
- }
- return h;
-#elif HASH_PERL
- register int val = 0;
-
- while ((c = *string++) != '\0') {
- val = val*33 + c;
- }
-
- return val + (val>>5);
-#else
- register int val = 0;
-
- while ((c = *string++) != '\0') {
- val = val*997 + c;
- }
-
- return val + (val>>5);
-#endif
-}
-
-static int
-numcmp(x, y)
- long x, y;
-{
- return x != y;
-}
-
-static int
-numhash(n)
- long n;
-{
- return n;
-}
diff --git a/st.h b/st.h
deleted file mode 100644
index 6397f8763b..0000000000
--- a/st.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/* This is a public domain general purpose hash table package written by Peter Moore @ UCB. */
-
-/* @(#) st.h 5.1 89/12/14 */
-
-#ifndef ST_INCLUDED
-
-#define ST_INCLUDED
-
-typedef struct st_table st_table;
-
-struct st_hash_type {
- int (*compare)();
- int (*hash)();
-};
-
-struct st_table {
- struct st_hash_type *type;
- int num_bins;
- int num_entries;
- struct st_table_entry **bins;
-};
-
-#define st_is_member(table,key) st_lookup(table,key,(char **)0)
-
-enum st_retval {ST_CONTINUE, ST_STOP, ST_DELETE};
-
-st_table *st_init_table();
-st_table *st_init_table_with_size();
-st_table *st_init_numtable();
-st_table *st_init_numtable_with_size();
-st_table *st_init_strtable();
-st_table *st_init_strtable_with_size();
-int st_delete(), st_delete_safe();
-int st_insert(), st_lookup();
-void st_foreach(), st_add_direct(), st_free_table(), st_cleanup_safe();
-st_table *st_copy();
-
-#define ST_NUMCMP ((int (*)()) 0)
-#define ST_NUMHASH ((int (*)()) -2)
-
-#define st_numcmp ST_NUMCMP
-#define st_numhash ST_NUMHASH
-
-int st_strhash();
-
-#endif /* ST_INCLUDED */
diff --git a/string.c b/string.c
deleted file mode 100644
index 72a1783aa8..0000000000
--- a/string.c
+++ /dev/null
@@ -1,3261 +0,0 @@
-/**********************************************************************
-
- string.c -
-
- $Author$
- $Date$
- created at: Mon Aug 9 17:12:58 JST 1993
-
- Copyright (C) 1993-2002 Yukihiro Matsumoto
- Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
- Copyright (C) 2000 Information-technology Promotion Agency, Japan
-
-**********************************************************************/
-
-#include "ruby.h"
-#include "re.h"
-
-#define BEG(no) regs->beg[no]
-#define END(no) regs->end[no]
-
-#include <math.h>
-#include <ctype.h>
-
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-
-VALUE rb_cString;
-
-#define STR_ASSOC FL_USER3
-
-#define RESIZE_CAPA(str,capacity) do {\
- REALLOC_N(RSTRING(str)->ptr, char, (capacity)+1);\
- RSTRING(str)->aux.capa = (capacity);\
-} while (0)
-
-VALUE rb_fs;
-
-static VALUE
-rb_str_s_alloc(klass)
- VALUE klass;
-{
- NEWOBJ(str, struct RString);
- OBJSETUP(str, klass, T_STRING);
-
- str->ptr = 0;
- str->len = 0;
- str->aux.capa = 0;
-
- return (VALUE)str;
-}
-
-static VALUE
-str_new(klass, ptr, len)
- VALUE klass;
- const char *ptr;
- long len;
-{
- VALUE str = rb_obj_alloc(klass);
-
- RSTRING(str)->len = len;
- RSTRING(str)->aux.capa = len;
- RSTRING(str)->ptr = ALLOC_N(char,len+1);
- if (ptr) {
- memcpy(RSTRING(str)->ptr, ptr, len);
- }
- RSTRING(str)->ptr[len] = '\0';
- return str;
-}
-
-VALUE
-rb_str_new(ptr, len)
- const char *ptr;
- long len;
-{
- return str_new(rb_cString, ptr, len);
-}
-
-VALUE
-rb_str_new2(ptr)
- const char *ptr;
-{
- if (!ptr) {
- rb_raise(rb_eArgError, "NULL pointer given");
- }
- return rb_str_new(ptr, strlen(ptr));
-}
-
-VALUE
-rb_tainted_str_new(ptr, len)
- const char *ptr;
- long len;
-{
- VALUE str = rb_str_new(ptr, len);
-
- OBJ_TAINT(str);
- return str;
-}
-
-VALUE
-rb_tainted_str_new2(ptr)
- const char *ptr;
-{
- VALUE str = rb_str_new2(ptr);
-
- OBJ_TAINT(str);
- return str;
-}
-
-static VALUE
-str_new3(klass, str)
- VALUE klass, str;
-{
- VALUE str2 = rb_obj_alloc(klass);
-
- RSTRING(str2)->len = RSTRING(str)->len;
- RSTRING(str2)->ptr = RSTRING(str)->ptr;
- RSTRING(str2)->aux.shared = str;
- FL_SET(str2, ELTS_SHARED);
- OBJ_INFECT(str2, str);
-
- return str2;
-}
-
-VALUE
-rb_str_new3(str)
- VALUE str;
-{
- return str_new3(rb_obj_class(str), str);
-}
-
-VALUE
-rb_str_new4(orig)
- VALUE orig;
-{
- VALUE klass, str;
-
- klass = rb_obj_class(orig);
- if (FL_TEST(orig, ELTS_SHARED)) {
- str = str_new3(klass, RSTRING(orig)->aux.shared);
- }
- else if (FL_TEST(orig, STR_ASSOC)) {
- str = str_new(klass, RSTRING(orig)->ptr, RSTRING(orig)->len);
- }
- else {
- str = rb_obj_alloc(klass);
-
- RSTRING(str)->len = RSTRING(orig)->len;
- RSTRING(str)->ptr = RSTRING(orig)->ptr;
- RSTRING(orig)->aux.shared = str;
- FL_SET(orig, ELTS_SHARED);
- }
- OBJ_INFECT(str, orig);
- OBJ_FREEZE(str);
- return str;
-}
-
-VALUE
-rb_str_new5(obj, ptr, len)
- VALUE obj;
- const char *ptr;
- long len;
-{
- return str_new(rb_obj_class(obj), ptr, len);
-}
-
-#define STR_BUF_MIN_SIZE 128
-
-VALUE
-rb_str_buf_new(capa)
- long capa;
-{
- VALUE str = rb_obj_alloc(rb_cString);
-
- if (capa < STR_BUF_MIN_SIZE)
- capa = STR_BUF_MIN_SIZE;
- RSTRING(str)->ptr = 0;
- RSTRING(str)->len = 0;
- RSTRING(str)->aux.capa = capa;
- RSTRING(str)->ptr = ALLOC_N(char, capa+1);
- RSTRING(str)->ptr[0] = '\0';
-
- return str;
-}
-
-VALUE
-rb_str_buf_new2(ptr)
- const char *ptr;
-{
- VALUE str;
- long len = strlen(ptr);
-
- str = rb_str_buf_new(len + STR_BUF_MIN_SIZE);
- rb_str_cat(str, ptr, len);
-
- return str;
-}
-
-VALUE
-rb_str_to_str(str)
- VALUE str;
-{
- return rb_convert_type(str, T_STRING, "String", "to_str");
-}
-
-static void
-rb_str_become(str, str2)
- VALUE str, str2;
-{
- if (str == str2) return;
- if (NIL_P(str2)) {
- RSTRING(str)->ptr = 0;
- RSTRING(str)->len = 0;
- RSTRING(str)->aux.capa = 0;
- return;
- }
- if (FL_TEST(str, ELTS_SHARED)) free(RSTRING(str)->ptr);
- RSTRING(str)->ptr = RSTRING(str2)->ptr;
- RSTRING(str)->len = RSTRING(str2)->len;
- if (FL_TEST(str2, ELTS_SHARED|STR_ASSOC)) {
- FL_SET(str, RBASIC(str2)->flags & (ELTS_SHARED|STR_ASSOC));
- RSTRING(str)->aux.shared = RSTRING(str2)->aux.shared;
- }
- else {
- RSTRING(str)->aux.capa = RSTRING(str2)->aux.capa;
- }
- RSTRING(str2)->ptr = 0; /* abandon str2 */
- RSTRING(str2)->len = 0;
- RSTRING(str2)->aux.capa = 0;
- FL_UNSET(str, ELTS_SHARED|STR_ASSOC);
- if (OBJ_TAINTED(str2)) OBJ_TAINT(str);
-}
-
-void
-rb_str_associate(str, add)
- VALUE str, add;
-{
- if (FL_TEST(str, STR_ASSOC)) {
- /* already associated */
- rb_ary_concat(RSTRING(str)->aux.shared, add);
- }
- else {
- if (FL_TEST(str, ELTS_SHARED)) {
- rb_str_modify(str);
- }
- else if (RSTRING(str)->aux.shared) {
- /* str_buf */
- if (RSTRING(str)->aux.capa != RSTRING(str)->len) {
- RESIZE_CAPA(str, RSTRING(str)->len);
- }
- }
- RSTRING(str)->aux.shared = add;
- FL_UNSET(str, ELTS_SHARED);
- FL_SET(str, STR_ASSOC);
- }
-}
-
-VALUE
-rb_str_associated(str)
- VALUE str;
-{
- if (FL_TEST(str, STR_ASSOC)) {
- return RSTRING(str)->aux.shared;
- }
- return Qfalse;
-}
-
-static ID id_to_s;
-
-VALUE
-rb_obj_as_string(obj)
- VALUE obj;
-{
- VALUE str;
-
- if (TYPE(obj) == T_STRING) {
- return obj;
- }
- str = rb_funcall(obj, id_to_s, 0);
- if (TYPE(str) != T_STRING)
- return rb_any_to_s(obj);
- if (OBJ_TAINTED(obj)) OBJ_TAINT(str);
- return str;
-}
-
-static VALUE
-str_copy(str, clone)
- VALUE str;
- int clone;
-{
- VALUE str2;
- VALUE klass;
- int flags;
-
- StringValue(str);
-
- if (FL_TEST(str, ELTS_SHARED)) {
- str2 = rb_str_new3(RSTRING(str)->aux.shared);
- }
- else if (FL_TEST(str, STR_ASSOC)) {
- str2 = str_new(RSTRING(str)->ptr, RSTRING(str)->len);
- RSTRING(str2)->aux.shared = RSTRING(str)->aux.shared;
- }
- else if (OBJ_FROZEN(str)) {
- str2 = rb_str_new3(str);
- }
- else {
- str2 = rb_str_new3(rb_str_new4(str));
- }
- flags = FL_TEST(str2, ELTS_SHARED|STR_ASSOC);
- if (clone) {
- CLONESETUP(str2, str);
- }
- else {
- DUPSETUP(str2, str);
- }
- if (flags) FL_SET(str2, flags);
- return str2;
-}
-
-VALUE
-rb_str_dup(str)
- VALUE str;
-{
- return str_copy(str, Qfalse);
-}
-
-static VALUE
-rb_str_clone(str)
- VALUE str;
-{
- return str_copy(str, Qtrue);
-}
-
-static VALUE rb_str_replace _((VALUE, VALUE));
-
-static VALUE
-rb_str_init(argc, argv, str)
- int argc;
- VALUE *argv;
- VALUE str;
-{
- VALUE orig;
-
- if (rb_scan_args(argc, argv, "01", &orig) == 1)
- rb_str_replace(str, orig);
- return str;
-}
-
-static VALUE
-rb_str_length(str)
- VALUE str;
-{
- return INT2NUM(RSTRING(str)->len);
-}
-
-static VALUE
-rb_str_empty(str)
- VALUE str;
-{
- if (RSTRING(str)->len == 0)
- return Qtrue;
- return Qfalse;
-}
-
-VALUE
-rb_str_plus(str1, str2)
- VALUE str1, str2;
-{
- VALUE str3;
-
- StringValue(str2);
- str3 = rb_str_new(0, RSTRING(str1)->len+RSTRING(str2)->len);
- memcpy(RSTRING(str3)->ptr, RSTRING(str1)->ptr, RSTRING(str1)->len);
- memcpy(RSTRING(str3)->ptr + RSTRING(str1)->len,
- RSTRING(str2)->ptr, RSTRING(str2)->len);
- RSTRING(str3)->ptr[RSTRING(str3)->len] = '\0';
-
- if (OBJ_TAINTED(str1) || OBJ_TAINTED(str2))
- OBJ_TAINT(str3);
- return str3;
-}
-
-VALUE
-rb_str_times(str, times)
- VALUE str;
- VALUE times;
-{
- VALUE str2;
- long i, len;
-
- len = NUM2LONG(times);
- if (len == 0) return rb_str_new5(str,0,0);
- if (len < 0) {
- rb_raise(rb_eArgError, "negative argument");
- }
- if (LONG_MAX/len < RSTRING(str)->len) {
- rb_raise(rb_eArgError, "argument too big");
- }
-
- str2 = rb_str_new5(str,0, RSTRING(str)->len*len);
- for (i=0; i<len; i++) {
- memcpy(RSTRING(str2)->ptr+(i*RSTRING(str)->len),
- RSTRING(str)->ptr, RSTRING(str)->len);
- }
- RSTRING(str2)->ptr[RSTRING(str2)->len] = '\0';
-
- OBJ_INFECT(str2, str);
-
- return str2;
-}
-
-static VALUE
-rb_str_format(str, arg)
- VALUE str, arg;
-{
- VALUE *argv;
-
- if (TYPE(arg) == T_ARRAY) {
- argv = ALLOCA_N(VALUE, RARRAY(arg)->len + 1);
- argv[0] = str;
- MEMCPY(argv+1, RARRAY(arg)->ptr, VALUE, RARRAY(arg)->len);
- return rb_f_sprintf(RARRAY(arg)->len+1, argv);
- }
-
- argv = ALLOCA_N(VALUE, 2);
- argv[0] = str;
- argv[1] = arg;
- return rb_f_sprintf(2, argv);
-}
-
-static int
-str_independent(str)
- VALUE str;
-{
- if (OBJ_FROZEN(str)) rb_error_frozen("string");
- if (!OBJ_TAINTED(str) && rb_safe_level() >= 4)
- rb_raise(rb_eSecurityError, "Insecure: can't modify string");
- if (!FL_TEST(str, ELTS_SHARED)) return 1;
- return 0;
-}
-
-static void
-str_make_independent(str)
- VALUE str;
-{
- char *ptr;
-
- ptr = ALLOC_N(char, RSTRING(str)->len+1);
- if (RSTRING(str)->ptr) {
- memcpy(ptr, RSTRING(str)->ptr, RSTRING(str)->len);
- }
- ptr[RSTRING(str)->len] = 0;
- RSTRING(str)->ptr = ptr;
- RSTRING(str)->aux.capa = RSTRING(str)->len;
- FL_UNSET(str, ELTS_SHARED|STR_ASSOC);
-}
-
-void
-rb_str_modify(str)
- VALUE str;
-{
- if (str_independent(str)) return;
- str_make_independent(str);
-}
-
-VALUE
-rb_string_value(ptr)
- volatile VALUE *ptr;
-{
- return *ptr = rb_str_to_str(*ptr);
-}
-
-VALUE
-rb_str_substr(str, beg, len)
- VALUE str;
- long beg, len;
-{
- VALUE str2;
-
- if (len < 0) return Qnil;
- if (beg > RSTRING(str)->len) return Qnil;
- if (beg < 0) {
- beg += RSTRING(str)->len;
- if (beg < 0) return Qnil;
- }
- if (beg + len > RSTRING(str)->len) {
- len = RSTRING(str)->len - beg;
- }
- if (len < 0) {
- len = 0;
- }
- if (len == 0) return rb_str_new5(str,0,0);
-
- str2 = rb_str_new5(str,RSTRING(str)->ptr+beg, len);
- OBJ_INFECT(str2, str);
-
- return str2;
-}
-
-VALUE
-rb_str_freeze(str)
- VALUE str;
-{
- return rb_obj_freeze(str);
-}
-
-VALUE
-rb_str_dup_frozen(str)
- VALUE str;
-{
- if (FL_TEST(str, ELTS_SHARED)) {
- OBJ_FREEZE(RSTRING(str)->aux.shared);
- return RSTRING(str)->aux.shared;
- }
- if (OBJ_FROZEN(str)) return str;
- str = rb_str_dup(str);
- OBJ_FREEZE(str);
- return str;
-}
-
-VALUE
-rb_str_resize(str, len)
- VALUE str;
- long len;
-{
- if (len != RSTRING(str)->len) {
- rb_str_modify(str);
-
- if (len >= 0) {
- if (RSTRING(str)->len < len || RSTRING(str)->len - len > 1024) {
- RESIZE_CAPA(str, len);
- }
- RSTRING(str)->len = len;
- RSTRING(str)->ptr[len] = '\0'; /* sentinel */
- }
- }
- return str;
-}
-
-VALUE
-rb_str_buf_cat(str, ptr, len)
- VALUE str;
- const char *ptr;
- long len;
-{
- long i, capa, total;
-
- if (FL_TEST(str, ELTS_SHARED)) {
- rb_str_modify(str);
- }
- capa = RSTRING(str)->aux.capa;
- total = RSTRING(str)->len+len;
- if (capa <= total) {
- while (total > capa) {
- capa = (capa + 1) * 2;
- }
- RESIZE_CAPA(str, capa);
- }
- memcpy(RSTRING(str)->ptr + RSTRING(str)->len, ptr, len);
- RSTRING(str)->len = total;
- RSTRING(str)->ptr[total] = '\0'; /* sentinel */
-
- return str;
-}
-
-VALUE
-rb_str_buf_cat2(str, ptr)
- VALUE str;
- const char *ptr;
-{
- return rb_str_buf_cat(str, ptr, strlen(ptr));
-}
-
-VALUE
-rb_str_cat(str, ptr, len)
- VALUE str;
- const char *ptr;
- long len;
-{
- long i, capa;
-
- rb_str_modify(str);
- if (len > 0) {
- if (!FL_TEST(str, ELTS_SHARED) && !FL_TEST(str, STR_ASSOC)) {
- return rb_str_buf_cat(str, ptr, len);
- }
- RESIZE_CAPA(str, RSTRING(str)->len + len);
- if (ptr) {
- memcpy(RSTRING(str)->ptr + RSTRING(str)->len, ptr, len);
- }
- else {
- MEMZERO(RSTRING(str)->ptr + RSTRING(str)->len, char, len);
- }
- RSTRING(str)->len += len;
- RSTRING(str)->ptr[RSTRING(str)->len] = '\0'; /* sentinel */
- }
-
- return str;
-}
-
-VALUE
-rb_str_cat2(str, ptr)
- VALUE str;
- const char *ptr;
-{
- return rb_str_cat(str, ptr, strlen(ptr));
-}
-
-VALUE
-rb_str_buf_append(str, str2)
- VALUE str, str2;
-{
- long i, capa, len;
-
- if (FL_TEST(str, ELTS_SHARED)) {
- rb_str_modify(str);
- }
- capa = RSTRING(str)->aux.capa;
-
- len = RSTRING(str)->len+RSTRING(str2)->len;
- if (capa <= len) {
- while (len > capa) {
- capa = (capa + 1) * 2;
- }
- RESIZE_CAPA(str, capa);
- }
- memcpy(RSTRING(str)->ptr + RSTRING(str)->len,
- RSTRING(str2)->ptr, RSTRING(str2)->len);
- RSTRING(str)->len += RSTRING(str2)->len;
- RSTRING(str)->ptr[RSTRING(str)->len] = '\0'; /* sentinel */
-
- return str;
-}
-
-VALUE
-rb_str_append(str, str2)
- VALUE str, str2;
-{
- long i, capa, len;
-
- StringValue(str2);
- rb_str_modify(str);
- if (RSTRING(str2)->len > 0) {
- len = RSTRING(str)->len+RSTRING(str2)->len;
- if (!FL_TEST(str, ELTS_SHARED) && !FL_TEST(str, STR_ASSOC)) {
- rb_str_buf_append(str, str2);
- OBJ_INFECT(str, str2);
- return str;
- }
- RESIZE_CAPA(str, len);
- memcpy(RSTRING(str)->ptr + RSTRING(str)->len,
- RSTRING(str2)->ptr, RSTRING(str2)->len);
- RSTRING(str)->len += RSTRING(str2)->len;
- RSTRING(str)->ptr[RSTRING(str)->len] = '\0'; /* sentinel */
- }
- OBJ_INFECT(str, str2);
-
- return str;
-}
-
-VALUE
-rb_str_concat(str1, str2)
- VALUE str1, str2;
-{
- if (FIXNUM_P(str2)) {
- int i = FIX2INT(str2);
- if (0 <= i && i <= 0xff) { /* byte */
- char c = i;
- return rb_str_cat(str1, &c, 1);
- }
- }
- str1 = rb_str_append(str1, str2);
-
- return str1;
-}
-
-int
-rb_str_hash(str)
- VALUE str;
-{
- register long len = RSTRING(str)->len;
- register char *p = RSTRING(str)->ptr;
- register int key = 0;
-
-#ifdef HASH_ELFHASH
- register unsigned int g;
-
- while (len--) {
- key = (key << 4) + *p++;
- if (g = key & 0xF0000000)
- key ^= g >> 24;
- key &= ~g;
- }
-#elif HASH_PERL
- while (len--) {
- key = key*33 + *p++;
- }
- key = key + (key>>5);
-#else
- while (len--) {
- key = key*65599 + *p;
- p++;
- }
- key = key + (key>>5);
-#endif
- return key;
-}
-
-static VALUE
-rb_str_hash_m(str)
- VALUE str;
-{
- int key = rb_str_hash(str);
- return INT2FIX(key);
-}
-
-#define lesser(a,b) (((a)>(b))?(b):(a))
-
-int
-rb_str_cmp(str1, str2)
- VALUE str1, str2;
-{
- long len;
- int retval;
-
- len = lesser(RSTRING(str1)->len, RSTRING(str2)->len);
- retval = rb_memcmp(RSTRING(str1)->ptr, RSTRING(str2)->ptr, len);
- if (retval == 0) {
- if (RSTRING(str1)->len == RSTRING(str2)->len) return 0;
- if (RSTRING(str1)->len > RSTRING(str2)->len) return 1;
- return -1;
- }
- if (retval > 0) return 1;
- return -1;
-}
-
-static VALUE
-rb_str_equal(str1, str2)
- VALUE str1, str2;
-{
- if (str1 == str2) return Qtrue;
- if (TYPE(str2) != T_STRING) {
- str2 = rb_check_convert_type(str2, T_STRING, "String", "to_str");
- if (NIL_P(str2)) return Qfalse;
- }
-
- if (RSTRING(str1)->len == RSTRING(str2)->len
- && rb_str_cmp(str1, str2) == 0) {
- return Qtrue;
- }
- return Qfalse;
-}
-
-static VALUE
-rb_str_eql(str1, str2)
- VALUE str1, str2;
-{
- if (TYPE(str2) != T_STRING || RSTRING(str1)->len != RSTRING(str2)->len)
- return Qfalse;
-
- if (memcmp(RSTRING(str1)->ptr, RSTRING(str2)->ptr,
- lesser(RSTRING(str1)->len, RSTRING(str2)->len)) == 0)
- return Qtrue;
-
- return Qfalse;
-}
-
-static VALUE
-rb_str_cmp_m(str1, str2)
- VALUE str1, str2;
-{
- int result;
-
- StringValue(str2);
- result = rb_str_cmp(str1, str2);
- return INT2FIX(result);
-}
-
-static VALUE
-rb_str_casecmp(str1, str2)
- VALUE str1, str2;
-{
- long len;
- int retval;
-
- StringValue(str2);
- len = lesser(RSTRING(str1)->len, RSTRING(str2)->len);
- retval = rb_memcicmp(RSTRING(str1)->ptr, RSTRING(str2)->ptr, len);
- if (retval == 0) {
- if (RSTRING(str1)->len == RSTRING(str2)->len) return INT2FIX(0);
- if (RSTRING(str1)->len > RSTRING(str2)->len) return INT2FIX(1);
- return INT2FIX(-1);
- }
- if (retval == 0) return INT2FIX(0);
- if (retval > 0) return INT2FIX(1);
- return INT2FIX(-1);
-}
-
-static VALUE
-rb_str_match(x, y)
- VALUE x, y;
-{
- VALUE reg;
- long start;
-
- switch (TYPE(y)) {
- case T_REGEXP:
- return rb_reg_match(y, x);
-
- case T_STRING:
- reg = rb_reg_regcomp(y);
- start = rb_reg_search(reg, x, 0, 0);
- if (start == -1) {
- return Qnil;
- }
- return INT2NUM(start);
-
- default:
- return rb_funcall(y, rb_intern("=~"), 1, x);
- }
-}
-
-static VALUE
-rb_str_match2(str)
- VALUE str;
-{
- StringValue(str);
- return rb_reg_match2(rb_reg_regcomp(str));
-}
-
-static VALUE
-rb_str_match_m(str, re)
- VALUE str, re;
-{
- VALUE str2 = rb_check_convert_type(re, T_STRING, "String", "to_str");
-
- if (!NIL_P(str2)) {
- StringValue(re);
- re = rb_reg_regcomp(re);
- }
- return rb_funcall(re, rb_intern("match"), 1, str);
-}
-
-static long
-rb_str_index(str, sub, offset)
- VALUE str, sub;
- long offset;
-{
- char *s, *e, *p;
- long len;
-
- if (offset < 0) {
- offset += RSTRING(str)->len;
- if (offset < 0) return -1;
- }
- if (RSTRING(str)->len - offset < RSTRING(sub)->len) return -1;
- s = RSTRING(str)->ptr+offset;
- p = RSTRING(sub)->ptr;
- len = RSTRING(sub)->len;
- if (len == 0) return offset;
- e = RSTRING(str)->ptr + RSTRING(str)->len - len + 1;
- while (s < e) {
- if (rb_memcmp(s, p, len) == 0) {
- return (s-(RSTRING(str)->ptr));
- }
- s++;
- }
- return -1;
-}
-
-static VALUE
-rb_str_index_m(argc, argv, str)
- int argc;
- VALUE *argv;
- VALUE str;
-{
- VALUE sub;
- VALUE initpos;
- long pos;
-
- if (rb_scan_args(argc, argv, "11", &sub, &initpos) == 2) {
- pos = NUM2LONG(initpos);
- }
- else {
- pos = 0;
- }
- if (pos < 0) {
- pos += RSTRING(str)->len;
- if (pos < 0) {
- if (TYPE(sub) == T_REGEXP) {
- rb_backref_set(Qnil);
- }
- return Qnil;
- }
- }
-
- switch (TYPE(sub)) {
- case T_REGEXP:
- pos = rb_reg_adjust_startpos(sub, str, pos, 0);
- pos = rb_reg_search(sub, str, pos, 0);
- break;
-
- case T_STRING:
- pos = rb_str_index(str, sub, pos);
- break;
-
- case T_FIXNUM:
- {
- int c = FIX2INT(sub);
- long len = RSTRING(str)->len;
- char *p = RSTRING(str)->ptr;
-
- for (;pos<len;pos++) {
- if (p[pos] == c) return INT2NUM(pos);
- }
- return Qnil;
- }
-
- default:
- rb_raise(rb_eTypeError, "type mismatch: %s given",
- rb_class2name(CLASS_OF(sub)));
- }
-
- if (pos == -1) return Qnil;
- return INT2NUM(pos);
-}
-
-static VALUE
-rb_str_rindex(argc, argv, str)
- int argc;
- VALUE *argv;
- VALUE str;
-{
- VALUE sub;
- VALUE position;
- int pos, len;
- char *s, *sbeg, *t;
-
- if (rb_scan_args(argc, argv, "11", &sub, &position) == 2) {
- pos = NUM2INT(position);
- if (pos < 0) {
- pos += RSTRING(str)->len;
- if (pos < 0) {
- if (TYPE(sub) == T_REGEXP) {
- rb_backref_set(Qnil);
- }
- return Qnil;
- }
- }
- if (pos > RSTRING(str)->len) pos = RSTRING(str)->len;
- }
- else {
- pos = RSTRING(str)->len;
- }
-
- switch (TYPE(sub)) {
- case T_REGEXP:
- if (RREGEXP(sub)->len) {
- pos = rb_reg_adjust_startpos(sub, str, pos, 1);
- pos = rb_reg_search(sub, str, pos, 1);
- }
- if (pos >= 0) return INT2NUM(pos);
- break;
-
- case T_STRING:
- len = RSTRING(sub)->len;
- /* substring longer than string */
- if (RSTRING(str)->len < len) return Qnil;
- if (RSTRING(str)->len - pos < len) {
- pos = RSTRING(str)->len - len;
- }
- sbeg = RSTRING(str)->ptr;
- s = RSTRING(str)->ptr + pos;
- t = RSTRING(sub)->ptr;
- if (len) {
- while (sbeg <= s) {
- if (rb_memcmp(s, t, len) == 0) {
- return INT2NUM(s - RSTRING(str)->ptr);
- }
- s--;
- }
- }
- else {
- return INT2NUM(pos);
- }
- break;
-
- case T_FIXNUM:
- {
- int c = FIX2INT(sub);
- char *p = RSTRING(str)->ptr + pos;
- char *pbeg = RSTRING(str)->ptr;
-
- while (pbeg <= p) {
- if (*p == c) return INT2NUM(p - RSTRING(str)->ptr);
- p--;
- }
- return Qnil;
- }
-
- default:
- rb_raise(rb_eTypeError, "type mismatch: %s given",
- rb_class2name(CLASS_OF(sub)));
- }
- return Qnil;
-}
-
-static char
-succ_char(s)
- char *s;
-{
- char c = *s;
-
- /* numerics */
- if ('0' <= c && c < '9') (*s)++;
- else if (c == '9') {
- *s = '0';
- return '1';
- }
- /* small alphabets */
- else if ('a' <= c && c < 'z') (*s)++;
- else if (c == 'z') {
- return *s = 'a';
- }
- /* capital alphabets */
- else if ('A' <= c && c < 'Z') (*s)++;
- else if (c == 'Z') {
- return *s = 'A';
- }
- return 0;
-}
-
-static VALUE
-rb_str_succ(orig)
- VALUE orig;
-{
- VALUE str;
- char *sbeg, *s;
- int c = -1;
- int n = 0;
-
- str = rb_str_new5(orig,RSTRING(orig)->ptr, RSTRING(orig)->len);
- OBJ_INFECT(str, orig);
- if (RSTRING(str)->len == 0) return str;
-
- sbeg = RSTRING(str)->ptr; s = sbeg + RSTRING(str)->len - 1;
-
- while (sbeg <= s) {
- if (ISALNUM(*s)) {
- if ((c = succ_char(s)) == 0) break;
- n = s - sbeg;
- }
- s--;
- }
- if (c == -1) { /* str contains no alnum */
- sbeg = RSTRING(str)->ptr; s = sbeg + RSTRING(str)->len - 1;
- c = '\001';
- while (sbeg <= s) {
- if ((*s += 1) != 0) break;
- s--;
- }
- }
- if (s < sbeg) {
- RESIZE_CAPA(str, RSTRING(str)->len + 1);
- s = RSTRING(str)->ptr + n;
- memmove(s+1, s, RSTRING(str)->len - n);
- *s = c;
- RSTRING(str)->len += 1;
- RSTRING(str)->ptr[RSTRING(str)->len] = '\0';
- }
-
- return str;
-}
-
-static VALUE
-rb_str_succ_bang(str)
- VALUE str;
-{
- rb_str_modify(str);
- rb_str_become(str, rb_str_succ(str));
-
- return str;
-}
-
-VALUE
-rb_str_upto(beg, end, excl)
- VALUE beg, end;
- int excl;
-{
- VALUE current;
- ID succ = rb_intern("succ");
-
- StringValue(end);
- current = beg;
- while (rb_str_cmp(current, end) <= 0) {
- rb_yield(current);
- if (!excl && rb_str_equal(current, end)) break;
- current = rb_funcall(current, succ, 0, 0);
- if (excl && rb_str_equal(current, end)) break;
- if (RSTRING(current)->len > RSTRING(end)->len)
- break;
- }
-
- return beg;
-}
-
-static VALUE
-rb_str_upto_m(beg, end)
- VALUE beg, end;
-{
- return rb_str_upto(beg, end, 0);
-}
-
-static VALUE
-rb_str_subpat(str, re, nth)
- VALUE str, re;
- int nth;
-{
- if (rb_reg_search(re, str, 0, 0) >= 0) {
- return rb_reg_nth_match(nth, rb_backref_get());
- }
- return Qnil;
-}
-
-static VALUE
-rb_str_aref(str, indx)
- VALUE str;
- VALUE indx;
-{
- long idx;
-
- switch (TYPE(indx)) {
- case T_FIXNUM:
- idx = FIX2LONG(indx);
-
- num_index:
- if (idx < 0) {
- idx = RSTRING(str)->len + idx;
- }
- if (idx < 0 || RSTRING(str)->len <= idx) {
- return Qnil;
- }
- return INT2FIX(RSTRING(str)->ptr[idx] & 0xff);
-
- case T_REGEXP:
- return rb_str_subpat(str, indx, 0);
-
- case T_STRING:
- if (rb_str_index(str, indx, 0) != -1)
- return rb_str_dup(indx);
- return Qnil;
-
- default:
- /* check if indx is Range */
- {
- long beg, len;
- switch (rb_range_beg_len(indx, &beg, &len, RSTRING(str)->len, 0)) {
- case Qfalse:
- break;
- case Qnil:
- return Qnil;
- default:
- return rb_str_substr(str, beg, len);
- }
- }
- idx = NUM2LONG(indx);
- goto num_index;
- }
- return Qnil; /* not reached */
-}
-
-static VALUE
-rb_str_aref_m(argc, argv, str)
- int argc;
- VALUE *argv;
- VALUE str;
-{
- if (argc == 2) {
- if (TYPE(argv[0]) == T_REGEXP) {
- return rb_str_subpat(str, argv[0], NUM2INT(argv[1]));
- }
- return rb_str_substr(str, NUM2INT(argv[0]), NUM2INT(argv[1]));
- }
- if (argc != 1) {
- rb_raise(rb_eArgError, "wrong number of arguments(%d for 1)", argc);
- }
- return rb_str_aref(str, argv[0]);
-}
-
-void
-rb_str_update(str, beg, len, val)
- VALUE str;
- long beg;
- long len;
- VALUE val;
-{
- if (len < 0) rb_raise(rb_eIndexError, "negative length %d", len);
- if (RSTRING(str)->len < beg) {
- out_of_range:
- rb_raise(rb_eIndexError, "index %d out of string", beg);
- }
- if (beg < 0) {
- if (-beg > RSTRING(str)->len) {
- goto out_of_range;
- }
- beg += RSTRING(str)->len;
- }
- if (RSTRING(str)->len < beg + len) {
- len = RSTRING(str)->len - beg;
- }
-
- StringValue(val);
- if (len < RSTRING(val)->len) {
- /* expand string */
- RESIZE_CAPA(str, RSTRING(str)->len + RSTRING(val)->len - len);
- }
-
- if (RSTRING(val)->len != len) {
- memmove(RSTRING(str)->ptr + beg + RSTRING(val)->len,
- RSTRING(str)->ptr + beg + len,
- RSTRING(str)->len - (beg + len));
- }
- if (RSTRING(str)->len < beg && len < 0) {
- MEMZERO(RSTRING(str)->ptr + RSTRING(str)->len, char, -len);
- }
- if (RSTRING(val)->len > 0) {
- memmove(RSTRING(str)->ptr+beg, RSTRING(val)->ptr, RSTRING(val)->len);
- }
- RSTRING(str)->len += RSTRING(val)->len - len;
- RSTRING(str)->ptr[RSTRING(str)->len] = '\0';
- OBJ_INFECT(str, val);
-}
-
-static void
-rb_str_subpat_set(str, re, nth, val)
- VALUE str, re;
- int nth;
- VALUE val;
-{
- VALUE match;
- int start, end, len;
-
- if (rb_reg_search(re, str, 0, 0) < 0) {
- rb_raise(rb_eIndexError, "regexp not matched");
- }
- match = rb_backref_get();
- if (nth >= RMATCH(match)->regs->num_regs) {
- out_of_range:
- rb_raise(rb_eIndexError, "index %d out of regexp", nth);
- }
- if (nth < 0) {
- if (-nth >= RMATCH(match)->regs->num_regs) {
- goto out_of_range;
- }
- nth += RMATCH(match)->regs->num_regs;
- }
-
- start = RMATCH(match)->BEG(nth);
- if (start == -1) {
- rb_raise(rb_eIndexError, "regexp group %d not matched", nth);
- }
- end = RMATCH(match)->END(nth);
- len = end - start;
- rb_str_modify(str);
- rb_str_update(str, start, len, val);
-}
-
-static VALUE
-rb_str_aset(str, indx, val)
- VALUE str;
- VALUE indx, val;
-{
- long idx, beg;
-
- switch (TYPE(indx)) {
- case T_FIXNUM:
- num_index:
- idx = NUM2INT(indx);
- if (RSTRING(str)->len <= idx) {
- out_of_range:
- rb_raise(rb_eIndexError, "index %d out of string", idx);
- }
- if (idx < 0) {
- if (-idx > RSTRING(str)->len)
- goto out_of_range;
- idx += RSTRING(str)->len;
- }
- if (FIXNUM_P(val)) {
- if (RSTRING(str)->len == idx) {
- RSTRING(str)->len += 1;
- RESIZE_CAPA(str, RSTRING(str)->len);
- }
- RSTRING(str)->ptr[idx] = NUM2INT(val) & 0xff;
- }
- else {
- rb_str_update(str, idx, 1, val);
- }
- return val;
-
- case T_REGEXP:
- rb_str_subpat_set(str, indx, 0, val);
- return val;
-
- case T_STRING:
- beg = rb_str_index(str, indx, 0);
- if (beg != -1) {
- rb_str_update(str, beg, RSTRING(indx)->len, val);
- }
- return val;
-
- default:
- /* check if indx is Range */
- {
- long beg, len;
- if (rb_range_beg_len(indx, &beg, &len, RSTRING(str)->len, 2)) {
- rb_str_update(str, beg, len, val);
- return val;
- }
- }
- idx = NUM2LONG(indx);
- goto num_index;
- }
-}
-
-static VALUE
-rb_str_aset_m(argc, argv, str)
- int argc;
- VALUE *argv;
- VALUE str;
-{
- rb_str_modify(str);
- if (argc == 3) {
- if (TYPE(argv[0]) == T_REGEXP) {
- rb_str_subpat_set(str, argv[0], NUM2INT(argv[1]), argv[2]);
- }
- else {
- rb_str_update(str, NUM2INT(argv[0]), NUM2INT(argv[1]), argv[2]);
- }
- return argv[2];
- }
- if (argc != 2) {
- rb_raise(rb_eArgError, "wrong number of arguments(%d for 2)", argc);
- }
- return rb_str_aset(str, argv[0], argv[1]);
-}
-
-static VALUE
-rb_str_insert(str, idx, str2)
- VALUE str, idx, str2;
-{
- long pos = NUM2LONG(idx);
-
- rb_str_modify(str);
- if (pos == -1) {
- pos = RSTRING(str)->len;
- }
- else if (pos < 0) {
- pos++;
- }
- rb_str_update(str, pos, 0, str2);
- return str;
-}
-
-static VALUE
-rb_str_slice_bang(argc, argv, str)
- int argc;
- VALUE *argv;
- VALUE str;
-{
- VALUE result;
- VALUE buf[3];
- int i;
-
- if (argc < 1 || 2 < argc) {
- rb_raise(rb_eArgError, "wrong number of arguments(%d for 1)", argc);
- }
- for (i=0; i<argc; i++) {
- buf[i] = argv[i];
- }
- buf[i] = rb_str_new(0,0);
- result = rb_str_aref_m(argc, buf, str);
- rb_str_aset_m(argc+1, buf, str);
- return result;
-}
-
-static VALUE
-get_pat(pat)
- VALUE pat;
-{
- switch (TYPE(pat)) {
- case T_REGEXP:
- break;
-
- case T_STRING:
- pat = rb_reg_regcomp(pat);
- break;
-
- default:
- /* type failed */
- Check_Type(pat, T_REGEXP);
- }
- return pat;
-}
-
-static VALUE
-rb_str_sub_bang(argc, argv, str)
- int argc;
- VALUE *argv;
- VALUE str;
-{
- VALUE pat, repl, match;
- struct re_registers *regs;
- int iter = 0;
- int tainted = 0;
- long plen;
-
- if (argc == 1 && rb_block_given_p()) {
- iter = 1;
- }
- else if (argc == 2) {
- repl = argv[1];
- StringValue(repl);
- if (OBJ_TAINTED(repl)) tainted = 1;
- }
- else {
- rb_raise(rb_eArgError, "wrong number of arguments(%d for 2)", argc);
- }
-
- pat = get_pat(argv[0]);
- if (rb_reg_search(pat, str, 0, 0) >= 0) {
- rb_str_modify(str);
- match = rb_backref_get();
- regs = RMATCH(match)->regs;
-
- if (iter) {
- rb_match_busy(match);
- repl = rb_obj_as_string(rb_yield(rb_reg_nth_match(0, match)));
- rb_backref_set(match);
- }
- else {
- repl = rb_reg_regsub(repl, str, regs);
- }
- if (OBJ_TAINTED(repl)) tainted = 1;
- plen = END(0) - BEG(0);
- if (RSTRING(repl)->len > plen) {
- RESIZE_CAPA(str, RSTRING(str)->len + RSTRING(repl)->len - plen);
- }
- if (RSTRING(repl)->len != plen) {
- memmove(RSTRING(str)->ptr + BEG(0) + RSTRING(repl)->len,
- RSTRING(str)->ptr + BEG(0) + plen,
- RSTRING(str)->len - BEG(0) - plen);
- }
- memcpy(RSTRING(str)->ptr + BEG(0),
- RSTRING(repl)->ptr, RSTRING(repl)->len);
- RSTRING(str)->len += RSTRING(repl)->len - plen;
- RSTRING(str)->ptr[RSTRING(str)->len] = '\0';
- if (tainted) OBJ_TAINT(str);
-
- return str;
- }
- return Qnil;
-}
-
-static VALUE
-rb_str_sub(argc, argv, str)
- int argc;
- VALUE *argv;
- VALUE str;
-{
- str = rb_str_dup(str);
- rb_str_sub_bang(argc, argv, str);
- return str;
-}
-
-static VALUE
-str_gsub(argc, argv, str, bang)
- int argc;
- VALUE *argv;
- VALUE str;
- int bang;
-{
- VALUE pat, val, repl, match;
- struct re_registers *regs;
- long beg, n;
- long offset, blen, len;
- int iter = 0;
- char *buf, *bp, *cp;
- int tainted = 0;
-
- if (argc == 1 && rb_block_given_p()) {
- iter = 1;
- }
- else if (argc == 2) {
- repl = argv[1];
- StringValue(repl);
- if (OBJ_TAINTED(repl)) tainted = 1;
- }
- else {
- rb_raise(rb_eArgError, "wrong number of arguments(%d for 2)", argc);
- }
-
- pat = get_pat(argv[0]);
- offset=0; n=0;
- beg = rb_reg_search(pat, str, 0, 0);
- if (beg < 0) {
- if (bang) return Qnil; /* no match, no substitution */
- return rb_str_dup(str);
- }
-
- blen = RSTRING(str)->len + 30; /* len + margin */
- buf = ALLOC_N(char, blen);
- bp = buf;
- cp = RSTRING(str)->ptr;
-
- while (beg >= 0) {
- n++;
- match = rb_backref_get();
- regs = RMATCH(match)->regs;
- if (iter) {
- rb_match_busy(match);
- val = rb_obj_as_string(rb_yield(rb_reg_nth_match(0, match)));
- rb_backref_set(match);
- }
- else {
- val = rb_reg_regsub(repl, str, regs);
- }
- if (OBJ_TAINTED(val)) tainted = 1;
- len = (bp - buf) + (beg - offset) + RSTRING(val)->len + 3;
- if (blen < len) {
- while (blen < len) blen *= 2;
- len = bp - buf;
- REALLOC_N(buf, char, blen);
- bp = buf + len;
- }
- len = beg - offset; /* copy pre-match substr */
- memcpy(bp, cp, len);
- bp += len;
- memcpy(bp, RSTRING(val)->ptr, RSTRING(val)->len);
- bp += RSTRING(val)->len;
- if (BEG(0) == END(0)) {
- /*
- * Always consume at least one character of the input string
- * in order to prevent infinite loops.
- */
- len = mbclen2(RSTRING(str)->ptr[END(0)], pat);
- if (RSTRING(str)->len > END(0)) {
- memcpy(bp, RSTRING(str)->ptr+END(0), len);
- bp += len;
- }
- offset = END(0) + len;
- }
- else {
- offset = END(0);
- }
- cp = RSTRING(str)->ptr + offset;
- if (offset > RSTRING(str)->len) break;
- beg = rb_reg_search(pat, str, offset, 0);
- }
- if (RSTRING(str)->len > offset) {
- len = bp - buf;
- if (blen - len < RSTRING(str)->len - offset + 1) {
- REALLOC_N(buf, char, len + RSTRING(str)->len - offset + 1);
- bp = buf + len;
- }
- memcpy(bp, cp, RSTRING(str)->len - offset);
- bp += RSTRING(str)->len - offset;
- }
- rb_backref_set(match);
- if (bang) {
- if (str_independent(str)) {
- free(RSTRING(str)->ptr);
- }
- FL_UNSET(str, ELTS_SHARED|STR_ASSOC);
- }
- else {
- VALUE dup = rb_obj_alloc(rb_obj_class(str));
-
- OBJ_INFECT(dup, str);
- str = dup;
- }
- RSTRING(str)->ptr = buf;
- RSTRING(str)->len = len = bp - buf;
- RSTRING(str)->ptr[len] = '\0';
- RSTRING(str)->aux.capa = len;
-
- if (tainted) OBJ_TAINT(str);
- return str;
-}
-
-static VALUE
-rb_str_gsub_bang(argc, argv, str)
- int argc;
- VALUE *argv;
- VALUE str;
-{
- return str_gsub(argc, argv, str, 1);
-}
-
-static VALUE
-rb_str_gsub(argc, argv, str)
- int argc;
- VALUE *argv;
- VALUE str;
-{
- return str_gsub(argc, argv, str, 0);
-}
-
-static VALUE
-rb_str_replace(str, str2)
- VALUE str, str2;
-{
- if (str == str2) return str;
-
- StringValue(str2);
- if (FL_TEST(str2, ELTS_SHARED)) {
- if (str_independent(str)) {
- free(RSTRING(str)->ptr);
- }
- RSTRING(str)->len = RSTRING(str2)->len;
- RSTRING(str)->ptr = RSTRING(str2)->ptr;
- if (FL_TEST(str2, ELTS_SHARED|STR_ASSOC)) {
- FL_SET(str, RBASIC(str2)->flags & (ELTS_SHARED|STR_ASSOC));
- RSTRING(str)->aux.shared = RSTRING(str2)->aux.shared;
- }
- else {
- RSTRING(str)->aux.capa = RSTRING(str2)->aux.capa;
- }
- }
- else {
- rb_str_modify(str);
- rb_str_resize(str, RSTRING(str2)->len);
- memcpy(RSTRING(str)->ptr, RSTRING(str2)->ptr, RSTRING(str2)->len);
- }
-
- OBJ_INFECT(str, str2);
- return str;
-}
-
-static VALUE
-uscore_get()
-{
- VALUE line;
-
- line = rb_lastline_get();
- if (TYPE(line) != T_STRING) {
- rb_raise(rb_eTypeError, "$_ value need to be String (%s given)",
- NIL_P(line) ? "nil" : rb_class2name(CLASS_OF(line)));
- }
- return line;
-}
-
-static VALUE
-rb_f_sub_bang(argc, argv)
- int argc;
- VALUE *argv;
-{
- return rb_str_sub_bang(argc, argv, uscore_get());
-}
-
-static VALUE
-rb_f_sub(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE str = rb_str_dup(uscore_get());
-
- if (NIL_P(rb_str_sub_bang(argc, argv, str)))
- return str;
- rb_lastline_set(str);
- return str;
-}
-
-static VALUE
-rb_f_gsub_bang(argc, argv)
- int argc;
- VALUE *argv;
-{
- return rb_str_gsub_bang(argc, argv, uscore_get());
-}
-
-static VALUE
-rb_f_gsub(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE str = rb_str_dup(uscore_get());
-
- if (NIL_P(rb_str_gsub_bang(argc, argv, str)))
- return str;
- rb_lastline_set(str);
- return str;
-}
-
-static VALUE
-rb_str_reverse_bang(str)
- VALUE str;
-{
- char *s, *e;
- char c;
-
- rb_str_modify(str);
- s = RSTRING(str)->ptr;
- e = s + RSTRING(str)->len - 1;
- while (s < e) {
- c = *s;
- *s++ = *e;
- *e-- = c;
- }
-
- return str;
-}
-
-static VALUE
-rb_str_reverse(str)
- VALUE str;
-{
- VALUE obj;
- char *s, *e, *p;
-
- if (RSTRING(str)->len <= 1) return rb_str_dup(str);
-
- obj = rb_str_new5(str, 0, RSTRING(str)->len);
- s = RSTRING(str)->ptr; e = s + RSTRING(str)->len - 1;
- p = RSTRING(obj)->ptr;
-
- while (e >= s) {
- *p++ = *e--;
- }
- OBJ_INFECT(obj, str);
-
- return obj;
-}
-
-static VALUE
-rb_str_include(str, arg)
- VALUE str, arg;
-{
- long i;
-
- if (FIXNUM_P(arg)) {
- int c = FIX2INT(arg);
- long len = RSTRING(str)->len;
- char *p = RSTRING(str)->ptr;
-
- for (i=0; i<len; i++) {
- if (p[i] == c) {
- return Qtrue;
- }
- }
- return Qfalse;
- }
-
- StringValue(arg);
- i = rb_str_index(str, arg, 0);
-
- if (i == -1) return Qfalse;
- return Qtrue;
-}
-
-static VALUE
-rb_str_to_i(argc, argv, str)
- int argc;
- VALUE *argv;
- VALUE str;
-{
- VALUE b;
- int base;
-
- rb_scan_args(argc, argv, "01", &b);
- if (argc == 0) base = 10;
- else base = NUM2INT(b);
-
- switch (base) {
- case 0: case 2: case 8: case 10: case 16:
- break;
- default:
- rb_raise(rb_eArgError, "illegal radix %d", base);
- }
- return rb_str_to_inum(str, base, Qfalse);
-}
-
-static VALUE
-rb_str_to_f(str)
- VALUE str;
-{
- return rb_float_new(rb_str_to_dbl(str, Qfalse));
-}
-
-static VALUE
-rb_str_to_s(str)
- VALUE str;
-{
- return str;
-}
-
-VALUE
-rb_str_inspect(str)
- VALUE str;
-{
- char *p, *pend;
- VALUE result = rb_str_buf_new2("\"");
- char s[5];
-
- p = RSTRING(str)->ptr; pend = p + RSTRING(str)->len;
- while (p < pend) {
- char c = *p++;
- if (ismbchar(c) && p < pend) {
- int len = mbclen(c);
- rb_str_buf_cat(result, p - 1, len);
- p += len - 1;
- }
- else if (c == '"'|| c == '\\') {
- s[0] = '\\'; s[1] = c;
- rb_str_buf_cat(result, s, 2);
- }
- else if (ISPRINT(c)) {
- s[0] = c;
- rb_str_buf_cat(result, s, 1);
- }
- else if (c == '\n') {
- s[0] = '\\'; s[1] = 'n';
- rb_str_buf_cat(result, s, 2);
- }
- else if (c == '\r') {
- s[0] = '\\'; s[1] = 'r';
- rb_str_buf_cat(result, s, 2);
- }
- else if (c == '\t') {
- s[0] = '\\'; s[1] = 't';
- rb_str_buf_cat(result, s, 2);
- }
- else if (c == '\f') {
- s[0] = '\\'; s[1] = 'f';
- rb_str_buf_cat(result, s, 2);
- }
- else if (c == '\013') {
- s[0] = '\\'; s[1] = 'v';
- rb_str_buf_cat(result, s, 2);
- }
- else if (c == '\007') {
- s[0] = '\\'; s[1] = 'a';
- rb_str_buf_cat(result, s, 2);
- }
- else if (c == 033) {
- s[0] = '\\'; s[1] = 'e';
- rb_str_buf_cat(result, s, 2);
- }
- else {
- sprintf(s, "\\%03o", c & 0377);
- rb_str_buf_cat2(result, s);
- }
- }
- rb_str_buf_cat2(result, "\"");
-
- OBJ_INFECT(result, str);
- return result;
-}
-
-static VALUE
-rb_str_dump(str)
- VALUE str;
-{
- long len;
- char *p, *pend;
- char *q, *qend;
- VALUE result;
-
- len = 2; /* "" */
- p = RSTRING(str)->ptr; pend = p + RSTRING(str)->len;
- while (p < pend) {
- char c = *p++;
- switch (c) {
- case '"': case '\\':
- case '\n': case '\r':
- case '\t': case '\f': case '#':
- case '\013': case '\007': case '\033':
- len += 2;
- break;
-
- default:
- if (ISPRINT(c)) {
- len++;
- }
- else {
- len += 4; /* \nnn */
- }
- break;
- }
- }
-
- result = rb_str_new5(str, 0, len);
- p = RSTRING(str)->ptr; pend = p + RSTRING(str)->len;
- q = RSTRING(result)->ptr; qend = q + len;
-
- *q++ = '"';
- while (p < pend) {
- char c = *p++;
-
- if (c == '"' || c == '\\') {
- *q++ = '\\';
- *q++ = c;
- }
- else if (c == '#') {
- *q++ = '\\';
- *q++ = '#';
- }
- else if (ISPRINT(c)) {
- *q++ = c;
- }
- else if (c == '\n') {
- *q++ = '\\';
- *q++ = 'n';
- }
- else if (c == '\r') {
- *q++ = '\\';
- *q++ = 'r';
- }
- else if (c == '\t') {
- *q++ = '\\';
- *q++ = 't';
- }
- else if (c == '\f') {
- *q++ = '\\';
- *q++ = 'f';
- }
- else if (c == '\013') {
- *q++ = '\\';
- *q++ = 'v';
- }
- else if (c == '\007') {
- *q++ = '\\';
- *q++ = 'a';
- }
- else if (c == '\033') {
- *q++ = '\\';
- *q++ = 'e';
- }
- else {
- *q++ = '\\';
- sprintf(q, "%03o", c&0xff);
- q += 3;
- }
- }
- *q++ = '"';
-
- OBJ_INFECT(result, str);
- return result;
-}
-
-static VALUE
-rb_str_upcase_bang(str)
- VALUE str;
-{
- char *s, *send;
- int modify = 0;
-
- rb_str_modify(str);
- s = RSTRING(str)->ptr; send = s + RSTRING(str)->len;
- while (s < send) {
- if (ismbchar(*s)) {
- s+=mbclen(*s) - 1;
- }
- else if (ISLOWER(*s)) {
- *s = toupper(*s);
- modify = 1;
- }
- s++;
- }
-
- if (modify) return str;
- return Qnil;
-}
-
-static VALUE
-rb_str_upcase(str)
- VALUE str;
-{
- str = rb_str_dup(str);
- rb_str_upcase_bang(str);
- return str;
-}
-
-static VALUE
-rb_str_downcase_bang(str)
- VALUE str;
-{
- char *s, *send;
- int modify = 0;
-
- rb_str_modify(str);
- s = RSTRING(str)->ptr; send = s + RSTRING(str)->len;
- while (s < send) {
- if (ismbchar(*s)) {
- s+=mbclen(*s) - 1;
- }
- else if (ISUPPER(*s)) {
- *s = tolower(*s);
- modify = 1;
- }
- s++;
- }
-
- if (modify) return str;
- return Qnil;
-}
-
-static VALUE
-rb_str_downcase(str)
- VALUE str;
-{
- str = rb_str_dup(str);
- rb_str_downcase_bang(str);
- return str;
-}
-
-static VALUE
-rb_str_capitalize_bang(str)
- VALUE str;
-{
- char *s, *send;
- int modify = 0;
-
- rb_str_modify(str);
- s = RSTRING(str)->ptr; send = s + RSTRING(str)->len;
- if (ISLOWER(*s)) {
- *s = toupper(*s);
- modify = 1;
- }
- while (++s < send) {
- if (ismbchar(*s)) {
- s+=mbclen(*s) - 1;
- }
- else if (ISUPPER(*s)) {
- *s = tolower(*s);
- modify = 1;
- }
- }
- if (modify) return str;
- return Qnil;
-}
-
-static VALUE
-rb_str_capitalize(str)
- VALUE str;
-{
- str = rb_str_dup(str);
- rb_str_capitalize_bang(str);
- return str;
-}
-
-static VALUE
-rb_str_swapcase_bang(str)
- VALUE str;
-{
- char *s, *send;
- int modify = 0;
-
- rb_str_modify(str);
- s = RSTRING(str)->ptr; send = s + RSTRING(str)->len;
- while (s < send) {
- if (ismbchar(*s)) {
- s+=mbclen(*s) - 1;
- }
- else if (ISUPPER(*s)) {
- *s = tolower(*s);
- modify = 1;
- }
- else if (ISLOWER(*s)) {
- *s = toupper(*s);
- modify = 1;
- }
- s++;
- }
-
- if (modify) return str;
- return Qnil;
-}
-
-static VALUE
-rb_str_swapcase(str)
- VALUE str;
-{
- str = rb_str_dup(str);
- rb_str_swapcase_bang(str);
- return str;
-}
-
-typedef unsigned char *USTR;
-
-struct tr {
- int gen, now, max;
- char *p, *pend;
-};
-
-static int
-trnext(t)
- struct tr *t;
-{
- for (;;) {
- if (!t->gen) {
- if (t->p == t->pend) return -1;
- if (t->p < t->pend - 1 && *t->p == '\\') {
- t->p++;
- }
- t->now = *(USTR)t->p++;
- if (t->p < t->pend - 1 && *t->p == '-') {
- t->p++;
- if (t->p < t->pend) {
- if (t->now > *(USTR)t->p) {
- t->p++;
- continue;
- }
- t->gen = 1;
- t->max = *(USTR)t->p++;
- }
- }
- return t->now;
- }
- else if (++t->now < t->max) {
- return t->now;
- }
- else {
- t->gen = 0;
- return t->max;
- }
- }
-}
-
-static VALUE rb_str_delete_bang _((int,VALUE*,VALUE));
-
-static VALUE
-tr_trans(str, src, repl, sflag)
- VALUE str, src, repl;
- int sflag;
-{
- struct tr trsrc, trrepl;
- int cflag = 0;
- int trans[256];
- int i, c, modify = 0;
- char *s, *send;
-
- rb_str_modify(str);
- StringValue(src);
- StringValue(repl);
- trsrc.p = RSTRING(src)->ptr; trsrc.pend = trsrc.p + RSTRING(src)->len;
- if (RSTRING(src)->len >= 2 && RSTRING(src)->ptr[0] == '^') {
- cflag++;
- trsrc.p++;
- }
- if (RSTRING(repl)->len == 0) {
- return rb_str_delete_bang(1, &src, str);
- }
- trrepl.p = RSTRING(repl)->ptr;
- trrepl.pend = trrepl.p + RSTRING(repl)->len;
- trsrc.gen = trrepl.gen = 0;
- trsrc.now = trrepl.now = 0;
- trsrc.max = trrepl.max = 0;
-
- if (cflag) {
- for (i=0; i<256; i++) {
- trans[i] = 1;
- }
- while ((c = trnext(&trsrc)) >= 0) {
- trans[c & 0xff] = -1;
- }
- while ((c = trnext(&trrepl)) >= 0)
- /* retrieve last replacer */;
- for (i=0; i<256; i++) {
- if (trans[i] >= 0) {
- trans[i] = trrepl.now;
- }
- }
- }
- else {
- int r;
-
- for (i=0; i<256; i++) {
- trans[i] = -1;
- }
- while ((c = trnext(&trsrc)) >= 0) {
- r = trnext(&trrepl);
- if (r == -1) r = trrepl.now;
- trans[c & 0xff] = r;
- }
- }
-
- s = RSTRING(str)->ptr; send = s + RSTRING(str)->len;
- if (sflag) {
- char *t = s;
- int c0, last = -1;
-
- while (s < send) {
- c0 = *s++;
- if ((c = trans[c0 & 0xff]) >= 0) {
- if (last == c) continue;
- last = c;
- *t++ = c & 0xff;
- modify = 1;
- }
- else {
- last = -1;
- *t++ = c0;
- }
- }
- if (RSTRING(str)->len > (t - RSTRING(str)->ptr)) {
- RSTRING(str)->len = (t - RSTRING(str)->ptr);
- modify = 1;
- *t = '\0';
- }
- }
- else {
- while (s < send) {
- if ((c = trans[*s & 0xff]) >= 0) {
- *s = c & 0xff;
- modify = 1;
- }
- s++;
- }
- }
-
- if (modify) return str;
- return Qnil;
-}
-
-static VALUE
-rb_str_tr_bang(str, src, repl)
- VALUE str, src, repl;
-{
- return tr_trans(str, src, repl, 0);
-}
-
-static VALUE
-rb_str_tr(str, src, repl)
- VALUE str, src, repl;
-{
- str = rb_str_dup(str);
- tr_trans(str, src, repl, 0);
- return str;
-}
-
-static void
-tr_setup_table(str, table, init)
- VALUE str;
- char table[256];
- int init;
-{
- char buf[256];
- struct tr tr;
- int i, c;
- int cflag = 0;
-
- tr.p = RSTRING(str)->ptr; tr.pend = tr.p + RSTRING(str)->len;
- tr.gen = tr.now = tr.max = 0;
- if (RSTRING(str)->len > 1 && RSTRING(str)->ptr[0] == '^') {
- cflag = 1;
- tr.p++;
- }
-
- if (init) {
- for (i=0; i<256; i++) {
- table[i] = 1;
- }
- }
- for (i=0; i<256; i++) {
- buf[i] = cflag;
- }
- while ((c = trnext(&tr)) >= 0) {
- buf[c & 0xff] = !cflag;
- }
- for (i=0; i<256; i++) {
- table[i] = table[i]&&buf[i];
- }
-}
-
-static VALUE
-rb_str_delete_bang(argc, argv, str)
- int argc;
- VALUE *argv;
- VALUE str;
-{
- char *s, *send, *t;
- char squeez[256];
- int modify = 0;
- int init = 1;
- int i;
-
- if (argc < 1) {
- rb_raise(rb_eArgError, "wrong number of arguments");
- }
- for (i=0; i<argc; i++) {
- VALUE s = argv[i];
-
- StringValue(s);
- tr_setup_table(s, squeez, init);
- init = 0;
- }
-
- rb_str_modify(str);
- s = t = RSTRING(str)->ptr;
- send = s + RSTRING(str)->len;
- while (s < send) {
- if (squeez[*s & 0xff])
- modify = 1;
- else
- *t++ = *s;
- s++;
- }
- *t = '\0';
- RSTRING(str)->len = t - RSTRING(str)->ptr;
-
- if (modify) return str;
- return Qnil;
-}
-
-static VALUE
-rb_str_delete(argc, argv, str)
- int argc;
- VALUE *argv;
- VALUE str;
-{
- str = rb_str_dup(str);
- rb_str_delete_bang(argc, argv, str);
- return str;
-}
-
-static VALUE
-rb_str_squeeze_bang(argc, argv, str)
- int argc;
- VALUE *argv;
- VALUE str;
-{
- char squeez[256];
- char *s, *send, *t;
- int c, save, modify = 0;
- int init = 1;
- int i;
-
- if (argc == 0) {
- for (i=0; i<256; i++) {
- squeez[i] = 1;
- }
- }
- else {
- for (i=0; i<argc; i++) {
- VALUE s = argv[i];
-
- StringValue(s);
- tr_setup_table(s, squeez, init);
- init = 0;
- }
- }
-
- rb_str_modify(str);
-
- s = t = RSTRING(str)->ptr;
- send = s + RSTRING(str)->len;
- save = -1;
- while (s < send) {
- c = *s++ & 0xff;
- if (c != save || !squeez[c]) {
- *t++ = save = c;
- }
- }
- *t = '\0';
- if (t - RSTRING(str)->ptr != RSTRING(str)->len) {
- RSTRING(str)->len = t - RSTRING(str)->ptr;
- modify = 1;
- }
-
- if (modify) return str;
- return Qnil;
-}
-
-static VALUE
-rb_str_squeeze(argc, argv, str)
- int argc;
- VALUE *argv;
- VALUE str;
-{
- str = rb_str_dup(str);
- rb_str_squeeze_bang(argc, argv, str);
- return str;
-}
-
-static VALUE
-rb_str_tr_s_bang(str, src, repl)
- VALUE str, src, repl;
-{
- return tr_trans(str, src, repl, 1);
-}
-
-static VALUE
-rb_str_tr_s(str, src, repl)
- VALUE str, src, repl;
-{
- str = rb_str_dup(str);
- tr_trans(str, src, repl, 1);
- return str;
-}
-
-static VALUE
-rb_str_count(argc, argv, str)
- int argc;
- VALUE *argv;
- VALUE str;
-{
- char table[256];
- char *s, *send;
- int init = 1;
- int i;
-
- if (argc < 1) {
- rb_raise(rb_eArgError, "wrong number of arguments");
- }
- for (i=0; i<argc; i++) {
- VALUE s = argv[i];
-
- StringValue(s);
- tr_setup_table(s, table, init);
- init = 0;
- }
-
- s = RSTRING(str)->ptr;
- send = s + RSTRING(str)->len;
- i = 0;
- while (s < send) {
- if (table[*s++ & 0xff]) {
- i++;
- }
- }
- return INT2NUM(i);
-}
-
-static VALUE
-rb_str_split_m(argc, argv, str)
- int argc;
- VALUE *argv;
- VALUE str;
-{
- VALUE spat;
- VALUE limit;
- int char_sep = -1;
- long beg, end, i;
- int lim = 0;
- VALUE result, tmp;
-
- if (rb_scan_args(argc, argv, "02", &spat, &limit) == 2) {
- lim = NUM2INT(limit);
- if (lim <= 0) limit = Qnil;
- else if (lim == 1) return rb_ary_new3(1, str);
- i = 1;
- }
-
- if (argc == 0) {
- if (!NIL_P(rb_fs)) {
- spat = rb_fs;
- goto fs_set;
- }
- char_sep = ' ';
- }
- else {
- fs_set:
- switch (TYPE(spat)) {
- case T_STRING:
- if (RSTRING(spat)->len == 1) {
- char_sep = (unsigned char)RSTRING(spat)->ptr[0];
- }
- else {
- spat = rb_reg_regcomp(spat);
- }
- break;
- case T_REGEXP:
- break;
- default:
- rb_raise(rb_eArgError, "bad separator");
- }
- }
-
- result = rb_ary_new();
- beg = 0;
- if (char_sep >= 0) {
- char *ptr = RSTRING(str)->ptr;
- long len = RSTRING(str)->len;
- char *eptr = ptr + len;
-
- if (char_sep == ' ') { /* AWK emulation */
- int skip = 1;
-
- for (end = beg = 0; ptr<eptr; ptr++) {
- if (skip) {
- if (ISSPACE(*ptr)) {
- beg++;
- }
- else {
- end = beg+1;
- skip = 0;
- }
- }
- else {
- if (ISSPACE(*ptr)) {
- rb_ary_push(result, rb_str_substr(str, beg, end-beg));
- skip = 1;
- beg = end + 1;
- if (!NIL_P(limit) && lim <= ++i) break;
- }
- else {
- end++;
- }
- }
- }
- }
- else {
- for (end = beg = 0; ptr<eptr; ptr++) {
- if (*ptr == (char)char_sep) {
- rb_ary_push(result, rb_str_substr(str, beg, end-beg));
- beg = end + 1;
- if (!NIL_P(limit) && lim <= ++i) break;
- }
- end++;
- }
- }
- }
- else {
- long start = beg;
- long idx;
- int last_null = 0;
- struct re_registers *regs;
-
- while ((end = rb_reg_search(spat, str, start, 0)) >= 0) {
- regs = RMATCH(rb_backref_get())->regs;
- if (start == end && BEG(0) == END(0)) {
- if (last_null == 1) {
- rb_ary_push(result, rb_str_substr(str, beg, mbclen2(RSTRING(str)->ptr[beg],spat)));
- beg = start;
- }
- else {
- start += mbclen2(RSTRING(str)->ptr[start],spat);
- last_null = 1;
- continue;
- }
- }
- else {
- rb_ary_push(result, rb_str_substr(str, beg, end-beg));
- beg = start = END(0);
- }
- last_null = 0;
-
- for (idx=1; idx < regs->num_regs; idx++) {
- if (BEG(idx) == -1) continue;
- if (BEG(idx) == END(idx))
- tmp = rb_str_new5(str, 0, 0);
- else
- tmp = rb_str_substr(str, BEG(idx), END(idx)-BEG(idx));
- rb_ary_push(result, tmp);
- }
- if (!NIL_P(limit) && lim <= ++i) break;
- }
- }
- if (!NIL_P(limit) || RSTRING(str)->len > beg || lim < 0) {
- if (RSTRING(str)->len == beg)
- tmp = rb_str_new5(str, 0, 0);
- else
- tmp = rb_str_substr(str, beg, RSTRING(str)->len-beg);
- rb_ary_push(result, tmp);
- }
- if (NIL_P(limit) && lim == 0) {
- while (RARRAY(result)->len > 0 &&
- RSTRING(RARRAY(result)->ptr[RARRAY(result)->len-1])->len == 0)
- rb_ary_pop(result);
- }
-
- return result;
-}
-
-VALUE
-rb_str_split(str, sep0)
- VALUE str;
- const char *sep0;
-{
- VALUE sep;
-
- StringValue(str);
- sep = rb_str_new2(sep0);
- return rb_str_split_m(1, &sep, str);
-}
-
-static VALUE
-rb_f_split(argc, argv)
- int argc;
- VALUE *argv;
-{
- return rb_str_split_m(argc, argv, uscore_get());
-}
-
-static VALUE
-rb_str_each_line(argc, argv, str)
- int argc;
- VALUE *argv;
- VALUE str;
-{
- VALUE rs;
- int newline;
- int rslen;
- char *p = RSTRING(str)->ptr, *pend = p + RSTRING(str)->len, *s;
- char *ptr = p;
- long len = RSTRING(str)->len;
- VALUE line;
-
- if (rb_scan_args(argc, argv, "01", &rs) == 0) {
- rs = rb_rs;
- }
-
- if (NIL_P(rs)) {
- rb_yield(str);
- return str;
- }
- StringValue(rs);
- rslen = RSTRING(rs)->len;
- if (rslen == 0) {
- newline = '\n';
- }
- else {
- newline = RSTRING(rs)->ptr[rslen-1];
- }
-
- for (s = p, p += rslen; p < pend; p++) {
- if (rslen == 0 && *p == '\n') {
- if (*++p != '\n') continue;
- while (*p == '\n') p++;
- }
- if (p[-1] == newline &&
- (rslen <= 1 ||
- rb_memcmp(RSTRING(rs)->ptr, p-rslen, rslen) == 0)) {
- line = rb_str_new5(str, s, p - s);
- OBJ_INFECT(line, str);
- rb_yield(line);
- if (RSTRING(str)->ptr != ptr || RSTRING(str)->len != len)
- rb_raise(rb_eArgError, "string modified");
- s = p;
- }
- }
-
- if (s != pend) {
- if (p > pend) p = pend;
- line = rb_str_new5(str, s, p - s);
- OBJ_INFECT(line, str);
- rb_yield(line);
- }
-
- return str;
-}
-
-static VALUE
-rb_str_each_byte(str)
- VALUE str;
-{
- long i;
-
- for (i=0; i<RSTRING(str)->len; i++) {
- rb_yield(INT2FIX(RSTRING(str)->ptr[i] & 0xff));
- }
- return str;
-}
-
-static VALUE
-rb_str_chop_bang(str)
- VALUE str;
-{
- if (RSTRING(str)->len > 0) {
- rb_str_modify(str);
- RSTRING(str)->len--;
- if (RSTRING(str)->ptr[RSTRING(str)->len] == '\n') {
- if (RSTRING(str)->len > 0 &&
- RSTRING(str)->ptr[RSTRING(str)->len-1] == '\r') {
- RSTRING(str)->len--;
- }
- }
- RSTRING(str)->ptr[RSTRING(str)->len] = '\0';
- return str;
- }
- return Qnil;
-}
-
-static VALUE
-rb_str_chop(str)
- VALUE str;
-{
- str = rb_str_dup(str);
- rb_str_chop_bang(str);
- return str;
-}
-
-static VALUE
-rb_f_chop_bang(str)
- VALUE str;
-{
- return rb_str_chop_bang(uscore_get());
-}
-
-static VALUE
-rb_f_chop()
-{
- VALUE str = uscore_get();
-
- if (RSTRING(str)->len > 0) {
- str = rb_str_dup(str);
- rb_str_chop_bang(str);
- rb_lastline_set(str);
- }
- return str;
-}
-
-static VALUE
-rb_str_chomp_bang(argc, argv, str)
- int argc;
- VALUE *argv;
- VALUE str;
-{
- VALUE rs;
- int newline;
- int rslen;
- char *p = RSTRING(str)->ptr;
- long len = RSTRING(str)->len;
-
- if (rb_scan_args(argc, argv, "01", &rs) == 0) {
- if (len == 0) return Qnil;
- rs = rb_rs;
- if (rs == rb_default_rs) {
- smart_chomp:
- rb_str_modify(str);
- if (RSTRING(str)->ptr[len-1] == '\n') {
- RSTRING(str)->len--;
- if (RSTRING(str)->len > 0 &&
- RSTRING(str)->ptr[RSTRING(str)->len-1] == '\r') {
- RSTRING(str)->len--;
- }
- }
- else if (RSTRING(str)->ptr[len-1] == '\r') {
- RSTRING(str)->len--;
- }
- else {
- return Qnil;
- }
- RSTRING(str)->ptr[RSTRING(str)->len] = '\0';
- return str;
- }
- }
- if (NIL_P(rs)) return Qnil;
- if (len == 0) return Qnil;
-
- StringValue(rs);
- rb_str_modify(str);
- rslen = RSTRING(rs)->len;
- if (rslen == 0) {
- while (len>0 && p[len-1] == '\n') {
- len--;
- if (len>0 && p[len-1] == '\r')
- len--;
- }
- if (len < RSTRING(str)->len) {
- rb_str_modify(str);
- RSTRING(str)->len = len;
- RSTRING(str)->ptr[len] = '\0';
- return str;
- }
- return Qnil;
- }
- if (rslen > len) return Qnil;
- newline = RSTRING(rs)->ptr[rslen-1];
- if (rslen == 1 && newline == '\n')
- goto smart_chomp;
-
- if (p[len-1] == newline &&
- (rslen <= 1 ||
- rb_memcmp(RSTRING(rs)->ptr, p+len-rslen, rslen) == 0)) {
- rb_str_modify(str);
- RSTRING(str)->len -= rslen;
- RSTRING(str)->ptr[RSTRING(str)->len] = '\0';
- return str;
- }
- return Qnil;
-}
-
-static VALUE
-rb_str_chomp(argc, argv, str)
- int argc;
- VALUE *argv;
- VALUE str;
-{
- str = rb_str_dup(str);
- rb_str_chomp_bang(argc, argv, str);
- return str;
-}
-
-static VALUE
-rb_f_chomp_bang(argc, argv)
- int argc;
- VALUE *argv;
-{
- return rb_str_chomp_bang(argc, argv, uscore_get());
-}
-
-static VALUE
-rb_f_chomp(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE str = uscore_get();
- VALUE dup = rb_str_dup(str);
-
- if (NIL_P(rb_str_chomp_bang(argc, argv, dup)))
- return str;
- rb_lastline_set(dup);
- return dup;
-}
-
-static VALUE
-rb_str_lstrip_bang(str)
- VALUE str;
-{
- char *s, *t, *e;
-
- rb_str_modify(str);
- s = RSTRING(str)->ptr;
- e = t = s + RSTRING(str)->len;
- /* remove spaces at head */
- while (s < t && ISSPACE(*s)) s++;
-
- RSTRING(str)->len = t-s;
- if (s > RSTRING(str)->ptr) {
- memmove(RSTRING(str)->ptr, s, RSTRING(str)->len);
- RSTRING(str)->ptr[RSTRING(str)->len] = '\0';
- return str;
- }
- return Qnil;
-}
-
-static VALUE
-rb_str_lstrip(str)
- VALUE str;
-{
- str = rb_str_dup(str);
- rb_str_lstrip_bang(str);
- return str;
-}
-
-static VALUE
-rb_str_rstrip_bang(str)
- VALUE str;
-{
- char *s, *t, *e;
-
- rb_str_modify(str);
- s = RSTRING(str)->ptr;
- e = t = s + RSTRING(str)->len;
-
- /* remove trailing spaces */
- t--;
- while (s <= t && ISSPACE(*t)) t--;
- t++;
-
- RSTRING(str)->len = t-s;
- if (t < e) {
- RSTRING(str)->ptr[RSTRING(str)->len] = '\0';
- return str;
- }
- return Qnil;
-}
-
-static VALUE
-rb_str_rstrip(str)
- VALUE str;
-{
- str = rb_str_dup(str);
- rb_str_rstrip_bang(str);
- return str;
-}
-
-static VALUE
-rb_str_strip_bang(str)
- VALUE str;
-{
- VALUE l = rb_str_lstrip_bang(str);
- VALUE r = rb_str_rstrip_bang(str);
-
- if (NIL_P(l) && NIL_P(r)) return Qnil;
- return str;
-}
-
-static VALUE
-rb_str_strip(str)
- VALUE str;
-{
- str = rb_str_dup(str);
- rb_str_strip_bang(str);
- return str;
-}
-
-static VALUE
-scan_once(str, pat, start)
- VALUE str, pat;
- long *start;
-{
- VALUE result, match;
- struct re_registers *regs;
- long i;
-
- if (rb_reg_search(pat, str, *start, 0) >= 0) {
- match = rb_backref_get();
- regs = RMATCH(match)->regs;
- if (BEG(0) == END(0)) {
- /*
- * Always consume at least one character of the input string
- */
- *start = END(0)+mbclen2(RSTRING(str)->ptr[END(0)],pat);
- }
- else {
- *start = END(0);
- }
- if (regs->num_regs == 1) {
- return rb_reg_nth_match(0, match);
- }
- result = rb_ary_new2(regs->num_regs);
- for (i=1; i < regs->num_regs; i++) {
- rb_ary_push(result, rb_reg_nth_match(i, match));
- }
-
- return result;
- }
- return Qnil;
-}
-
-static VALUE
-rb_str_scan(str, pat)
- VALUE str, pat;
-{
- VALUE result;
- long start = 0;
- VALUE match = Qnil;
-
- pat = get_pat(pat);
- if (!rb_block_given_p()) {
- VALUE ary = rb_ary_new();
-
- while (!NIL_P(result = scan_once(str, pat, &start))) {
- match = rb_backref_get();
- rb_ary_push(ary, result);
- }
- rb_backref_set(match);
- return ary;
- }
-
- while (!NIL_P(result = scan_once(str, pat, &start))) {
- match = rb_backref_get();
- rb_match_busy(match);
- rb_yield(result);
- rb_backref_set(match); /* restore $~ value */
- }
- rb_backref_set(match);
- return str;
-}
-
-static VALUE
-rb_f_scan(self, pat)
- VALUE self, pat;
-{
- return rb_str_scan(uscore_get(), pat);
-}
-
-static VALUE
-rb_str_hex(str)
- VALUE str;
-{
- return rb_str_to_inum(str, 16, Qfalse);
-}
-
-static VALUE
-rb_str_oct(str)
- VALUE str;
-{
- return rb_str_to_inum(str, -8, Qfalse);
-}
-
-static VALUE
-rb_str_crypt(str, salt)
- VALUE str, salt;
-{
- extern char *crypt();
-
- StringValue(salt);
- if (RSTRING(salt)->len < 2)
- rb_raise(rb_eArgError, "salt too short(need >=2 bytes)");
- return rb_tainted_str_new2(crypt(RSTRING(str)->ptr, RSTRING(salt)->ptr));
-}
-
-static VALUE
-rb_str_intern(str)
- VALUE str;
-{
- ID id;
-
- if (strlen(RSTRING(str)->ptr) != RSTRING(str)->len)
- rb_raise(rb_eArgError, "string contains `\\0'");
- id = rb_intern(RSTRING(str)->ptr);
- return ID2SYM(id);
-}
-
-static VALUE
-rb_str_sum(argc, argv, str)
- int argc;
- VALUE *argv;
- VALUE str;
-{
- VALUE vbits;
- int bits;
- char *p, *pend;
-
- if (rb_scan_args(argc, argv, "01", &vbits) == 0) {
- bits = 16;
- }
- else bits = NUM2INT(vbits);
-
- p = RSTRING(str)->ptr; pend = p + RSTRING(str)->len;
- if (bits > sizeof(long)*CHAR_BIT) {
- VALUE res = INT2FIX(0);
- VALUE mod;
-
- mod = rb_funcall(INT2FIX(1), rb_intern("<<"), 1, INT2FIX(bits));
- mod = rb_funcall(mod, '-', 1, INT2FIX(1));
-
- while (p < pend) {
- res = rb_funcall(res, '+', 1, INT2FIX((unsigned int)*p));
- p++;
- }
- res = rb_funcall(res, '&', 1, mod);
- return res;
- }
- else {
- unsigned int res = 0;
- unsigned int mod = (1<<bits)-1;
-
- if (mod == 0) {
- mod = -1;
- }
- while (p < pend) {
- res += (unsigned int)*p;
- p++;
- }
- res &= mod;
- return rb_int2inum(res);
- }
-}
-
-static VALUE
-rb_str_ljust(str, w)
- VALUE str;
- VALUE w;
-{
- long width = NUM2LONG(w);
- VALUE res;
- char *p, *pend;
-
- if (width < 0 || RSTRING(str)->len >= width) return rb_str_dup(str);
- res = rb_str_new5(str, 0, width);
- memcpy(RSTRING(res)->ptr, RSTRING(str)->ptr, RSTRING(str)->len);
- p = RSTRING(res)->ptr + RSTRING(str)->len; pend = RSTRING(res)->ptr + width;
- while (p < pend) {
- *p++ = ' ';
- }
- OBJ_INFECT(res, str);
- return res;
-}
-
-static VALUE
-rb_str_rjust(str, w)
- VALUE str;
- VALUE w;
-{
- long width = NUM2LONG(w);
- VALUE res;
- char *p, *pend;
-
- if (width < 0 || RSTRING(str)->len >= width) return rb_str_dup(str);
- res = rb_str_new5(str, 0, width);
- p = RSTRING(res)->ptr; pend = p + width - RSTRING(str)->len;
- while (p < pend) {
- *p++ = ' ';
- }
- memcpy(pend, RSTRING(str)->ptr, RSTRING(str)->len);
- OBJ_INFECT(res, str);
- return res;
-}
-
-static VALUE
-rb_str_center(str, w)
- VALUE str;
- VALUE w;
-{
- long width = NUM2LONG(w);
- VALUE res;
- char *p, *pend;
- long n;
-
- if (width < 0 || RSTRING(str)->len >= width) return rb_str_dup(str);
- res = rb_str_new5(str, 0, width);
- n = (width - RSTRING(str)->len)/2;
- p = RSTRING(res)->ptr; pend = p + n;
- while (p < pend) {
- *p++ = ' ';
- }
- memcpy(pend, RSTRING(str)->ptr, RSTRING(str)->len);
- p = pend + RSTRING(str)->len; pend = RSTRING(res)->ptr + width;
- while (p < pend) {
- *p++ = ' ';
- }
- OBJ_INFECT(res, str);
- return res;
-}
-
-void
-rb_str_setter(val, id, var)
- VALUE val;
- ID id;
- VALUE *var;
-{
- if (!NIL_P(val) && TYPE(val) != T_STRING) {
- rb_raise(rb_eTypeError, "value of %s must be String", rb_id2name(id));
- }
- *var = val;
-}
-
-void
-Init_String()
-{
- rb_cString = rb_define_class("String", rb_cObject);
- rb_include_module(rb_cString, rb_mComparable);
- rb_include_module(rb_cString, rb_mEnumerable);
- rb_define_singleton_method(rb_cString, "allocate", rb_str_s_alloc, 0);
- rb_define_method(rb_cString, "initialize", rb_str_init, -1);
- rb_define_method(rb_cString, "clone", rb_str_clone, 0);
- rb_define_method(rb_cString, "dup", rb_str_dup, 0);
- rb_define_method(rb_cString, "<=>", rb_str_cmp_m, 1);
- rb_define_method(rb_cString, "==", rb_str_equal, 1);
- rb_define_method(rb_cString, "===", rb_str_equal, 1);
- rb_define_method(rb_cString, "eql?", rb_str_eql, 1);
- rb_define_method(rb_cString, "hash", rb_str_hash_m, 0);
- rb_define_method(rb_cString, "casecmp", rb_str_casecmp, 1);
- rb_define_method(rb_cString, "+", rb_str_plus, 1);
- rb_define_method(rb_cString, "*", rb_str_times, 1);
- rb_define_method(rb_cString, "%", rb_str_format, 1);
- rb_define_method(rb_cString, "[]", rb_str_aref_m, -1);
- rb_define_method(rb_cString, "[]=", rb_str_aset_m, -1);
- rb_define_method(rb_cString, "insert", rb_str_insert, 2);
- rb_define_method(rb_cString, "length", rb_str_length, 0);
- rb_define_method(rb_cString, "size", rb_str_length, 0);
- rb_define_method(rb_cString, "empty?", rb_str_empty, 0);
- rb_define_method(rb_cString, "=~", rb_str_match, 1);
- rb_define_method(rb_cString, "~", rb_str_match2, 0);
- rb_define_method(rb_cString, "match", rb_str_match_m, 1);
- rb_define_method(rb_cString, "succ", rb_str_succ, 0);
- rb_define_method(rb_cString, "succ!", rb_str_succ_bang, 0);
- rb_define_method(rb_cString, "next", rb_str_succ, 0);
- rb_define_method(rb_cString, "next!", rb_str_succ_bang, 0);
- rb_define_method(rb_cString, "upto", rb_str_upto_m, 1);
- rb_define_method(rb_cString, "index", rb_str_index_m, -1);
- rb_define_method(rb_cString, "rindex", rb_str_rindex, -1);
- rb_define_method(rb_cString, "replace", rb_str_replace, 1);
-
- rb_define_method(rb_cString, "to_i", rb_str_to_i, -1);
- rb_define_method(rb_cString, "to_f", rb_str_to_f, 0);
- rb_define_method(rb_cString, "to_s", rb_str_to_s, 0);
- rb_define_method(rb_cString, "to_str", rb_str_to_s, 0);
- rb_define_method(rb_cString, "inspect", rb_str_inspect, 0);
- rb_define_method(rb_cString, "dump", rb_str_dump, 0);
-
- rb_define_method(rb_cString, "upcase", rb_str_upcase, 0);
- rb_define_method(rb_cString, "downcase", rb_str_downcase, 0);
- rb_define_method(rb_cString, "capitalize", rb_str_capitalize, 0);
- rb_define_method(rb_cString, "swapcase", rb_str_swapcase, 0);
-
- rb_define_method(rb_cString, "upcase!", rb_str_upcase_bang, 0);
- rb_define_method(rb_cString, "downcase!", rb_str_downcase_bang, 0);
- rb_define_method(rb_cString, "capitalize!", rb_str_capitalize_bang, 0);
- rb_define_method(rb_cString, "swapcase!", rb_str_swapcase_bang, 0);
-
- rb_define_method(rb_cString, "hex", rb_str_hex, 0);
- rb_define_method(rb_cString, "oct", rb_str_oct, 0);
- rb_define_method(rb_cString, "split", rb_str_split_m, -1);
- rb_define_method(rb_cString, "reverse", rb_str_reverse, 0);
- rb_define_method(rb_cString, "reverse!", rb_str_reverse_bang, 0);
- rb_define_method(rb_cString, "concat", rb_str_concat, 1);
- rb_define_method(rb_cString, "<<", rb_str_concat, 1);
- rb_define_method(rb_cString, "crypt", rb_str_crypt, 1);
- rb_define_method(rb_cString, "intern", rb_str_intern, 0);
-
- rb_define_method(rb_cString, "include?", rb_str_include, 1);
-
- rb_define_method(rb_cString, "scan", rb_str_scan, 1);
-
- rb_define_method(rb_cString, "ljust", rb_str_ljust, 1);
- rb_define_method(rb_cString, "rjust", rb_str_rjust, 1);
- rb_define_method(rb_cString, "center", rb_str_center, 1);
-
- rb_define_method(rb_cString, "sub", rb_str_sub, -1);
- rb_define_method(rb_cString, "gsub", rb_str_gsub, -1);
- rb_define_method(rb_cString, "chop", rb_str_chop, 0);
- rb_define_method(rb_cString, "chomp", rb_str_chomp, -1);
- rb_define_method(rb_cString, "strip", rb_str_strip, 0);
- rb_define_method(rb_cString, "lstrip", rb_str_lstrip, 0);
- rb_define_method(rb_cString, "rstrip", rb_str_rstrip, 0);
-
- rb_define_method(rb_cString, "sub!", rb_str_sub_bang, -1);
- rb_define_method(rb_cString, "gsub!", rb_str_gsub_bang, -1);
- rb_define_method(rb_cString, "chop!", rb_str_chop_bang, 0);
- rb_define_method(rb_cString, "chomp!", rb_str_chomp_bang, -1);
- rb_define_method(rb_cString, "strip!", rb_str_strip_bang, 0);
- rb_define_method(rb_cString, "lstrip!", rb_str_lstrip_bang, 0);
- rb_define_method(rb_cString, "rstrip!", rb_str_rstrip_bang, 0);
-
- rb_define_method(rb_cString, "tr", rb_str_tr, 2);
- rb_define_method(rb_cString, "tr_s", rb_str_tr_s, 2);
- rb_define_method(rb_cString, "delete", rb_str_delete, -1);
- rb_define_method(rb_cString, "squeeze", rb_str_squeeze, -1);
- rb_define_method(rb_cString, "count", rb_str_count, -1);
-
- rb_define_method(rb_cString, "tr!", rb_str_tr_bang, 2);
- rb_define_method(rb_cString, "tr_s!", rb_str_tr_s_bang, 2);
- rb_define_method(rb_cString, "delete!", rb_str_delete_bang, -1);
- rb_define_method(rb_cString, "squeeze!", rb_str_squeeze_bang, -1);
-
- rb_define_method(rb_cString, "each_line", rb_str_each_line, -1);
- rb_define_method(rb_cString, "each", rb_str_each_line, -1);
- rb_define_method(rb_cString, "each_byte", rb_str_each_byte, 0);
-
- rb_define_method(rb_cString, "sum", rb_str_sum, -1);
-
- rb_define_global_function("sub", rb_f_sub, -1);
- rb_define_global_function("gsub", rb_f_gsub, -1);
-
- rb_define_global_function("sub!", rb_f_sub_bang, -1);
- rb_define_global_function("gsub!", rb_f_gsub_bang, -1);
-
- rb_define_global_function("chop", rb_f_chop, 0);
- rb_define_global_function("chop!", rb_f_chop_bang, 0);
-
- rb_define_global_function("chomp", rb_f_chomp, -1);
- rb_define_global_function("chomp!", rb_f_chomp_bang, -1);
-
- rb_define_global_function("split", rb_f_split, -1);
- rb_define_global_function("scan", rb_f_scan, 1);
-
- rb_define_method(rb_cString, "slice", rb_str_aref_m, -1);
- rb_define_method(rb_cString, "slice!", rb_str_slice_bang, -1);
-
- id_to_s = rb_intern("to_s");
-
- rb_fs = Qnil;
- rb_define_hooked_variable("$;", &rb_fs, 0, rb_str_setter);
- rb_define_hooked_variable("$-F", &rb_fs, 0, rb_str_setter);
-}
diff --git a/struct.c b/struct.c
deleted file mode 100644
index 6a2bb640ab..0000000000
--- a/struct.c
+++ /dev/null
@@ -1,592 +0,0 @@
-/**********************************************************************
-
- struct.c -
-
- $Author$
- $Date$
- created at: Tue Mar 22 18:44:30 JST 1995
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
-
-**********************************************************************/
-
-#include "ruby.h"
-
-VALUE rb_cStruct;
-
-static VALUE struct_alloc _((VALUE));
-
-VALUE
-rb_struct_iv_get(c, name)
- VALUE c;
- char *name;
-{
- ID id;
-
- id = rb_intern(name);
- for (;;) {
- if (rb_ivar_defined(c, id))
- return rb_ivar_get(c, id);
- c = RCLASS(c)->super;
- if (c == 0 || c == rb_cStruct)
- return Qnil;
- }
-}
-
-static VALUE
-rb_struct_s_members(obj)
- VALUE obj;
-{
- VALUE member, ary;
- VALUE *p, *pend;
-
- member = rb_struct_iv_get(obj, "__member__");
- if (NIL_P(member)) {
- rb_bug("uninitialized struct");
- }
- ary = rb_ary_new2(RARRAY(member)->len);
- p = RARRAY(member)->ptr; pend = p + RARRAY(member)->len;
- while (p < pend) {
- rb_ary_push(ary, rb_str_new2(rb_id2name(SYM2ID(*p))));
- p++;
- }
-
- return ary;
-}
-
-static VALUE
-rb_struct_members(obj)
- VALUE obj;
-{
- return rb_struct_s_members(rb_obj_class(obj));
-}
-
-VALUE
-rb_struct_getmember(obj, id)
- VALUE obj;
- ID id;
-{
- VALUE member, slot;
- long i;
-
- member = rb_struct_iv_get(rb_obj_class(obj), "__member__");
- if (NIL_P(member)) {
- rb_bug("uninitialized struct");
- }
- slot = ID2SYM(id);
- for (i=0; i<RARRAY(member)->len; i++) {
- if (RARRAY(member)->ptr[i] == slot) {
- return RSTRUCT(obj)->ptr[i];
- }
- }
- rb_name_error(id, "%s is not struct member", rb_id2name(id));
- return Qnil; /* not reached */
-}
-
-static VALUE
-rb_struct_ref(obj)
- VALUE obj;
-{
- return rb_struct_getmember(obj, rb_frame_last_func());
-}
-
-static VALUE rb_struct_ref0(obj) VALUE obj; {return RSTRUCT(obj)->ptr[0];}
-static VALUE rb_struct_ref1(obj) VALUE obj; {return RSTRUCT(obj)->ptr[1];}
-static VALUE rb_struct_ref2(obj) VALUE obj; {return RSTRUCT(obj)->ptr[2];}
-static VALUE rb_struct_ref3(obj) VALUE obj; {return RSTRUCT(obj)->ptr[3];}
-static VALUE rb_struct_ref4(obj) VALUE obj; {return RSTRUCT(obj)->ptr[4];}
-static VALUE rb_struct_ref5(obj) VALUE obj; {return RSTRUCT(obj)->ptr[5];}
-static VALUE rb_struct_ref6(obj) VALUE obj; {return RSTRUCT(obj)->ptr[6];}
-static VALUE rb_struct_ref7(obj) VALUE obj; {return RSTRUCT(obj)->ptr[7];}
-static VALUE rb_struct_ref8(obj) VALUE obj; {return RSTRUCT(obj)->ptr[8];}
-static VALUE rb_struct_ref9(obj) VALUE obj; {return RSTRUCT(obj)->ptr[9];}
-
-static VALUE (*ref_func[10])() = {
- rb_struct_ref0,
- rb_struct_ref1,
- rb_struct_ref2,
- rb_struct_ref3,
- rb_struct_ref4,
- rb_struct_ref5,
- rb_struct_ref6,
- rb_struct_ref7,
- rb_struct_ref8,
- rb_struct_ref9,
-};
-
-static void
-rb_struct_modify(s)
- VALUE s;
-{
- if (OBJ_FROZEN(s)) rb_error_frozen("Struct");
- if (!OBJ_TAINTED(s) && rb_safe_level() >= 4)
- rb_raise(rb_eSecurityError, "Insecure: can't modify Struct");
-}
-
-static VALUE
-rb_struct_set(obj, val)
- VALUE obj, val;
-{
- VALUE member, slot;
- long i;
-
- member = rb_struct_iv_get(rb_obj_class(obj), "__member__");
- if (NIL_P(member)) {
- rb_bug("uninitialized struct");
- }
- rb_struct_modify(obj);
- for (i=0; i<RARRAY(member)->len; i++) {
- slot = RARRAY(member)->ptr[i];
- if (rb_id_attrset(SYM2ID(slot)) == rb_frame_last_func()) {
- return RSTRUCT(obj)->ptr[i] = val;
- }
- }
- rb_name_error(rb_frame_last_func(), "`%s' is not a struct member",
- rb_id2name(rb_frame_last_func()));
- return Qnil; /* not reached */
-}
-
-static VALUE
-make_struct(name, member, klass)
- VALUE name, member, klass;
-{
- VALUE nstr;
- ID id;
- long i;
-
- if (NIL_P(name)) {
- nstr = rb_class_new(klass);
- rb_class_inherited(klass, nstr);
- }
- else {
- char *cname = StringValuePtr(name);
- id = rb_intern(cname);
- if (!rb_is_const_id(id)) {
- rb_name_error(id, "identifier %s needs to be constant", cname);
- }
- nstr = rb_define_class_under(klass, cname, klass);
- }
- rb_iv_set(nstr, "__size__", INT2NUM(RARRAY(member)->len));
- rb_iv_set(nstr, "__member__", member);
-
- rb_define_singleton_method(nstr, "allocate", struct_alloc, 0);
- rb_define_singleton_method(nstr, "new", rb_class_new_instance, -1);
- rb_define_singleton_method(nstr, "[]", rb_class_new_instance, -1);
- rb_define_singleton_method(nstr, "members", rb_struct_s_members, 0);
- for (i=0; i< RARRAY(member)->len; i++) {
- ID id = SYM2ID(RARRAY(member)->ptr[i]);
- if (i<10) {
- rb_define_method_id(nstr, id, ref_func[i], 0);
- }
- else {
- rb_define_method_id(nstr, id, rb_struct_ref, 0);
- }
- rb_define_method_id(nstr, rb_id_attrset(id), rb_struct_set, 1);
- }
-
- return nstr;
-}
-
-#ifdef HAVE_STDARG_PROTOTYPES
-#include <stdarg.h>
-#define va_init_list(a,b) va_start(a,b)
-#else
-#include <varargs.h>
-#define va_init_list(a,b) va_start(a)
-#endif
-
-VALUE
-#ifdef HAVE_STDARG_PROTOTYPES
-rb_struct_define(const char *name, ...)
-#else
-rb_struct_define(name, va_alist)
- const char *name;
- va_dcl
-#endif
-{
- va_list ar;
- VALUE nm, ary;
- char *mem;
-
- if (!name) nm = Qnil;
- else nm = rb_str_new2(name);
- ary = rb_ary_new();
-
- va_init_list(ar, name);
- while (mem = va_arg(ar, char*)) {
- ID slot = rb_intern(mem);
- rb_ary_push(ary, ID2SYM(slot));
- }
- va_end(ar);
-
- return make_struct(nm, ary, rb_cStruct);
-}
-
-static VALUE
-rb_struct_s_def(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- VALUE name, rest;
- long i;
- VALUE st;
- ID id;
-
- rb_scan_args(argc, argv, "1*", &name, &rest);
- for (i=0; i<RARRAY(rest)->len; i++) {
- id = rb_to_id(RARRAY(rest)->ptr[i]);
- RARRAY(rest)->ptr[i] = ID2SYM(id);
- }
- if (!NIL_P(name) && TYPE(name) != T_STRING) {
- id = rb_to_id(name);
- rb_ary_unshift(rest, ID2SYM(id));
- name = Qnil;
- }
- st = make_struct(name, rest, klass);
-
- return st;
-}
-
-static VALUE
-rb_struct_initialize(self, values)
- VALUE self, values;
-{
- VALUE klass = rb_obj_class(self);
- VALUE size;
- long n;
-
- rb_struct_modify(self);
- size = rb_struct_iv_get(klass, "__size__");
- n = FIX2LONG(size);
- if (n < RARRAY(values)->len) {
- rb_raise(rb_eArgError, "struct size differs");
- }
- MEMCPY(RSTRUCT(self)->ptr, RARRAY(values)->ptr, VALUE, RARRAY(values)->len);
- if (n > RARRAY(values)->len) {
- rb_mem_clear(RSTRUCT(self)->ptr+RARRAY(values)->len,
- n-RARRAY(values)->len);
- }
- return Qnil;
-}
-
-static VALUE
-struct_alloc(klass)
- VALUE klass;
-{
- VALUE size;
- long n;
- NEWOBJ(st, struct RStruct);
- OBJSETUP(st, klass, T_STRUCT);
-
- size = rb_struct_iv_get(klass, "__size__");
- n = FIX2LONG(size);
-
- st->ptr = ALLOC_N(VALUE, n);
- rb_mem_clear(st->ptr, n);
- st->len = n;
-
- return (VALUE)st;
-}
-
-VALUE
-rb_struct_alloc(klass, values)
- VALUE klass, values;
-{
- return rb_class_new_instance(RARRAY(values)->len, RARRAY(values)->ptr, klass);
-}
-
-VALUE
-#ifdef HAVE_STDARG_PROTOTYPES
-rb_struct_new(VALUE klass, ...)
-#else
-rb_struct_new(klass, va_alist)
- VALUE klass;
- va_dcl
-#endif
-{
- VALUE sz, *mem;
- long size, i;
- va_list args;
-
- sz = rb_struct_iv_get(klass, "__size__");
- size = FIX2LONG(sz);
- mem = ALLOCA_N(VALUE, size);
- va_init_list(args, klass);
- for (i=0; i<size; i++) {
- mem[i] = va_arg(args, VALUE);
- }
- va_end(args);
-
- return rb_class_new_instance(size, mem, klass);
-}
-
-static VALUE
-rb_struct_each(s)
- VALUE s;
-{
- long i;
-
- for (i=0; i<RSTRUCT(s)->len; i++) {
- rb_yield(RSTRUCT(s)->ptr[i]);
- }
- return s;
-}
-
-static VALUE
-rb_struct_to_s(s)
- VALUE s;
-{
- char *cname = rb_class2name(rb_obj_class(s));
- VALUE str = rb_str_new(0, strlen(cname) + 4);
-
- sprintf(RSTRING(str)->ptr, "#<%s>", cname);
- RSTRING(str)->len = strlen(RSTRING(str)->ptr);
- return str;
-}
-
-static VALUE
-inspect_struct(s)
- VALUE s;
-{
- char *cname = rb_class2name(rb_obj_class(s));
- VALUE str, member;
- long i;
-
- member = rb_struct_iv_get(rb_obj_class(s), "__member__");
- if (NIL_P(member)) {
- rb_bug("non-initialized struct");
- }
-
- str = rb_str_buf_new2("#<");
- rb_str_cat2(str, cname);
- rb_str_cat2(str, " ");
- for (i=0; i<RSTRUCT(s)->len; i++) {
- VALUE str2, slot;
- char *p;
-
- if (i > 0) {
- rb_str_cat2(str, ", ");
- }
- slot = RARRAY(member)->ptr[i];
- p = rb_id2name(SYM2ID(slot));
- rb_str_cat2(str, p);
- rb_str_cat2(str, "=");
- str2 = rb_inspect(RSTRUCT(s)->ptr[i]);
- rb_str_append(str, str2);
- }
- rb_str_cat2(str, ">");
- OBJ_INFECT(str, s);
-
- return str;
-}
-
-static VALUE
-rb_struct_inspect(s)
- VALUE s;
-{
- if (rb_inspecting_p(s)) {
- char *cname = rb_class2name(rb_obj_class(s));
- VALUE str = rb_str_new(0, strlen(cname) + 8);
-
- sprintf(RSTRING(str)->ptr, "#<%s:...>", cname);
- RSTRING(str)->len = strlen(RSTRING(str)->ptr);
- return str;
- }
- return rb_protect_inspect(inspect_struct, s, 0);
-}
-
-static VALUE
-rb_struct_to_a(s)
- VALUE s;
-{
- return rb_ary_new4(RSTRUCT(s)->len, RSTRUCT(s)->ptr);
-}
-
-static VALUE
-rb_struct_clone(s)
- VALUE s;
-{
- VALUE clone = rb_obj_clone(s);
-
- RSTRUCT(clone)->ptr = ALLOC_N(VALUE, RSTRUCT(s)->len);
- RSTRUCT(clone)->len = RSTRUCT(s)->len;
- MEMCPY(RSTRUCT(clone)->ptr, RSTRUCT(s)->ptr, VALUE, RSTRUCT(clone)->len);
-
- return clone;
-}
-
-static VALUE
-rb_struct_aref_id(s, id)
- VALUE s;
- ID id;
-{
- VALUE member;
- long i, len;
-
- member = rb_struct_iv_get(rb_obj_class(s), "__member__");
- if (NIL_P(member)) {
- rb_bug("non-initialized struct");
- }
-
- len = RARRAY(member)->len;
- for (i=0; i<len; i++) {
- if (SYM2ID(RARRAY(member)->ptr[i]) == id) {
- return RSTRUCT(s)->ptr[i];
- }
- }
- rb_name_error(id, "no member '%s' in struct", rb_id2name(id));
- return Qnil; /* not reached */
-}
-
-VALUE
-rb_struct_aref(s, idx)
- VALUE s, idx;
-{
- long i;
-
- if (TYPE(idx) == T_STRING || TYPE(idx) == T_SYMBOL) {
- return rb_struct_aref_id(s, rb_to_id(idx));
- }
-
- i = NUM2LONG(idx);
- if (i < 0) i = RSTRUCT(s)->len + i;
- if (i < 0)
- rb_raise(rb_eIndexError, "offset %d too small for struct(size:%d)",
- i, RSTRUCT(s)->len);
- if (RSTRUCT(s)->len <= i)
- rb_raise(rb_eIndexError, "offset %d too large for struct(size:%d)",
- i, RSTRUCT(s)->len);
- return RSTRUCT(s)->ptr[i];
-}
-
-static VALUE
-rb_struct_aset_id(s, id, val)
- VALUE s, val;
- ID id;
-{
- VALUE member;
- long i, len;
-
- member = rb_struct_iv_get(rb_obj_class(s), "__member__");
- if (NIL_P(member)) {
- rb_bug("non-initialized struct");
- }
-
- rb_struct_modify(s);
- len = RARRAY(member)->len;
- for (i=0; i<len; i++) {
- if (SYM2ID(RARRAY(member)->ptr[i]) == id) {
- RSTRUCT(s)->ptr[i] = val;
- return val;
- }
- }
- rb_name_error(id, "no member '%s' in struct", rb_id2name(id));
-}
-
-VALUE
-rb_struct_aset(s, idx, val)
- VALUE s, idx, val;
-{
- long i;
-
- if (TYPE(idx) == T_STRING || TYPE(idx) == T_SYMBOL) {
- return rb_struct_aset_id(s, rb_to_id(idx), val);
- }
-
- i = NUM2LONG(idx);
- if (i < 0) i = RSTRUCT(s)->len + i;
- if (i < 0) {
- rb_raise(rb_eIndexError, "offset %d too small for struct(size:%d)",
- i, RSTRUCT(s)->len);
- }
- if (RSTRUCT(s)->len <= i) {
- rb_raise(rb_eIndexError, "offset %d too large for struct(size:%d)",
- i, RSTRUCT(s)->len);
- }
- rb_struct_modify(s);
- return RSTRUCT(s)->ptr[i] = val;
-}
-
-
-static VALUE
-rb_struct_select(argc, argv, s)
- int argc;
- VALUE *argv;
- VALUE s;
-{
- VALUE result = rb_ary_new();
- long i;
-
- if (rb_block_given_p()) {
- if (argc > 0) {
- rb_raise(rb_eArgError, "wrong number arguments(%d for 0)", argc);
- }
- for (i = 0; i < RSTRUCT(s)->len; i++) {
- if (RTEST(rb_yield(RARRAY(s)->ptr[i]))) {
- rb_ary_push(result, RSTRUCT(s)->ptr[i]);
- }
- }
- }
- else {
- for (i=0; i<argc; i++) {
- rb_ary_push(result, rb_struct_aref(s, argv[i]));
- }
- }
- return result;
-}
-
-static VALUE
-rb_struct_equal(s, s2)
- VALUE s, s2;
-{
- long i;
-
- if (s == s2) return Qtrue;
- if (TYPE(s2) != T_STRUCT) return Qfalse;
- if (rb_obj_class(s) != rb_obj_class(s2)) return Qfalse;
- if (RSTRUCT(s)->len != RSTRUCT(s2)->len) {
- rb_bug("inconsistent struct"); /* should never happen */
- }
-
- for (i=0; i<RSTRUCT(s)->len; i++) {
- if (!rb_equal(RSTRUCT(s)->ptr[i], RSTRUCT(s2)->ptr[i])) return Qfalse;
- }
- return Qtrue;
-}
-
-static VALUE
-rb_struct_size(s)
- VALUE s;
-{
- return INT2FIX(RSTRUCT(s)->len);
-}
-
-void
-Init_Struct()
-{
- rb_cStruct = rb_define_class("Struct", rb_cObject);
- rb_include_module(rb_cStruct, rb_mEnumerable);
-
- rb_undef_method(CLASS_OF(rb_cStruct), "allocate");
- rb_define_singleton_method(rb_cStruct, "new", rb_struct_s_def, -1);
-
- rb_define_method(rb_cStruct, "initialize", rb_struct_initialize, -2);
- rb_define_method(rb_cStruct, "clone", rb_struct_clone, 0);
-
- rb_define_method(rb_cStruct, "==", rb_struct_equal, 1);
-
- rb_define_method(rb_cStruct, "to_s", rb_struct_to_s, 0);
- rb_define_method(rb_cStruct, "inspect", rb_struct_inspect, 0);
- rb_define_method(rb_cStruct, "to_a", rb_struct_to_a, 0);
- rb_define_method(rb_cStruct, "values", rb_struct_to_a, 0);
- rb_define_method(rb_cStruct, "size", rb_struct_size, 0);
- rb_define_method(rb_cStruct, "length", rb_struct_size, 0);
-
- rb_define_method(rb_cStruct, "each", rb_struct_each, 0);
- rb_define_method(rb_cStruct, "[]", rb_struct_aref, 1);
- rb_define_method(rb_cStruct, "[]=", rb_struct_aset, 2);
- rb_define_method(rb_cStruct, "select", rb_struct_select, -1);
-
- rb_define_method(rb_cStruct, "members", rb_struct_members, 0);
-}
diff --git a/time.c b/time.c
deleted file mode 100644
index 1f0cf2736e..0000000000
--- a/time.c
+++ /dev/null
@@ -1,1485 +0,0 @@
-/**********************************************************************
-
- time.c -
-
- $Author$
- $Date$
- created at: Tue Dec 28 14:31:59 JST 1993
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
-
-**********************************************************************/
-
-#include "ruby.h"
-#include <sys/types.h>
-
-#include <time.h>
-#ifndef NT
-#ifdef HAVE_SYS_TIME_H
-# include <sys/time.h>
-#else
-#define time_t long
-struct timeval {
- time_t tv_sec; /* seconds */
- time_t tv_usec; /* and microseconds */
-};
-#endif
-#endif /* NT */
-
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-#include <math.h>
-
-VALUE rb_cTime;
-
-struct time_object {
- struct timeval tv;
- struct tm tm;
- int gmt;
- int tm_got;
-};
-
-#define GetTimeval(obj, tobj) {\
- Data_Get_Struct(obj, struct time_object, tobj);\
-}
-
-static VALUE
-time_s_alloc(klass)
- VALUE klass;
-{
- VALUE obj;
- struct time_object *tobj;
-
- obj = Data_Make_Struct(klass, struct time_object, 0, free, tobj);
- tobj->tm_got=0;
- if (gettimeofday(&tobj->tv, 0) < 0) {
- rb_sys_fail("gettimeofday");
- }
-
- return obj;
-}
-
-static VALUE
-time_s_now(klass)
- VALUE klass;
-{
- return rb_obj_alloc(klass);
-}
-
-
-#define NDIV(x,y) (-(-((x)+1)/(y))-1)
-#define NMOD(x,y) ((y)-(-((x)+1)%(y))-1)
-
-static VALUE
-time_new_internal(klass, sec, usec)
- VALUE klass;
- time_t sec, usec;
-{
- VALUE obj;
- time_t tmp;
- struct time_object *tobj;
-
- if (usec >= 1000000) { /* usec positive overflow */
- tmp = sec + usec / 1000000;
- usec %= 1000000;
- if (sec > 0 && tmp < 0) {
- rb_raise(rb_eRangeError, "out of Time range");
- }
- sec = tmp;
- }
- if (usec < 0) { /* usec negative overflow */
- tmp = sec + NDIV(usec,1000000); /* negative div */
- usec = NMOD(usec,1000000); /* negative mod */
- if (sec < 0 && tmp > 0) {
- rb_raise(rb_eRangeError, "out of Time range");
- }
- sec = tmp;
- }
-#ifndef NEGATIVE_TIME_T
- if (sec < 0 || (sec == 0 && usec < 0))
- rb_raise(rb_eArgError, "time must be positive");
-#endif
-
- obj = Data_Make_Struct(klass, struct time_object, 0, free, tobj);
- tobj->tm_got = 0;
- tobj->tv.tv_sec = sec;
- tobj->tv.tv_usec = usec;
-
- return obj;
-}
-
-VALUE
-rb_time_new(sec, usec)
- time_t sec, usec;
-{
- return time_new_internal(rb_cTime, sec, usec);
-}
-
-static struct timeval
-time_timeval(time, interval)
- VALUE time;
- int interval;
-{
- struct timeval t;
- char *tstr = interval ? "time interval" : "time";
-
-#ifndef NEGATIVE_TIME_T
- interval = 1;
-#endif
-
- switch (TYPE(time)) {
- case T_FIXNUM:
- t.tv_sec = FIX2LONG(time);
- if (interval && t.tv_sec < 0)
- rb_raise(rb_eArgError, "%s must be positive", tstr);
- t.tv_usec = 0;
- break;
-
- case T_FLOAT:
- if (interval && RFLOAT(time)->value < 0.0)
- rb_raise(rb_eArgError, "%s must be positive", tstr);
- else {
- double f, d;
-
- d = modf(RFLOAT(time)->value, &f);
- t.tv_sec = (time_t)f;
- if (f != t.tv_sec) {
- rb_raise(rb_eRangeError, "%f out of Time range", RFLOAT(time)->value);
- }
- t.tv_usec = (time_t)(d*1e6);
- }
- break;
-
- case T_BIGNUM:
- t.tv_sec = NUM2LONG(time);
- if (interval && t.tv_sec < 0)
- rb_raise(rb_eArgError, "%s must be positive", tstr);
- t.tv_usec = 0;
- break;
-
- default:
- rb_raise(rb_eTypeError, "can't convert %s into %s",
- rb_class2name(CLASS_OF(time)), tstr);
- break;
- }
- return t;
-}
-
-struct timeval
-rb_time_interval(time)
- VALUE time;
-{
- return time_timeval(time, Qtrue);
-}
-
-struct timeval
-rb_time_timeval(time)
- VALUE time;
-{
- struct time_object *tobj;
- struct timeval t;
-
- if (rb_obj_is_kind_of(time, rb_cTime)) {
- GetTimeval(time, tobj);
- t = tobj->tv;
- return t;
- }
- return time_timeval(time, Qfalse);
-}
-
-static VALUE
-time_s_at(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- struct timeval tv;
- VALUE time, t;
-
- if (rb_scan_args(argc, argv, "11", &time, &t) == 2) {
- tv.tv_sec = NUM2LONG(time);
- tv.tv_usec = NUM2LONG(t);
- }
- else {
- tv = rb_time_timeval(time);
- }
- t = time_new_internal(klass, tv.tv_sec, tv.tv_usec);
- if (TYPE(time) == T_DATA) {
- struct time_object *tobj, *tobj2;
-
- GetTimeval(time, tobj);
- GetTimeval(t, tobj2);
- tobj2->gmt = tobj->gmt;
- }
- return t;
-}
-
-static char *months [12] = {
- "jan", "feb", "mar", "apr", "may", "jun",
- "jul", "aug", "sep", "oct", "nov", "dec",
-};
-
-static long
-obj2long(obj)
- VALUE obj;
-{
- if (TYPE(obj) == T_STRING) {
- obj = rb_str_to_inum(obj, 10, Qfalse);
- }
-
- return NUM2LONG(obj);
-}
-
-static void
-time_arg(argc, argv, tm, usec)
- int argc;
- VALUE *argv;
- struct tm *tm;
- time_t *usec;
-{
- VALUE v[7];
- int i;
- long year;
-
- MEMZERO(tm, struct tm, 1);
- if (argc == 10) {
- v[0] = argv[5];
- v[1] = argv[4];
- v[2] = argv[3];
- v[3] = argv[2];
- v[4] = argv[1];
- v[5] = argv[0];
- *usec = 0;
- tm->tm_isdst = RTEST(argv[8]) ? 1 : 0;
- }
- else {
- rb_scan_args(argc, argv, "16", &v[0],&v[1],&v[2],&v[3],&v[4],&v[5],&v[6]);
- *usec = (argc == 7) ? NUM2INT(v[6]) : 0;
- tm->tm_isdst = -1;
- }
-
- year = obj2long(v[0]);
-
- if (0 <= year && year < 39) {
- year += 2000;
- rb_warning("2 digits year is used");
- }
- else if (69 <= year && year < 139) {
- year += 1900;
- rb_warning("2 or 3 digits year is used");
- }
-
- year -= 1900;
- tm->tm_year = year;
-
- if (NIL_P(v[1])) {
- tm->tm_mon = 0;
- }
- else if (TYPE(v[1]) == T_STRING) {
- tm->tm_mon = -1;
- for (i=0; i<12; i++) {
- if (RSTRING(v[1])->len == 3 &&
- strcasecmp(months[i], RSTRING(v[1])->ptr) == 0) {
- tm->tm_mon = i;
- break;
- }
- }
- if (tm->tm_mon == -1) {
- char c = RSTRING(v[1])->ptr[0];
-
- if ('0' <= c && c <= '9') {
- tm->tm_mon = obj2long(v[1])-1;
- }
- }
- }
- else {
- tm->tm_mon = obj2long(v[1]) - 1;
- }
- if (NIL_P(v[2])) {
- tm->tm_mday = 1;
- }
- else {
- tm->tm_mday = obj2long(v[2]);
- }
- tm->tm_hour = NIL_P(v[3])?0:obj2long(v[3]);
- tm->tm_min = NIL_P(v[4])?0:obj2long(v[4]);
- tm->tm_sec = NIL_P(v[5])?0:obj2long(v[5]);
-
- /* value validation */
- if (
- tm->tm_year != year ||
-#ifndef NEGATIVE_TIME_T
- tm->tm_year < 69 ||
-#endif
- tm->tm_mon < 0 || tm->tm_mon > 11
- || tm->tm_mday < 1 || tm->tm_mday > 31
- || tm->tm_hour < 0 || tm->tm_hour > 23
- || tm->tm_min < 0 || tm->tm_min > 59
- || tm->tm_sec < 0 || tm->tm_sec > 60)
- rb_raise(rb_eArgError, "argument out of range");
-}
-
-static VALUE time_gmtime _((VALUE));
-static VALUE time_localtime _((VALUE));
-static VALUE time_get_tm _((VALUE, int));
-
-static int
-tmcmp(a, b)
- struct tm *a;
- struct tm *b;
-{
- if (a->tm_year != b->tm_year)
- return a->tm_year < b->tm_year ? -1 : 1;
- else if (a->tm_mon != b->tm_mon)
- return a->tm_mon < b->tm_mon ? -1 : 1;
- else if (a->tm_mday != b->tm_mday)
- return a->tm_mday < b->tm_mday ? -1 : 1;
- else if (a->tm_hour != b->tm_hour)
- return a->tm_hour < b->tm_hour ? -1 : 1;
- else if (a->tm_min != b->tm_min)
- return a->tm_min < b->tm_min ? -1 : 1;
- else if (a->tm_sec != b->tm_sec)
- return a->tm_sec < b->tm_sec ? -1 : 1;
- else
- return 0;
-}
-
-static time_t
-search_time_t(tptr, utc_p)
- struct tm *tptr;
- int utc_p;
-{
- time_t guess, guess_lo, guess_hi;
- struct tm *tm, tm_lo, tm_hi;
- int d, have_guess;
- int find_dst;
-
- find_dst = 0 < tptr->tm_isdst;
-
-#ifdef NEGATIVE_TIME_T
- guess_lo = 1L << (8 * sizeof(time_t) - 1);
-#else
- guess_lo = 0;
-#endif
- guess_hi = ((time_t)-1) < ((time_t)0) ?
- (1UL << (8 * sizeof(time_t) - 1)) - 1 :
- ~(time_t)0;
-
- tm = (utc_p ? gmtime : localtime)(&guess_lo);
- if (!tm) goto error;
- d = tmcmp(tptr, tm);
- if (d < 0) goto out_of_range;
- if (d == 0) return guess_lo;
- tm_lo = *tm;
-
- tm = (utc_p ? gmtime : localtime)(&guess_hi);
- if (!tm) goto error;
- d = tmcmp(tptr, tm);
- if (d > 0) goto out_of_range;
- if (d == 0) return guess_hi;
- tm_hi = *tm;
-
- have_guess = 0;
-
- while (guess_lo + 1 < guess_hi) {
- /* there is a gap between guess_lo and guess_hi. */
- unsigned long range = 0;
- if (!have_guess) {
- int a, b;
- /*
- Try precious guess by a linear interpolation at first.
- `a' and `b' is a coefficient of guess_lo and guess_hi as:
-
- guess = (guess_lo * a + guess_hi * b) / (a + b)
-
- However this causes overflow in most cases, following assignment
- is used instead:
-
- guess = guess_lo / d * a + (guess_lo % d) * a / d
- + guess_hi / d * b + (guess_hi % d) * b / d
- where d = a + b
-
- To avoid overflow in this assignment, `d' is restricted to less than
- sqrt(2**31). By this restriction and other reasons, the guess is
- not accurate and some error is expected. `range' approximates
- the maximum error.
-
- When these parameters are not suitable, i.e. guess is not within
- guess_lo and guess_hi, simple guess by binary search is used.
- */
- range = 366 * 24 * 60 * 60;
- a = (tm_hi.tm_year - tptr->tm_year);
- b = (tptr->tm_year - tm_lo.tm_year);
- /* 46000 is selected as `some big number less than sqrt(2**31)'. */
- if (a + b <= 46000 / 12) {
- range = 31 * 24 * 60 * 60;
- a *= 12;
- b *= 12;
- a += tm_hi.tm_mon - tptr->tm_mon;
- b += tptr->tm_mon - tm_lo.tm_mon;
- if (a + b <= 46000 / 31) {
- range = 24 * 60 * 60;
- a *= 31;
- b *= 31;
- a += tm_hi.tm_mday - tptr->tm_mday;
- b += tptr->tm_mday - tm_lo.tm_mday;
- if (a + b <= 46000 / 24) {
- range = 60 * 60;
- a *= 24;
- b *= 24;
- a += tm_hi.tm_hour - tptr->tm_hour;
- b += tptr->tm_hour - tm_lo.tm_hour;
- if (a + b <= 46000 / 60) {
- range = 60;
- a *= 60;
- b *= 60;
- a += tm_hi.tm_min - tptr->tm_min;
- b += tptr->tm_min - tm_lo.tm_min;
- if (a + b <= 46000 / 60) {
- range = 1;
- a *= 60;
- b *= 60;
- a += tm_hi.tm_sec - tptr->tm_sec;
- b += tptr->tm_sec - tm_lo.tm_sec;
- }
- }
- }
- }
- }
- if (a <= 0) a = 1;
- if (b <= 0) b = 1;
- d = a + b;
- /*
- Although `/' and `%' may produce unexpected result with negative
- argument, it doesn't cause serious problem because there is a
- fail safe.
- */
- guess = guess_lo / d * a + (guess_lo % d) * a / d
- + guess_hi / d * b + (guess_hi % d) * b / d;
- have_guess = 1;
- }
-
- if (guess <= guess_lo || guess_hi <= guess) {
- /* Precious guess is invalid. try binary search. */
- guess = guess_lo / 2 + guess_hi / 2;
- if (guess <= guess_lo)
- guess = guess_lo + 1;
- else if (guess >= guess_hi)
- guess = guess_hi - 1;
- range = 0;
- }
-
- tm = (utc_p ? gmtime : localtime)(&guess);
- if (!tm) goto error;
- have_guess = 0;
-
- d = tmcmp(tptr, tm);
- if (d < 0) {
- guess_hi = guess;
- tm_hi = *tm;
- if (range) {
- guess = guess - range;
- range = 0;
- if (guess_lo < guess && guess < guess_hi)
- have_guess = 1;
- }
- }
- else if (d > 0) {
- guess_lo = guess;
- tm_lo = *tm;
- if (range) {
- guess = guess + range;
- range = 0;
- if (guess_lo < guess && guess < guess_hi)
- have_guess = 1;
- }
- }
- else {
- if (!utc_p) {
- /* If localtime is nonmonotonic, another result may exist. */
- time_t guess2;
- if (find_dst) {
- guess2 = guess - 2 * 60 * 60;
- tm = localtime(&guess2);
- if (tm) {
- if (tptr->tm_hour != (tm->tm_hour + 2) % 24 ||
- tptr->tm_min != tm->tm_min ||
- tptr->tm_sec != tm->tm_sec) {
- guess2 -= (tm->tm_hour - tptr->tm_hour) * 60 * 60 +
- (tm->tm_min - tptr->tm_min) * 60 +
- (tm->tm_sec - tptr->tm_sec);
- if (tptr->tm_mday != tm->tm_mday)
- guess2 += 24 * 60 * 60;
- if (guess != guess2) {
- tm = localtime(&guess2);
- if (tmcmp(tptr, tm) == 0) {
- if (guess < guess2)
- return guess;
- else
- return guess2;
- }
- }
- }
- }
- }
- else {
- guess2 = guess + 2 * 60 * 60;
- tm = localtime(&guess2);
- if (tm) {
- if ((tptr->tm_hour + 2) % 24 != tm->tm_hour ||
- tptr->tm_min != tm->tm_min ||
- tptr->tm_sec != tm->tm_sec) {
- guess2 -= (tm->tm_hour - tptr->tm_hour) * 60 * 60 +
- (tm->tm_min - tptr->tm_min) * 60 +
- (tm->tm_sec - tptr->tm_sec);
- if (tptr->tm_mday != tm->tm_mday)
- guess2 -= 24 * 60 * 60;
- if (guess != guess2) {
- tm = localtime(&guess2);
- if (tmcmp(tptr, tm) == 0) {
- if (guess < guess2)
- return guess2;
- else
- return guess;
- }
- }
- }
- }
- }
- }
- return guess;
- }
- }
- /* Given argument has no corresponding time_t. Let's outerpolation. */
- if (tm_lo.tm_year == tptr->tm_year && tm_lo.tm_mon == tptr->tm_mon) {
- return guess_lo +
- (tptr->tm_mday - tm_lo.tm_mday) * 24 * 60 * 60 +
- (tptr->tm_hour - tm_lo.tm_hour) * 60 * 60 +
- (tptr->tm_min - tm_lo.tm_min) * 60 +
- (tptr->tm_sec - tm_lo.tm_sec);
- }
- else if (tm_hi.tm_year == tptr->tm_year && tm_hi.tm_mon == tptr->tm_mon) {
- return guess_hi +
- (tptr->tm_mday - tm_hi.tm_mday) * 24 * 60 * 60 +
- (tptr->tm_hour - tm_hi.tm_hour) * 60 * 60 +
- (tptr->tm_min - tm_hi.tm_min) * 60 +
- (tptr->tm_sec - tm_hi.tm_sec);
- }
-
- out_of_range:
- rb_raise(rb_eArgError, "time out of range");
-
- error:
- rb_raise(rb_eArgError, "gmtime/localtime error");
- return 0; /* not reached */
-}
-
-static time_t
-make_time_t(tptr, utc_p)
- struct tm *tptr;
- int utc_p;
-{
- time_t t;
- struct tm *tmp, buf;
- buf = *tptr;
- if (utc_p) {
-#if defined(HAVE_TIMEGM)
- t = timegm(&buf);
- if (t == -1) {
-#ifdef NEGATIVE_TIME_T
- if (!(tmp = gmtime(&t)) ||
- tptr->tm_year != tmp->tm_year ||
- tptr->tm_mon != tmp->tm_mon ||
- tptr->tm_mday != tmp->tm_mday ||
- tptr->tm_hour != tmp->tm_hour ||
- tptr->tm_min != tmp->tm_min ||
- tptr->tm_sec != tmp->tm_sec)
-#endif
- rb_raise(rb_eArgError, "gmtime error");
- }
-#else
- t = search_time_t(&buf, utc_p);
-#endif
- }
- else {
-#if defined(HAVE_MKTIME)
- t = mktime(&buf);
- if (t == -1) {
-#ifdef NEGATIVE_TIME_T
- if (!(tmp = localtime(&t)) ||
- tptr->tm_year != tmp->tm_year ||
- tptr->tm_mon != tmp->tm_mon ||
- tptr->tm_mday != tmp->tm_mday ||
- tptr->tm_hour != tmp->tm_hour ||
- tptr->tm_min != tmp->tm_min ||
- tptr->tm_sec != tmp->tm_sec)
-#endif
- rb_raise(rb_eArgError, "localtime error");
- }
-#else
- t = search_time_t(&buf, utc_p);
-#endif
- }
- return t;
-}
-
-static VALUE
-time_utc_or_local(argc, argv, utc_p, klass)
- int argc;
- VALUE *argv;
- int utc_p;
- VALUE klass;
-{
- struct tm tm;
- VALUE time;
- time_t usec;
-
- time_arg(argc, argv, &tm, &usec);
- time = time_new_internal(klass, make_time_t(&tm, utc_p), usec);
- if (utc_p) return time_gmtime(time);
- return time_localtime(time);
-}
-
-static VALUE
-time_s_mkutc(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- return time_utc_or_local(argc, argv, Qtrue, klass);
-}
-
-static VALUE
-time_s_mktime(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- return time_utc_or_local(argc, argv, Qfalse, klass);
-}
-
-static VALUE
-time_to_i(time)
- VALUE time;
-{
- struct time_object *tobj;
-
- GetTimeval(time, tobj);
- return LONG2NUM(tobj->tv.tv_sec);
-}
-
-static VALUE
-time_to_f(time)
- VALUE time;
-{
- struct time_object *tobj;
-
- GetTimeval(time, tobj);
- return rb_float_new((double)tobj->tv.tv_sec+(double)tobj->tv.tv_usec/1e6);
-}
-
-static VALUE
-time_usec(time)
- VALUE time;
-{
- struct time_object *tobj;
-
- GetTimeval(time, tobj);
- return INT2NUM(tobj->tv.tv_usec);
-}
-
-static VALUE
-time_cmp(time1, time2)
- VALUE time1, time2;
-{
- struct time_object *tobj1, *tobj2;
- long i;
-
- GetTimeval(time1, tobj1);
- switch (TYPE(time2)) {
- case T_FIXNUM:
- i = FIX2LONG(time2);
- if (tobj1->tv.tv_sec == i) {
- if (tobj1->tv.tv_usec == 0)
- return INT2FIX(0);
- if (tobj1->tv.tv_usec > 0)
- return INT2FIX(1);
- return INT2FIX(-1);
- }
- if (tobj1->tv.tv_sec > i) return INT2FIX(1);
- return INT2FIX(-1);
-
- case T_FLOAT:
- {
- double t;
-
- t = (double)tobj1->tv.tv_sec + (double)tobj1->tv.tv_usec*1e-6;
- if (t > RFLOAT(time2)->value)
- return INT2FIX(1);
- if (t < RFLOAT(time2)->value)
- return INT2FIX(-1);
- return INT2FIX(0);
- }
- }
-
- if (rb_obj_is_kind_of(time2, rb_cTime)) {
- GetTimeval(time2, tobj2);
- if (tobj1->tv.tv_sec == tobj2->tv.tv_sec) {
- if (tobj1->tv.tv_usec == tobj2->tv.tv_usec) return INT2FIX(0);
- if (tobj1->tv.tv_usec > tobj2->tv.tv_usec) return INT2FIX(1);
- return INT2FIX(-1);
- }
- if (tobj1->tv.tv_sec > tobj2->tv.tv_sec) return INT2FIX(1);
- return INT2FIX(-1);
- }
- if (TYPE(time2) == T_BIGNUM) {
- double a = (double)tobj1->tv.tv_sec+(double)tobj1->tv.tv_usec/1e6;
- double b = rb_big2dbl(time2);
-
- if (a == b) return INT2FIX(0);
- if (a > b) return INT2FIX(1);
- if (a < b) return INT2FIX(-1);
- }
- i = NUM2LONG(time2);
- if (tobj1->tv.tv_sec == i) {
- if (tobj1->tv.tv_usec == 0)
- return INT2FIX(0);
- if (tobj1->tv.tv_usec > 0)
- return INT2FIX(1);
- return INT2FIX(-1);
- }
- if (tobj1->tv.tv_sec > i) return INT2FIX(1);
- return INT2FIX(-1);
-}
-
-static VALUE
-time_eql(time1, time2)
- VALUE time1, time2;
-{
- struct time_object *tobj1, *tobj2;
-
- GetTimeval(time1, tobj1);
- if (rb_obj_is_kind_of(time2, rb_cTime)) {
- GetTimeval(time2, tobj2);
- if (tobj1->tv.tv_sec == tobj2->tv.tv_sec) {
- if (tobj1->tv.tv_usec == tobj2->tv.tv_usec) return Qtrue;
- }
- }
- return Qfalse;
-}
-
-static VALUE
-time_utc_p(time)
- VALUE time;
-{
- struct time_object *tobj;
-
- GetTimeval(time, tobj);
- if (tobj->gmt) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-time_hash(time)
- VALUE time;
-{
- struct time_object *tobj;
- long hash;
-
- GetTimeval(time, tobj);
- hash = tobj->tv.tv_sec ^ tobj->tv.tv_usec;
- return INT2FIX(hash);
-}
-
-static VALUE
-time_clone(time)
- VALUE time;
-{
- VALUE clone;
- struct time_object *tobj, *tclone;
-
- GetTimeval(time, tobj);
- clone = Data_Make_Struct(0, struct time_object, 0, free, tclone);
- CLONESETUP(clone, time);
- MEMCPY(tclone, tobj, struct time_object, 1);
-
- return clone;
-}
-
-static void
-time_modify(time)
- VALUE time;
-{
- if (OBJ_FROZEN(time)) rb_error_frozen("Time");
- if (!OBJ_TAINTED(time) && rb_safe_level() >= 4)
- rb_raise(rb_eSecurityError, "Insecure: can't modify Time");
-}
-
-static VALUE
-time_localtime(time)
- VALUE time;
-{
- struct time_object *tobj;
- struct tm *tm_tmp;
- time_t t;
-
- GetTimeval(time, tobj);
- if (!tobj->gmt) {
- if (tobj->tm_got)
- return time;
- }
- else {
- time_modify(time);
- }
- t = tobj->tv.tv_sec;
- tm_tmp = localtime(&t);
- if (!tm_tmp)
- rb_raise(rb_eArgError, "localtime error");
- tobj->tm = *tm_tmp;
- tobj->tm_got = 1;
- tobj->gmt = 0;
- return time;
-}
-
-static VALUE
-time_gmtime(time)
- VALUE time;
-{
- struct time_object *tobj;
- struct tm *tm_tmp;
- time_t t;
-
- GetTimeval(time, tobj);
- if (tobj->gmt) {
- if (tobj->tm_got)
- return time;
- }
- else {
- time_modify(time);
- }
- t = tobj->tv.tv_sec;
- tm_tmp = gmtime(&t);
- if (!tm_tmp)
- rb_raise(rb_eArgError, "gmtime error");
- tobj->tm = *tm_tmp;
- tobj->tm_got = 1;
- tobj->gmt = 1;
- return time;
-}
-
-static VALUE
-time_dup(time)
- VALUE time;
-{
- VALUE clone;
- struct time_object *tobj, *tclone;
-
- GetTimeval(time, tobj);
- clone = Data_Make_Struct(0, struct time_object, 0, free, tclone);
- DUPSETUP(clone, time);
- MEMCPY(tclone, tobj, struct time_object, 1);
-
- return clone;
-}
-
-static VALUE
-time_getlocaltime(time)
- VALUE time;
-{
- return time_localtime(time_dup(time));
-}
-
-static VALUE
-time_getgmtime(time)
- VALUE time;
-{
- return time_gmtime(time_dup(time));
-}
-
-static VALUE
-time_get_tm(time, gmt)
- VALUE time;
- int gmt;
-{
- if (gmt) return time_gmtime(time);
- return time_localtime(time);
-}
-
-static VALUE
-time_asctime(time)
- VALUE time;
-{
- struct time_object *tobj;
- char *s;
-
- GetTimeval(time, tobj);
- if (tobj->tm_got == 0) {
- time_get_tm(time, tobj->gmt);
- }
- s = asctime(&tobj->tm);
- if (s[24] == '\n') s[24] = '\0';
-
- return rb_str_new2(s);
-}
-
-static VALUE
-time_to_s(time)
- VALUE time;
-{
- struct time_object *tobj;
- char buf[128];
- int len;
-
- GetTimeval(time, tobj);
- if (tobj->tm_got == 0) {
- time_get_tm(time, tobj->gmt);
- }
- if (tobj->gmt == 1) {
- len = strftime(buf, 128, "%a %b %d %H:%M:%S UTC %Y", &tobj->tm);
- }
- else {
- len = strftime(buf, 128, "%a %b %d %H:%M:%S %Z %Y", &tobj->tm);
- }
- return rb_str_new(buf, len);
-}
-
-static VALUE
-time_plus(time1, time2)
- VALUE time1, time2;
-{
- struct time_object *tobj;
- time_t sec, usec;
- double f, d, v;
-
- GetTimeval(time1, tobj);
-
- if (rb_obj_is_kind_of(time2, rb_cTime)) {
- rb_raise(rb_eTypeError, "time + time?");
- }
- v = NUM2DBL(time2);
- d = modf(v, &f);
- sec = (time_t)f;
- if (f != (double)sec) {
- rb_raise(rb_eRangeError, "time + %f out of Time range", v);
- }
-#ifndef NEGATIVE_TIME_T
- if (f < 0 && -f >= tobj->tv.tv_sec) {
- rb_raise(rb_eArgError, "time must be positive");
- }
-#endif
- usec = tobj->tv.tv_usec + (time_t)(d*1e6);
- sec = tobj->tv.tv_sec + (time_t)f;
-
-#ifdef NEGATIVE_TIME_T
- if ((tobj->tv.tv_sec >= 0 && f >= 0 && sec < 0) ||
- (tobj->tv.tv_sec <= 0 && f <= 0 && sec > 0)) {
- rb_raise(rb_eRangeError, "time + %f out of Time range", v);
- }
-#endif
- time2 = rb_time_new(sec, usec);
- if (tobj->gmt) {
- GetTimeval(time2, tobj);
- tobj->gmt = 1;
- }
- return time2;
-}
-
-static VALUE
-time_minus(time1, time2)
- VALUE time1, time2;
-{
- struct time_object *tobj;
- time_t sec, usec;
- double f, d, v;
-
- GetTimeval(time1, tobj);
- if (rb_obj_is_kind_of(time2, rb_cTime)) {
- struct time_object *tobj2;
-
- GetTimeval(time2, tobj2);
- f = (double)tobj->tv.tv_sec - (double)tobj2->tv.tv_sec;
- f += ((double)tobj->tv.tv_usec - (double)tobj2->tv.tv_usec)*1e-6;
- /* XXX: should check float overflow on 64bit time_t platforms */
-
- return rb_float_new(f);
- }
- v = NUM2DBL(time2);
- d = modf(v, &f);
- sec = (time_t)f;
- if (f != (double)sec) {
- rb_raise(rb_eRangeError, "time - %f out of Time range", v);
- }
-#ifndef NEGATIVE_TIME_T
- if (f > 0 && f >= tobj->tv.tv_sec) {
- rb_raise(rb_eArgError, "time must be positive");
- }
-#endif
- usec = tobj->tv.tv_usec - (time_t)(d*1e6);
- sec = tobj->tv.tv_sec - (time_t)f;
-#ifdef NEGATIVE_TIME_T
- if ((tobj->tv.tv_sec <= 0 && f >= 0 && sec > 0) ||
- (tobj->tv.tv_sec >= 0 && f <= 0 && sec < 0)) {
- rb_raise(rb_eRangeError, "time - %f out of Time range", v);
- }
-#endif
-
- time2 = rb_time_new(sec, usec);
- if (tobj->gmt) {
- GetTimeval(time2, tobj);
- tobj->gmt = 1;
- }
- return time2;
-}
-
-static VALUE
-time_sec(time)
- VALUE time;
-{
- struct time_object *tobj;
-
- GetTimeval(time, tobj);
- if (tobj->tm_got == 0) {
- time_get_tm(time, tobj->gmt);
- }
- return INT2FIX(tobj->tm.tm_sec);
-}
-
-static VALUE
-time_min(time)
- VALUE time;
-{
- struct time_object *tobj;
-
- GetTimeval(time, tobj);
- if (tobj->tm_got == 0) {
- time_get_tm(time, tobj->gmt);
- }
- return INT2FIX(tobj->tm.tm_min);
-}
-
-static VALUE
-time_hour(time)
- VALUE time;
-{
- struct time_object *tobj;
-
- GetTimeval(time, tobj);
- if (tobj->tm_got == 0) {
- time_get_tm(time, tobj->gmt);
- }
- return INT2FIX(tobj->tm.tm_hour);
-}
-
-static VALUE
-time_mday(time)
- VALUE time;
-{
- struct time_object *tobj;
-
- GetTimeval(time, tobj);
- if (tobj->tm_got == 0) {
- time_get_tm(time, tobj->gmt);
- }
- return INT2FIX(tobj->tm.tm_mday);
-}
-
-static VALUE
-time_mon(time)
- VALUE time;
-{
- struct time_object *tobj;
-
- GetTimeval(time, tobj);
- if (tobj->tm_got == 0) {
- time_get_tm(time, tobj->gmt);
- }
- return INT2FIX(tobj->tm.tm_mon+1);
-}
-
-static VALUE
-time_year(time)
- VALUE time;
-{
- struct time_object *tobj;
-
- GetTimeval(time, tobj);
- if (tobj->tm_got == 0) {
- time_get_tm(time, tobj->gmt);
- }
- return LONG2NUM((long)tobj->tm.tm_year+1900);
-}
-
-static VALUE
-time_wday(time)
- VALUE time;
-{
- struct time_object *tobj;
-
- GetTimeval(time, tobj);
- if (tobj->tm_got == 0) {
- time_get_tm(time, tobj->gmt);
- }
- return INT2FIX(tobj->tm.tm_wday);
-}
-
-static VALUE
-time_yday(time)
- VALUE time;
-{
- struct time_object *tobj;
-
- GetTimeval(time, tobj);
- if (tobj->tm_got == 0) {
- time_get_tm(time, tobj->gmt);
- }
- return INT2FIX(tobj->tm.tm_yday+1);
-}
-
-static VALUE
-time_isdst(time)
- VALUE time;
-{
- struct time_object *tobj;
-
- GetTimeval(time, tobj);
- if (tobj->tm_got == 0) {
- time_get_tm(time, tobj->gmt);
- }
- return tobj->tm.tm_isdst?Qtrue:Qfalse;
-}
-
-static VALUE
-time_zone(time)
- VALUE time;
-{
- struct time_object *tobj;
- char buf[64];
- int len;
-
- GetTimeval(time, tobj);
- if (tobj->tm_got == 0) {
- time_get_tm(time, tobj->gmt);
- }
-
- if (tobj->gmt == 1) {
- return rb_str_new2("UTC");
- }
-#if defined(HAVE_TM_ZONE)
- return rb_str_new2(tobj->tm.tm_zone);
-#elif defined(HAVE_TZNAME) && defined(HAVE_DAYLIGHT)
- return rb_str_new2(tzname[daylight && tobj->tm.tm_isdst]);
-#else
- len = strftime(buf, 64, "%Z", &tobj->tm);
- return rb_str_new(buf, len);
-#endif
-}
-
-static VALUE
-time_utc_offset(time)
- VALUE time;
-{
- struct time_object *tobj;
-
- GetTimeval(time, tobj);
- if (tobj->tm_got == 0) {
- time_get_tm(time, tobj->gmt);
- }
-
- if (tobj->gmt == 1) {
- return INT2FIX(0);
- }
- else {
-#if defined(HAVE_STRUCT_TM_TM_GMTOFF)
- return INT2NUM(tobj->tm.tm_gmtoff);
-#else
- struct tm *u, *l;
- time_t t;
- int off;
- l = &tobj->tm;
- t = tobj->tv.tv_sec;
- u = gmtime(&t);
- if (!u)
- rb_raise(rb_eArgError, "gmtime error");
- if (l->tm_year != u->tm_year)
- off = l->tm_year < u->tm_year ? -1 : 1;
- else if (l->tm_mon != u->tm_mon)
- off = l->tm_mon < u->tm_mon ? -1 : 1;
- else if (l->tm_mday != u->tm_mday)
- off = l->tm_mday < u->tm_mday ? -1 : 1;
- else
- off = 0;
- off = off * 24 + l->tm_hour - u->tm_hour;
- off = off * 60 + l->tm_min - u->tm_min;
- off = off * 60 + l->tm_sec - u->tm_sec;
- return INT2FIX(off);
-#endif
- }
-}
-
-static VALUE
-time_to_a(time)
- VALUE time;
-{
- struct time_object *tobj;
-
- GetTimeval(time, tobj);
- if (tobj->tm_got == 0) {
- time_get_tm(time, tobj->gmt);
- }
- return rb_ary_new3(10,
- INT2FIX(tobj->tm.tm_sec),
- INT2FIX(tobj->tm.tm_min),
- INT2FIX(tobj->tm.tm_hour),
- INT2FIX(tobj->tm.tm_mday),
- INT2FIX(tobj->tm.tm_mon+1),
- LONG2NUM((long)tobj->tm.tm_year+1900),
- INT2FIX(tobj->tm.tm_wday),
- INT2FIX(tobj->tm.tm_yday+1),
- tobj->tm.tm_isdst?Qtrue:Qfalse,
- time_zone(time));
-}
-
-#define SMALLBUF 100
-static int
-rb_strftime(buf, format, time)
- char ** volatile buf;
- char * volatile format;
- struct tm * volatile time;
-{
- volatile int size;
- int len, flen;
-
- (*buf)[0] = '\0';
- flen = strlen(format);
- if (flen == 0) {
- return 0;
- }
- len = strftime(*buf, SMALLBUF, format, time);
- if (len != 0 || **buf == '\0') return len;
- for (size=1024; ; size*=2) {
- *buf = xmalloc(size);
- (*buf)[0] = '\0';
- len = strftime(*buf, size, format, time);
- /*
- * buflen can be zero EITHER because there's not enough
- * room in the string, or because the control command
- * goes to the empty string. Make a reasonable guess that
- * if the buffer is 1024 times bigger than the length of the
- * format string, it's not failing for lack of room.
- */
- if (len > 0 || size >= 1024 * flen) return len;
- free(*buf);
- }
- /* not reached */
-}
-
-static VALUE
-time_strftime(time, format)
- VALUE time, format;
-{
- struct time_object *tobj;
- char buffer[SMALLBUF];
- char *fmt;
- char *buf = buffer;
- int len;
- VALUE str;
-
- GetTimeval(time, tobj);
- if (tobj->tm_got == 0) {
- time_get_tm(time, tobj->gmt);
- }
- StringValue(format);
- fmt = RSTRING(format)->ptr;
- len = RSTRING(format)->len;
- if (len == 0) {
- rb_warning("strftime called with empty format string");
- }
- if (strlen(fmt) < len) {
- /* Ruby string may contain \0's. */
- char *p = fmt, *pe = fmt + len;
-
- str = rb_str_new(0, 0);
- while (p < pe) {
- len = rb_strftime(&buf, p, &tobj->tm);
- rb_str_cat(str, buf, len);
- p += strlen(p) + 1;
- if (p <= pe)
- rb_str_cat(str, "\0", 1);
- if (buf != buffer) {
- free(buf);
- buf = buffer;
- }
- }
- return str;
- }
- len = rb_strftime(&buf, RSTRING(format)->ptr, &tobj->tm);
- str = rb_str_new(buf, len);
- if (buf != buffer) free(buf);
- return str;
-}
-
-static VALUE
-time_s_times(obj)
- VALUE obj;
-{
- rb_warn("obsolete method Time::times; use Process::times");
- return rb_proc_times(obj);
-}
-
-static VALUE
-time_dump(argc, argv, time)
- int argc;
- VALUE *argv;
- VALUE time;
-{
- VALUE dummy;
- struct time_object *tobj;
- struct tm *tm;
- unsigned long p, s;
- unsigned char buf[8];
- time_t t;
- int i;
-
- rb_scan_args(argc, argv, "01", &dummy);
- GetTimeval(time, tobj);
-
- t = tobj->tv.tv_sec;
- tm = gmtime(&t);
-
- if ((tm->tm_year & 0x1ffff) != tm->tm_year)
- rb_raise(rb_eArgError, "too big year to marshal");
-
- p = 0x1 << 31 | /* 1 */
- tm->tm_year << 14 | /* 17 */
- tm->tm_mon << 10 | /* 4 */
- tm->tm_mday << 5 | /* 5 */
- tm->tm_hour; /* 5 */
- s = tm->tm_min << 26 | /* 6 */
- tm->tm_sec << 20 | /* 6 */
- tobj->tv.tv_usec; /* 20 */
-
- for (i=0; i<4; i++) {
- buf[i] = p & 0xff;
- p = RSHIFT(p, 8);
- }
- for (i=4; i<8; i++) {
- buf[i] = s & 0xff;
- s = RSHIFT(s, 8);
- }
-
- return rb_str_new(buf, 8);
-}
-
-static VALUE
-time_load(klass, str)
- VALUE klass, str;
-{
- unsigned long p, s;
- time_t sec, usec;
- unsigned char *buf;
- struct tm tm;
- int i;
-
- StringValue(str);
- buf = RSTRING(str)->ptr;
- if (RSTRING(str)->len != 8) {
- rb_raise(rb_eTypeError, "marshaled time format differ");
- }
-
- p = s = 0;
- for (i=0; i<4; i++) {
- p |= buf[i]<<(8*i);
- }
- for (i=4; i<8; i++) {
- s |= buf[i]<<(8*(i-4));
- }
-
- if ((p & (1<<31)) == 0) {
- return time_new_internal(klass, p, s);
- }
- p &= ~(1<<31);
- tm.tm_year = (p >> 14) & 0x1ffff;
- tm.tm_mon = (p >> 10) & 0xf;
- tm.tm_mday = (p >> 5) & 0x1f;
- tm.tm_hour = p & 0x1f;
- tm.tm_min = (s >> 26) & 0x3f;
- tm.tm_sec = (s >> 20) & 0x3f;
- tm.tm_isdst = 0;
-
- sec = make_time_t(&tm, Qtrue);
- usec = (time_t)(s & 0xfffff);
-
- return time_new_internal(klass, sec, usec);
-}
-
-void
-Init_Time()
-{
- rb_cTime = rb_define_class("Time", rb_cObject);
- rb_include_module(rb_cTime, rb_mComparable);
-
- rb_define_singleton_method(rb_cTime, "now", time_s_now, 0);
- rb_define_singleton_method(rb_cTime, "allocate", time_s_alloc, 0);
- rb_define_singleton_method(rb_cTime, "at", time_s_at, -1);
- rb_define_singleton_method(rb_cTime, "utc", time_s_mkutc, -1);
- rb_define_singleton_method(rb_cTime, "gm", time_s_mkutc, -1);
- rb_define_singleton_method(rb_cTime, "local", time_s_mktime, -1);
- rb_define_singleton_method(rb_cTime, "mktime", time_s_mktime, -1);
-
- rb_define_singleton_method(rb_cTime, "times", time_s_times, 0);
-
- rb_define_method(rb_cTime, "to_i", time_to_i, 0);
- rb_define_method(rb_cTime, "to_f", time_to_f, 0);
- rb_define_method(rb_cTime, "<=>", time_cmp, 1);
- rb_define_method(rb_cTime, "eql?", time_eql, 1);
- rb_define_method(rb_cTime, "hash", time_hash, 0);
- rb_define_method(rb_cTime, "clone", time_clone, 0);
- rb_define_method(rb_cTime, "dup", time_dup, 0);
-
- rb_define_method(rb_cTime, "localtime", time_localtime, 0);
- rb_define_method(rb_cTime, "gmtime", time_gmtime, 0);
- rb_define_method(rb_cTime, "utc", time_gmtime, 0);
- rb_define_method(rb_cTime, "getlocal", time_getlocaltime, 0);
- rb_define_method(rb_cTime, "getgm", time_getgmtime, 0);
- rb_define_method(rb_cTime, "getutc", time_getgmtime, 0);
-
- rb_define_method(rb_cTime, "ctime", time_asctime, 0);
- rb_define_method(rb_cTime, "asctime", time_asctime, 0);
- rb_define_method(rb_cTime, "to_s", time_to_s, 0);
- rb_define_method(rb_cTime, "inspect", time_to_s, 0);
- rb_define_method(rb_cTime, "to_a", time_to_a, 0);
-
- rb_define_method(rb_cTime, "+", time_plus, 1);
- rb_define_method(rb_cTime, "-", time_minus, 1);
-
- rb_define_method(rb_cTime, "sec", time_sec, 0);
- rb_define_method(rb_cTime, "min", time_min, 0);
- rb_define_method(rb_cTime, "hour", time_hour, 0);
- rb_define_method(rb_cTime, "mday", time_mday, 0);
- rb_define_method(rb_cTime, "day", time_mday, 0);
- rb_define_method(rb_cTime, "mon", time_mon, 0);
- rb_define_method(rb_cTime, "month", time_mon, 0);
- rb_define_method(rb_cTime, "year", time_year, 0);
- rb_define_method(rb_cTime, "wday", time_wday, 0);
- rb_define_method(rb_cTime, "yday", time_yday, 0);
- rb_define_method(rb_cTime, "isdst", time_isdst, 0);
- rb_define_method(rb_cTime, "dst?", time_isdst, 0);
- rb_define_method(rb_cTime, "zone", time_zone, 0);
- rb_define_method(rb_cTime, "gmtoff", time_utc_offset, 0);
- rb_define_method(rb_cTime, "gmt_offset", time_utc_offset, 0);
- rb_define_method(rb_cTime, "utc_offset", time_utc_offset, 0);
-
- rb_define_method(rb_cTime, "utc?", time_utc_p, 0);
- rb_define_method(rb_cTime, "gmt?", time_utc_p, 0);
-
- rb_define_method(rb_cTime, "tv_sec", time_to_i, 0);
- rb_define_method(rb_cTime, "tv_usec", time_usec, 0);
- rb_define_method(rb_cTime, "usec", time_usec, 0);
-
- rb_define_method(rb_cTime, "strftime", time_strftime, 1);
-
- /* methods for marshaling */
- rb_define_method(rb_cTime, "_dump", time_dump, -1);
- rb_define_singleton_method(rb_cTime, "_load", time_load, 1);
-}
diff --git a/util.c b/util.c
deleted file mode 100644
index 512b00b47a..0000000000
--- a/util.c
+++ /dev/null
@@ -1,650 +0,0 @@
-/**********************************************************************
-
- util.c -
-
- $Author$
- $Date$
- created at: Fri Mar 10 17:22:34 JST 1995
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
-
-**********************************************************************/
-
-#include <stdio.h>
-#include <errno.h>
-
-#ifdef NT
-#include "missing/file.h"
-#endif
-
-#include "ruby.h"
-
-#include "util.h"
-#ifndef HAVE_STRING_H
-char *strchr _((char*,char));
-#endif
-
-unsigned long
-scan_oct(start, len, retlen)
-const char *start;
-int len;
-int *retlen;
-{
- register const char *s = start;
- register unsigned long retval = 0;
-
- while (len-- && *s >= '0' && *s <= '7') {
- retval <<= 3;
- retval |= *s++ - '0';
- }
- *retlen = s - start;
- return retval;
-}
-
-unsigned long
-scan_hex(start, len, retlen)
-const char *start;
-int len;
-int *retlen;
-{
- static char hexdigit[] = "0123456789abcdef0123456789ABCDEF";
- register const char *s = start;
- register unsigned long retval = 0;
- char *tmp;
-
- while (len-- && *s && (tmp = strchr(hexdigit, *s))) {
- retval <<= 4;
- retval |= (tmp - hexdigit) & 15;
- s++;
- }
- *retlen = s - start;
- return retval;
-}
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-#if defined(HAVE_FCNTL_H)
-#include <fcntl.h>
-#endif
-
-#ifndef S_ISDIR
-# define S_ISDIR(m) ((m & S_IFMT) == S_IFDIR)
-#endif
-
-#ifdef NT
-#include "missing/file.h"
-#endif
-
-#if defined(MSDOS) || defined(__CYGWIN32__) || defined(NT)
-/*
- * Copyright (c) 1993, Intergraph Corporation
- *
- * You may distribute under the terms of either the GNU General Public
- * License or the Artistic License, as specified in the perl README file.
- *
- * Various Unix compatibility functions and NT specific functions.
- *
- * Some of this code was derived from the MSDOS port(s) and the OS/2 port.
- *
- */
-
-
-/*
- * Suffix appending for in-place editing under MS-DOS and OS/2 (and now NT!).
- *
- * Here are the rules:
- *
- * Style 0: Append the suffix exactly as standard perl would do it.
- * If the filesystem groks it, use it. (HPFS will always
- * grok it. So will NTFS. FAT will rarely accept it.)
- *
- * Style 1: The suffix begins with a '.'. The extension is replaced.
- * If the name matches the original name, use the fallback method.
- *
- * Style 2: The suffix is a single character, not a '.'. Try to add the
- * suffix to the following places, using the first one that works.
- * [1] Append to extension.
- * [2] Append to filename,
- * [3] Replace end of extension,
- * [4] Replace end of filename.
- * If the name matches the original name, use the fallback method.
- *
- * Style 3: Any other case: Ignore the suffix completely and use the
- * fallback method.
- *
- * Fallback method: Change the extension to ".$$$". If that matches the
- * original name, then change the extension to ".~~~".
- *
- * If filename is more than 1000 characters long, we die a horrible
- * death. Sorry.
- *
- * The filename restriction is a cheat so that we can use buf[] to store
- * assorted temporary goo.
- *
- * Examples, assuming style 0 failed.
- *
- * suffix = ".bak" (style 1)
- * foo.bar => foo.bak
- * foo.bak => foo.$$$ (fallback)
- * foo.$$$ => foo.~~~ (fallback)
- * makefile => makefile.bak
- *
- * suffix = "~" (style 2)
- * foo.c => foo.c~
- * foo.c~ => foo.c~~
- * foo.c~~ => foo~.c~~
- * foo~.c~~ => foo~~.c~~
- * foo~~~~~.c~~ => foo~~~~~.$$$ (fallback)
- *
- * foo.pas => foo~.pas
- * makefile => makefile.~
- * longname.fil => longname.fi~
- * longname.fi~ => longnam~.fi~
- * longnam~.fi~ => longnam~.$$$
- *
- */
-
-
-static int valid_filename(char *s);
-
-static char suffix1[] = ".$$$";
-static char suffix2[] = ".~~~";
-
-#define ext (&buf[1000])
-
-#define strEQ(s1,s2) (strcmp(s1,s2) == 0)
-
-void
-ruby_add_suffix(str, suffix)
- VALUE str;
- char *suffix;
-{
- int baselen;
- int extlen = strlen(suffix);
- char *s, *t, *p;
- int slen;
- char buf[1024];
-
- if (RSTRING(str)->len > 1000)
- rb_fatal("Cannot do inplace edit on long filename (%d characters)",
- RSTRING(str)->len);
-
-#if defined(DJGPP) || defined(__CYGWIN32__) || defined(NT)
- /* Style 0 */
- slen = RSTRING(str)->len;
- rb_str_cat(str, suffix, extlen);
-#if defined(DJGPP)
- if (_USE_LFN) return;
-#else
- if (valid_filename(RSTRING(str)->ptr)) return;
-#endif
-
- /* Fooey, style 0 failed. Fix str before continuing. */
- RSTRING(str)->ptr[RSTRING(str)->len = slen] = '\0';
-#endif
-
- slen = extlen;
- t = buf; baselen = 0; s = RSTRING(str)->ptr;
- while ((*t = *s) && *s != '.') {
- baselen++;
- if (*s == '\\' || *s == '/') baselen = 0;
- s++; t++;
- }
- p = t;
-
- t = ext; extlen = 0;
- while (*t++ = *s++) extlen++;
- if (extlen == 0) { ext[0] = '.'; ext[1] = 0; extlen++; }
-
- if (*suffix == '.') { /* Style 1 */
- if (strEQ(ext, suffix)) goto fallback;
- strcpy(p, suffix);
- }
- else if (suffix[1] == '\0') { /* Style 2 */
- if (extlen < 4) {
- ext[extlen] = *suffix;
- ext[++extlen] = '\0';
- }
- else if (baselen < 8) {
- *p++ = *suffix;
- }
- else if (ext[3] != *suffix) {
- ext[3] = *suffix;
- }
- else if (buf[7] != *suffix) {
- buf[7] = *suffix;
- }
- else goto fallback;
- strcpy(p, ext);
- }
- else { /* Style 3: Panic */
-fallback:
- (void)memcpy(p, strEQ(ext, suffix1) ? suffix2 : suffix1, 5);
- }
- rb_str_resize(str, strlen(buf));
- memcpy(RSTRING(str)->ptr, buf, RSTRING(str)->len);
-}
-
-#if defined(__CYGWIN32__) || defined(NT)
-static int
-valid_filename(char *s)
-{
- int fd;
-
- /*
- // if the file exists, then it's a valid filename!
- */
-
- if (_access(s, 0) == 0) {
- return 1;
- }
-
- /*
- // It doesn't exist, so see if we can open it.
- */
-
- if ((fd = _open(s, O_CREAT, 0666)) >= 0) {
- _close(fd);
- _unlink (s); /* don't leave it laying around */
- return 1;
- }
- return 0;
-}
-#endif
-#endif
-
-#if defined __DJGPP__
-
-#include <dpmi.h>
-
-static char dbcs_table[256];
-
-int
-make_dbcs_table()
-{
- __dpmi_regs r;
- struct {
- unsigned char start;
- unsigned char end;
- } vec;
- int offset;
-
- memset(&r, 0, sizeof(r));
- r.x.ax = 0x6300;
- __dpmi_int(0x21, &r);
- offset = r.x.ds * 16 + r.x.si;
-
- for (;;) {
- int i;
- dosmemget(offset, sizeof vec, &vec);
- if (!vec.start && !vec.end)
- break;
- for (i = vec.start; i <= vec.end; i++)
- dbcs_table[i] = 1;
- offset += 2;
- }
-}
-
-int
-mblen(const char *s, size_t n)
-{
- static int need_init = 1;
- if (need_init) {
- make_dbcs_table();
- need_init = 0;
- }
- if (s) {
- if (n == 0 || *s == 0)
- return 0;
- return dbcs_table[(unsigned char)*s] + 1;
- }
- else
- return 1;
-}
-
-struct PathList {
- struct PathList *next;
- char *path;
-};
-
-struct PathInfo {
- struct PathList *head;
- int count;
-};
-
-static void
-push_element(char *path, struct PathInfo *info)
-{
- struct PathList *p;
-
- p = ALLOC(struct PathList);
- MEMZERO(p, struct PathList, 1);
- p->path = ruby_strdup(path);
- p->next = info->head;
- info->head = p;
- info->count++;
-}
-
-#include <dirent.h>
-int __opendir_flags = __OPENDIR_PRESERVE_CASE;
-
-char **
-__crt0_glob_function(char *path)
-{
- int len = strlen(path);
- int i;
- char **rv;
- char path_buffer[PATH_MAX];
- char *buf = path_buffer;
- char *p;
- struct PathInfo info;
- struct PathList *plist;
-
- if (PATH_MAX <= len)
- buf = ruby_xmalloc(len + 1);
-
- strncpy(buf, path, len);
- buf[len] = '\0';
-
- for (p = buf; *p; p += mblen(p, MB_CUR_MAX))
- if (*p == '\\')
- *p = '/';
-
- info.count = 0;
- info.head = 0;
-
- rb_globi(buf, push_element, (VALUE)&info);
-
- if (buf != path_buffer)
- ruby_xfree(buf);
-
- if (info.count == 0)
- return 0;
-
- rv = ruby_xmalloc((info.count + 1) * sizeof (char *));
-
- plist = info.head;
- i = 0;
- while (plist) {
- struct PathList *cur;
- rv[i] = plist->path;
- cur = plist;
- plist = plist->next;
- ruby_xfree(cur);
- i++;
- }
- rv[i] = 0;
- return rv;
-}
-
-#endif
-
-/* mm.c */
-
-#define A ((int*)a)
-#define B ((int*)b)
-#define C ((int*)c)
-#define D ((int*)d)
-
-#define mmprepare(base, size) do {\
- if (((long)base & (0x3)) == 0)\
- if (size >= 16) mmkind = 1;\
- else mmkind = 0;\
- else mmkind = -1;\
- high = (size & (~0xf));\
- low = (size & 0x0c);\
-} while (0)\
-
-#define mmarg mmkind, size, high, low
-
-static void mmswap_(a, b, mmarg)
- register char *a, *b;
- int mmarg;
-{
- register int s;
- if (a == b) return;
- if (mmkind >= 0) {
- if (mmkind > 0) {
- register char *t = a + high;
- do {
- s = A[0]; A[0] = B[0]; B[0] = s;
- s = A[1]; A[1] = B[1]; B[1] = s;
- s = A[2]; A[2] = B[2]; B[2] = s;
- s = A[3]; A[3] = B[3]; B[3] = s; a += 16; b += 16;
- } while (a < t);
- }
- if (low != 0) { s = A[0]; A[0] = B[0]; B[0] = s;
- if (low >= 8) { s = A[1]; A[1] = B[1]; B[1] = s;
- if (low == 12) {s = A[2]; A[2] = B[2]; B[2] = s;}}}
- }
- else {
- register char *t = a + size;
- do {s = *a; *a++ = *b; *b++ = s;} while (a < t);
- }
-}
-#define mmswap(a,b) mmswap_((a),(b),mmarg)
-
-static void mmrot3_(a, b, c, mmarg)
- register char *a, *b, *c;
- int mmarg;
-{
- register int s;
- if (mmkind >= 0) {
- if (mmkind > 0) {
- register char *t = a + high;
- do {
- s = A[0]; A[0] = B[0]; B[0] = C[0]; C[0] = s;
- s = A[1]; A[1] = B[1]; B[1] = C[1]; C[1] = s;
- s = A[2]; A[2] = B[2]; B[2] = C[2]; C[2] = s;
- s = A[3]; A[3] = B[3]; B[3] = C[3]; C[3] = s; a += 16; b += 16; c += 16;
- } while (a < t);
- }
- if (low != 0) { s = A[0]; A[0] = B[0]; B[0] = C[0]; C[0] = s;
- if (low >= 8) { s = A[1]; A[1] = B[1]; B[1] = C[1]; C[1] = s;
- if (low == 12) {s = A[2]; A[2] = B[2]; B[2] = C[2]; C[2] = s;}}}
- }
- else {
- register char *t = a + size;
- do {s = *a; *a++ = *b; *b++ = *c; *c++ = s;} while (a < t);
- }
-}
-#define mmrot3(a,b,c) mmrot3_((a),(b),(c),mmarg)
-
-/* qs6.c */
-/*****************************************************/
-/* */
-/* qs6 (Quick sort function) */
-/* */
-/* by Tomoyuki Kawamura 1995.4.21 */
-/* kawamura@tokuyama.ac.jp */
-/*****************************************************/
-
-typedef struct { char *LL, *RR; } stack_node; /* Stack structure for L,l,R,r */
-#define PUSH(ll,rr) {top->LL = (ll); top->RR = (rr); ++top;} /* Push L,l,R,r */
-#define POP(ll,rr) {--top; ll = top->LL; rr = top->RR;} /* Pop L,l,R,r */
-
-#define med3(a,b,c) ((*cmp)(a,b)<0 ? \
- ((*cmp)(b,c)<0 ? b : ((*cmp)(a,c)<0 ? c : a)) : \
- ((*cmp)(b,c)>0 ? b : ((*cmp)(a,c)<0 ? a : c)))
-
-void ruby_qsort (base, nel, size, cmp)
- void* base;
- const int nel;
- const int size;
- int (*cmp)();
-{
- register char *l, *r, *m; /* l,r:left,right group m:median point */
- register int t, eq_l, eq_r; /* eq_l: all items in left group are equal to S */
- char *L = base; /* left end of curren region */
- char *R = (char*)base + size*(nel-1); /* right end of current region */
- int chklim = 63; /* threshold of ordering element check */
- stack_node stack[32], *top = stack; /* 32 is enough for 32bit CPU */
- int mmkind, high, low;
-
- if (nel <= 1) return; /* need not to sort */
- mmprepare(base, size);
- goto start;
-
- nxt:
- if (stack == top) return; /* return if stack is empty */
- POP(L,R);
-
- for (;;) {
- start:
- if (L + size == R) { /* 2 elements */
- if ((*cmp)(L,R) > 0) mmswap(L,R); goto nxt;
- }
-
- l = L; r = R;
- t = (r - l + size) / size; /* number of elements */
- m = l + size * (t >> 1); /* calculate median value */
-
- if (t >= 60) {
- register char *m1;
- register char *m3;
- if (t >= 200) {
- t = size*(t>>3); /* number of bytes in splitting 8 */
- {
- register char *p1 = l + t;
- register char *p2 = p1 + t;
- register char *p3 = p2 + t;
- m1 = med3(p1, p2, p3);
- p1 = m + t;
- p2 = p1 + t;
- p3 = p2 + t;
- m3 = med3(p1, p2, p3);
- }
- }
- else {
- t = size*(t>>2); /* number of bytes in splitting 4 */
- m1 = l + t;
- m3 = m + t;
- }
- m = med3(m1, m, m3);
- }
-
- if ((t = (*cmp)(l,m)) < 0) { /*3-5-?*/
- if ((t = (*cmp)(m,r)) < 0) { /*3-5-7*/
- if (chklim && nel >= chklim) { /* check if already ascending order */
- char *p;
- chklim = 0;
- for (p=l; p<r; p+=size) if ((*cmp)(p,p+size) > 0) goto fail;
- goto nxt;
- }
- fail: goto loopA; /*3-5-7*/
- }
- if (t > 0) {
- if ((*cmp)(l,r) <= 0) {mmswap(m,r); goto loopA;} /*3-5-4*/
- mmrot3(r,m,l); goto loopA; /*3-5-2*/
- }
- goto loopB; /*3-5-5*/
- }
-
- if (t > 0) { /*7-5-?*/
- if ((t = (*cmp)(m,r)) > 0) { /*7-5-3*/
- if (chklim && nel >= chklim) { /* check if already ascending order */
- char *p;
- chklim = 0;
- for (p=l; p<r; p+=size) if ((*cmp)(p,p+size) < 0) goto fail2;
- while (l<r) {mmswap(l,r); l+=size; r-=size;} /* reverse region */
- goto nxt;
- }
- fail2: mmswap(l,r); goto loopA; /*7-5-3*/
- }
- if (t < 0) {
- if ((*cmp)(l,r) <= 0) {mmswap(l,m); goto loopB;} /*7-5-8*/
- mmrot3(l,m,r); goto loopA; /*7-5-6*/
- }
- mmswap(l,r); goto loopA; /*7-5-5*/
- }
-
- if ((t = (*cmp)(m,r)) < 0) {goto loopA;} /*5-5-7*/
- if (t > 0) {mmswap(l,r); goto loopB;} /*5-5-3*/
-
- /* determining splitting type in case 5-5-5 */ /*5-5-5*/
- for (;;) {
- if ((l += size) == r) goto nxt; /*5-5-5*/
- if (l == m) continue;
- if ((t = (*cmp)(l,m)) > 0) {mmswap(l,r); l = L; goto loopA;} /*575-5*/
- if (t < 0) {mmswap(L,l); l = L; goto loopB;} /*535-5*/
- }
-
- loopA: eq_l = 1; eq_r = 1; /* splitting type A */ /* left <= median < right */
- for (;;) {
- for (;;) {
- if ((l += size) == r)
- {l -= size; if (l != m) mmswap(m,l); l -= size; goto fin;}
- if (l == m) continue;
- if ((t = (*cmp)(l,m)) > 0) {eq_r = 0; break;}
- if (t < 0) eq_l = 0;
- }
- for (;;) {
- if (l == (r -= size))
- {l -= size; if (l != m) mmswap(m,l); l -= size; goto fin;}
- if (r == m) {m = l; break;}
- if ((t = (*cmp)(r,m)) < 0) {eq_l = 0; break;}
- if (t == 0) break;
- }
- mmswap(l,r); /* swap left and right */
- }
-
- loopB: eq_l = 1; eq_r = 1; /* splitting type B */ /* left < median <= right */
- for (;;) {
- for (;;) {
- if (l == (r -= size))
- {r += size; if (r != m) mmswap(r,m); r += size; goto fin;}
- if (r == m) continue;
- if ((t = (*cmp)(r,m)) < 0) {eq_l = 0; break;}
- if (t > 0) eq_r = 0;
- }
- for (;;) {
- if ((l += size) == r)
- {r += size; if (r != m) mmswap(r,m); r += size; goto fin;}
- if (l == m) {m = r; break;}
- if ((t = (*cmp)(l,m)) > 0) {eq_r = 0; break;}
- if (t == 0) break;
- }
- mmswap(l,r); /* swap left and right */
- }
-
- fin:
- if (eq_l == 0) /* need to sort left side */
- if (eq_r == 0) /* need to sort right side */
- if (l-L < R-r) {PUSH(r,R); R = l;} /* sort left side first */
- else {PUSH(L,l); L = r;} /* sort right side first */
- else R = l; /* need to sort left side only */
- else if (eq_r == 0) L = r; /* need to sort right side only */
- else goto nxt; /* need not to sort both sides */
- }
-}
-
-char *
-ruby_strdup(str)
- const char *str;
-{
- char *tmp;
- int len = strlen(str) + 1;
-
- tmp = xmalloc(len);
- if (tmp == NULL) return NULL;
- memcpy(tmp, str, len);
-
- return tmp;
-}
-
-char *
-ruby_getcwd()
-{
- int size = 200;
- char *buf = xmalloc(size);
-
- while (!getcwd(buf, size)) {
- if (errno != ERANGE) rb_sys_fail(NULL);
- size *= 2;
- buf = xrealloc(buf, size);
- }
- return buf;
-}
diff --git a/util.h b/util.h
deleted file mode 100644
index 51f32d0179..0000000000
--- a/util.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/**********************************************************************
-
- util.h -
-
- $Author$
- $Date$
- created at: Thu Mar 9 11:55:53 JST 1995
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
-
-**********************************************************************/
-
-#ifndef UTIL_H
-#define UTIL_H
-
-#ifndef _
-#ifdef __cplusplus
-# ifndef HAVE_PROTOTYPES
-# define HAVE_PROTOTYPES 1
-# endif
-# ifndef HAVE_STDARG_PROTOTYPES
-# define HAVE_STDARG_PROTOTYPES 1
-# endif
-#endif
-#ifdef HAVE_PROTOTYPES
-# define _(args) args
-#else
-# define _(args) ()
-#endif
-#ifdef HAVE_STDARG_PROTOTYPES
-# define __(args) args
-#else
-# define __(args) ()
-#endif
-#endif
-
-#define scan_oct ruby_scan_oct
-unsigned long scan_oct _((const char*, int, int*));
-#define scan_hex ruby_scan_hex
-unsigned long scan_hex _((const char*, int, int*));
-
-#if defined(MSDOS) || defined(__CYGWIN32__) || defined(NT)
-void ruby_add_suffix();
-#define add_suffix ruby_add_suffix
-#endif
-
-void ruby_qsort _((void*, const int, const int, int (*)()));
-#define qsort(b,n,s,c) ruby_qsort(b,n,s,c)
-
-void ruby_setenv _((const char*, const char*));
-void ruby_unsetenv _((const char*));
-#undef setenv
-#undef unsetenv
-#define setenv(name,val) ruby_setenv((name),(val))
-#define unsetenv(name,val) ruby_unsetenv((name));
-
-char *ruby_strdup _((const char*));
-#undef strdup
-#define strdup(s) ruby_strdup((s))
-
-char *ruby_getcwd _((void));
-#define my_getcwd() ruby_getcwd()
-
-#endif /* UTIL_H */
diff --git a/variable.c b/variable.c
deleted file mode 100644
index e8b8605576..0000000000
--- a/variable.c
+++ /dev/null
@@ -1,1633 +0,0 @@
-/**********************************************************************
-
- variable.c -
-
- $Author$
- $Date$
- created at: Tue Apr 19 23:55:15 JST 1994
-
- Copyright (C) 1993-2001 Yukihiro Matsumoto
- Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
- Copyright (C) 2000 Information-technology Promotion Agency, Japan
-
-**********************************************************************/
-
-#include "ruby.h"
-#include "env.h"
-#include "node.h"
-#include "st.h"
-#include "util.h"
-
-static st_table *rb_global_tbl;
-st_table *rb_class_tbl;
-
-void
-Init_var_tables()
-{
- rb_global_tbl = st_init_numtable();
- rb_class_tbl = st_init_numtable();
-}
-
-struct fc_result {
- ID name;
- VALUE klass;
- VALUE path;
- VALUE track;
- struct fc_result *prev;
-};
-
-static VALUE
-fc_path(fc, name)
- struct fc_result *fc;
- ID name;
-{
- VALUE path, tmp;
-
- path = rb_str_new2(rb_id2name(name));
- while (fc) {
- if (fc->track == rb_cObject) break;
- if (ROBJECT(fc->track)->iv_tbl &&
- st_lookup(ROBJECT(fc->track)->iv_tbl, rb_intern("__classpath__"), &tmp)) {
- tmp = rb_str_dup(tmp);
- rb_str_cat2(tmp, "::");
- rb_str_append(tmp, path);
-
- return tmp;
- }
- tmp = rb_str_new2(rb_id2name(fc->name));
- rb_str_cat2(tmp, "::");
- rb_str_append(tmp, path);
- path = tmp;
- fc = fc->prev;
- }
- return path;
-}
-
-static int
-fc_i(key, value, res)
- ID key;
- VALUE value;
- struct fc_result *res;
-{
- VALUE path;
-
- if (!rb_is_const_id(key)) return ST_CONTINUE;
-
- if (value == res->klass) {
- res->path = fc_path(res, key);
- return ST_STOP;
- }
- switch (TYPE(value)) {
- case T_MODULE:
- case T_CLASS:
- if (!RCLASS(value)->iv_tbl) return ST_CONTINUE;
- else {
- struct fc_result arg;
- struct fc_result *list;
-
- list = res;
- while (list) {
- if (list->track == value) return ST_CONTINUE;
- list = list->prev;
- }
-
- arg.name = key;
- arg.path = 0;
- arg.klass = res->klass;
- arg.track = value;
- arg.prev = res;
- st_foreach(RCLASS(value)->iv_tbl, fc_i, &arg);
- if (arg.path) {
- res->path = arg.path;
- return ST_STOP;
- }
- }
- break;
-
- default:
- break;
-
- }
- return ST_CONTINUE;
-}
-
-static VALUE
-find_class_path(klass)
- VALUE klass;
-{
- struct fc_result arg;
-
- arg.name = 0;
- arg.path = 0;
- arg.klass = klass;
- arg.track = rb_cObject;
- arg.prev = 0;
- if (RCLASS(rb_cObject)->iv_tbl) {
- st_foreach(RCLASS(rb_cObject)->iv_tbl, fc_i, &arg);
- }
- if (arg.path == 0) {
- st_foreach(rb_class_tbl, fc_i, &arg);
- }
- if (arg.path) {
- if (!ROBJECT(klass)->iv_tbl) {
- ROBJECT(klass)->iv_tbl = st_init_numtable();
- }
- st_insert(ROBJECT(klass)->iv_tbl,rb_intern("__classpath__"),arg.path);
- return arg.path;
- }
- return Qnil;
-}
-
-static VALUE
-classname(klass)
- VALUE klass;
-{
- VALUE path = Qnil;
- ID classpath = rb_intern("__classpath__");
-
- if (TYPE(klass) == T_ICLASS) {
- klass = RBASIC(klass)->klass;
- }
- klass = rb_class_real(klass);
- if (!klass) klass = rb_cObject;
- if (ROBJECT(klass)->iv_tbl &&
- !st_lookup(ROBJECT(klass)->iv_tbl, classpath, &path)) {
- ID classid = rb_intern("__classid__");
-
- if (st_lookup(ROBJECT(klass)->iv_tbl, classid, &path)) {
- path = rb_str_new2(rb_id2name(SYM2ID(path)));
- st_insert(ROBJECT(klass)->iv_tbl, classpath, path);
- st_delete(RCLASS(klass)->iv_tbl, &classid, 0);
- }
- }
- if (NIL_P(path)) {
- path = find_class_path(klass);
- if (NIL_P(path)) {
- return 0;
- }
- return path;
- }
- if (TYPE(path) != T_STRING)
- rb_bug("class path is not set properly");
- return path;
-}
-
-VALUE
-rb_mod_name(mod)
- VALUE mod;
-{
- VALUE path = classname(mod);
-
- if (path) return rb_str_dup(path);
- return rb_str_new(0,0);
-}
-
-VALUE
-rb_class_path(klass)
- VALUE klass;
-{
- VALUE path = classname(klass);
-
- if (path) return path;
- else {
- char buf[256];
- char *s = "Class";
-
- if (TYPE(klass) == T_MODULE) {
- if (rb_obj_class(klass) == rb_cModule)
- s = "Module";
- else
- s = rb_class2name(RBASIC(klass)->klass);
- }
- sprintf(buf, "#<%s:0x%lx>", s, klass);
- return rb_str_new2(buf);
- }
-}
-
-void
-rb_set_class_path(klass, under, name)
- VALUE klass, under;
- const char *name;
-{
- VALUE str;
-
- if (under == rb_cObject) {
- str = rb_str_new2(name);
- }
- else {
- str = rb_str_dup(rb_class_path(under));
- rb_str_cat2(str, "::");
- rb_str_cat2(str, name);
- }
- rb_iv_set(klass, "__classpath__", str);
-}
-
-VALUE
-rb_path2class(path)
- const char *path;
-{
- VALUE c;
-
- if (path[0] == '#') {
- rb_raise(rb_eArgError, "can't retrieve anonymous class %s", path);
- }
- c = rb_eval_string(path);
- switch (TYPE(c)) {
- case T_MODULE:
- case T_CLASS:
- break;
- default:
- rb_raise(rb_eTypeError, "class path %s does not point class", path);
- }
- return c;
-}
-
-void
-rb_name_class(klass, id)
- VALUE klass;
- ID id;
-{
- rb_iv_set(klass, "__classid__", ID2SYM(id));
-}
-
-static st_table *autoload_tbl = 0;
-
-static void
-rb_autoload_id(id, filename)
- ID id;
- const char *filename;
-{
- rb_secure(4);
- if (!rb_is_const_id(id)) {
- rb_name_error(id, "autoload must be constant name", rb_id2name(id));
- }
-
- if (!autoload_tbl) {
- autoload_tbl = st_init_numtable();
- }
- st_insert(autoload_tbl, id, strdup(filename));
-}
-
-void
-rb_autoload(klass, filename)
- const char *klass, *filename;
-{
- rb_autoload_id(rb_intern(klass), filename);
-}
-
-VALUE
-rb_f_autoload(obj, klass, file)
- VALUE obj, klass, file;
-{
- rb_autoload_id(rb_to_id(klass), StringValuePtr(file));
- return Qnil;
-}
-
-char *
-rb_class2name(klass)
- VALUE klass;
-{
- return RSTRING(rb_class_path(klass))->ptr;
-}
-
-struct trace_var {
- int removed;
- void (*func)();
- VALUE data;
- struct trace_var *next;
-};
-
-struct global_variable {
- int counter;
- void *data;
- VALUE (*getter)();
- void (*setter)();
- void (*marker)();
- int block_trace;
- struct trace_var *trace;
-};
-
-struct global_entry {
- struct global_variable *var;
- ID id;
-};
-
-static VALUE undef_getter();
-static void undef_setter();
-static void undef_marker();
-
-static VALUE val_getter();
-static void val_setter();
-static void val_marker();
-
-static VALUE var_getter();
-static void var_setter();
-static void var_marker();
-
-struct global_entry*
-rb_global_entry(id)
- ID id;
-{
- struct global_entry *entry;
-
- if (!st_lookup(rb_global_tbl, id, &entry)) {
- struct global_variable *var;
- entry = ALLOC(struct global_entry);
- st_add_direct(rb_global_tbl, id, entry);
- var = ALLOC(struct global_variable);
- entry->id = id;
- entry->var = var;
- var->counter = 1;
- var->data = 0;
- var->getter = undef_getter;
- var->setter = undef_setter;
- var->marker = undef_marker;
-
- var->block_trace = 0;
- var->trace = 0;
- }
- return entry;
-}
-
-static VALUE
-undef_getter(id)
- ID id;
-{
- if (ruby_verbose) {
- rb_warning("global variable `%s' not initialized", rb_id2name(id));
- }
- return Qnil;
-}
-
-static void
-undef_setter(val, id, data, var)
- VALUE val;
- ID id;
- void *data;
- struct global_variable *var;
-{
- var->getter = val_getter;
- var->setter = val_setter;
- var->marker = val_marker;
-
- var->data = (void*)val;
-}
-
-static void
-undef_marker()
-{
-}
-
-static VALUE
-val_getter(id, val)
- ID id;
- VALUE val;
-{
- return val;
-}
-
-static void
-val_setter(val, id, data, var)
- VALUE val;
- ID id;
- void *data;
- struct global_variable *var;
-{
- var->data = (void*)val;
-}
-
-static void
-val_marker(data)
- VALUE data;
-{
- if (data) rb_gc_mark_maybe(data);
-}
-
-static VALUE
-var_getter(id, var)
- ID id;
- VALUE *var;
-{
- if (!var) return Qnil;
- return *var;
-}
-
-static void
-var_setter(val, id, var)
- VALUE val;
- ID id;
- VALUE *var;
-{
- *var = val;
-}
-
-static void
-var_marker(var)
- VALUE *var;
-{
- if (var) rb_gc_mark_maybe(*var);
-}
-
-static void
-readonly_setter(val, id, var)
- VALUE val;
- ID id;
- void *var;
-{
- rb_name_error(id, "can't set variable %s", rb_id2name(id));
-}
-
-static int
-mark_global_entry(key, entry)
- ID key;
- struct global_entry *entry;
-{
- struct trace_var *trace;
- struct global_variable *var = entry->var;
-
- (*var->marker)(var->data);
- trace = var->trace;
- while (trace) {
- if (trace->data) rb_gc_mark_maybe(trace->data);
- trace = trace->next;
- }
- return ST_CONTINUE;
-}
-
-void
-rb_gc_mark_global_tbl()
-{
- st_foreach(rb_global_tbl, mark_global_entry, 0);
-}
-
-static ID
-global_id(name)
- const char *name;
-{
- ID id;
-
- if (name[0] == '$') id = rb_intern(name);
- else {
- char *buf = ALLOCA_N(char, strlen(name)+2);
- buf[0] = '$';
- strcpy(buf+1, name);
- id = rb_intern(buf);
- }
- return id;
-}
-
-void
-rb_define_hooked_variable(name, var, getter, setter)
- const char *name;
- VALUE *var;
- VALUE (*getter)();
- void (*setter)();
-{
- struct global_variable *gvar;
- ID id = global_id(name);
-
- gvar = rb_global_entry(id)->var;
- gvar->data = (void*)var;
- gvar->getter = getter?getter:var_getter;
- gvar->setter = setter?setter:var_setter;
- gvar->marker = var_marker;
-}
-
-void
-rb_define_variable(name, var)
- const char *name;
- VALUE *var;
-{
- rb_define_hooked_variable(name, var, 0, 0);
-}
-
-void
-rb_define_readonly_variable(name, var)
- const char *name;
- VALUE *var;
-{
- rb_define_hooked_variable(name, var, 0, readonly_setter);
-}
-
-void
-rb_define_virtual_variable(name, getter, setter)
- const char *name;
- VALUE (*getter)();
- void (*setter)();
-{
- if (!getter) getter = val_getter;
- if (!setter) setter = readonly_setter;
- rb_define_hooked_variable(name, 0, getter, setter);
-}
-
-static void
-rb_trace_eval(cmd, val)
- VALUE cmd, val;
-{
- rb_eval_cmd(cmd, rb_ary_new3(1, val), 0);
-}
-
-VALUE
-rb_f_trace_var(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE var, cmd;
- struct global_entry *entry;
- struct trace_var *trace;
-
- rb_secure(4);
- if (rb_scan_args(argc, argv, "11", &var, &cmd) == 1) {
- cmd = rb_f_lambda();
- }
- if (NIL_P(cmd)) {
- return rb_f_untrace_var(argc, argv);
- }
- entry = rb_global_entry(rb_to_id(var));
- if (OBJ_TAINTED(cmd)) {
- rb_raise(rb_eSecurityError, "Insecure: tainted variable trace");
- }
- trace = ALLOC(struct trace_var);
- trace->next = entry->var->trace;
- trace->func = rb_trace_eval;
- trace->data = cmd;
- trace->removed = 0;
- entry->var->trace = trace;
-
- return Qnil;
-}
-
-static void
-remove_trace(var)
- struct global_variable *var;
-{
- struct trace_var *trace = var->trace;
- struct trace_var t;
- struct trace_var *next;
-
- t.next = trace;
- trace = &t;
- while (trace->next) {
- next = trace->next;
- if (next->removed) {
- trace->next = next->next;
- free(next);
- }
- else {
- trace = next;
- }
- }
- var->trace = t.next;
-}
-
-VALUE
-rb_f_untrace_var(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE var, cmd;
- ID id;
- struct global_entry *entry;
- struct trace_var *trace;
-
- rb_scan_args(argc, argv, "11", &var, &cmd);
- id = rb_to_id(var);
- if (!st_lookup(rb_global_tbl, id, &entry)) {
- rb_name_error(id, "undefined global variable %s", rb_id2name(id));
- }
-
- trace = entry->var->trace;
- if (NIL_P(cmd)) {
- VALUE ary = rb_ary_new();
-
- while (trace) {
- struct trace_var *next = trace->next;
- rb_ary_push(ary, (VALUE)trace->data);
- trace->removed = 1;
- trace = next;
- }
-
- if (!entry->var->block_trace) remove_trace(entry->var);
- return ary;
- }
- else {
- while (trace) {
- if (trace->data == cmd) {
- trace->removed = 1;
- if (!entry->var->block_trace) remove_trace(entry->var);
- return rb_ary_new3(1, cmd);
- }
- trace = trace->next;
- }
- }
- return Qnil;
-}
-
-VALUE
-rb_gvar_get(entry)
- struct global_entry *entry;
-{
- struct global_variable *var = entry->var;
- return (*var->getter)(entry->id, var->data, var);
-}
-
-struct trace_data {
- struct trace_var *trace;
- VALUE val;
-};
-
-static VALUE
-trace_ev(data)
- struct trace_data *data;
-{
- struct trace_var *trace = data->trace;
-
- while (trace) {
- (*trace->func)(trace->data, data->val);
- trace = trace->next;
- }
- return Qnil; /* not reached */
-}
-
-static VALUE
-trace_en(var)
- struct global_variable *var;
-{
- var->block_trace = 0;
- remove_trace(var);
- return Qnil; /* not reached */
-}
-
-VALUE
-rb_gvar_set(entry, val)
- struct global_entry *entry;
- VALUE val;
-{
- struct trace_data trace;
- struct global_variable *var = entry->var;
-
- if (rb_safe_level() >= 4)
- rb_raise(rb_eSecurityError, "Insecure: can't change global variable value");
- (*var->setter)(val, entry->id, var->data, var);
-
- if (var->trace && !var->block_trace) {
- var->block_trace = 1;
- trace.trace = var->trace;
- trace.val = val;
- rb_ensure(trace_ev, (VALUE)&trace, trace_en, (VALUE)var);
- }
- return val;
-}
-
-VALUE
-rb_gv_set(name, val)
- const char *name;
- VALUE val;
-{
- struct global_entry *entry;
-
- entry = rb_global_entry(global_id(name));
- return rb_gvar_set(entry, val);
-}
-
-VALUE
-rb_gv_get(name)
- const char *name;
-{
- struct global_entry *entry;
-
- entry = rb_global_entry(global_id(name));
- return rb_gvar_get(entry);
-}
-
-VALUE
-rb_gvar_defined(entry)
- struct global_entry *entry;
-{
- if (entry->var->getter == undef_getter) return Qfalse;
- return Qtrue;
-}
-
-static int
-gvar_i(key, entry, ary)
- ID key;
- struct global_entry *entry;
- VALUE ary;
-{
- rb_ary_push(ary, rb_str_new2(rb_id2name(key)));
- return ST_CONTINUE;
-}
-
-VALUE
-rb_f_global_variables()
-{
- VALUE ary = rb_ary_new();
- char buf[4];
- char *s = "&`'+123456789";
-
- st_foreach(rb_global_tbl, gvar_i, ary);
- if (!NIL_P(rb_backref_get())) {
- while (*s) {
- sprintf(buf, "$%c", *s++);
- rb_ary_push(ary, rb_str_new2(buf));
- }
- }
- return ary;
-}
-
-void
-rb_alias_variable(name1, name2)
- ID name1;
- ID name2;
-{
- struct global_entry *entry1, *entry2;
-
- if (rb_safe_level() >= 4)
- rb_raise(rb_eSecurityError, "Insecure: can't alias global variable");
-
- entry2 = rb_global_entry(name2);
- if (!st_lookup(rb_global_tbl, name1, &entry1)) {
- entry1 = ALLOC(struct global_entry);
- st_add_direct(rb_global_tbl, name1, entry1);
- entry1->id = name1;
- }
- else if (entry1->var != entry2->var) {
- struct global_variable *var = entry1->var;
- if (var->block_trace) {
- rb_raise(rb_eRuntimeError, "can't alias in tracer");
- }
- var->counter--;
- if (var->counter == 0) {
- struct trace_var *trace = var->trace;
- while (trace) {
- struct trace_var *next = trace->next;
- free(trace);
- trace = next;
- }
- free(var);
- }
- }
- else {
- return;
- }
- entry2->var->counter++;
- entry1->var = entry2->var;
-}
-
-static int special_generic_ivar = 0;
-static st_table *generic_iv_tbl;
-
-st_table*
-rb_generic_ivar_table(obj)
- VALUE obj;
-{
- st_table *tbl;
-
- if (!generic_iv_tbl) return 0;
- if (!st_lookup(generic_iv_tbl, obj, &tbl)) return 0;
- return tbl;
-}
-
-static VALUE
-generic_ivar_get(obj, id)
- VALUE obj;
- ID id;
-{
- st_table *tbl;
- VALUE val;
-
- if (!generic_iv_tbl) return Qnil;
- if (!st_lookup(generic_iv_tbl, obj, &tbl)) return Qnil;
- if (st_lookup(tbl, id, &val)) {
- return val;
- }
- return Qnil;
-}
-
-static void
-generic_ivar_set(obj, id, val)
- VALUE obj;
- ID id;
- VALUE val;
-{
- st_table *tbl;
-
- if (rb_special_const_p(obj)) {
- special_generic_ivar = 1;
- }
- if (!generic_iv_tbl) {
- generic_iv_tbl = st_init_numtable();
- }
-
- if (!st_lookup(generic_iv_tbl, obj, &tbl)) {
- FL_SET(obj, FL_EXIVAR);
- tbl = st_init_numtable();
- st_add_direct(generic_iv_tbl, obj, tbl);
- st_add_direct(tbl, id, val);
- return;
- }
- st_insert(tbl, id, val);
-}
-
-static VALUE
-generic_ivar_defined(obj, id)
- VALUE obj;
- ID id;
-{
- st_table *tbl;
- VALUE val;
-
- if (!generic_iv_tbl) return Qfalse;
- if (!st_lookup(generic_iv_tbl, obj, &tbl)) return Qfalse;
- if (st_lookup(tbl, id, &val)) {
- return Qtrue;
- }
- return Qfalse;
-}
-
-static VALUE
-generic_ivar_remove(obj, id)
- VALUE obj;
- ID id;
-{
- st_table *tbl;
- VALUE val;
-
- if (!generic_iv_tbl) return Qnil;
- if (!st_lookup(generic_iv_tbl, obj, &tbl)) return Qnil;
- st_delete(tbl, &id, &val);
- if (tbl->num_entries == 0) {
- st_delete(generic_iv_tbl, &obj, &tbl);
- st_free_table(tbl);
- }
- return val;
-}
-
-void
-rb_mark_generic_ivar(obj)
- VALUE obj;
-{
- st_table *tbl;
-
- if (!generic_iv_tbl) return;
- if (st_lookup(generic_iv_tbl, obj, &tbl)) {
- rb_mark_tbl(tbl);
- }
-}
-
-static int
-givar_mark_i(key, value)
- ID key;
- VALUE value;
-{
- rb_gc_mark(value);
- return ST_CONTINUE;
-}
-
-static int
-givar_i(obj, tbl)
- VALUE obj;
- st_table *tbl;
-{
- if (rb_special_const_p(obj)) {
- st_foreach(tbl, givar_mark_i, 0);
- }
- return ST_CONTINUE;
-}
-
-void
-rb_mark_generic_ivar_tbl()
-{
- if (!generic_iv_tbl) return;
- if (special_generic_ivar == 0) return;
- st_foreach(generic_iv_tbl, givar_i, 0);
-}
-
-void
-rb_free_generic_ivar(obj)
- VALUE obj;
-{
- st_table *tbl;
-
- if (st_delete(generic_iv_tbl, &obj, &tbl))
- st_free_table(tbl);
-}
-
-void
-rb_copy_generic_ivar(clone, obj)
- VALUE clone, obj;
-{
- st_table *tbl;
-
- if (!generic_iv_tbl) return;
- if (st_lookup(generic_iv_tbl, obj, &tbl)) {
- st_add_direct(generic_iv_tbl, clone, st_copy(tbl));
- }
-}
-
-VALUE
-rb_ivar_get(obj, id)
- VALUE obj;
- ID id;
-{
- VALUE val;
-
- switch (TYPE(obj)) {
- case T_OBJECT:
- case T_CLASS:
- case T_MODULE:
- if (ROBJECT(obj)->iv_tbl && st_lookup(ROBJECT(obj)->iv_tbl, id, &val))
- return val;
- break;
- default:
- if (FL_TEST(obj, FL_EXIVAR) || rb_special_const_p(obj))
- return generic_ivar_get(obj, id);
- break;
- }
- if (ruby_verbose) {
- rb_warning("instance variable %s not initialized", rb_id2name(id));
- }
- return Qnil;
-}
-
-VALUE
-rb_ivar_set(obj, id, val)
- VALUE obj;
- ID id;
- VALUE val;
-{
- if (!OBJ_TAINTED(obj) && rb_safe_level() >= 4)
- rb_raise(rb_eSecurityError, "Insecure: can't modify instance variable");
- if (OBJ_FROZEN(obj)) rb_error_frozen("object");
- switch (TYPE(obj)) {
- case T_OBJECT:
- case T_CLASS:
- case T_MODULE:
- if (!ROBJECT(obj)->iv_tbl) ROBJECT(obj)->iv_tbl = st_init_numtable();
- st_insert(ROBJECT(obj)->iv_tbl, id, val);
- break;
- default:
- generic_ivar_set(obj, id, val);
- break;
- }
- return val;
-}
-
-VALUE
-rb_ivar_defined(obj, id)
- VALUE obj;
- ID id;
-{
- switch (TYPE(obj)) {
- case T_OBJECT:
- case T_CLASS:
- case T_MODULE:
- if (ROBJECT(obj)->iv_tbl && st_lookup(ROBJECT(obj)->iv_tbl, id, 0))
- return Qtrue;
- break;
- default:
- if (FL_TEST(obj, FL_EXIVAR) || rb_special_const_p(obj))
- return generic_ivar_defined(obj, id);
- break;
- }
- return Qfalse;
-}
-
-static int
-ivar_i(key, entry, ary)
- ID key;
- struct global_entry *entry;
- VALUE ary;
-{
- if (rb_is_instance_id(key)) {
- rb_ary_push(ary, rb_str_new2(rb_id2name(key)));
- }
- return ST_CONTINUE;
-}
-
-VALUE
-rb_obj_instance_variables(obj)
- VALUE obj;
-{
- VALUE ary;
-
- ary = rb_ary_new();
- switch (TYPE(obj)) {
- case T_OBJECT:
- case T_CLASS:
- case T_MODULE:
- if (ROBJECT(obj)->iv_tbl) {
- st_foreach(ROBJECT(obj)->iv_tbl, ivar_i, ary);
- }
- break;
- default:
- if (!generic_iv_tbl) break;
- if (FL_TEST(obj, FL_EXIVAR) || rb_special_const_p(obj)) {
- st_table *tbl;
-
- if (st_lookup(generic_iv_tbl, obj, &tbl)) {
- st_foreach(tbl, ivar_i, ary);
- }
- }
- break;
- }
- return ary;
-}
-
-VALUE
-rb_obj_remove_instance_variable(obj, name)
- VALUE obj, name;
-{
- VALUE val = Qnil;
- ID id = rb_to_id(name);
-
- if (!OBJ_TAINTED(obj) && rb_safe_level() >= 4)
- rb_raise(rb_eSecurityError, "Insecure: can't modify instance variable");
- if (OBJ_FROZEN(obj)) rb_error_frozen("object");
- if (!rb_is_instance_id(id)) {
- rb_name_error(id, "`%s' is not an instance variable", rb_id2name(id));
- }
-
- switch (TYPE(obj)) {
- case T_OBJECT:
- case T_CLASS:
- case T_MODULE:
- if (ROBJECT(obj)->iv_tbl) {
- st_delete(ROBJECT(obj)->iv_tbl, &id, &val);
- }
- break;
- default:
- if (FL_TEST(obj, FL_EXIVAR) || rb_special_const_p(obj))
- return generic_ivar_remove(obj, id);
- break;
- }
- return val;
-}
-
-static int
-top_const_get(id, klassp)
- ID id;
- VALUE *klassp;
-{
- /* pre-defined class */
- if (st_lookup(rb_class_tbl, id, klassp)) return Qtrue;
-
- /* autoload */
- if (autoload_tbl && st_lookup(autoload_tbl, id, 0)) {
- rb_autoload_load(id);
- *klassp = rb_const_get(rb_cObject, id);
- return Qtrue;
- }
- return Qfalse;
-}
-
-VALUE
-rb_const_get_at(klass, id)
- VALUE klass;
- ID id;
-{
- VALUE value;
-
- if (RCLASS(klass)->iv_tbl && st_lookup(RCLASS(klass)->iv_tbl, id, &value)) {
- return value;
- }
- if (klass == rb_cObject && top_const_get(id, &value)) {
- return value;
- }
- rb_name_error(id, "uninitialized constant %s::%s",
- RSTRING(rb_class_path(klass))->ptr,
- rb_id2name(id));
- return Qnil; /* not reached */
-}
-
-void
-rb_autoload_load(id)
- ID id;
-{
- char *modname;
- VALUE module;
-
- st_delete(autoload_tbl, &id, &modname);
- if (rb_provided(modname)) {
- free(modname);
- return;
- }
- module = rb_str_new2(modname);
- free(modname);
- FL_UNSET(module, FL_TAINT);
- rb_f_require(Qnil, module);
-}
-
-VALUE
-rb_const_get(klass, id)
- VALUE klass;
- ID id;
-{
- VALUE value, tmp;
- int mod_retry = 0;
-
- tmp = klass;
- retry:
- while (tmp) {
- if (RCLASS(tmp)->iv_tbl && st_lookup(RCLASS(tmp)->iv_tbl,id,&value)) {
- return value;
- }
- if (tmp == rb_cObject && top_const_get(id, &value)) return value;
- tmp = RCLASS(tmp)->super;
- }
- if (!mod_retry && BUILTIN_TYPE(klass) == T_MODULE) {
- mod_retry = 1;
- tmp = rb_cObject;
- goto retry;
- }
-
- /* Uninitialized constant */
- if (klass && klass != rb_cObject) {
- rb_name_error(id, "uninitialized constant %s at %s",
- rb_id2name(id),
- RSTRING(rb_class_path(klass))->ptr);
- }
- else {
- global_uninitialized:
- rb_name_error(id, "uninitialized constant %s",rb_id2name(id));
- }
- return Qnil; /* not reached */
-}
-
-VALUE
-rb_mod_remove_const(mod, name)
- VALUE mod, name;
-{
- ID id = rb_to_id(name);
- VALUE val;
-
- if (!rb_is_const_id(id)) {
- rb_name_error(id, "`%s' is not constant", rb_id2name(id));
- }
- if (!OBJ_TAINTED(mod) && rb_safe_level() >= 4)
- rb_raise(rb_eSecurityError, "Insecure: can't remove constant");
- if (OBJ_FROZEN(mod)) rb_error_frozen("class/module");
-
- if (RCLASS(mod)->iv_tbl && st_delete(ROBJECT(mod)->iv_tbl, &id, &val)) {
- return val;
- }
- if (rb_const_defined_at(mod, id)) {
- rb_name_error(id, "cannot remove %s::%s",
- rb_class2name(mod), rb_id2name(id));
- }
- rb_name_error(id, "constant %s::%s not defined",
- rb_class2name(mod), rb_id2name(id));
- return Qnil; /* not reached */
-}
-
-static int
-sv_i(key, value, tbl)
- ID key;
- VALUE value;
- st_table *tbl;
-{
- if (rb_is_const_id(key)) {
- if (!st_lookup(tbl, key, 0)) {
- st_insert(tbl, key, key);
- }
- }
- return ST_CONTINUE;
-}
-
-static int
-autoload_i(key, name, tbl)
- ID key;
- const char *name;
- st_table *tbl;
-{
- if (!st_lookup(tbl, key, 0)) {
- st_insert(tbl, key, key);
- }
- return ST_CONTINUE;
-}
-
-void*
-rb_mod_const_at(mod, data)
- VALUE mod;
- void *data;
-{
- st_table *tbl = data;
- if (!tbl) {
- tbl = st_init_numtable();
- }
- if (RCLASS(mod)->iv_tbl) {
- st_foreach(RCLASS(mod)->iv_tbl, sv_i, tbl);
- }
- if ((VALUE)mod == rb_cObject) {
- st_foreach(rb_class_tbl, sv_i, tbl);
- if (autoload_tbl) {
- st_foreach(autoload_tbl, autoload_i, tbl);
- }
- }
- return tbl;
-}
-
-void*
-rb_mod_const_of(mod, data)
- VALUE mod;
- void *data;
-{
- for (;;) {
- data = rb_mod_const_at(mod, data);
- mod = RCLASS(mod)->super;
- if (!mod) break;
- }
- return data;
-}
-
-static int
-list_i(key, value, ary)
- ID key, value;
- VALUE ary;
-{
- rb_ary_push(ary, rb_str_new2(rb_id2name(key)));
- return ST_CONTINUE;
-}
-
-VALUE
-rb_const_list(data)
- void *data;
-{
- st_table *tbl = data;
- VALUE ary;
-
- if (!tbl) return rb_ary_new2(0);
- ary = rb_ary_new2(tbl->num_entries);
- st_foreach(tbl, list_i, ary);
- st_free_table(tbl);
-
- return ary;
-}
-
-VALUE
-rb_mod_constants(mod)
- VALUE mod;
-{
- return rb_const_list(rb_mod_const_of(mod, 0));
-}
-
-int
-rb_const_defined_at(klass, id)
- VALUE klass;
- ID id;
-{
- if (RCLASS(klass)->iv_tbl && st_lookup(RCLASS(klass)->iv_tbl, id, 0)) {
- return Qtrue;
- }
- if (klass == rb_cObject) {
- return rb_const_defined(klass, id);
- }
- return Qfalse;
-}
-
-int
-rb_autoload_defined(id)
- ID id;
-{
- if (autoload_tbl && st_lookup(autoload_tbl, id, 0))
- return Qtrue;
- return Qfalse;
-}
-
-int
-rb_const_defined(klass, id)
- VALUE klass;
- ID id;
-{
- VALUE tmp = klass;
-
- while (tmp) {
- if (RCLASS(tmp)->iv_tbl && st_lookup(RCLASS(tmp)->iv_tbl,id,0)) {
- return Qtrue;
- }
- tmp = RCLASS(tmp)->super;
- }
- if (BUILTIN_TYPE(klass) == T_MODULE) {
- return rb_const_defined(rb_cObject, id);
- }
- if (st_lookup(rb_class_tbl, id, 0))
- return Qtrue;
- return rb_autoload_defined(id);
-}
-
-static void
-mod_av_set(klass, id, val, isconst)
- VALUE klass;
- ID id;
- VALUE val;
- int isconst;
-{
- char *dest = isconst ? "constant" : "class variable";
-
- if (!OBJ_TAINTED(klass) && rb_safe_level() >= 4)
- rb_raise(rb_eSecurityError, "Insecure: can't set %s", dest);
- if (OBJ_FROZEN(klass)) rb_error_frozen("class/module");
- if (!RCLASS(klass)->iv_tbl) {
- RCLASS(klass)->iv_tbl = st_init_numtable();
- }
- else if (isconst) {
- if (st_lookup(RCLASS(klass)->iv_tbl, id, 0) ||
- (klass == rb_cObject && st_lookup(rb_class_tbl, id, 0))) {
- rb_warn("already initialized %s %s", dest, rb_id2name(id));
- }
- }
-
- st_insert(RCLASS(klass)->iv_tbl, id, val);
-}
-
-void
-rb_const_set(klass, id, val)
- VALUE klass;
- ID id;
- VALUE val;
-{
- mod_av_set(klass, id, val, Qtrue);
-}
-
-void
-rb_const_assign(klass, id, val)
- VALUE klass;
- ID id;
- VALUE val;
-{
- VALUE tmp = klass;
-
- while (tmp) {
- if (RCLASS(tmp)->iv_tbl && st_lookup(RCLASS(tmp)->iv_tbl,id,0)) {
- st_insert(RCLASS(tmp)->iv_tbl, id, val);
- return;
- }
- tmp = RCLASS(tmp)->super;
- }
- /* pre-defined class */
- if (st_lookup(rb_class_tbl, id, 0)) {
- st_delete(rb_class_tbl, id, 0);
- st_insert(RCLASS(rb_cObject)->iv_tbl, id, val);
- return;
- }
-
- /* autoload */
- if (autoload_tbl && st_lookup(autoload_tbl, id, 0)) {
- char *modname;
-
- st_delete(autoload_tbl, &id, &modname);
- free(modname);
- st_insert(RCLASS(rb_cObject)->iv_tbl, id, val);
- return;
- }
-
- /* Uninitialized constant */
- if (klass && klass != rb_cObject)
- rb_name_error(id, "uninitialized constant %s::%s",
- RSTRING(rb_class_path(klass))->ptr,
- rb_id2name(id));
- else {
- rb_name_error(id, "uninitialized constant %s",rb_id2name(id));
- }
-}
-
-void
-rb_define_const(klass, name, val)
- VALUE klass;
- const char *name;
- VALUE val;
-{
- ID id = rb_intern(name);
-
- if (klass == rb_cObject) {
- rb_secure(4);
- }
- rb_const_set(klass, id, val);
-}
-
-void
-rb_define_global_const(name, val)
- const char *name;
- VALUE val;
-{
- rb_define_const(rb_cObject, name, val);
-}
-
-static VALUE
-original_module(c)
- VALUE c;
-{
- if (TYPE(c) == T_ICLASS)
- return RBASIC(c)->klass;
- return c;
-}
-
-static void
-cvar_override_check(id, a)
- VALUE a;
-{
- VALUE base = original_module(a);
-
- a = RCLASS(a)->super;
- while (a) {
- if (RCLASS(a)->iv_tbl) {
- if (st_lookup(RCLASS(a)->iv_tbl,id,0)) {
- rb_warning("class variable %s of %s is overridden by %s",
- rb_id2name(id), rb_class2name(original_module(a)),
- rb_class2name(base));
- }
- }
- a = RCLASS(a)->super;
- }
-}
-
-void
-rb_cvar_set(klass, id, val, warn)
- VALUE klass;
- ID id;
- VALUE val;
- int warn;
-{
- VALUE tmp;
-
- tmp = klass;
- while (tmp) {
- if (RCLASS(tmp)->iv_tbl && st_lookup(RCLASS(tmp)->iv_tbl,id,0)) {
- if (OBJ_FROZEN(tmp)) rb_error_frozen("class/module");
- if (!OBJ_TAINTED(tmp) && rb_safe_level() >= 4)
- rb_raise(rb_eSecurityError, "Insecure: can't modify class variable");
- if (warn && ruby_verbose && klass != tmp) {
- rb_warning("already initialized class variable %s", rb_id2name(id));
- }
- st_insert(RCLASS(tmp)->iv_tbl,id,val);
- if (ruby_verbose) {
- cvar_override_check(id, tmp);
- }
- return;
- }
- tmp = RCLASS(tmp)->super;
- }
-
- mod_av_set(klass, id, val, Qfalse);
-}
-
-VALUE
-rb_cvar_get(klass, id)
- VALUE klass;
- ID id;
-{
- VALUE value;
- VALUE tmp;
-
- tmp = klass;
- while (tmp) {
- if (RCLASS(tmp)->iv_tbl) {
- if (st_lookup(RCLASS(tmp)->iv_tbl,id,&value)) {
- if (ruby_verbose) {
- cvar_override_check(id, tmp);
- }
- return value;
- }
- }
- tmp = RCLASS(tmp)->super;
- }
-
- rb_name_error(id,"uninitialized class variable %s in %s",
- rb_id2name(id), rb_class2name(klass));
- return Qnil; /* not reached */
-}
-
-VALUE
-rb_cvar_defined(klass, id)
- VALUE klass;
- ID id;
-{
- VALUE tmp;
-
- tmp = klass;
- while (tmp) {
- if (RCLASS(tmp)->iv_tbl && st_lookup(RCLASS(tmp)->iv_tbl,id,0)) {
- return Qtrue;
- }
- tmp = RCLASS(tmp)->super;
- }
-
- return Qfalse;
-}
-
-void
-rb_cv_set(klass, name, val)
- VALUE klass;
- const char *name;
- VALUE val;
-{
- ID id = rb_intern(name);
- if (!rb_is_class_id(id)) {
- rb_name_error(id, "wrong class variable name %s", name);
- }
- rb_cvar_set(klass, id, val, Qfalse);
-}
-
-VALUE
-rb_cv_get(klass, name)
- VALUE klass;
- const char *name;
-{
- ID id = rb_intern(name);
- if (!rb_is_class_id(id)) {
- rb_name_error(id, "wrong class variable name %s", name);
- }
- return rb_cvar_get(klass, id);
-}
-
-void
-rb_define_class_variable(klass, name, val)
- VALUE klass;
- const char *name;
- VALUE val;
-{
- ID id = rb_intern(name);
-
- if (!rb_is_class_id(id)) {
- rb_name_error(id, "wrong class variable name %s", name);
- }
- rb_cvar_set(klass, id, val, Qtrue);
-}
-
-static int
-cv_i(key, value, ary)
- ID key;
- VALUE value;
- VALUE ary;
-{
- if (rb_is_class_id(key)) {
- VALUE kval = rb_str_new2(rb_id2name(key));
- if (!rb_ary_includes(ary, kval)) {
- rb_ary_push(ary, kval);
- }
- }
- return ST_CONTINUE;
-}
-
-VALUE
-rb_mod_class_variables(obj)
- VALUE obj;
-{
- VALUE ary = rb_ary_new();
-
- for (;;) {
- if (RCLASS(obj)->iv_tbl) {
- st_foreach(RCLASS(obj)->iv_tbl, cv_i, ary);
- }
- obj = RCLASS(obj)->super;
- if (!obj) break;
- }
- return ary;
-}
-
-VALUE
-rb_mod_remove_cvar(mod, name)
- VALUE mod, name;
-{
- ID id = rb_to_id(name);
- VALUE val;
-
- if (!rb_is_class_id(id)) {
- rb_name_error(id, "wrong class variable name %s", rb_id2name(id));
- }
- if (!OBJ_TAINTED(mod) && rb_safe_level() >= 4)
- rb_raise(rb_eSecurityError, "Insecure: can't remove class variable");
- if (OBJ_FROZEN(mod)) rb_error_frozen("class/module");
-
- if (RCLASS(mod)->iv_tbl && st_delete(ROBJECT(mod)->iv_tbl, &id, &val)) {
- return val;
- }
- if (rb_cvar_defined(mod, id)) {
- rb_name_error(id, "cannot remove %s for %s",
- rb_id2name(id), rb_class2name(mod));
- }
- rb_name_error(id, "class variable %s not defined for %s",
- rb_id2name(id), rb_class2name(mod));
- return Qnil; /* not reached */
-}
-
-VALUE
-rb_iv_get(obj, name)
- VALUE obj;
- const char *name;
-{
- ID id = rb_intern(name);
-
- return rb_ivar_get(obj, id);
-}
-
-VALUE
-rb_iv_set(obj, name, val)
- VALUE obj;
- const char *name;
- VALUE val;
-{
- ID id = rb_intern(name);
-
- return rb_ivar_set(obj, id, val);
-}
diff --git a/version.c b/version.c
deleted file mode 100644
index 25c6440620..0000000000
--- a/version.c
+++ /dev/null
@@ -1,45 +0,0 @@
-/**********************************************************************
-
- version.c -
-
- $Author$
- $Date$
- created at: Thu Sep 30 20:08:01 JST 1993
-
- Copyright (C) 1993-2002 Yukihiro Matsumoto
-
-**********************************************************************/
-
-#include "ruby.h"
-#include "version.h"
-#include <stdio.h>
-
-void
-Init_version()
-{
- VALUE v = rb_obj_freeze(rb_str_new2(RUBY_VERSION));
- VALUE d = rb_obj_freeze(rb_str_new2(RUBY_RELEASE_DATE));
- VALUE p = rb_obj_freeze(rb_str_new2(RUBY_PLATFORM));
-
- rb_define_global_const("RUBY_VERSION", v);
- rb_define_global_const("RUBY_RELEASE_DATE", d);
- rb_define_global_const("RUBY_PLATFORM", p);
-
- /* obsolete constants */
- rb_define_global_const("VERSION", v);
- rb_define_global_const("RELEASE_DATE", d);
- rb_define_global_const("PLATFORM", p);
-}
-
-void
-ruby_show_version()
-{
- printf("ruby %s (%s) [%s]\n", RUBY_VERSION, RUBY_RELEASE_DATE, RUBY_PLATFORM);
-}
-
-void
-ruby_show_copyright()
-{
- printf("ruby - Copyright (C) 1993-2002 Yukihiro Matsumoto\n");
- exit(0);
-}
diff --git a/version.h b/version.h
deleted file mode 100644
index 0a880de8c7..0000000000
--- a/version.h
+++ /dev/null
@@ -1,4 +0,0 @@
-#define RUBY_VERSION "1.7.2"
-#define RUBY_RELEASE_DATE "2002-03-20"
-#define RUBY_VERSION_CODE 172
-#define RUBY_RELEASE_CODE 20020320
diff --git a/win32/Makefile.sub b/win32/Makefile.sub
deleted file mode 100644
index 67809c48a8..0000000000
--- a/win32/Makefile.sub
+++ /dev/null
@@ -1,459 +0,0 @@
-SHELL = $(COMSPEC)
-
-#### Start of system configuration section. ####
-
-## variables may be overridden by $(compile_dir)/Makefile
-!ifndef srcdir
-srcdir = ..
-!endif
-!ifndef RUBY_INSTALL_NAME
-RUBY_INSTALL_NAME = ruby
-!endif
-!if !defined(RUBYW_INSTALL_NAME) || "$(RUBYW_INSTALL_NAME)" == "$(RUBY_INSTALL_NAME)"
-RUBYW_INSTALL_NAME = $(RUBY_INSTALL_NAME:ruby=rubyw)
-!endif
-!if "$(RUBYW_INSTALL_NAME)" == "$(RUBY_INSTALL_NAME)"
-RUBYW_INSTALL_NAME = $(RUBY_INSTALL_NAME)w
-!endif
-!ifndef RUBY_SO_NAME
-RUBY_SO_NAME = rubymw
-!endif
-!if !defined(icondirs) && defined(ICONDIRS)
-icondirs=$(ICONDIRS)
-!endif
-!if defined(icondirs)
-icondirs=$(icondirs:\=/)
-iconinc=-I$(icondirs: = -I)
-!endif
-###############
-
-VPATH = $(srcdir):$(srcdir)/missing
-.SUFFIXES: .y
-
-!if !defined(CC)
-CC = cl
-!endif
-!if !defined(YACC)
-YACC = byacc
-!endif
-PURIFY =
-AUTOCONF = autoconf
-
-!if !defined(PROCESSOR_ARCHITECTURE) || "$(PROCESSOR_ARCHITECTURE)" == "x86"
-!if !defined(PROCESSOR_LEVEL)
-PROCESSOR_LEVEL = 5
-!endif
-PROCESSOR_FLAG = -G$(PROCESSOR_LEVEL)
-CPU = i$(PROCESSOR_LEVEL)86
-ARCH = i386
-!else
-CPU = $(PROCESSOR_ARCHITECTURE)
-ARCH = $(PROCESSOR_ARCHITECTURE)
-!endif
-!if !defined(DEBUGFLAGS)
-DEBUGFLAGS = -Zi
-!endif
-!if !defined(OPTFLAGS)
-OPTFLAGS = -O2b2xg-
-!endif
-OS = mswin32
-
-!if !defined(prefix)
-prefix = /usr
-!endif
-!if !defined(DESTDIR)
-DESTDIR = $(prefix)
-!endif
-!if !defined(CFLAGS)
-CFLAGS = -nologo -MD $(DEBUGFLAGS) $(OPTFLAGS) $(PROCESSOR_FLAG)
-!endif
-!if !defined(CPPFLAGS)
-CPPFLAGS = -I. -I$(srcdir) -I$(srcdir)/missing -DLIBRUBY_SO=\"$(LIBRUBY_SO)\" -DNT=1
-!endif
-!if !defined(LDFLAGS)
-LDFLAGS = $(CFLAGS) -Fm
-!endif
-!if !defined(XLDFLAGS)
-XLDFLAGS =
-!endif
-!if !defined(RFLAGS)
-RFLAGS = -r
-!endif
-!if !defined(EXTLIBS)
-EXTLIBS =
-!endif
-LIBS = user32.lib advapi32.lib wsock32.lib $(EXTLIBS)
-MISSING = crypt.obj win32.obj isinf.obj isnan.obj
-LDSHARED = $(CC) -LD
-DLDFLAGS =
-SOLIBS =
-
-EXEEXT = .exe
-PROGRAM=$(RUBY_INSTALL_NAME)$(EXEEXT)
-WPROGRAM=$(RUBYW_INSTALL_NAME)$(EXEEXT)
-RUBYDEF = $(RUBY_SO_NAME).def
-MINIRUBY=miniruby$(EXEEXT)
-
-!if !defined(STACK)
-STACK = 0x2000000
-!endif
-ORGLIBPATH = $(LIB)
-
-#### End of system configuration section. ####
-
-LIBRUBY_A = lib$(RUBY_INSTALL_NAME).lib
-LIBRUBY_SO = $(RUBY_SO_NAME).dll
-LIBRUBY = $(RUBY_SO_NAME).lib
-LIBRUBYARG = $(LIBRUBY)
-
-EXTOBJS = dmyext.obj
-
-MAINOBJ = main.obj
-WINMAINOBJ = winmain.obj
-
-OBJS = array.obj \
- bignum.obj \
- class.obj \
- compar.obj \
- dir.obj \
- dln.obj \
- enum.obj \
- error.obj \
- eval.obj \
- file.obj \
- gc.obj \
- hash.obj \
- inits.obj \
- io.obj \
- marshal.obj \
- math.obj \
- numeric.obj \
- object.obj \
- pack.obj \
- parse.obj \
- prec.obj \
- process.obj \
- random.obj \
- range.obj \
- re.obj \
- regex.obj \
- ruby.obj \
- signal.obj \
- sprintf.obj \
- st.obj \
- string.obj \
- struct.obj \
- time.obj \
- util.obj \
- variable.obj \
- version.obj \
- $(MISSING)
-
-all: miniruby$(EXEEXT) rbconfig.rb ext/extmk.rb \
- $(LIBRUBY) $(MISCLIBS)
- set LIB=..\..;$(ORGLIBPATH)
- @.\miniruby$(EXEEXT) -Cext extmk.rb
-
-ruby: $(PROGRAM)
-rubyw: $(WPROGRAM)
-lib: $(LIBRUBY)
-dll: $(LIBRUBY_SO)
-
-config: config.h config.status
-
-config.h: $(srcdir)/win32/$$@.in
- @echo Creating config.h
- @type $(srcdir:/=\)\win32\$@.in > $@
- @echo #undef RUBY_PLATFORM >> $@
- @echo #define RUBY_PLATFORM "$(ARCH)-$(OS)" >> $@
-
-config.status: Makefile $(srcdir)/win32/Makefile.sub $(MINIRUBY)
- @echo Creating config.status
- @$(MINIRUBY) -pe "chomp(' ');~/@CFLAGS@/||$$_['$(CFLAGS)']='$$(CFLAGS)'" << > $@
-# Generated automatically by Makefile.sub.
-s,@SHELL@,$$(COMSPEC),;t t
-s,@CFLAGS@,$(CFLAGS),;t t
-s,@CPPFLAGS@,$(CPPFLAGS),;t t
-s,@CXXFLAGS@,$(CXXFLAGS),;t t
-s,@FFLAGS@,$(FFLAGS),;t t
-s,@LDFLAGS@,$(LDFLAGS),;t t
-s,@LIBS@,user32.lib advapi32.lib wsock32.lib,;t t
-s,@exec_prefix@,$${prefix},;t t
-s,@prefix@,,;t t
-s,@program_transform_name@,s,,,,;t t
-s,@bindir@,$${exec_prefix}/bin,;t t
-s,@sbindir@,$${exec_prefix}/sbin,;t t
-s,@libexecdir@,$${exec_prefix}/libexec,;t t
-s,@datadir@,$${prefix}/share,;t t
-s,@sysconfdir@,$${prefix}/etc,;t t
-s,@sharedstatedir@,/etc,;t t
-s,@localstatedir@,/var,;t t
-s,@libdir@,$${exec_prefix}/lib,;t t
-s,@includedir@,$${prefix}/include,;t t
-s,@oldincludedir@,/usr/include,;t t
-s,@infodir@,$${prefix}/info,;t t
-s,@mandir@,$${prefix}/man,;t t
-s,@build@,$(CPU)-pc-$(OS),;t t
-s,@build_alias@,$(CPU)-$(OS),;t t
-s,@build_cpu@,$(CPU),;t t
-s,@build_vendor@,pc,;t t
-s,@build_os@,$(OS),;t t
-s,@host@,$(CPU)-pc-$(OS),;t t
-s,@host_alias@,$(CPU)-$(OS),;t t
-s,@host_cpu@,$(CPU),;t t
-s,@host_vendor@,pc,;t t
-s,@host_os@,$(OS),;t t
-s,@target@,$(ARCH)-pc-$(OS),;t t
-s,@target_alias@,$(ARCH)-$(OS),;t t
-s,@target_cpu@,$(ARCH),;t t
-s,@target_vendor@,pc,;t t
-s,@target_os@,$(OS),;t t
-s,@CC@,cl,;t t
-s,@CPP@,$$(CC) -E,;t t
-s,@YACC@,$(YACC),;t t
-s,@RANLIB@,rem,;t t
-s,@AR@,lib -nologo,;t t
-s,@LN_S@,$(LN_S),;t t
-s,@SET_MAKE@,$(SET_MAKE),;t t
-s,@LIBOBJS@, crypt.obj win32.obj isinf.obj isnan.obj,;t t
-s,@ALLOCA@,$(ALLOCA),;t t
-s,@DEFAULT_KCODE@,$(DEFAULT_KCODE),;t t
-s,@EXEEXT@,.exe,;t t
-s,@OBJEXT@,obj,;t t
-s,@XLDFLAGS@,$(XLDFLAGS),;t t
-s,@DLDFLAGS@,$$(CFLAGS),;t t
-s,@STATIC@,$(STATIC),;t t
-s,@CCDLFLAGS@,-DIMPORT,;t t
-s,@LDSHARED@,$$(CC) -LD,;t t
-s,@DLEXT@,so,;t t
-s,@DLEXT2@,dll,;t t
-s,@STRIP@,$(STRIP),;t t
-s,@EXTSTATIC@,$(EXTSTATIC),;t t
-s,@setup@,Setup,;t t
-s,@LIBRUBY_LDSHARED@,$(LIBRUBY_LDSHARED),;t t
-s,@LIBRUBY_DLDFLAGS@,$(LIBRUBY_DLDFLAGS),;t t
-s,@RUBY_INSTALL_NAME@,$(RUBY_INSTALL_NAME),;t t
-s,@RUBY_SO_NAME@,$(RUBY_SO_NAME),;t t
-s,@LIBRUBY_A@,lib$$(RUBY_INSTALL_NAME).lib,;t t
-s,@LIBRUBY_SO@,$$(RUBY_SO_NAME).dll,;t t
-s,@LIBRUBY_ALIASES@,$(LIBRUBY_ALIASES),;t t
-s,@LIBRUBY@,$$(RUBY_SO_NAME).lib,;t t
-s,@LIBRUBYARG@,$$(RUBY_SO_NAME).lib,;t t
-s,@SOLIBS@,$(SOLIBS),;t t
-s,@DLDLIBS@,$(DLDLIBS),;t t
-s,@ENABLE_SHARED@,yes,;t t
-s,@arch@,$(ARCH)-$(OS),;t t
-s,@sitedir@,$${prefix}/lib/ruby/site_ruby,;t t
-s,@configure_args@,--with-make-prog=nmake --enable-shared $(configure_args),;t t
-s,@configure_input@,$$configure_input,;t t
-s,@srcdir@,$(srcdir),;t t
-s,@top_srcdir@,$(srcdir),;t t
-<<
-
-ext/extmk.rb: $(srcdir)/ext/extmk.rb.in config.status
- @echo Creating ext/extmk.rb
- @.\miniruby$(EXEEXT) $(srcdir)/ext/configsub.rb \
- -srcdir=$(srcdir) \
- -install_name=$(RUBY_INSTALL_NAME) \
- -so_name=$(RUBY_SO_NAME) \
- -output=$@ $(srcdir)/ext/extmk.rb.in
-
-miniruby$(EXEEXT): $(OBJS) $(MAINOBJ) $(EXTOBJS)
- @echo $(EXTOBJS)
- @echo $(LIBS)
- $(PURIFY) $(CC) $(LDFLAGS) $(MAINOBJ) $(EXTOBJS) $(OBJS) $(LIBS) -Fe$@
-
-$(PROGRAM): $(MAINOBJ) $(LIBRUBY_SO) $*.res
- $(PURIFY) $(CC) $(LDFLAGS) $(XLDFLAGS) $(MAINOBJ) $*.res \
- -Fe$@ $(LIBRUBYARG) -link -stack:$(STACK) -incremental:no
-
-$(WPROGRAM): $(MAINOBJ) $(WINMAINOBJ) $(LIBRUBY_SO) $*.res
- $(PURIFY) $(CC) $(LDFLAGS) $(MAINOBJ) $(WINMAINOBJ) $*.res \
- -Fe$@ $(LIBRUBYARG) -link -stack:$(STACK) -subsystem:Windows -incremental:no
-
-$(LIBRUBY_A): $(OBJS) dmyext.obj
- lib -nologo /OUT:$@ $(OBJS) dmyext.obj
-
-$(LIBRUBY): $(RUBYDEF)
- lib -nologo /OUT:$@ /DEF:$(RUBYDEF)
-
-$(LIBRUBY_SO): $(LIBRUBY_A) $(EXTOBJS) $(RUBYDEF) $@.res
- set LIB=.\win32;$(ORGLIBPATH)
- $(CC) $(LDFLAGS) $(MAINOBJ) $(EXTOBJS) $(LIBRUBY_A) $@.res $(LIBS) \
- -Fe$@ -link -dll -def:$(RUBYDEF)
-
-!if "$(LIBRUBY_SO)" != "rubymw.dll"
-rubymw.dll: $(LIBRUBY)
- $(CC) -nologo $(EXTOBJS) $(LIBRUBY) -o $@ -link /DLL /DEF:$(RUBYDEF)
-!endif
-
-$(RUBYDEF): $(LIBRUBY_A) miniruby$(EXEEXT)
- .\miniruby$(EXEEXT) $(srcdir)/win32/mkexports.rb -output=$@ $(LIBRUBY_A)
-
-install: rbconfig.rb
- .\miniruby.exe $(srcdir)/instruby.rb $(DESTDIR)
-
-clean: clean-ext clean-local
-
-clean-local:
- @if exist $(LIBRUBY_A) del $(LIBRUBY_A)
- @if exist $(MAINOBJ) del $(MAINOBJ)
- @if exist rbconfig.rb del rbconfig.rb
- @if exist ext\extinit.c del ext\extinit.c
- @if exist ext\extinit.obj del ext\extinit.obj
- @if exist ext\vc*.pdb del ext\vc*.pdb
- @if exist *.obj del *.obj
- @if exist *.res del *.res
-
-clean-ext:
- @-.\miniruby$(EXEEXT) -Cext extmk.rb clean
-
-distclean: distclean-ext distclean-local
-
-distclean-local: clean-local
- @if exist Makefile del Makefile
- @if exist ext\extmk.rb del ext\extmk.rb
- @if exist config.h del config.h
- @if exist ext\config.cache del ext\config.cache
- @if exist config.cache del config.cache
- @if exist config.log del config.log
- @if exist config.status del config.status
- @if exist *~ del *~
- @if exist *.bak del *.bak
- @if exist *.stackdump del *.stackdump
- @if exist *.core del *.core
- @if exist gmon.out del gmon.out
- @if exist y.tab.c del y.tab.c
- @if exist y.output del y.output
- @if exist *.map del *.map
- @if exist *.pdb del *.pdb
- @if exist *.ilk del *.ilk
- @if exist *.exp del *.exp
- @if exist $(RUBYDEF) del $(RUBYDEF)
- @if exist $(RUBY_INSTALL_NAME).rc del $(RUBY_INSTALL_NAME).rc
- @if exist $(RUBYW_INSTALL_NAME).rc del $(RUBYW_INSTALL_NAME).rc
- @if exist $(LIBRUBY_SO).rc del $(LIBRUBY_SO).rc
- @if exist $(PROGRAM) del $(PROGRAM)
- @if exist $(WPROGRAM) del $(WPROGRAM)
- @if exist $(LIBRUBY_SO) del $(LIBRUBY_SO)
- @if exist $(LIBRUBY) del $(LIBRUBY)
- @if exist ext\nul if not exist ext\* rmdir ext
- @if exist miniruby$(EXEEXT) del miniruby$(EXEEXT)
-
-distclean-ext:
- @-.\miniruby$(EXEEXT) -Cext extmk.rb distclean
-
-realclean: distclean
- @if exist parse.c del parse.c
- @if exist lex.c del lex.c
-
-test: miniruby$(EXEEXT)
- @.\miniruby$(EXEEXT) $(srcdir)/rubytest.rb
-
-rbconfig.rb: miniruby$(EXEEXT) config.status
- @.\miniruby$(EXEEXT) $(srcdir)/mkconfig.rb -srcdir=$(srcdir) \
- -install_name=$(RUBY_INSTALL_NAME) \
- -so_name=$(RUBY_SO_NAME) rbconfig.rb
-
-$(RUBY_INSTALL_NAME).rc $(RUBYW_INSTALL_NAME).rc $(LIBRUBY_SO).rc: rbconfig.rb
- @.\miniruby$(EXEEXT) $(srcdir)/win32/resource.rb \
- -ruby_name=$(RUBY_INSTALL_NAME) \
- -rubyw_name=$(RUBYW_INSTALL_NAME) \
- -so_name=$(LIBRUBY_SO) \
- . $(icondirs) $(srcdir)/win32
-
-#config.status: $(srcdir)/configure
-# $(SHELL) ./config.status --recheck
-
-{$(srcdir)/missing}.c.obj:
- $(CC) $(CFLAGS) -I. -I$(<D) $(CPPFLAGS) -c -Tc$(<:\=/)
-{$(srcdir)/win32}.c.obj:
- $(CC) $(CFLAGS) -I. -I$(<D) $(CPPFLAGS) -c -Tc$(<:\=/)
-{$(srcdir)}.c.obj:
- $(CC) $(CFLAGS) -I. -I$(<D) $(CPPFLAGS) -c -Tc$(<:\=/)
-.c.obj:
- $(CC) $(CFLAGS) -I. $(CPPFLAGS) -c -Tc$(<:\=/)
-
-.rc.res:
- $(RC) -I. -I$(<D) $(iconinc) -I$(srcdir)/win32 $(RFLAGS) -fo$@ $(<:\=/)
-
-{$(srcdir)}.y.c:
- $(YACC) $(YFLAGS) $(<:\=/)
- sed -e "s!^extern char \*getenv();!/* & */!;s/^\(#.*\)y\.tab/\1parse/" y.tab.c > $@
- @del y.tab.c
-
-{$(srcdir)}parse.c: parse.y
-
-alloca.obj: $(srcdir)/missing/alloca.c
-crypt.obj: $(srcdir)/missing/crypt.c
-dup2.obj: $(srcdir)/missing/dup2.c
-finite.obj: $(srcdir)/missing/finite.c
-flock.obj: $(srcdir)/missing/flock.c
-isinf.obj: $(srcdir)/missing/isinf.c
-isnan.obj: $(srcdir)/missing/isnan.c
-memcmp.obj: $(srcdir)/missing/memcmp.c
-memmove.obj: $(srcdir)/missing/memmove.c
-mkdir.obj: $(srcdir)/missing/mkdir.c
-vsnprintf.obj: $(srcdir)/missing/vsnprintf.c
-strcasecmp.obj: $(srcdir)/missing/strcasecmp.c
-strncasecmp.obj: $(srcdir)/missing/strncasecmp.c
-strchr.obj: $(srcdir)/missing/strchr.c
-strdup.obj: $(srcdir)/missing/strdup.c
-strerror.obj: $(srcdir)/missing/strerror.c
-strftime.obj: $(srcdir)/missing/strftime.c
-strstr.obj: $(srcdir)/missing/strstr.c
-strtod.obj: $(srcdir)/missing/strtod.c
-strtol.obj: $(srcdir)/missing/strtol.c
-strtoul.obj: $(srcdir)/missing/strtoul.c
-nt.obj: $(srcdir)/missing/nt.c
-x68.obj: $(srcdir)/missing/x68.c
-os2.obj: $(srcdir)/missing/os2.c
-dl_os2.obj: $(srcdir)/missing/dl_os2.c
-
-# when I use -I., there is confliction at "OpenFile"
-# so, set . into environment varible "include"
-win32.obj: $(srcdir)/win32/win32.c
-
-# Prevent GNU make v3 from overflowing arg limit on SysV.
-.NOEXPORT:
-###
-parse.obj: {$(srcdir)}parse.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h $(srcdir)/env.h $(srcdir)/node.h $(srcdir)/st.h $(srcdir)/regex.h $(srcdir)/util.h $(srcdir)/lex.c
-###
-array.obj: $(srcdir)/array.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h
-bignum.obj: $(srcdir)/bignum.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h
-class.obj: $(srcdir)/class.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h $(srcdir)/node.h $(srcdir)/st.h
-compar.obj: $(srcdir)/compar.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h
-dir.obj: $(srcdir)/dir.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h
-dln.obj: $(srcdir)/dln.c config.h $(srcdir)/defines.h $(srcdir)/dln.h
-dmyext.obj: $(srcdir)/dmyext.c
-enum.obj: $(srcdir)/enum.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h
-error.obj: $(srcdir)/error.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h $(srcdir)/env.h
-eval.obj: $(srcdir)/eval.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h $(srcdir)/node.h $(srcdir)/env.h $(srcdir)/rubysig.h $(srcdir)/st.h $(srcdir)/dln.h
-file.obj: $(srcdir)/file.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h $(srcdir)/rubyio.h $(srcdir)/rubysig.h
-gc.obj: $(srcdir)/gc.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h $(srcdir)/rubysig.h $(srcdir)/st.h $(srcdir)/node.h $(srcdir)/env.h $(srcdir)/re.h $(srcdir)/regex.h
-hash.obj: $(srcdir)/hash.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h $(srcdir)/st.h $(srcdir)/rubysig.h $(srcdir)/util.h
-inits.obj: $(srcdir)/inits.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h
-io.obj: $(srcdir)/io.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h $(srcdir)/rubyio.h $(srcdir)/rubysig.h $(srcdir)/env.h
-main.obj: $(srcdir)/main.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h
-marshal.obj: $(srcdir)/marshal.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h $(srcdir)/rubyio.h $(srcdir)/st.h
-prec.obj: $(srcdir)/prec.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h
-math.obj: $(srcdir)/math.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h
-numeric.obj: $(srcdir)/numeric.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h
-object.obj: $(srcdir)/object.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h $(srcdir)/st.h
-pack.obj: $(srcdir)/pack.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h
-process.obj: $(srcdir)/process.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h $(srcdir)/rubysig.h $(srcdir)/st.h
-random.obj: $(srcdir)/random.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h
-range.obj: $(srcdir)/range.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h
-re.obj: $(srcdir)/re.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h $(srcdir)/re.h $(srcdir)/regex.h
-regex.obj: $(srcdir)/regex.c config.h $(srcdir)/regex.h $(srcdir)/util.h
-ruby.obj: $(srcdir)/ruby.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h $(srcdir)/dln.h $(srcdir)/util.h
-signal.obj: $(srcdir)/signal.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h $(srcdir)/rubysig.h
-sprintf.obj: $(srcdir)/sprintf.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h
-st.obj: $(srcdir)/st.c config.h $(srcdir)/st.h
-string.obj: $(srcdir)/string.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h $(srcdir)/re.h $(srcdir)/regex.h
-struct.obj: $(srcdir)/struct.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h
-time.obj: $(srcdir)/time.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h
-util.obj: $(srcdir)/util.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h $(srcdir)/util.h
-variable.obj: $(srcdir)/variable.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h $(srcdir)/env.h $(srcdir)/node.h $(srcdir)/st.h
-version.obj: $(srcdir)/version.c $(srcdir)/ruby.h config.h $(srcdir)/defines.h $(srcdir)/intern.h $(srcdir)/version.h
-$(OBJS) $(MAINOBJ) $(WINMAINOBJ): $(srcdir)/win32/win32.h
diff --git a/win32/README.win32 b/win32/README.win32
deleted file mode 100644
index 774a5c424c..0000000000
--- a/win32/README.win32
+++ /dev/null
@@ -1,123 +0,0 @@
-=begin
-
-= How to build ruby using Visual C++
-
-== Requirement
-
-(1) Visual C++ 4.0 or later.
-
-(2) If you want to run `((%nmake clean%))' or `((%nmake distclean%))'
- properly, you must install UNIX compatible `((%rm%))' command on
- your ((|PATH|)).
-
-(3) Please set environment variable (({INCLUDE})), (({LIB})), (({PATH}))
- to run required commands properly from the command line.
-
- Note: building ruby requires following commands.
- * nmake
- * cl
- * lib
- * dumpbin
- * rm
-
-== How to compile and install
-
-(1) Execute win32\configure.bat on your build directory.
-
-(2) Change ((|RUBY_INSTALL_NAME|)) and ((|RUBY_SO_NAME|)) in (({Makefile}))
- if you want to change the name of the executable files.
- And add ((|RUBYW_INSTALL_NAME|)) to change the name of the
- executable without console window if also you want.
-
-(3) Run `((%nmake%))'
-
-(4) Run `((%nmake test%))'
-
-(5) Run `((%nmake DESTDIR=<install_directory> install%))'
-
- This command will create following directories and install files onto them.
- * <install_directory>\bin
- * <install_directory>\lib
- * <install_directory>\lib\ruby
- * <install_directory>\lib\ruby\<MAJOR>.<MINOR>
- * <install_directory>\lib\ruby\<MAJOR>.<MINOR>\<PLATFORM>
- * <install_directory>\lib\ruby\site_ruby
- * <install_directory>\lib\ruby\site_ruby\<MAJOR>.<MINOR>
- * <install_directory>\lib\ruby\site_ruby\<MAJOR>.<MINOR>\<PLATFORM>
- * <install_directory>\man\man1
- If Ruby's version is `x.y.z', the ((|<MAJOR>|)) is `x' and the ((|<MINOR>|)) is `y'.
- The ((|<PLATFORM>|)) is usually `(({i586-mswin32}))'.
-
-== Icons
-
-Any icon files(*.ico) in the build directory, directories specified with
-((|icondirs|)) make variable and (({win32})) directory under the ruby
-source directory will be included in DLL or executable files, according
-to their base names.
- $(RUBY_INSTALL_NAME).ico or ruby.ico --> $(RUBY_INSTALL_NAME).exe
- $(RUBYW_INSTALL_NAME).ico or rubyw.ico --> $(RUBYW_INSTALL_NAME).exe
- the others --> $(RUBY_SO_NAME).dll
-
-Although no icons are distributed with the ruby source or in the official
-site, you can use anything you like. For example, followings are written
-in Japanese, but you can download at least.
-
-* ((<URL:http://member.nifty.ne.jp/ueivu/rubyico.html>)) or
- ((<zipped icons|URL:http://member.nifty.ne.jp/ueivu/Ruby_ico.zip>))
-* ((<URL:http://homepage1.nifty.com/a_nakata/ruby/>)) or
- ((<icon itself|URL:http://homepage1.nifty.com/a_nakata/ruby/RubyIcon.ico>))
-
-== Build examples
-
-* Build on the ruby source directory.
-
- ex.)
- ruby source directory: C:\ruby
- build directory: C:\ruby
- install directory: C:\usr\local
-
- C:
- cd \ruby
- win32\configure
- nmake
- nmake test
- nmake DESTDIR=/usr/local install
-
-* Build on the relative directory from the ruby source directory.
-
- ex.)
- ruby source directory: C:\ruby
- build directory: C:\ruby\mswin32
- install directory: C:\usr\local
-
- C:
- cd \ruby
- mkdir mswin32
- cd mswin32
- ..\win32\configure
- nmake
- nmake test
- nmake DESTDIR=/usr/local install
-
-* Build on the different drive.
-
- ex.)
- ruby source directory: C:\src\ruby
- build directory: D:\build\ruby
- install directory: C:\usr\local
-
- D:
- cd D:\build\ruby
- C:\src\ruby\win32\configure
- nmake
- nmake test
- nmake DESTDIR=C:/usr/local install
-
-== Bugs
-
-You can ((*NOT*)) use a path name contains any white space characters as
-the ruby source directory, this restriction comes from the behavior of
-(({!INCLUDE})) directives of (({NMAKE})).
-((- you may call it a bug. -))
-
-=end
diff --git a/win32/config.h.in b/win32/config.h.in
deleted file mode 100644
index 870845b1a6..0000000000
--- a/win32/config.h.in
+++ /dev/null
@@ -1,67 +0,0 @@
-#define HAVE_PROTOTYPES 1
-#define HAVE_STDARG_PROTOTYPES 1
-/* #define HAVE_ATTR_NORETURN 1 */
-#if _MSC_VER > 1100 && !defined NORETURN
-#define NORETURN(x) __declspec(noreturn) x
-#else
-#define NORETURN(x) x
-#endif
-#define TOKEN_PASTE(x,y) x##y
-#define inline __inline
-/* #define HAVE_DIRENT_H 1 */
-/* #define HAVE_UNISTD_H 1 */
-#define HAVE_STDLIB_H 1
-#define HAVE_LIMITS_H 1
-/* #define HAVE_SYS_FILE_H 1 */
-#define HAVE_FCNTL_H 1
-/* #define HAVE_PWD_H 1 */
-/* #define HAVE_SYS_TIME_H 1 */
-/* #define HAVE_SYS_TIMES_H 1 */
-/* #define HAVE_SYS_PARAM_H 1 */
-/* #define HAVE_SYS_WAIT_H 1 */
-#define HAVE_STRING_H 1
-/* #define HAVE_UTIME_H 1 */
-#define HAVE_MEMORY_H 1
-/* #define HAVE_ST_BLKSIZE 1 */
-#define HAVE_ST_RDEV 1
-/* #define GETGROUPS_T gid_t */
-#define GETGROUPS_T int
-#define RETSIGTYPE void
-#define HAVE_ALLOCA 1
-#define vfork fork
-#define HAVE_FMOD 1
-/* #define HAVE_RANDOM 1 */
-#define HAVE_WAITPID 1
-#define HAVE_GETCWD 1
-/* #define HAVE_TRUNCATE 1 */
-#define HAVE_CHSIZE 1
-#define HAVE_TIMES 1
-/* #define HAVE_UTIMES 1 */
-/* #define HAVE_FCNTL 1 */
-/* #define HAVE_SETITIMER 1 */
-#define HAVE_GETGROUPS 1
-/* #define HAVE_SIGPROCMASK 1 */
-#define HAVE_GETLOGIN 1
-#define HAVE_TELLDIR 1
-#define HAVE_SEEKDIR 1
-
-#define RSHIFT(x,y) ((x)>>y)
-#define FILE_COUNT _cnt
-#define FILE_READPTR _ptr
-#define DEFAULT_KCODE KCODE_NONE
-#define DLEXT ".so"
-#define DLEXT2 ".dll"
-#define RUBY_LIB "/lib/ruby/1.7"
-#define RUBY_SITE_LIB "/lib/ruby/site_ruby"
-#define RUBY_SITE_LIB2 "/lib/ruby/site_ruby/1.7"
-#define RUBY_PLATFORM "i586-mswin32"
-#define RUBY_ARCHLIB "/lib/ruby/1.7/" RUBY_PLATFORM
-#define RUBY_SITE_ARCHLIB "/lib/ruby/site_ruby/1.7/" RUBY_PLATFORM
-
-#define SIZEOF_INT 4
-#define SIZEOF_SHORT 2
-#define SIZEOF_LONG 4
-#define SIZEOF___INT64 8
-#define SIZEOF_VOIDP 4
-#define SIZEOF_FLOAT 4
-#define SIZEOF_DOUBLE 8
diff --git a/win32/configure.bat b/win32/configure.bat
deleted file mode 100755
index e35a4c312c..0000000000
--- a/win32/configure.bat
+++ /dev/null
@@ -1,13 +0,0 @@
-@echo off
-::: Don't set environment variable in batch file other than autoexec.bat
-::: to avoid "Out of environment space" problem on Windows 95/98.
-::: set TMPMAKE=~tmp~.mak
-
-echo> ~tmp~.mak ####
-echo>> ~tmp~.mak conf = %0
-echo>> ~tmp~.mak $(conf:\=/): nul
-echo>> ~tmp~.mak @del ~tmp~.mak
-echo>> ~tmp~.mak @-$(MAKE) -l$(MAKEFLAGS) -f $(@D)/setup.mak \
-if not "%1" == "" echo>> ~tmp~.mak srcdir="%1" \
-echo>> ~tmp~.mak WIN32DIR=$(@D)
-nmake -alf ~tmp~.mak
diff --git a/win32/dir.h b/win32/dir.h
deleted file mode 100644
index 8aa793de42..0000000000
--- a/win32/dir.h
+++ /dev/null
@@ -1,20 +0,0 @@
-struct direct
-{
- long d_namlen;
- ino_t d_ino;
- char d_name[256];
-};
-typedef struct {
- char *start;
- char *curr;
- long size;
- long nfiles;
- struct direct dirstr;
-} DIR;
-
-DIR* opendir(const char*);
-struct direct* readdir(DIR *);
-long telldir(DIR *);
-void seekdir(DIR *, long);
-void rewinddir(DIR *);
-void closedir(DIR *);
diff --git a/win32/mkexports.rb b/win32/mkexports.rb
deleted file mode 100644
index f8205d9dff..0000000000
--- a/win32/mkexports.rb
+++ /dev/null
@@ -1,30 +0,0 @@
-#!./miniruby -s
-
-SYM = {}
-
-objs = ARGV.collect {|s| s.tr('/', '\\')}
-IO.foreach("|dumpbin -symbols " + objs.join(' ')) do |l|
- next if /^[0-9A-F]+ 0+ UNDEF / =~ l
- next unless l.sub!(/.*\sExternal\s+\|\s+/, '')
- if l.sub!(/^_/, '')
- next if /@.*@/ =~ l
- elsif !l.sub!(/^(\S+) \([^@?]*\)$/, '\1')
- next
- end
- SYM[l.strip] = true
-end
-
-exports = []
-if $name
- exports << "Name " + $name
-elsif $library
- exports << "Library " + $library
-end
-exports << "Description " + $description.dump if $description
-exports << "EXPORTS" << SYM.keys.sort
-
-if $output
- open($output, 'w') {|f| f.puts exports.join("\n")}
-else
- puts exports.join("\n")
-end
diff --git a/win32/resource.rb b/win32/resource.rb
deleted file mode 100644
index 7eca372df1..0000000000
--- a/win32/resource.rb
+++ /dev/null
@@ -1,94 +0,0 @@
-#!./miniruby -sI.
-
-require 'rbconfig'
-
-CONFIG = Config::MAKEFILE_CONFIG
-
-fversion = "#{CONFIG['MAJOR']},#{CONFIG['MINOR']},#{CONFIG['TEENY']},0"
-
-$ruby_name ||= CONFIG["RUBY_INSTALL_NAME"]
-$rubyw_name ||= CONFIG["RUBYW_INSTALL_NAME"] || $ruby_name.sub(/ruby/, '\&w')
-$so_name ||= CONFIG["RUBY_SO_NAME"] + '.dll'
-
-icons = {}
-def icons.find(path)
- if File.directory?(path)
- Dir.open(File.expand_path(path)) do |d|
- d.grep(/\.ico$/i) {|i| self[$`] = i}
- end
- else
- self[File.basename(path, '.ico')] = path
- end
- self
-end
-
-if ARGV.empty?
- icons.find('.')
-else
- ARGV.each {|i| icons.find(i)}
-end
-
-ruby_icon = rubyw_icon = nil
-[$ruby_name, 'ruby'].each do |i|
- if i = icons.delete(i)
- ruby_icon = "1 ICON DISCARDABLE "+i.dump+"\n"
- break
- end
-end
-[$rubyw_name, 'rubyw'].each do |i|
- if i = icons.delete(i)
- rubyw_icon = "1 ICON DISCARDABLE "+i.dump+"\n"
- break
- end
-end
-dll_icons = []
-icons.keys.sort.each do |i|
- dll_icons << "#{dll_icons.size + 1} ICON DISCARDABLE "+icons[i].dump+"\n"
-end
-
-[ # base name extension file type icons
- [$ruby_name, CONFIG["EXEEXT"], 'VFT_APP', ruby_icon],
- [$rubyw_name, CONFIG["EXEEXT"], 'VFT_APP', rubyw_icon],
- [$so_name, '', 'VFT_DLL', dll_icons],
-].each do |base, ext, type, icons|
- open(base + '.rc', "w") { |f|
- f.binmode if /mingw/ =~ RUBY_PLATFORM
-
- f.print <<EOF
-#include <windows.h>
-
-#{icons}
-VS_VERSION_INFO VERSIONINFO
- FILEVERSION #{fversion}
- PRODUCTVERSION #{fversion}
- FILEFLAGSMASK 0x3fL
- FILEFLAGS 0x0L
- FILEOS VOS__WINDOWS32
- FILETYPE #{type}
- FILESUBTYPE VFT2_UNKNOWN
-BEGIN
- BLOCK "StringFileInfo"
- BEGIN
- BLOCK "000004b0"
- BEGIN
- VALUE "FileDescription", "Ruby interpreter\\0"
- VALUE "FileVersion", "#{fversion}\\0"
- VALUE "Home Page", "http://www.ruby-lang.org/\\0"
- VALUE "InternalName", "#{base + ext}\\0"
- VALUE "LegalCopyright", "Copyright (C) 1993-2002 Yukihiro Matsumoto\\0"
- VALUE "OriginalFilename", "#{base + ext}\\0"
- VALUE "Platform", "#{RUBY_PLATFORM}\\0"
- VALUE "ProductVersion", "#{fversion}\\0"
- VALUE "Release Date", "#{RUBY_RELEASE_DATE}\\0"
- VALUE "Version", "#{RUBY_VERSION}\\0"
- END
- END
- BLOCK "VarFileInfo"
- BEGIN
- VALUE "Translation", 0x0, 0x4b0
- END
-END
-EOF
- }
-end
-
diff --git a/win32/setup.mak b/win32/setup.mak
deleted file mode 100644
index 0c0acfa1e6..0000000000
--- a/win32/setup.mak
+++ /dev/null
@@ -1,30 +0,0 @@
-# -*- makefile -*-
-
-!IF "$(WIN32DIR)" == "win32"
-srcdir = .
-!ELSEIF "$(WIN32DIR)" == "$(WIN32DIR:/win32=)/win32"
-srcdir = $(WIN32DIR:/win32=)
-!ELSE
-srcdir = $(WIN32DIR)/..
-!ENDIF
-OS = mswin32
-
-all: ext
-all: Makefile
-all:; @echo type `nmake' to make ruby for mswin32.
-
-Makefile:
- @echo ### makefile for ruby $(OS) ###> $@
- @echo srcdir = $(srcdir:\=/)>> $@
- @echo RUBY_INSTALL_NAME = ruby>> $@
- @echo RUBY_SO_NAME = $(OS)-$$(RUBY_INSTALL_NAME)17>> $@
- @echo prefix = /usr>> $@
- @echo CFLAGS = -nologo -MD $$(DEBUGFLAGS) $$(OPTFLAGS) $$(PROCESSOR_FLAG)>> $@
- @echo CPPFLAGS = -I. -I$$(srcdir) -I$$(srcdir)/missing -DLIBRUBY_SO=\"$$(LIBRUBY_SO)\" -DNT=1>> $@
- @echo LDFLAGS = $$(CFLAGS) -Fm>> $@
- @echo XLDFLAGS = >> $@
- @echo RFLAGS = -r>> $@
- @echo EXTLIBS =>> $@
- @echo !INCLUDE $$(srcdir)/win32/Makefile.sub>> $@
-
-ext:; @if not exist $@\* mkdir $@
diff --git a/win32/win32.c b/win32/win32.c
deleted file mode 100644
index 01e824baab..0000000000
--- a/win32/win32.c
+++ /dev/null
@@ -1,2817 +0,0 @@
-/*
- * Copyright (c) 1993, Intergraph Corporation
- *
- * You may distribute under the terms of either the GNU General Public
- * License or the Artistic License, as specified in the perl README file.
- *
- * Various Unix compatibility functions and NT specific functions.
- *
- * Some of this code was derived from the MSDOS port(s) and the OS/2 port.
- *
- */
-
-#include "ruby.h"
-#include "rubysig.h"
-#include <fcntl.h>
-#include <process.h>
-#include <sys/stat.h>
-/* #include <sys/wait.h> */
-#include <stdio.h>
-#include <stdlib.h>
-#include <errno.h>
-#include <assert.h>
-
-#include <windows.h>
-#include <winbase.h>
-#include <wincon.h>
-#include "win32.h"
-#include "win32/dir.h"
-#ifndef index
-#define index(x, y) strchr((x), (y))
-#endif
-#define isdirsep(x) ((x) == '/' || (x) == '\\')
-#undef stat
-
-#ifndef bool
-#define bool int
-#endif
-
-#ifdef _M_IX86
-# define WIN95 1
-#else
-# undef WIN95
-#endif
-
-#if HAVE_WSAWAITFORMULTIPLEEVENTS
-# define USE_INTERRUPT_WINSOCK
-#endif
-
-#if USE_INTERRUPT_WINSOCK
-# define WaitForMultipleEvents WSAWaitForMultipleEvents
-# define CreateSignal() (HANDLE)WSACreateEvent()
-# define SetSignal(ev) WSASetEvent(ev)
-# define ResetSignal(ev) WSAResetEvent(ev)
-#else /* USE_INTERRUPT_WINSOCK */
-# define WaitForMultipleEvents WaitForMultipleObjectsEx
-# define CreateSignal() CreateEvent(NULL, FALSE, FALSE, NULL);
-# define SetSignal(ev) SetEvent(ev)
-# define ResetSignal(ev) (void)0
-#endif /* USE_INTERRUPT_WINSOCK */
-
-#ifdef WIN32_DEBUG
-#define Debug(something) something
-#else
-#define Debug(something) /* nothing */
-#endif
-
-#define TO_SOCKET(x) _get_osfhandle(x)
-
-bool NtSyncProcess = TRUE;
-
-static struct ChildRecord *CreateChild(char *, SECURITY_ATTRIBUTES *, HANDLE, HANDLE, HANDLE);
-static bool NtHasRedirection (char *);
-static int valid_filename(char *s);
-static void StartSockets ();
-static char *str_grow(struct RString *str, size_t new_size);
-static DWORD wait_events(HANDLE event, DWORD timeout);
-
-char *NTLoginName;
-
-#ifdef WIN95
-DWORD Win32System = (DWORD)-1;
-
-static DWORD
-IdOS(void)
-{
- static OSVERSIONINFO osver;
-
- if (osver.dwPlatformId != Win32System) {
- memset(&osver, 0, sizeof(OSVERSIONINFO));
- osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
- GetVersionEx(&osver);
- Win32System = osver.dwPlatformId;
- }
- return (Win32System);
-}
-
-static int
-IsWin95(void) {
- return (IdOS() == VER_PLATFORM_WIN32_WINDOWS);
-}
-
-static int
-IsWinNT(void) {
- return (IdOS() == VER_PLATFORM_WIN32_NT);
-}
-#else
-# define IsWinNT() TRUE
-# define IsWin95() FALSE
-#endif
-
-/* main thread constants */
-static struct {
- HANDLE handle;
- DWORD id;
-} main_thread;
-
-/* interrupt stuff */
-static HANDLE interrupted_event;
-
-HANDLE GetCurrentThreadHandle(void)
-{
- static HANDLE current_process_handle = NULL;
- HANDLE h;
-
- if (!current_process_handle)
- current_process_handle = GetCurrentProcess();
- if (!DuplicateHandle(current_process_handle, GetCurrentThread(),
- current_process_handle, &h,
- 0, FALSE, DUPLICATE_SAME_ACCESS))
- return NULL;
- return h;
-}
-
-/* simulate flock by locking a range on the file */
-
-
-#define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
-#define LK_LEN 0xffff0000
-
-static VALUE
-flock_winnt(VALUE self, int argc, VALUE* argv)
-{
- OVERLAPPED o;
- int i = -1;
- const HANDLE fh = (HANDLE)self;
- const int oper = argc;
-
- memset(&o, 0, sizeof(o));
-
- switch(oper) {
- case LOCK_SH: /* shared lock */
- LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o), i);
- break;
- case LOCK_EX: /* exclusive lock */
- LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o), i);
- break;
- case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
- LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o), i);
- break;
- case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
- LK_ERR(LockFileEx(fh,
- LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
- 0, LK_LEN, 0, &o), i);
- if (errno == EDOM)
- errno = EWOULDBLOCK;
- break;
- case LOCK_UN: /* unlock lock */
- if (UnlockFileEx(fh, 0, LK_LEN, 0, &o)) {
- i = 0;
- if (errno == EDOM)
- errno = EWOULDBLOCK;
- }
- else {
- /* GetLastError() must returns `ERROR_NOT_LOCKED' */
- errno = EWOULDBLOCK;
- }
- break;
- default: /* unknown */
- errno = EINVAL;
- break;
- }
- return i;
-}
-
-#ifdef WIN95
-static VALUE
-flock_win95(VALUE self, int argc, VALUE* argv)
-{
- int i = -1;
- const HANDLE fh = (HANDLE)self;
- const int oper = argc;
-
- switch(oper) {
- case LOCK_EX:
- while(i == -1) {
- LK_ERR(LockFile(fh, 0, 0, LK_LEN, 0), i);
- if (errno != EDOM && i == -1) break;
- }
- break;
- case LOCK_EX | LOCK_NB:
- LK_ERR(LockFile(fh, 0, 0, LK_LEN, 0), i);
- if (errno == EDOM)
- errno = EWOULDBLOCK;
- break;
- case LOCK_UN:
- LK_ERR(UnlockFile(fh, 0, 0, LK_LEN, 0), i);
- if (errno == EDOM)
- errno = EWOULDBLOCK;
- break;
- default:
- errno = EINVAL;
- break;
- }
- return i;
-}
-#endif
-
-#undef LK_ERR
-#undef LK_LEN
-
-int
-flock(int fd, int oper)
-{
-#ifdef WIN95
- static asynchronous_func_t locker = NULL;
-
- if (!locker) {
- if (IsWinNT())
- locker = flock_winnt;
- else
- locker = flock_win95;
- }
-#else
- const asynchronous_func_t locker = flock_winnt;
-#endif
-
- return win32_asynchronize(locker,
- (VALUE)_get_osfhandle(fd), oper, NULL,
- (DWORD)-1);
-}
-
-//#undef const
-//FILE *fdopen(int, const char *);
-
-//
-// Initialization stuff
-//
-void
-NtInitialize(int *argc, char ***argv)
-{
-
- WORD version;
- int ret;
-
- //
- // subvert cmd.exe's feeble attempt at command line parsing
- //
- *argc = NtMakeCmdVector((char *)GetCommandLine(), argv, TRUE);
-
- //
- // Now set up the correct time stuff
- //
-
- tzset();
-
- // Initialize Winsock
- StartSockets();
-}
-
-char *getlogin()
-{
- char buffer[200];
- DWORD len = 200;
- extern char *NTLoginName;
-
- if (NTLoginName == NULL) {
- if (GetUserName(buffer, &len)) {
- NTLoginName = ALLOC_N(char, len+1);
- strncpy(NTLoginName, buffer, len);
- NTLoginName[len] = '\0';
- }
- else {
- NTLoginName = "<Unknown>";
- }
- }
- return NTLoginName;
-}
-
-#define MAXCHILDNUM 256 /* max num of child processes */
-
-struct ChildRecord {
- HANDLE hProcess; /* process handle */
- pid_t pid; /* process id */
- FILE* pipe; /* pipe */
-} ChildRecord[MAXCHILDNUM];
-
-#define FOREACH_CHILD(v) do { \
- struct ChildRecord* v; \
- for (v = ChildRecord; v < ChildRecord + sizeof(ChildRecord) / sizeof(ChildRecord[0]); ++v)
-#define END_FOREACH_CHILD } while (0)
-
-static struct ChildRecord *
-FindFirstChildSlot(void)
-{
- FOREACH_CHILD(child) {
- if (child->pid) return child;
- } END_FOREACH_CHILD;
- return NULL;
-}
-
-static struct ChildRecord *
-FindChildSlot(pid_t pid)
-{
-
- FOREACH_CHILD(child) {
- if (child->pid == pid) {
- return child;
- }
- } END_FOREACH_CHILD;
- return NULL;
-}
-
-static struct ChildRecord *
-FindPipedChildSlot(FILE *fp)
-{
- FOREACH_CHILD(child) {
- if (child->pid && child->pipe == fp) {
- return child;
- }
- } END_FOREACH_CHILD;
- return NULL;
-}
-
-static void
-CloseChildHandle(struct ChildRecord *child)
-{
- HANDLE h = child->hProcess;
- child->hProcess = NULL;
- child->pid = 0;
- CloseHandle(h);
-}
-
-static struct ChildRecord *
-FindFreeChildSlot(void)
-{
- FOREACH_CHILD(child) {
- if (!child->pid) {
- child->pid = -1; /* lock the slot */
- child->hProcess = NULL;
- child->pipe = NULL;
- return child;
- }
- } END_FOREACH_CHILD;
- return NULL;
-}
-
-
-int SafeFree(char **vec, int vecc)
-{
- // vec
- // |
- // V ^---------------------V
- // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
- // | | | .... | NULL | | ..... |\0 | | ..... |\0 |...
- // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
- // |- elements+1 -| ^ 1st element ^ 2nd element
-
- char *p;
-
- p = (char *)vec;
- free(p);
-
- return 0;
-}
-
-
-static char *szInternalCmds[] = {
- "append",
- "break",
- "call",
- "cd",
- "chdir",
- "cls",
- "copy",
- "date",
- "del",
- "dir",
- "echo",
- "erase",
- "label",
- "md",
- "mkdir",
- "path",
- "pause",
- "rd",
- "rem",
- "ren",
- "rename",
- "rmdir",
- "set",
- "start",
- "time",
- "type",
- "ver",
- "vol",
- NULL
-};
-
-int
-isInternalCmd(char *cmd)
-{
- int i, fRet=0;
- char **vec;
- int vecc = NtMakeCmdVector(cmd, &vec, FALSE);
-
- if (vecc == 0)
- return 0;
- for( i = 0; szInternalCmds[i] ; i++){
- if(!strcasecmp(szInternalCmds[i], vec[0])){
- fRet = 1;
- break;
- }
- }
-
- SafeFree(vec, vecc);
-
- return fRet;
-}
-
-
-SOCKET
-myget_osfhandle(int fh)
-{
- return _get_osfhandle(fh);
-
-}
-
-
-FILE *
-mypopen (char *cmd, char *mode)
-{
- FILE *fp;
- int reading;
- int pipemode;
- struct ChildRecord* child;
- BOOL fRet;
- HANDLE hInFile, hOutFile, hSavedStdIo, hDupFile;
- HANDLE hCurProc;
- SECURITY_ATTRIBUTES sa;
- int fd;
-
- //
- // Figure out what we're doing...
- //
-
- reading = (*mode == 'r') ? TRUE : FALSE;
- pipemode = (*(mode+1) == 'b') ? O_BINARY : O_TEXT;
-
- //
- // Now get a pipe
- //
- sa.nLength = sizeof (SECURITY_ATTRIBUTES);
- sa.lpSecurityDescriptor = NULL;
- sa.bInheritHandle = TRUE;
-
- fRet = CreatePipe(&hInFile, &hOutFile, &sa, 2048L);
- if (!fRet) {
- errno = GetLastError();
- return NULL;
- }
-
- /* save parent's STDIO and redirect for child */
- hCurProc = GetCurrentProcess();
- if (reading) {
- hSavedStdIo = GetStdHandle(STD_OUTPUT_HANDLE);
- if (!SetStdHandle(STD_OUTPUT_HANDLE, hOutFile) ||
- !DuplicateHandle(hCurProc, hInFile, hCurProc, &hDupFile, 0, FALSE,
- DUPLICATE_SAME_ACCESS)) {
- errno = GetLastError();
- CloseHandle(hInFile);
- CloseHandle(hOutFile);
- CloseHandle(hCurProc);
- return NULL;
- }
- CloseHandle(hInFile);
- }
- else {
- hSavedStdIo = GetStdHandle(STD_INPUT_HANDLE);
- if (!SetStdHandle(STD_INPUT_HANDLE, hInFile) ||
- !DuplicateHandle(hCurProc, hOutFile, hCurProc, &hDupFile, 0, FALSE,
- DUPLICATE_SAME_ACCESS)) {
- errno = GetLastError();
- CloseHandle(hInFile);
- CloseHandle(hOutFile);
- CloseHandle(hCurProc);
- return NULL;
- }
- CloseHandle(hOutFile);
- }
- CloseHandle(hCurProc);
-
- /* create child process */
- child = CreateChild(cmd, &sa, NULL, NULL, NULL);
- if (!child) {
- CloseHandle(reading ? hOutFile : hInFile);
- CloseHandle(hDupFile);
- return NULL;
- }
-
- /* restore STDIO */
- if (reading) {
- if (!SetStdHandle(STD_OUTPUT_HANDLE, hSavedStdIo)) {
- errno = GetLastError();
- CloseChildHandle(child);
- CloseHandle(hDupFile);
- CloseHandle(hOutFile);
- return NULL;
- }
- }
- else {
- if (!SetStdHandle(STD_INPUT_HANDLE, hSavedStdIo)) {
- errno = GetLastError();
- CloseChildHandle(child);
- CloseHandle(hInFile);
- CloseHandle(hDupFile);
- return NULL;
- }
- }
-
- if (reading) {
- fd = _open_osfhandle((long)hDupFile, (_O_RDONLY | pipemode));
- CloseHandle(hOutFile);
- }
- else {
- fd = _open_osfhandle((long)hDupFile, (_O_WRONLY | pipemode));
- CloseHandle(hInFile);
- }
-
- if (fd == -1) {
- CloseHandle(hDupFile);
- CloseChildHandle(child);
- return NULL;
- }
-
- if ((fp = (FILE *) fdopen(fd, mode)) == NULL) {
- _close(fd);
- CloseChildHandle(child);
- return NULL;
- }
-
- child->pipe = fp;
-
- return fp;
-}
-
-extern VALUE rb_last_status;
-
-int
-mypclose(FILE *fp)
-{
- struct ChildRecord *child = FindPipedChildSlot(fp);
-
- if (!child) {
- return -1; /* may closed in waitpid() */
- }
-
- //
- // close the pipe
- //
- child->pipe = NULL;
- fflush(fp);
- fclose(fp);
-
- //
- // get the return status of the process
- //
- rb_syswait(child->pid);
- return NUM2INT(rb_last_status);
-}
-
-int
-do_spawn(cmd)
-char *cmd;
-{
- struct ChildRecord *child = CreateChild(cmd, NULL, NULL, NULL, NULL);
- if (!child) {
- return -1;
- }
- rb_syswait(child->pid);
- return NUM2INT(rb_last_status);
-}
-
-static struct ChildRecord *
-CreateChild(char *cmd, SECURITY_ATTRIBUTES *psa, HANDLE hInput, HANDLE hOutput, HANDLE hError)
-{
- BOOL fRet;
- DWORD dwCreationFlags;
- STARTUPINFO aStartupInfo;
- PROCESS_INFORMATION aProcessInformation;
- SECURITY_ATTRIBUTES sa;
- char *shell;
- struct ChildRecord *child;
-
- child = FindFreeChildSlot();
- if (!child) {
- errno = EAGAIN;
- return NULL;
- }
-
- if (!psa) {
- sa.nLength = sizeof (SECURITY_ATTRIBUTES);
- sa.lpSecurityDescriptor = NULL;
- sa.bInheritHandle = TRUE;
- psa = &sa;
- }
-
- memset(&aStartupInfo, 0, sizeof (STARTUPINFO));
- memset(&aProcessInformation, 0, sizeof (PROCESS_INFORMATION));
- aStartupInfo.cb = sizeof (STARTUPINFO);
- if (hInput || hOutput || hError) {
- aStartupInfo.dwFlags = STARTF_USESTDHANDLES;
- if (hInput) {
- aStartupInfo.hStdInput = hInput;
- }
- else {
- aStartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
- }
- if (hOutput) {
- aStartupInfo.hStdOutput = hOutput;
- }
- else {
- aStartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
- }
- if (hError) {
- aStartupInfo.hStdError = hError;
- }
- else {
- aStartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
- }
- }
-
- dwCreationFlags = (NORMAL_PRIORITY_CLASS);
-
- if ((shell = getenv("RUBYSHELL")) && NtHasRedirection(cmd)) {
- char *tmp = ALLOCA_N(char, strlen(shell) + strlen(cmd) + sizeof (" -c "));
- sprintf(tmp, "%s -c %s", shell, cmd);
- cmd = tmp;
- }
- else if ((shell = getenv("COMSPEC")) &&
- (NtHasRedirection(cmd) || isInternalCmd(cmd))) {
- char *tmp = ALLOCA_N(char, strlen(shell) + strlen(cmd) + sizeof (" /c "));
- sprintf(tmp, "%s /c %s", shell, cmd);
- cmd = tmp;
- }
- else {
- shell = NULL;
- }
-
- RUBY_CRITICAL({
- fRet = CreateProcess(shell, cmd, psa, psa,
- psa->bInheritHandle, dwCreationFlags, NULL, NULL,
- &aStartupInfo, &aProcessInformation);
- errno = GetLastError();
- });
-
- if (!fRet) {
- child->pid = 0; /* release the slot */
- return NULL;
- }
-
- CloseHandle(aProcessInformation.hThread);
-
- child->hProcess = aProcessInformation.hProcess;
- child->pid = (pid_t)aProcessInformation.dwProcessId;
-
- if (!IsWinNT()) {
- /* On Win9x, make pid positive similarly to cygwin and perl */
- child->pid = -child->pid;
- }
-
- return child;
-}
-
-typedef struct _NtCmdLineElement {
- struct _NtCmdLineElement *next, *prev;
- char *str;
- int len;
- int flags;
-} NtCmdLineElement;
-
-//
-// Possible values for flags
-//
-
-#define NTGLOB 0x1 // element contains a wildcard
-#define NTMALLOC 0x2 // string in element was malloc'ed
-#define NTSTRING 0x4 // element contains a quoted string
-
-NtCmdLineElement *NtCmdHead = NULL, *NtCmdTail = NULL;
-
-void
-NtFreeCmdLine(void)
-{
- NtCmdLineElement *ptr;
-
- while(NtCmdHead) {
- ptr = NtCmdHead;
- NtCmdHead = NtCmdHead->next;
- free(ptr);
- }
- NtCmdHead = NtCmdTail = NULL;
-}
-
-//
-// This function expands wild card characters that were spotted
-// during the parse phase. The idea here is to call FindFirstFile and
-// FindNextFile with the wildcard pattern specified, and splice in the
-// resulting list of new names. If the wildcard pattern doesn't match
-// any existing files, just leave it in the list.
-//
-typedef struct {
- NtCmdLineElement *head;
- NtCmdLineElement *tail;
-} ListInfo;
-
-static void
-insert(char *path, ListInfo *listinfo)
-{
- NtCmdLineElement *tmpcurr;
-
- tmpcurr = ALLOC(NtCmdLineElement);
- MEMZERO(tmpcurr, NtCmdLineElement, 1);
- tmpcurr->len = strlen(path);
- tmpcurr->str = ALLOC_N(char, tmpcurr->len + 1);
- tmpcurr->flags |= NTMALLOC;
- strcpy(tmpcurr->str, path);
- if (listinfo->tail) {
- listinfo->tail->next = tmpcurr;
- tmpcurr->prev = listinfo->tail;
- listinfo->tail = tmpcurr;
- }
- else {
- listinfo->tail = listinfo->head = tmpcurr;
- }
-}
-
-#ifdef HAVE_SYS_PARAM_H
-# include <sys/param.h>
-#else
-# define MAXPATHLEN 512
-#endif
-
-void
-NtCmdGlob (NtCmdLineElement *patt)
-{
- ListInfo listinfo;
- char buffer[MAXPATHLEN], *buf = buffer;
- char *p;
-
- listinfo.head = listinfo.tail = 0;
-
- if (patt->len >= MAXPATHLEN)
- buf = ruby_xmalloc(patt->len + 1);
-
- strncpy (buf, patt->str, patt->len);
- buf[patt->len] = '\0';
- for (p = buf; *p; p = CharNext(p))
- if (*p == '\\')
- *p = '/';
- rb_globi(buf, (void (*) _((const char*, VALUE)))insert, (VALUE)&listinfo);
- if (buf != buffer)
- free(buf);
-
- if (listinfo.head && listinfo.tail) {
- listinfo.head->prev = patt->prev;
- listinfo.tail->next = patt->next;
- if (listinfo.head->prev)
- listinfo.head->prev->next = listinfo.head;
- if (listinfo.tail->next)
- listinfo.tail->next->prev = listinfo.tail;
- }
- if (patt->flags & NTMALLOC)
- free(patt->str);
- // free(patt); //TODO: memory leak occures here. we have to fix it.
-}
-
-//
-// Check a command string to determine if it has I/O redirection
-// characters that require it to be executed by a command interpreter
-//
-
-static bool
-NtHasRedirection (char *cmd)
-{
- int inquote = 0;
- char quote = '\0';
- char *ptr ;
-
- //
- // Scan the string, looking for redirection (< or >) or pipe
- // characters (|) that are not in a quoted string
- //
-
- for (ptr = cmd; *ptr; ptr++) {
-
- switch (*ptr) {
-
- case '\'':
- case '\"':
- if (inquote) {
- if (quote == *ptr) {
- inquote = 0;
- quote = '\0';
- }
- }
- else {
- quote = *ptr;
- inquote++;
- }
- break;
-
- case '>':
- case '<':
- case '|':
-
- if (!inquote)
- return TRUE;
- }
- }
- return FALSE;
-}
-
-
-int
-NtMakeCmdVector (char *cmdline, char ***vec, int InputCmd)
-{
- int cmdlen = strlen(cmdline);
- int done, instring, globbing, quoted, len;
- int newline, need_free = 0, i;
- int elements, strsz;
- int slashes = 0;
- char *ptr, *base, *buffer;
- char **vptr;
- char quote;
- NtCmdLineElement *curr;
-
- //
- // just return if we don't have a command line
- //
-
- if (cmdlen == 0) {
- *vec = NULL;
- return 0;
- }
-
- cmdline = strdup(cmdline);
-
- //
- // strip trailing white space
- //
-
- ptr = cmdline+(cmdlen - 1);
- while(ptr >= cmdline && ISSPACE(*ptr))
- --ptr;
- *++ptr = '\0';
-
-
- //
- // Ok, parse the command line, building a list of CmdLineElements.
- // When we've finished, and it's an input command (meaning that it's
- // the processes argv), we'll do globing and then build the argument
- // vector.
- // The outer loop does one interation for each element seen.
- // The inner loop does one interation for each character in the element.
- //
-
- for (done = 0, ptr = cmdline; *ptr;) {
-
- //
- // zap any leading whitespace
- //
-
- while(ISSPACE(*ptr))
- ptr++;
- base = ptr;
-
- for (done = newline = globbing = instring = quoted = 0;
- *ptr && !done; ptr++) {
-
- //
- // Switch on the current character. We only care about the
- // white-space characters, the wild-card characters, and the
- // quote characters.
- //
-
- switch (*ptr) {
- case '\\':
- if (ptr[1] == '"') ptr++;
- break;
- case ' ':
- case '\t':
-#if 0
- case '/': // have to do this for NT/DOS option strings
-
- //
- // check to see if we're parsing an option switch
- //
-
- if (*ptr == '/' && base == ptr)
- continue;
-#endif
- //
- // if we're not in a string, then we're finished with this
- // element
- //
-
- if (!instring)
- done++;
- break;
-
- case '*':
- case '?':
-
- //
- // record the fact that this element has a wildcard character
- // N.B. Don't glob if inside a single quoted string
- //
-
- if (!(instring && quote == '\''))
- globbing++;
- break;
-
- case '\n':
-
- //
- // If this string contains a newline, mark it as such so
- // we can replace it with the two character sequence "\n"
- // (cmd.exe doesn't like raw newlines in strings...sigh).
- //
-
- newline++;
- break;
-
- case '\'':
- case '\"':
-
- //
- // if we're already in a string, see if this is the
- // terminating close-quote. If it is, we're finished with
- // the string, but not neccessarily with the element.
- // If we're not already in a string, start one.
- //
-
- if (instring) {
- if (quote == *ptr) {
- instring = 0;
- quote = '\0';
- }
- }
- else {
- instring++;
- quote = *ptr;
- quoted++;
- }
- break;
- }
- }
-
- //
- // need to back up ptr by one due to last increment of for loop
- // (if we got out by seeing white space)
- //
-
- if (*ptr)
- ptr--;
-
- //
- // when we get here, we've got a pair of pointers to the element,
- // base and ptr. Base points to the start of the element while ptr
- // points to the character following the element.
- //
-
- curr = ALLOC(NtCmdLineElement);
- memset (curr, 0, sizeof(*curr));
-
- len = ptr - base;
-
- //
- // if it's an input vector element and it's enclosed by quotes,
- // we can remove them.
- //
-
- if (InputCmd && (base[0] == '\"' && base[len-1] == '\"')) {
- char *p;
- base++;
- len -= 2;
- base[len] = 0;
- for (p = base; p < base + len; p++) {
- if ((p[0] == '\\' || p[0] == '\"') && p[1] == '"') {
- strcpy(p, p + 1);
- len--;
- }
- }
- }
- else if (InputCmd && (base[0] == '\'' && base[len-1] == '\'')) {
- base++;
- len -= 2;
- }
-
- curr->str = base;
- curr->len = len;
- curr->flags |= (globbing ? NTGLOB : 0);
-
- //
- // Now put it in the list of elements
- //
- if (NtCmdTail) {
- NtCmdTail->next = curr;
- curr->prev = NtCmdTail;
- NtCmdTail = curr;
- }
- else {
- NtCmdHead = NtCmdTail = curr;
- }
- }
-
- if (InputCmd) {
-
- //
- // When we get here we've finished parsing the command line. Now
- // we need to run the list, expanding any globbing patterns.
- //
-
- for(curr = NtCmdHead; curr; curr = curr->next) {
- if (curr->flags & NTGLOB) {
- NtCmdGlob(curr);
- }
- }
- }
-
- //
- // Almost done!
- // Count up the elements, then allocate space for a vector of pointers
- // (argv) and a string table for the elements.
- //
-
- for (elements = 0, strsz = 0, curr = NtCmdHead; curr; curr = curr->next) {
- elements++;
- strsz += (curr->len + 1);
- }
-
- len = (elements+1)*sizeof(char *) + strsz;
- buffer = ALLOC_N(char, len);
-
- memset (buffer, 0, len);
-
- //
- // make vptr point to the start of the buffer
- // and ptr point to the area we'll consider the string table.
- //
- // buffer (*vec)
- // |
- // V ^---------------------V
- // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
- // | | | .... | NULL | | ..... |\0 | | ..... |\0 |...
- // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
- // |- elements+1 -| ^ 1st element ^ 2nd element
-
- vptr = (char **) buffer;
-
- ptr = buffer + (elements+1) * sizeof(char *);
-
- for (curr = NtCmdHead; curr; curr = curr->next) {
- strncpy (ptr, curr->str, curr->len);
- ptr[curr->len] = '\0';
- *vptr++ = ptr;
- ptr += curr->len + 1;
- }
- NtFreeCmdLine();
- *vec = (char **) buffer;
- free(cmdline);
- return elements;
-}
-
-//
-// UNIX compatible directory access functions for NT
-//
-
-#define PATHLEN 1024
-
-//
-// The idea here is to read all the directory names into a string table
-// (separated by nulls) and when one of the other dir functions is called
-// return the pointer to the current file name.
-//
-
-DIR *
-opendir(const char *filename)
-{
- DIR *p;
- long len;
- long idx;
- char scannamespc[PATHLEN];
- char *scanname = scannamespc;
- struct stat sbuf;
- WIN32_FIND_DATA FindData;
- HANDLE fh;
-
- //
- // check to see if we've got a directory
- //
-
- if ((win32_stat (filename, &sbuf) < 0 ||
- sbuf.st_mode & _S_IFDIR == 0) &&
- (!ISALPHA(filename[0]) || filename[1] != ':' || filename[2] != '\0' ||
- ((1 << (filename[0] & 0x5f) - 'A') & GetLogicalDrives()) == 0)) {
- return NULL;
- }
-
- //
- // Get us a DIR structure
- //
-
- p = xcalloc(sizeof(DIR), 1);
- if (p == NULL)
- return NULL;
-
- //
- // Create the search pattern
- //
-
- strcpy(scanname, filename);
-
- if (index("/\\:", *CharPrev(scanname, scanname + strlen(scanname))) == NULL)
- strcat(scanname, "/*");
- else
- strcat(scanname, "*");
-
- //
- // do the FindFirstFile call
- //
-
- fh = FindFirstFile (scanname, &FindData);
- if (fh == INVALID_HANDLE_VALUE) {
- return NULL;
- }
-
- //
- // now allocate the first part of the string table for the
- // filenames that we find.
- //
-
- idx = strlen(FindData.cFileName)+1;
- p->start = ALLOC_N(char, idx);
- strcpy (p->start, FindData.cFileName);
- p->nfiles++;
-
- //
- // loop finding all the files that match the wildcard
- // (which should be all of them in this directory!).
- // the variable idx should point one past the null terminator
- // of the previous string found.
- //
- while (FindNextFile(fh, &FindData)) {
- len = strlen (FindData.cFileName);
-
- //
- // bump the string table size by enough for the
- // new name and it's null terminator
- //
-
- #define Renew(x, y, z) (x = (z *)realloc(x, y))
-
- Renew (p->start, idx+len+1, char);
- if (p->start == NULL) {
- rb_fatal ("opendir: malloc failed!\n");
- }
- strcpy(&p->start[idx], FindData.cFileName);
- p->nfiles++;
- idx += len+1;
- }
- FindClose(fh);
- p->size = idx;
- p->curr = p->start;
- return p;
-}
-
-
-//
-// Readdir just returns the current string pointer and bumps the
-// string pointer to the next entry.
-//
-
-struct direct *
-readdir(DIR *dirp)
-{
- int len;
- static int dummy = 0;
-
- if (dirp->curr) {
-
- //
- // first set up the structure to return
- //
-
- len = strlen(dirp->curr);
- strcpy(dirp->dirstr.d_name, dirp->curr);
- dirp->dirstr.d_namlen = len;
-
- //
- // Fake inode
- //
- dirp->dirstr.d_ino = dummy++;
-
- //
- // Now set up for the next call to readdir
- //
-
- dirp->curr += len + 1;
- if (dirp->curr >= (dirp->start + dirp->size)) {
- dirp->curr = NULL;
- }
-
- return &(dirp->dirstr);
-
- } else
- return NULL;
-}
-
-//
-// Telldir returns the current string pointer position
-//
-
-long
-telldir(DIR *dirp)
-{
- return (long) dirp->curr; /* ouch! pointer to long cast */
-}
-
-//
-// Seekdir moves the string pointer to a previously saved position
-// (Saved by telldir).
-
-void
-seekdir(DIR *dirp, long loc)
-{
- dirp->curr = (char *) loc; /* ouch! long to pointer cast */
-}
-
-//
-// Rewinddir resets the string pointer to the start
-//
-
-void
-rewinddir(DIR *dirp)
-{
- dirp->curr = dirp->start;
-}
-
-//
-// This just free's the memory allocated by opendir
-//
-
-void
-closedir(DIR *dirp)
-{
- free(dirp->start);
- free(dirp);
-}
-
-static int
-valid_filename(char *s)
-{
- int fd;
-
- //
- // if the file exists, then it's a valid filename!
- //
-
- if (_access(s, 0) == 0) {
- return 1;
- }
-
- //
- // It doesn't exist, so see if we can open it.
- //
-
- if ((fd = _open(s, _O_CREAT, 0666)) >= 0) {
- close(fd);
- _unlink (s); // don't leave it laying around
- return 1;
- }
- return 0;
-}
-
-//
-// This is a clone of fdopen so that we can handle the
-// brain damaged version of sockets that NT gets to use.
-//
-// The problem is that sockets are not real file handles and
-// cannot be fdopen'ed. This causes problems in the do_socket
-// routine in doio.c, since it tries to create two file pointers
-// for the socket just created. We'll fake out an fdopen and see
-// if we can prevent perl from trying to do stdio on sockets.
-//
-
-//EXTERN_C int __cdecl _alloc_osfhnd(void);
-//EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
-EXTERN_C void __cdecl _lock_fhandle(int);
-EXTERN_C void __cdecl _unlock_fhandle(int);
-EXTERN_C void __cdecl _unlock(int);
-
-#if defined _MT || defined __MSVCRT__
-#define MSVCRT_THREADS
-#endif
-#ifdef MSVCRT_THREADS
-# define MTHREAD_ONLY(x) x
-# define STHREAD_ONLY(x)
-#else
-# define MTHREAD_ONLY(x)
-# define STHREAD_ONLY(x) x
-#endif
-
-typedef struct {
- long osfhnd; /* underlying OS file HANDLE */
- char osfile; /* attributes of file (e.g., open in text mode?) */
- char pipech; /* one char buffer for handles opened on pipes */
-#ifdef MSVCRT_THREADS
- int lockinitflag;
- CRITICAL_SECTION lock;
-#endif
-} ioinfo;
-
-#if !defined _CRTIMP
-#define _CRTIMP __declspec(dllimport)
-#endif
-
-EXTERN_C _CRTIMP ioinfo * __pioinfo[];
-
-#define IOINFO_L2E 5
-#define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
-#define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
-
-#define _osfhnd(i) (_pioinfo(i)->osfhnd)
-#define _osfile(i) (_pioinfo(i)->osfile)
-#define _pipech(i) (_pioinfo(i)->pipech)
-
-#define FOPEN 0x01 /* file handle open */
-#define FNOINHERIT 0x10 /* file handle opened O_NOINHERIT */
-#define FAPPEND 0x20 /* file handle opened O_APPEND */
-#define FDEV 0x40 /* file handle refers to device */
-#define FTEXT 0x80 /* file handle is in text mode */
-
-#define _set_osfhnd(fh, osfh) (void)(_osfhnd(fh) = osfh)
-
-static int
-my_open_osfhandle(long osfhandle, int flags)
-{
- int fh;
- char fileflags; /* _osfile flags */
-
- /* copy relevant flags from second parameter */
- fileflags = FDEV;
-
- if (flags & O_APPEND)
- fileflags |= FAPPEND;
-
- if (flags & O_TEXT)
- fileflags |= FTEXT;
-
- if (flags & O_NOINHERIT)
- fileflags |= FNOINHERIT;
-
- RUBY_CRITICAL({
- /* attempt to allocate a C Runtime file handle */
- HANDLE hF = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
- fh = _open_osfhandle((long)hF, 0);
- CloseHandle(hF);
- if (fh == -1) {
- errno = EMFILE; /* too many open files */
- _doserrno = 0L; /* not an OS error */
- }
- else {
-
- MTHREAD_ONLY(EnterCriticalSection(&(_pioinfo(fh)->lock)));
- /* the file is open. now, set the info in _osfhnd array */
- _set_osfhnd(fh, osfhandle);
-
- fileflags |= FOPEN; /* mark as open */
-
- _osfile(fh) = fileflags; /* set osfile entry */
- MTHREAD_ONLY(LeaveCriticalSection(&_pioinfo(fh)->lock));
- }
- });
-
- return fh; /* return handle */
-}
-
-#undef getsockopt
-
-static int
-is_socket(SOCKET fd)
-{
- char sockbuf[80];
- int optlen;
- int retval;
-
- optlen = sizeof(sockbuf);
- retval = getsockopt(fd, SOL_SOCKET, SO_TYPE, sockbuf, &optlen);
- if (retval == SOCKET_ERROR) {
- int iRet;
-
- iRet = WSAGetLastError();
- if (iRet == WSAENOTSOCK || iRet == WSANOTINITIALISED)
- return FALSE;
- }
-
- //
- // If we get here, then fd is actually a socket.
- //
-
- return TRUE;
-}
-
-int
-myfddup (int fd)
-{
- SOCKET s = TO_SOCKET(fd);
-
- if (s == -1)
- return -1;
-
- return my_open_osfhandle(s, O_RDWR|O_BINARY);
-}
-
-
-void
-myfdclose(FILE *fp)
-{
- RUBY_CRITICAL({
- STHREAD_ONLY(_free_osfhnd(fileno(fp)));
- fclose(fp);
- });
-}
-
-//
-// Since the errors returned by the socket error function
-// WSAGetLastError() are not known by the library routine strerror
-// we have to roll our own.
-//
-
-#undef strerror
-
-char *
-mystrerror(int e)
-{
- static char buffer[512];
-#if !defined __MINGW32__
- extern int sys_nerr;
-#endif
- DWORD source = 0;
- char *p;
-
- if (e < 0 || e > sys_nerr) {
- if (e < 0)
- e = GetLastError();
- if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
- FORMAT_MESSAGE_IGNORE_INSERTS, &source, e, 0,
- buffer, 512, NULL) == 0) {
- strcpy(buffer, "Unknown Error");
- }
- for (p = buffer + strlen(buffer) - 1; buffer <= p; p--) {
- if (*p != '\r' && *p != '\n') break;
- *p = 0;
- }
- return buffer;
- }
- return strerror(e);
-}
-
-//
-// various stubs
-//
-
-
-// Ownership
-//
-// Just pretend that everyone is a superuser. NT will let us know if
-// we don't really have permission to do something.
-//
-
-#define ROOT_UID 0
-#define ROOT_GID 0
-
-UIDTYPE
-getuid(void)
-{
- return ROOT_UID;
-}
-
-UIDTYPE
-geteuid(void)
-{
- return ROOT_UID;
-}
-
-GIDTYPE
-getgid(void)
-{
- return ROOT_GID;
-}
-
-GIDTYPE
-getegid(void)
-{
- return ROOT_GID;
-}
-
-int
-setuid(int uid)
-{
- return (uid == ROOT_UID ? 0 : -1);
-}
-
-int
-setgid(int gid)
-{
- return (gid == ROOT_GID ? 0 : -1);
-}
-
-//
-// File system stuff
-//
-
-int
-/* ioctl(int i, unsigned int u, char *data) */
-ioctl(int i, unsigned int u, long data)
-{
- return -1;
-}
-
-#undef FD_SET
-
-void
-myfdset(int fd, fd_set *set)
-{
- unsigned int i;
- SOCKET s = TO_SOCKET(fd);
-
- for (i = 0; i < set->fd_count; i++) {
- if (set->fd_array[i] == s) {
- return;
- }
- }
- if (i == set->fd_count) {
- if (set->fd_count < FD_SETSIZE) {
- set->fd_array[i] = s;
- set->fd_count++;
- }
- }
-}
-
-#undef FD_CLR
-
-void
-myfdclr(int fd, fd_set *set)
-{
- unsigned int i;
- SOCKET s = TO_SOCKET(fd);
-
- for (i = 0; i < set->fd_count; i++) {
- if (set->fd_array[i] == s) {
- while (i < set->fd_count - 1) {
- set->fd_array[i] = set->fd_array[i + 1];
- i++;
- }
- set->fd_count--;
- break;
- }
- }
-}
-
-#undef FD_ISSET
-
-int
-myfdisset(int fd, fd_set *set)
-{
- return __WSAFDIsSet(TO_SOCKET(fd), set);
-}
-
-//
-// Networking trampolines
-// These are used to avoid socket startup/shutdown overhead in case
-// the socket routines aren't used.
-//
-
-#undef select
-
-static int NtSocketsInitialized = 0;
-
-static int
-extract_file_fd(fd_set *set, fd_set *fileset)
-{
- int idx;
-
- fileset->fd_count = 0;
- if (!set)
- return 0;
- for (idx = 0; idx < set->fd_count; idx++) {
- SOCKET fd = set->fd_array[idx];
-
- if (!is_socket(fd)) {
- int i;
-
- for (i = 0; i < fileset->fd_count; i++) {
- if (fileset->fd_array[i] == fd) {
- break;
- }
- }
- if (i == fileset->fd_count) {
- if (fileset->fd_count < FD_SETSIZE) {
- fileset->fd_array[i] = fd;
- fileset->fd_count++;
- }
- }
- }
- }
- return fileset->fd_count;
-}
-
-long
-myselect (int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
- struct timeval *timeout)
-{
- long r;
- fd_set file_rd;
- fd_set file_wr;
-#ifdef USE_INTERRUPT_WINSOCK
- fd_set trap;
-#endif /* USE_INTERRUPT_WINSOCK */
- int file_nfds;
-
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- r = 0;
- if (rd && rd->fd_count > r) r = rd->fd_count;
- if (wr && wr->fd_count > r) r = wr->fd_count;
- if (ex && ex->fd_count > r) r = ex->fd_count;
- if (nfds > r) nfds = r;
- if (nfds == 0 && timeout) {
- Sleep(timeout->tv_sec * 1000 + timeout->tv_usec / 1000);
- return 0;
- }
- file_nfds = extract_file_fd(rd, &file_rd);
- file_nfds += extract_file_fd(wr, &file_wr);
- if (file_nfds)
- {
- // assume normal files are always readable/writable
- // fake read/write fd_set and return value
- if (rd) *rd = file_rd;
- if (wr) *wr = file_wr;
- return file_nfds;
- }
-
-#if USE_INTERRUPT_WINSOCK
- if (ex)
- trap = *ex;
- else
- trap.fd_count = 0;
- if (trap.fd_count < FD_SETSIZE)
- trap.fd_array[trap.fd_count++] = (SOCKET)interrupted_event;
- // else unable to catch interrupt.
- ex = &trap;
-#endif /* USE_INTERRUPT_WINSOCK */
-
- RUBY_CRITICAL(r = select (nfds, rd, wr, ex, timeout));
- if (r == SOCKET_ERROR) {
- errno = WSAGetLastError();
- switch (errno) {
- case WSAEINTR:
- errno = EINTR;
- break;
- }
- }
- return r;
-}
-
-static void
-StartSockets ()
-{
- WORD version;
- WSADATA retdata;
- int ret;
- int iSockOpt;
-
- //
- // initalize the winsock interface and insure that it's
- // cleaned up at exit.
- //
- version = MAKEWORD(1, 1);
- if (ret = WSAStartup(version, &retdata))
- rb_fatal ("Unable to locate winsock library!\n");
- if (LOBYTE(retdata.wVersion) != 1)
- rb_fatal("could not find version 1 of winsock dll\n");
-
- if (HIBYTE(retdata.wVersion) != 1)
- rb_fatal("could not find version 1 of winsock dll\n");
-
- atexit((void (*)(void)) WSACleanup);
-
- iSockOpt = SO_SYNCHRONOUS_NONALERT;
- /*
- * Enable the use of sockets as filehandles
- */
- setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
- (char *)&iSockOpt, sizeof(iSockOpt));
-
- main_thread.handle = GetCurrentThreadHandle();
- main_thread.id = GetCurrentThreadId();
-
- interrupted_event = CreateSignal();
- if (!interrupted_event)
- rb_fatal("Unable to create interrupt event!\n");
-}
-
-#undef accept
-
-SOCKET
-myaccept (SOCKET s, struct sockaddr *addr, int *addrlen)
-{
- SOCKET r;
-
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- RUBY_CRITICAL(r = accept (TO_SOCKET(s), addr, addrlen));
- if (r == INVALID_SOCKET)
- errno = WSAGetLastError();
- return my_open_osfhandle(r, O_RDWR|O_BINARY);
-}
-
-#undef bind
-
-int
-mybind (SOCKET s, struct sockaddr *addr, int addrlen)
-{
- int r;
-
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- RUBY_CRITICAL(r = bind (TO_SOCKET(s), addr, addrlen));
- if (r == SOCKET_ERROR)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef connect
-
-int
-myconnect (SOCKET s, struct sockaddr *addr, int addrlen)
-{
- int r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- RUBY_CRITICAL(r = connect (TO_SOCKET(s), addr, addrlen));
- if (r == SOCKET_ERROR)
- errno = WSAGetLastError();
- return r;
-}
-
-
-#undef getpeername
-
-int
-mygetpeername (SOCKET s, struct sockaddr *addr, int *addrlen)
-{
- int r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- RUBY_CRITICAL(r = getpeername (TO_SOCKET(s), addr, addrlen));
- if (r == SOCKET_ERROR)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef getsockname
-
-int
-mygetsockname (SOCKET s, struct sockaddr *addr, int *addrlen)
-{
- int r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- RUBY_CRITICAL(r = getsockname (TO_SOCKET(s), addr, addrlen));
- if (r == SOCKET_ERROR)
- errno = WSAGetLastError();
- return r;
-}
-
-int
-mygetsockopt (SOCKET s, int level, int optname, char *optval, int *optlen)
-{
- int r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- RUBY_CRITICAL(r = getsockopt (TO_SOCKET(s), level, optname, optval, optlen));
- if (r == SOCKET_ERROR)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef ioctlsocket
-
-int
-myioctlsocket (SOCKET s, long cmd, u_long *argp)
-{
- int r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- RUBY_CRITICAL(r = ioctlsocket (TO_SOCKET(s), cmd, argp));
- if (r == SOCKET_ERROR)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef listen
-
-int
-mylisten (SOCKET s, int backlog)
-{
- int r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- RUBY_CRITICAL(r = listen (TO_SOCKET(s), backlog));
- if (r == SOCKET_ERROR)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef recv
-
-int
-myrecv (SOCKET s, char *buf, int len, int flags)
-{
- int r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- RUBY_CRITICAL(r = recv (TO_SOCKET(s), buf, len, flags));
- if (r == SOCKET_ERROR)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef recvfrom
-
-int
-myrecvfrom (SOCKET s, char *buf, int len, int flags,
- struct sockaddr *from, int *fromlen)
-{
- int r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- RUBY_CRITICAL(r = recvfrom (TO_SOCKET(s), buf, len, flags, from, fromlen));
- if (r == SOCKET_ERROR)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef send
-
-int
-mysend (SOCKET s, char *buf, int len, int flags)
-{
- int r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- RUBY_CRITICAL(r = send (TO_SOCKET(s), buf, len, flags));
- if (r == SOCKET_ERROR)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef sendto
-
-int
-mysendto (SOCKET s, char *buf, int len, int flags,
- struct sockaddr *to, int tolen)
-{
- int r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- RUBY_CRITICAL(r = sendto (TO_SOCKET(s), buf, len, flags, to, tolen));
- if (r == SOCKET_ERROR)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef setsockopt
-
-int
-mysetsockopt (SOCKET s, int level, int optname, char *optval, int optlen)
-{
- int r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- RUBY_CRITICAL(r = setsockopt (TO_SOCKET(s), level, optname, optval, optlen));
- if (r == SOCKET_ERROR)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef shutdown
-
-int
-myshutdown (SOCKET s, int how)
-{
- int r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- RUBY_CRITICAL(r = shutdown (TO_SOCKET(s), how));
- if (r == SOCKET_ERROR)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef socket
-
-SOCKET
-mysocket (int af, int type, int protocol)
-{
- SOCKET s;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- RUBY_CRITICAL(s = socket (af, type, protocol));
- if (s == INVALID_SOCKET) {
- errno = WSAGetLastError();
- //fprintf(stderr, "socket fail (%d)", WSAGetLastError());
- }
- return my_open_osfhandle(s, O_RDWR|O_BINARY);
-}
-
-#undef gethostbyaddr
-
-struct hostent *
-mygethostbyaddr (char *addr, int len, int type)
-{
- struct hostent *r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- RUBY_CRITICAL(r = gethostbyaddr (addr, len, type));
- if (r == NULL)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef gethostbyname
-
-struct hostent *
-mygethostbyname (char *name)
-{
- struct hostent *r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- RUBY_CRITICAL(r = gethostbyname (name));
- if (r == NULL)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef gethostname
-
-int
-mygethostname (char *name, int len)
-{
- int r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- RUBY_CRITICAL(r = gethostname (name, len));
- if (r == SOCKET_ERROR)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef getprotobyname
-
-struct protoent *
-mygetprotobyname (char *name)
-{
- struct protoent *r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- RUBY_CRITICAL(r = getprotobyname (name));
- if (r == NULL)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef getprotobynumber
-
-struct protoent *
-mygetprotobynumber (int num)
-{
- struct protoent *r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- RUBY_CRITICAL(r = getprotobynumber (num));
- if (r == NULL)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef getservbyname
-
-struct servent *
-mygetservbyname (char *name, char *proto)
-{
- struct servent *r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- RUBY_CRITICAL(r = getservbyname (name, proto));
- if (r == NULL)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef getservbyport
-
-struct servent *
-mygetservbyport (int port, char *proto)
-{
- struct servent *r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- RUBY_CRITICAL(r = getservbyport (port, proto));
- if (r == NULL)
- errno = WSAGetLastError();
- return r;
-}
-
-//
-// Networking stubs
-//
-
-void endhostent() {}
-void endnetent() {}
-void endprotoent() {}
-void endservent() {}
-
-struct netent *getnetent (void) {return (struct netent *) NULL;}
-
-struct netent *getnetbyaddr(char *name) {return (struct netent *)NULL;}
-
-struct netent *getnetbyname(long net, int type) {return (struct netent *)NULL;}
-
-struct protoent *getprotoent (void) {return (struct protoent *) NULL;}
-
-struct servent *getservent (void) {return (struct servent *) NULL;}
-
-void sethostent (int stayopen) {}
-
-void setnetent (int stayopen) {}
-
-void setprotoent (int stayopen) {}
-
-void setservent (int stayopen) {}
-
-#ifndef WNOHANG
-#define WNOHANG -1
-#endif
-
-static pid_t
-poll_child_status(struct ChildRecord *child, int *stat_loc)
-{
- DWORD exitcode;
-
- if (!GetExitCodeProcess(child->hProcess, &exitcode)) {
- /* If an error occured, return immediatly. */
- errno = GetLastError();
- if (errno == ERROR_INVALID_PARAMETER) {
- errno = ECHILD;
- }
- CloseChildHandle(child);
- return -1;
- }
- if (exitcode != STILL_ACTIVE) {
- /* If already died, return immediatly. */
- pid_t pid = child->pid;
- CloseChildHandle(child);
- if (stat_loc) *stat_loc = exitcode << 8;
- return pid;
- }
- return 0;
-}
-
-pid_t
-waitpid (pid_t pid, int *stat_loc, int options)
-{
- DWORD timeout;
-
- if (options == WNOHANG) {
- timeout = 0;
- } else {
- timeout = INFINITE;
- }
-
- if (pid == -1) {
- int count = 0;
- DWORD ret;
- HANDLE events[MAXCHILDNUM + 1];
-
- FOREACH_CHILD(child) {
- if (!child->pid || child->pid < 0) continue;
- if ((pid = poll_child_status(child, stat_loc))) return pid;
- events[count++] = child->hProcess;
- } END_FOREACH_CHILD;
- if (!count) {
- errno = ECHILD;
- return -1;
- }
- events[count] = interrupted_event;
-
- ret = WaitForMultipleEvents(count + 1, events, FALSE, timeout, TRUE);
- if (ret == WAIT_TIMEOUT) return 0;
- if ((ret -= WAIT_OBJECT_0) == count) {
- ResetSignal(interrupted_event);
- errno = EINTR;
- return -1;
- }
- if (ret > count) {
- errno = GetLastError();
- return -1;
- }
-
- return poll_child_status(ChildRecord + ret, stat_loc);
- }
- else {
- struct ChildRecord* child = FindChildSlot(pid);
- if (!child) {
- errno = ECHILD;
- return -1;
- }
-
- while (!(pid = poll_child_status(child, stat_loc))) {
- /* wait... */
- if (wait_events(child->hProcess, timeout) != WAIT_OBJECT_0) {
- /* still active */
- pid = 0;
- break;
- }
- }
- }
-
- return pid;
-}
-
-#include <sys/timeb.h>
-
-int _cdecl
-gettimeofday(struct timeval *tv, struct timezone *tz)
-{
- SYSTEMTIME st;
- time_t t;
- struct tm tm;
-
- GetLocalTime(&st);
- tm.tm_sec = st.wSecond;
- tm.tm_min = st.wMinute;
- tm.tm_hour = st.wHour;
- tm.tm_mday = st.wDay;
- tm.tm_mon = st.wMonth - 1;
- tm.tm_year = st.wYear - 1900;
- tm.tm_isdst = -1;
- t = mktime(&tm);
- tv->tv_sec = t;
- tv->tv_usec = st.wMilliseconds * 1000;
-
- return 0;
-}
-
-char *
-win32_getcwd(buffer, size)
- char *buffer;
- int size;
-{
- int length;
- char *bp;
-
- if (_getcwd(buffer, size) == NULL) {
- return NULL;
- }
- length = strlen(buffer);
- if (length >= size) {
- return NULL;
- }
-
- for (bp = buffer; *bp != '\0'; bp = CharNext(bp)) {
- if (*bp == '\\') {
- *bp = '/';
- }
- }
- return buffer;
-}
-
-static char *
-str_grow(struct RString *str, size_t new_size)
-{
- char *p;
-
- p = realloc(str->ptr, new_size);
- if (p == NULL)
- rb_fatal("cannot grow string\n");
-
- str->len = new_size;
- str->ptr = p;
-
- return p;
-}
-
-int
-chown(const char *path, int owner, int group)
-{
- return 0;
-}
-
-#include <signal.h>
-#ifndef SIGINT
-#define SIGINT 2
-#endif
-#ifndef SIGKILL
-#define SIGKILL 9
-#endif
-int
-kill(int pid, int sig)
-{
- int ret = 0;
-
- if ((unsigned int)pid == GetCurrentProcessId() && sig != SIGKILL)
- return raise(sig);
-
- if (sig == SIGINT && pid > 0) {
- RUBY_CRITICAL({
- if (!GenerateConsoleCtrlEvent(CTRL_C_EVENT, (DWORD)pid)) {
- errno = GetLastError();
- ret = -1;
- }
- });
- }
- else if (sig == SIGKILL && pid > 0) {
- HANDLE hProc;
-
- RUBY_CRITICAL({
- hProc = OpenProcess(PROCESS_TERMINATE, FALSE,
- IsWin95() ? -pid : pid);
- if (hProc == NULL || hProc == INVALID_HANDLE_VALUE) {
- if (GetLastError() == ERROR_INVALID_PARAMETER) {
- errno = ESRCH;
- }
- else {
- errno = EPERM;
- }
- ret = -1;
- }
- else if (!TerminateProcess(hProc, 0)) {
- errno = EPERM;
- ret = -1;
- }
- CloseHandle(hProc);
- });
- }
- else {
- errno = EINVAL;
- ret = -1;
- }
-
- return ret;
-}
-
-int
-link(char *from, char *to)
-{
- return -1;
-}
-
-int
-wait()
-{
- return 0;
-}
-
-char *
-win32_getenv(const char *name)
-{
- static char *curitem = NULL;
- static DWORD curlen = 0;
- DWORD needlen;
-
- if (curitem == NULL || curlen == 0) {
- curlen = 512;
- curitem = ALLOC_N(char, curlen);
- }
-
- needlen = GetEnvironmentVariable(name, curitem, curlen);
- if (needlen != 0) {
- while (needlen > curlen) {
- REALLOC_N(curitem, char, needlen);
- curlen = needlen;
- needlen = GetEnvironmentVariable(name, curitem, curlen);
- }
- }
- else {
- return NULL;
- }
-
- return curitem;
-}
-
-int
-myrename(const char *oldpath, const char *newpath)
-{
- int res = 0;
- int oldatts;
- int newatts;
-
- oldatts = GetFileAttributes(oldpath);
- newatts = GetFileAttributes(newpath);
-
- if (oldatts == -1) {
- errno = GetLastError();
- return -1;
- }
-
- RUBY_CRITICAL({
- if (newatts != -1 && newatts & FILE_ATTRIBUTE_READONLY)
- SetFileAttributesA(newpath, newatts & ~ FILE_ATTRIBUTE_READONLY);
-
- if (!MoveFile(oldpath, newpath))
- res = -1;
-
- if (res) {
- switch (GetLastError()) {
- case ERROR_ALREADY_EXISTS:
- case ERROR_FILE_EXISTS:
- if (IsWinNT()) {
- if (MoveFileEx(oldpath, newpath, MOVEFILE_REPLACE_EXISTING))
- res = 0;
- } else {
- for (;;) {
- if (!DeleteFile(newpath) && GetLastError() != ERROR_FILE_NOT_FOUND)
- break;
- else if (MoveFile(oldpath, newpath)) {
- res = 0;
- break;
- }
- }
- }
- }
- }
-
- if (res)
- errno = GetLastError();
- else
- SetFileAttributes(newpath, oldatts);
- });
-
- return res;
-}
-
-static int
-isUNCRoot(const char *path)
-{
- if (path[0] == '\\' && path[1] == '\\') {
- const char *p;
- for (p = path + 3; *p; p = CharNext(p)) {
- if (*p == '\\')
- break;
- }
- if (p[0] && p[1]) {
- for (p++; *p; p = CharNext(p)) {
- if (*p == '\\')
- break;
- }
- if (!p[0] || !p[1])
- return 1;
- }
- }
- return 0;
-}
-
-int
-win32_stat(const char *path, struct stat *st)
-{
- const char *p;
- char *buf1 = ALLOCA_N(char, strlen(path) + 1);
- char *buf2 = ALLOCA_N(char, MAXPATHLEN);
- char *s;
- int len;
-
- for (p = path, s = buf1; *p; p++, s++) {
- if (*p == '/')
- *s = '\\';
- else
- *s = *p;
- }
- *s = '\0';
- len = strlen(buf1);
- p = CharPrev(buf1, buf1 + len);
- if (isUNCRoot(buf1)) {
- if (*p != '\\')
- strcat(buf1, "\\");
- } else if (*p == '\\' || *p == ':')
- strcat(buf1, ".");
- if (_fullpath(buf2, buf1, MAXPATHLEN))
- return stat(buf2, st);
- else
- return -1;
-}
-
-static long
-filetime_to_clock(FILETIME *ft)
-{
- __int64 qw = ft->dwHighDateTime;
- qw <<= 32;
- qw |= ft->dwLowDateTime;
- qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
- return (long) qw;
-}
-
-int
-mytimes(struct tms *tmbuf)
-{
- FILETIME create, exit, kernel, user;
-
- if (GetProcessTimes(GetCurrentProcess(),&create, &exit, &kernel, &user)) {
- tmbuf->tms_utime = filetime_to_clock(&user);
- tmbuf->tms_stime = filetime_to_clock(&kernel);
- tmbuf->tms_cutime = 0;
- tmbuf->tms_cstime = 0;
- }
- else {
- tmbuf->tms_utime = clock();
- tmbuf->tms_stime = 0;
- tmbuf->tms_cutime = 0;
- tmbuf->tms_cstime = 0;
- }
- return 0;
-}
-
-#undef Sleep
-#define yield_once() Sleep(0)
-#define yield_until(condition) do yield_once(); while (!(condition))
-
-static DWORD wait_events(HANDLE event, DWORD timeout)
-{
- HANDLE events[2];
- int count = 0;
- DWORD ret;
-
- if (event) {
- events[count++] = event;
- }
- events[count++] = interrupted_event;
-
- ret = WaitForMultipleEvents(count, events, FALSE, timeout, TRUE);
-
- if (ret == WAIT_OBJECT_0 + count - 1) {
- ResetSignal(interrupted_event);
- errno = EINTR;
- }
-
- return ret;
-}
-
-static CRITICAL_SECTION* system_state(void)
-{
- static int initialized = 0;
- static CRITICAL_SECTION syssect;
-
- if (!initialized) {
- InitializeCriticalSection(&syssect);
- initialized = 1;
- }
- return &syssect;
-}
-
-static LONG flag_interrupt = -1;
-static volatile DWORD tlsi_interrupt = TLS_OUT_OF_INDEXES;
-
-void win32_enter_critical(void)
-{
- if (IsWinNT()) {
- EnterCriticalSection(system_state());
- return;
- }
-
- if (tlsi_interrupt == TLS_OUT_OF_INDEXES) {
- tlsi_interrupt = TlsAlloc();
- }
-
- {
- DWORD ti = (DWORD)TlsGetValue(tlsi_interrupt);
- while (InterlockedIncrement(&flag_interrupt) > 0 && !ti) {
- InterlockedDecrement(&flag_interrupt);
- Sleep(1);
- }
- TlsSetValue(tlsi_interrupt, (PVOID)++ti);
- }
-}
-
-void win32_leave_critical(void)
-{
- if (IsWinNT()) {
- LeaveCriticalSection(system_state());
- return;
- }
-
- InterlockedDecrement(&flag_interrupt);
- TlsSetValue(tlsi_interrupt, (PVOID)((DWORD)TlsGetValue(tlsi_interrupt) - 1));
-}
-
-struct handler_arg_t {
- void (*handler)(int);
- int arg;
- int status;
- int finished;
- HANDLE handshake;
-};
-
-static void win32_call_handler(struct handler_arg_t* h)
-{
- int status;
- RUBY_CRITICAL(rb_protect((VALUE (*)(VALUE))h->handler, (VALUE)h->arg, &h->status);
- status = h->status;
- SetEvent(h->handshake));
- if (status) {
- rb_jump_tag(status);
- }
- h->finished = 1;
- Sleep(INFINITE); /* safe on Win95? */
-}
-
-static struct handler_arg_t* setup_handler(struct handler_arg_t *harg,
- int arg,
- void (*handler)(int),
- HANDLE handshake)
-{
- harg->handler = handler;
- harg->arg = arg;
- harg->status = 0;
- harg->finished = 0;
- harg->handshake = handshake;
- return harg;
-}
-
-static void setup_call(CONTEXT* ctx, struct handler_arg_t *harg)
-{
-#ifdef _M_IX86
- DWORD *esp = (DWORD *)ctx->Esp;
- *--esp = (DWORD)harg;
- *--esp = ctx->Eip;
- ctx->Esp = (DWORD)esp;
- ctx->Eip = (DWORD)win32_call_handler;
-#else
-#error unsupported processor
-#endif
-}
-
-int win32_main_context(int arg, void (*handler)(int))
-{
- static HANDLE interrupt_done = NULL;
- struct handler_arg_t harg;
- CONTEXT ctx_orig;
- HANDLE current_thread = GetCurrentThread();
- int old_priority = GetThreadPriority(current_thread);
-
- if (GetCurrentThreadId() == main_thread.id) return FALSE;
-
- SetSignal(interrupted_event);
-
- RUBY_CRITICAL({ /* the main thread must be in user state */
- CONTEXT ctx;
-
- SuspendThread(main_thread.handle);
- SetThreadPriority(current_thread, GetThreadPriority(main_thread.handle));
-
- ZeroMemory(&ctx, sizeof(CONTEXT));
- ctx.ContextFlags = CONTEXT_FULL | CONTEXT_FLOATING_POINT;
- GetThreadContext(main_thread.handle, &ctx);
- ctx_orig = ctx;
-
- /* handler context setup */
- if (!interrupt_done) {
- interrupt_done = CreateEvent(NULL, FALSE, FALSE, NULL);
- /* anonymous one-shot event */
- }
- else {
- ResetEvent(interrupt_done);
- }
- setup_call(&ctx, setup_handler(&harg, arg, handler, interrupt_done));
-
- ctx.ContextFlags = CONTEXT_CONTROL;
- SetThreadContext(main_thread.handle, &ctx);
- ResumeThread(main_thread.handle);
- });
-
- /* give a chance to the main thread */
- yield_once();
- WaitForSingleObject(interrupt_done, INFINITE); /* handshaking */
-
- if (!harg.status) {
- /* no exceptions raised, restore old context. */
- RUBY_CRITICAL({
- /* ensure the main thread is in user state. */
- yield_until(harg.finished);
-
- SuspendThread(main_thread.handle);
- ctx_orig.ContextFlags = CONTEXT_FULL | CONTEXT_FLOATING_POINT;
- SetThreadContext(main_thread.handle, &ctx_orig);
- ResumeThread(main_thread.handle);
- });
- }
- /* otherwise leave the main thread raised */
-
- SetThreadPriority(current_thread, old_priority);
-
- return TRUE;
-}
-
-int win32_sleep(unsigned long msec)
-{
- DWORD ret;
- RUBY_CRITICAL(ret = wait_events(NULL, msec));
- yield_once();
- CHECK_INTS;
- return ret != WAIT_TIMEOUT;
-}
-
-static void catch_interrupt(void)
-{
- yield_once();
- RUBY_CRITICAL(wait_events(NULL, 0));
- CHECK_INTS;
-}
-
-#undef fgetc
-int win32_getc(FILE* stream)
-{
- int c, trap_immediate = rb_trap_immediate;
- if (--stream->_cnt >= 0) {
- c = (unsigned char)*stream->_ptr++;
- rb_trap_immediate = trap_immediate;
- }
- else {
- c = _filbuf(stream);
- rb_trap_immediate = trap_immediate;
- catch_interrupt();
- }
- return c;
-}
-
-#undef fputc
-int win32_putc(int c, FILE* stream)
-{
- int trap_immediate = rb_trap_immediate;
- if (--stream->_cnt >= 0) {
- c = (unsigned char)(*stream->_ptr++ = (char)c);
- rb_trap_immediate = trap_immediate;
- }
- else {
- c = _flsbuf(c, stream);
- rb_trap_immediate = trap_immediate;
- catch_interrupt();
- }
- return c;
-}
-
-struct asynchronous_arg_t {
- /* output field */
- void* stackaddr;
-
- /* input field */
- VALUE (*func)(VALUE self, int argc, VALUE* argv);
- VALUE self;
- int argc;
- VALUE* argv;
-};
-
-static DWORD WINAPI
-call_asynchronous(PVOID argp)
-{
- struct asynchronous_arg_t *arg = argp;
- arg->stackaddr = &argp;
- return (DWORD)arg->func(arg->self, arg->argc, arg->argv);
-}
-
-VALUE win32_asynchronize(asynchronous_func_t func,
- VALUE self, int argc, VALUE* argv, VALUE intrval)
-{
- DWORD val;
- BOOL interrupted = FALSE;
- HANDLE thr;
-
- RUBY_CRITICAL({
- struct asynchronous_arg_t arg;
-
- arg.stackaddr = NULL;
- arg.func = func;
- arg.self = self;
- arg.argc = argc;
- arg.argv = argv;
-
- thr = CreateThread(NULL, 0, call_asynchronous, &arg, 0, &val);
-
- if (thr) {
- yield_until(arg.stackaddr);
-
- if (wait_events(thr, INFINITE) != WAIT_OBJECT_0) {
- interrupted = TRUE;
-
- if (TerminateThread(thr, intrval)) {
- yield_once();
- }
- }
-
- GetExitCodeThread(thr, &val);
- CloseHandle(thr);
-
- if (interrupted) {
- /* must release stack of killed thread, why doesn't Windows? */
- MEMORY_BASIC_INFORMATION m;
-
- memset(&m, 0, sizeof(m));
- if (!VirtualQuery(arg.stackaddr, &m, sizeof(m))) {
- Debug(fprintf(stderr, "couldn't get stack base:%p:%d\n",
- arg.stackaddr, GetLastError()));
- }
- else if (!VirtualFree(m.AllocationBase, 0, MEM_RELEASE)) {
- Debug(fprintf(stderr, "couldn't release stack:%p:%d\n",
- m.AllocationBase, GetLastError()));
- }
- }
- }
- });
-
- if (!thr) {
- rb_fatal("failed to launch waiter thread:%d", GetLastError());
- }
-
- if (interrupted) {
- errno = EINTR;
- CHECK_INTS;
- }
-
- return val;
-}
-
-char **win32_get_environ(void)
-{
- char *envtop, *env;
- char **myenvtop, **myenv;
- int num;
-
- /*
- * We avoid values started with `='. If you want to deal those values,
- * change this function, and some functions in hash.c which recognize
- * `=' as delimiter or win32_getenv() and ruby_setenv().
- * CygWin deals these values by changing first `=' to '!'. But we don't
- * use such trick and follow cmd.exe's way that just doesn't show these
- * values.
- * (U.N. 2001-11-15)
- */
- envtop = GetEnvironmentStrings();
- for (env = envtop, num = 0; *env; env += strlen(env) + 1)
- if (*env != '=') num++;
-
- myenvtop = ALLOC_N(char*, num + 1);
- for (env = envtop, myenv = myenvtop; *env; env += strlen(env) + 1) {
- if (*env != '=') {
- *myenv = ALLOC_N(char, strlen(env) + 1);
- strcpy(*myenv, env);
- myenv++;
- }
- }
- *myenv = NULL;
- FreeEnvironmentStrings(envtop);
-
- return myenvtop;
-}
-
-void win32_free_environ(char **env)
-{
- char **t = env;
-
- while (*t) free(*t++);
- free(env);
-}
diff --git a/win32/win32.h b/win32/win32.h
deleted file mode 100644
index 6dda8658ee..0000000000
--- a/win32/win32.h
+++ /dev/null
@@ -1,422 +0,0 @@
-#ifndef EXT_NT_H
-#define EXT_NT_H
-
-/*
- * Copyright (c) 1993, Intergraph Corporation
- *
- * You may distribute under the terms of either the GNU General Public
- * License or the Artistic License, as specified in the perl README file.
- *
- */
-
-#undef EXTERN
-#if defined(IMPORT)
-#define EXTERN extern __declspec(dllimport)
-#elif defined(EXPORT)
-#define EXTERN extern __declspec(dllexport)
-#endif
-
-//
-// Definitions for NT port of Perl
-//
-
-
-//
-// Ok now we can include the normal include files.
-//
-
-// #include <stdarg.h> conflict with varargs.h?
-// There is function-name conflitct, so we rename it
-#if !defined(IN) && !defined(FLOAT)
-#define OpenFile WINAPI_OpenFile
-#include <windows.h>
-#include <winsock.h>
-#undef OpenFile
-#endif
-//
-// We're not using Microsoft's "extensions" to C for
-// Structured Exception Handling (SEH) so we can nuke these
-//
-#undef try
-#undef except
-#undef finally
-#undef leave
-
-#if defined(__cplusplus)
-extern "C++" {
-#endif
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <direct.h>
-#include <process.h>
-#include <time.h>
-#include <math.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#if !defined(__BORLANDC__)
-# include <sys/utime.h>
-#else
-# include <utime.h>
-#endif
-#include <io.h>
-#include <malloc.h>
-
-#if defined(__cplusplus)
-}
-#endif
-
-#define UIDTYPE int
-#define GIDTYPE int
-#define pid_t int
-#define WNOHANG -1
-
-#undef getc
-#undef putc
-#undef fgetc
-#undef fputc
-#undef getchar
-#undef putchar
-#undef fgetchar
-#undef fputchar
-#define getc(_stream) win32_getc(_stream)
-#define putc(_c, _stream) win32_putc(_c, _stream)
-#define fgetc(_stream) getc(_stream)
-#define fputc(_c, _stream) putc(_c, _stream)
-#define getchar() win32_getc(stdin)
-#define putchar(_c) win32_putc(_c, stdout)
-#define fgetchar(_stream) getchar()
-#define fputchar(_c, _stream) putchar(_c)
-
-#define access _access
-#define chmod _chmod
-#define chsize _chsize
-#define close _close
-#define creat _creat
-#define dup _dup
-#define dup2 _dup2
-#define eof _eof
-#define filelength _filelength
-#define isatty _isatty
-#define locking _locking
-#define lseek _lseek
-#define mktemp _mktemp
-#define open _open
-#define perror _perror
-#define read _read
-#define setmode _setmode
-#define sopen _sopen
-#define tell _tell
-#define umask _umask
-#define unlink _unlink
-#define write _write
-#define execl _execl
-#define execle _execle
-#define execlp _execlp
-#define execlpe _execlpe
-#define execv _execv
-#define execve _execve
-#define execvp _execvp
-#define execvpe _execvpe
-#define getpid _getpid
-#define sleep(x) win32_sleep((x)*1000)
-#define spawnl _spawnl
-#define spawnle _spawnle
-#define spawnlp _spawnlp
-#define spawnlpe _spawnlpe
-#define spawnv _spawnv
-#define spawnve _spawnve
-#define spawnvp _spawnvp
-#define spawnvpe _spawnvpe
-#if _MSC_VER < 800
-#define fileno _fileno
-#endif
-#define utime _utime
-#define vsnprintf _vsnprintf
-#define snprintf _snprintf
-#define popen _popen
-#define pclose _pclose
-#define strcasecmp _stricmp
-#define strncasecmp _strnicmp
-#undef stat
-#define stat(path,st) win32_stat(path,st)
-/* these are defined in nt.c */
-
-#ifdef __MINGW32__
-struct timezone {
- int tz_minuteswest;
- int tz_dsttime;
-};
-#endif
-extern int NtMakeCmdVector(char *, char ***, int);
-extern void NtInitialize(int *, char ***);
-extern char *NtGetLib(void);
-extern char *NtGetBin(void);
-extern FILE *mypopen(char *, char *);
-extern int mypclose(FILE *);
-extern int flock(int fd, int oper);
-extern int myfddup(int);
-extern void myfdclose(FILE *);
-extern SOCKET myaccept(SOCKET, struct sockaddr *, int *);
-extern int mybind(SOCKET, struct sockaddr *, int);
-extern int myconnect(SOCKET, struct sockaddr *, int);
-extern void myfdset(int, fd_set*);
-extern void myfdclr(int, fd_set*);
-extern int myfdisset(int, fd_set*);
-extern long myselect(int, fd_set *, fd_set *, fd_set *, struct timeval *);
-extern int mygetpeername(SOCKET, struct sockaddr *, int *);
-extern int mygetsockname(SOCKET, struct sockaddr *, int *);
-extern int mygetsockopt(SOCKET, int, int, char *, int *);
-extern int myioctlsocket(SOCKET, long, u_long *);
-extern int mylisten(SOCKET, int);
-extern int myrecv(SOCKET, char *, int, int);
-extern int myrecvfrom(SOCKET, char *, int, int, struct sockaddr *, int *);
-extern int mysend(SOCKET, char *, int, int);
-extern int mysendto(SOCKET, char *, int, int, struct sockaddr *, int);
-extern int mysetsockopt(SOCKET, int, int, char *, int);
-extern int myshutdown(SOCKET, int);
-extern SOCKET mysocket(int, int, int);
-extern SOCKET myget_osfhandle(int);
-extern struct hostent * mygethostbyaddr(char *, int, int);
-extern struct hostent * mygethostbyname(char *);
-extern int mygethostname(char *, int);
-extern struct protoent * mygetprotobyname(char *);
-extern struct protoent * mygetprotobynumber(int);
-extern struct servent * mygetservbyname(char *, char *);
-extern struct servent * mygetservbyport(int, char *);
-extern char *win32_getenv(const char *);
-extern int myrename(const char *, const char *);
-extern char **win32_get_environ(void);
-extern void win32_free_environ(char **);
-
-extern int chown(const char *, int, int);
-extern int link(char *, char *);
-extern int gettimeofday(struct timeval *, struct timezone *);
-extern pid_t waitpid (pid_t, int *, int);
-extern int do_spawn(char *);
-extern int kill(int, int);
-extern int isinf(double);
-extern int isnan(double);
-
-
-//
-// define this so we can do inplace editing
-//
-
-#define SUFFIX
-
-//
-// stubs
-//
-#if !defined(__BORLANDC__)
-extern int ioctl (int, unsigned int, long);
-#endif
-extern UIDTYPE getuid (void);
-extern UIDTYPE geteuid (void);
-extern GIDTYPE getgid (void);
-extern GIDTYPE getegid (void);
-extern int setuid (int);
-extern int setgid (int);
-
-extern char *mystrerror(int);
-
-#define strerror(e) mystrerror(e)
-
-#define PIPE_BUF 1024
-
-#define LOCK_SH 1
-#define LOCK_EX 2
-#define LOCK_NB 4
-#define LOCK_UN 8
-#ifndef EWOULDBLOCK
-#define EWOULDBLOCK 10035 /* EBASEERR + 35 (winsock.h) */
-#endif
-
-#ifdef popen
-#undef popen
-#define popen mypopen
-#endif
-#ifdef pclose
-#undef pclose
-#define pclose mypclose
-#endif
-
-/* #undef va_start */
-/* #undef va_end */
-
-#ifdef accept
-#undef accept
-#endif
-#define accept myaccept
-
-#ifdef bind
-#undef bind
-#endif
-#define bind mybind
-
-#ifdef connect
-#undef connect
-#endif
-#define connect myconnect
-
-#undef FD_SET
-#define FD_SET myfdset
-
-#undef FD_CLR
-#define FD_CLR myfdclr
-
-#undef FD_ISSET
-#define FD_ISSET myfdisset
-
-#undef select
-#define select myselect
-
-#ifdef getpeername
-#undef getpeername
-#endif
-#define getpeername mygetpeername
-
-#ifdef getsockname
-#undef getsockname
-#endif
-#define getsockname mygetsockname
-
-#ifdef getsockopt
-#undef getsockopt
-#endif
-#define getsockopt mygetsockopt
-
-#ifdef ioctlsocket
-#undef ioctlsocket
-#endif
-#define ioctlsocket myioctlsocket
-
-#ifdef listen
-#undef listen
-#endif
-#define listen mylisten
-
-#ifdef recv
-#undef recv
-#endif
-#define recv myrecv
-
-#ifdef recvfrom
-#undef recvfrom
-#endif
-#define recvfrom myrecvfrom
-
-#ifdef send
-#undef send
-#endif
-#define send mysend
-
-#ifdef sendto
-#undef sendto
-#endif
-#define sendto mysendto
-
-#ifdef setsockopt
-#undef setsockopt
-#endif
-#define setsockopt mysetsockopt
-
-#ifdef shutdown
-#undef shutdown
-#endif
-#define shutdown myshutdown
-
-#ifdef socket
-#undef socket
-#endif
-#define socket mysocket
-
-#ifdef gethostbyaddr
-#undef gethostbyaddr
-#endif
-#define gethostbyaddr mygethostbyaddr
-
-#ifdef gethostbyname
-#undef gethostbyname
-#endif
-#define gethostbyname mygethostbyname
-
-#ifdef gethostname
-#undef gethostname
-#endif
-#define gethostname mygethostname
-
-#ifdef getprotobyname
-#undef getprotobyname
-#endif
-#define getprotobyname mygetprotobyname
-
-#ifdef getprotobynumber
-#undef getprotobynumber
-#endif
-#define getprotobynumber mygetprotobynumber
-
-#ifdef getservbyname
-#undef getservbyname
-#endif
-#define getservbyname mygetservbyname
-
-#ifdef getservbyport
-#undef getservbyport
-#endif
-#define getservbyport mygetservbyport
-
-#ifdef get_osfhandle
-#undef get_osfhandle
-#endif
-#define get_osfhandle myget_osfhandle
-
-#ifdef getcwd
-#undef getcwd
-#endif
-#define getcwd win32_getcwd
-
-#ifdef getenv
-#undef getenv
-#endif
-#define getenv win32_getenv
-
-#ifdef rename
-#undef rename
-#endif
-#define rename myrename
-
-struct tms {
- long tms_utime;
- long tms_stime;
- long tms_cutime;
- long tms_cstime;
-};
-
-#ifdef times
-#undef times
-#endif
-#define times mytimes
-
-/* thread stuff */
-HANDLE GetCurrentThreadHandle(void);
-int win32_main_context(int arg, void (*handler)(int));
-int win32_sleep(unsigned long msec);
-void win32_enter_critical(void);
-void win32_leave_critical(void);
-int win32_putc(int, FILE*);
-int win32_getc(FILE*);
-#define Sleep(msec) (void)win32_sleep(msec)
-
-/*
-== ***CAUTION***
-Since this function is very dangerous, ((*NEVER*))
-* lock any HANDLEs(i.e. Mutex, Semaphore, CriticalSection and so on) or,
-* use anything like TRAP_BEG...TRAP_END block structure,
-in asynchronous_func_t.
-*/
-typedef DWORD (*asynchronous_func_t)(DWORD self, int argc, DWORD* argv);
-DWORD win32_asynchronize(asynchronous_func_t func, DWORD self, int argc, DWORD* argv, DWORD intrval);
-
-#endif
diff --git a/win32/winmain.c b/win32/winmain.c
deleted file mode 100644
index 4902d1daaf..0000000000
--- a/win32/winmain.c
+++ /dev/null
@@ -1,10 +0,0 @@
-#include <windows.h>
-#include <stdio.h>
-
-extern int main(int, char**, char**);
-
-int WINAPI
-WinMain(HINSTANCE current, HINSTANCE prev, LPSTR cmdline, int showcmd)
-{
- return main(0, NULL, NULL);
-}
diff --git a/x68/_dtos18.c b/x68/_dtos18.c
deleted file mode 100644
index 4712a66bf7..0000000000
--- a/x68/_dtos18.c
+++ /dev/null
@@ -1,250 +0,0 @@
-/*
- * PROJECT C Library, X68000 PROGRAMMING INTERFACE DEFINITION
- * --------------------------------------------------------------------
- * This file is written by the Project C Library Group, and completely
- * in public domain. You can freely use, copy, modify, and redistribute
- * the whole contents, without this notice.
- * --------------------------------------------------------------------
- * $Id$
- */
-
-/* System headers */
-#include <stdlib.h>
-#include <sys/xstdlib.h>
-
-/*
-** 本関数は浮動小数点を倍精度整数に変換してから文字列にするため、精度的には
-** 倍精度整数に格納できる桁数までしか扱うことができない。したがって最高精度
-** は18桁である。
-*/
-
-/* File scope variables */
-static double _pos1[32] = {
- 1.0e+17, /* + 0 */
- 1.0e+18, /* + 1 */
- 1.0e+19, /* + 2 */
- 1.0e+20, /* + 3 */
- 1.0e+21, /* + 4 */
- 1.0e+22, /* + 5 */
- 1.0e+23, /* + 6 */
- 1.0e+24, /* + 7 */
- 1.0e+25, /* + 8 */
- 1.0e+26, /* + 9 */
- 1.0e+27, /* +10 */
- 1.0e+28, /* +11 */
- 1.0e+29, /* +12 */
- 1.0e+30, /* +13 */
- 1.0e+31, /* +14 */
- 1.0e+32, /* +15 */
- 1.0e+33, /* +16 */
- 1.0e+34, /* +17 */
- 1.0e+35, /* +18 */
- 1.0e+36, /* +19 */
- 1.0e+37, /* +20 */
- 1.0e+38, /* +21 */
- 1.0e+39, /* +22 */
- 1.0e+40, /* +23 */
- 1.0e+41, /* +24 */
- 1.0e+42, /* +25 */
- 1.0e+43, /* +26 */
- 1.0e+44, /* +27 */
- 1.0e+45, /* +28 */
- 1.0e+46, /* +29 */
- 1.0e+47, /* +30 */
- 1.0e+48, /* +31 */
-};
-
-/* File scope variables */
-static double _neg1[32] = {
- 1.0e+17, /* - 0 */
- 1.0e+16, /* - 1 */
- 1.0e+15, /* - 2 */
- 1.0e+14, /* - 3 */
- 1.0e+13, /* - 4 */
- 1.0e+12, /* - 5 */
- 1.0e+11, /* - 6 */
- 1.0e+10, /* - 7 */
- 1.0e+9, /* - 8 */
- 1.0e+8, /* - 9 */
- 1.0e+7, /* -10 */
- 1.0e+6, /* -11 */
- 1.0e+5, /* -12 */
- 1.0e+4, /* -13 */
- 1.0e+3, /* -14 */
- 1.0e+2, /* -15 */
- 1.0e+1, /* -16 */
- 1.0e+0, /* -17 */
- 1.0e-1, /* -18 */
- 1.0e-2, /* -19 */
- 1.0e-3, /* -20 */
- 1.0e-4, /* -21 */
- 1.0e-5, /* -22 */
- 1.0e-6, /* -23 */
- 1.0e-7, /* -24 */
- 1.0e-8, /* -25 */
- 1.0e-9, /* -26 */
- 1.0e-10, /* -27 */
- 1.0e-11, /* -28 */
- 1.0e-12, /* -29 */
- 1.0e-13, /* -30 */
- 1.0e-14, /* -31 */
-};
-
-/* File scope variables */
-static double _pos2[10] = {
- 1.0e+0, /* 000 */
- 1.0e+32, /* 001 */
- 1.0e+64, /* 010 */
- 1.0e+96, /* 011 */
- 1.0e+128, /* 100 */
- 1.0e+160, /* 101 */
- 1.0e+192, /* 110 */
- 1.0e+224, /* 111 */
- 1.0e+256, /* 1000 */
- 1.0e+288, /* 1001 */
-};
-
-/* File scope variables */
-static double _neg2[10] = {
- 1.0e-0, /* 000 */
- 1.0e-32, /* 001 */
- 1.0e-64, /* 010 */
- 1.0e-96, /* 011 */
- 1.0e-128, /* 100 */
- 1.0e-160, /* 101 */
- 1.0e-192, /* 110 */
- 1.0e-224, /* 111 */
- 1.0e-256, /* 1000 */
- 1.0e-288, /* 1001 */
-};
-
-/* File scope functions */
-static int _cmpd (double x, double y)
-{
- unsigned long vx, vy, rc;
- unsigned long *x_ptr = (unsigned long *) &x;
- unsigned long *y_ptr = (unsigned long *) &y;
-
- /* xの指数ビットを取り出す */
- vx = x_ptr[0] & 0x7FF00000;
-
- /* yの指数ビットを取り出す */
- vy = y_ptr[0] & 0x7FF00000;
-
- /* 指数ビットだけで判断する */
- if ((rc = vy - vx) != 0)
- return rc;
-
- /* xの有効数字の上位ビットを取り出す */
- vx = x_ptr[0] & 0x000FFFFF;
-
- /* yの有効数字の上位ビットを取り出す */
- vy = y_ptr[0] & 0x000FFFFF;
-
- /* 上位ビットだけで判断する */
- if ((rc = vy - vx) != 0)
- return rc;
-
- /* xの有効数字の下位ビットを取り出す */
- vx = x_ptr[1];
-
- /* yの有効数字の下位ビットを取り出す */
- vy = y_ptr[1];
-
- /* 最終判断 */
- return vy - vx;
-}
-
-/* Functions */
-void _dtos18 (double x, int *decpt, int *sign, char *buffer)
-{
- short e2;
- int e, n;
-
- /* 基数2の指数を求める(バイアスなしの状態) */
- e2 = (((unsigned short *) &x)[0] & 0x7FF0U) >> 4;
-
- /* 指数が0の場合は±0.0チェック */
- if (e2 == 0) {
-
- unsigned long hi = ((unsigned long *) &x)[0] & 0xFFFFF;
- unsigned long lo = ((unsigned long *) &x)[1];
-
- /* 有効数字が全部0かどうか */
- if (hi == 0 && lo == 0) {
-
- /* 文字列を設定 */
- buffer[0] = '0';
-
- /* NULを設定 */
- buffer[1] = '\0';
-
- /* 小数点位置を計算 */
- *decpt = 1;
-
- /* 符号を計算 */
- /* *sign = hi & 0x80000000UL; */
- *sign = 0;
-
- /* 確定 */
- return;
-
- }
-
- }
-
- /* 2の指数にバイアスをかけてから10の指数を概算 (approx. log10(2)) */
- e = ((int) ((e2 - 1023) * 77)) >> 8;
-
- /* 指数が正の場合 */
- if (e >= 0) {
-
- /* 指数が32より小さい場合はテーブル1から */
- if (e < 32)
- x *= _neg1[e];
-
- /* 指数が32より大きい場合はテーブル1,2から */
- else
- x *= _neg1[e & 31] * _neg2[e >> 5];
-
- }
-
- /* 指数が負の場合 */
- else {
-
- /* 絶対値を計算 */
- n = -e;
-
- /* 絶対値が32より小さい場合はテーブル1から */
- if (n < 32)
- x *= _pos1[n];
-
- /* 絶対値が32より大きい場合はテーブル1,2から */
- else {
- x *= _pos1[n & 31];
- x *= _pos2[n >> 5];
- }
-
- }
-
- /* スケーリングしすぎた場合は戻す */
- if (_cmpd (1.0e+18, x) >= 0) {
- e++;
- x *= 1.0e-1;
- }
-
- /* スケーリングし足りない場合は追加 */
- else if (_cmpd (1.0e+17, x) < 0) {
- e--;
- x *= 1.0e+1;
- }
-
- /* 小数点位置を計算 */
- *decpt = e + 1;
-
- /* 符号を計算 */
- *sign = ((unsigned char *) &x)[0] & 0x80U;
-
- /* 文字列に変換 */
- _ulltoa ((unsigned long long) x, buffer);
-}
diff --git a/x68/_round.c b/x68/_round.c
deleted file mode 100644
index 761930fb8c..0000000000
--- a/x68/_round.c
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * PROJECT C Library, X68000 PROGRAMMING INTERFACE DEFINITION
- * --------------------------------------------------------------------
- * This file is written by the Project C Library Group, and completely
- * in public domain. You can freely use, copy, modify, and redistribute
- * the whole contents, without this notice.
- * --------------------------------------------------------------------
- * $Id$
- */
-/* changed 1997.2.2 by K.Okabe */
-
-/* System headers */
-#include <stdlib.h>
-#include <sys/xstdlib.h>
-
-/* Functions */
-int _round (char *top, char *cur, int undig)
-{
- char *ptr;
-
- /* 最後が5未満なら丸めは必要ない */
- if (undig < '5')
- return 0;
-
- /* ポインタ設定 */
- ptr = cur - 1;
-
- /* 先頭まで戻りながら丸め処理 */
- while (ptr >= top) {
-
- /* 繰り上がらなければそれで終わり */
- if (++(*ptr) <= '9')
- return 0;
-
- /* その桁を0に戻す */
- *ptr-- = '0';
-
- }
-
- /* 先頭を1にする */
- *++ptr = '1';
-
- /* 繰り上がりをしらせる */
- return 1;
-}
diff --git a/x68/fconvert.c b/x68/fconvert.c
deleted file mode 100644
index 9a0bc0e088..0000000000
--- a/x68/fconvert.c
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * PROJECT C Library, X68000 PROGRAMMING INTERFACE DEFINITION
- * --------------------------------------------------------------------
- * This file is written by the Project C Library Group, and completely
- * in public domain. You can freely use, copy, modify, and redistribute
- * the whole contents, without this notice.
- * --------------------------------------------------------------------
- * $Id$
- */
-/* changed 1997.2.3 by K.Okabe */
-
-/* System headers */
-#include <stdlib.h>
-#include <sys/xstdlib.h>
-
-/* Functions */
-char *fconvert (double x, int ndigit, int *decpt, int *sign, char *buffer)
-{
- int pos, n;
- char *src, *dst;
- char string[24];
- int figup;
-
- /* 18桁の文字列に変換 */
- _dtos18 (x, decpt, sign, string);
-
- /* コピー元アドレスを設定 */
- src = string;
-
- /* コピー先アドレスを設定 */
- dst = buffer;
-
- /* 小数点位置を得る */
- pos = *decpt;
-
- /* 小数点位置が負なら */
- if (pos < 0) {
-
- /* 埋める桁数を計算 */
- n = min (-pos, ndigit);
-
- /* 先頭を0で埋める */
- while (n-- > 0)
- *dst++ = '0';
-
- /* 小数点位置は0になる */
- *decpt = 0;
-
- }
-
- /* 残りのコピー桁数 */
- n = ndigit + pos;
-
- /* 格納先にコピー */
- while (n-- > 0) {
-
- /* 足りない部分は0で埋める */
- if (*src == '\0') {
- while (n-- >= 0)
- *dst++ = '0';
- break;
- }
-
- /* 変換文字列からコピー */
- *dst++ = *src++;
-
- }
-
- /* 丸める */
- *decpt += (figup = _round (buffer, dst, *src));
-
- /* 繰り上がりがあれば末尾に0を追加する */
- if (figup)
- *dst++ = '0';
-
- /* 終端に NUL を打つ */
- *dst = '\0';
-
- /* アドレスを返す */
- return buffer;
-}
diff --git a/x68/select.c b/x68/select.c
deleted file mode 100644
index b4bf464032..0000000000
--- a/x68/select.c
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * PROJECT C Library, X68000 PROGRAMMING INTERFACE DEFINITION
- * --------------------------------------------------------------------
- * This file is written by the Project C Library Group, and completely
- * in public domain. You can freely use, copy, modify, and redistribute
- * the whole contents, without this notice.
- * --------------------------------------------------------------------
- * $Id$
- */
-
-#ifndef __IOCS_INLINE__
-#define __IOCS_INLINE__
-#define __DOS_INLINE__
-#define __DOS_DOSCALL__
-#endif
-
-/* System headers */
-#include <errno.h>
-#include <fcntl.h>
-#include <string.h>
-#include <sys/dos.h>
-#include <sys/iocs.h>
-#include <sys/time.h>
-#include <sys/types.h>
-#if 0
-#include <sys/select.h>
-#include <sys/xsocket.h>
-#endif
-#include <sys/xunistd.h>
-
-/* Macros */
-#define XFD_ISSET(fd,fds) ((fds) && FD_ISSET ((fd), (fds)))
-#define isreadable(mode) ((mode) == O_RDONLY || (mode) == O_RDWR)
-#define iswritable(mode) ((mode) == O_WRONLY || (mode) == O_RDWR)
-#ifndef _POSIX_FD_SETSIZE
-#define _POSIX_FD_SETSIZE OPEN_MAX
-#endif
-
-/* Functions */
-int
-select (int fds, fd_set *rfds, fd_set *wfds, fd_set *efds, struct timeval *timeout)
-{
- fd_set oread, owrite, oexcept;
- int ticks, start;
- int nfds;
-
- if (fds > _POSIX_FD_SETSIZE)
- {
- errno = EINVAL;
- return -1;
- }
-
- FD_ZERO (&oread);
- FD_ZERO (&owrite);
- FD_ZERO (&oexcept);
-
- nfds = 0;
- ticks = -1;
-
- if (timeout)
- {
- ticks = timeout->tv_sec * 100 + timeout->tv_usec / 10000;
- if (ticks < 0)
- {
- errno = EINVAL;
- return -1;
- }
- }
-
- start = _iocs_ontime ();
- for (;;)
- {
- {
- int fd;
-
- for (fd = 0; fd < fds; fd++)
- {
- int accmode;
-
- if (_fddb[fd].inuse == _FD_NOTUSED)
- continue;
-
- accmode = _fddb[fd].oflag & O_ACCMODE;
-
- if (isatty (fd))
- {
- if (XFD_ISSET (fd, rfds) && isreadable (accmode) && _dos_k_keysns ())
- {
- FD_SET (fd, &oread);
- nfds++;
- }
-
- if (XFD_ISSET (fd, wfds) && iswritable (accmode))
- {
- FD_SET (fd, &owrite);
- nfds++;
- }
- }
-#if 0
- else if (_fddb[fd].sockno >= 0)
- {
- if (XFD_ISSET (fd, rfds) && _socklen (_fddb[fd].sockno, 0))
- {
- FD_SET (fd, &oread);
- nfds++;
- }
-
- if (XFD_ISSET (fd, wfds) /* && _socklen (_fddb[fd].sockno, 1) == 0 */)
- {
- FD_SET (fd, &owrite);
- nfds++;
- }
- }
-#endif
- else
- {
- if (XFD_ISSET (fd, rfds) && isreadable (accmode) && _dos_ioctrlis (fd))
- {
- FD_SET (fd, &oread);
- nfds++;
- }
-
- if (XFD_ISSET (fd, wfds) && iswritable (accmode) && _dos_ioctrlos (fd))
- {
- FD_SET (fd, &owrite);
- nfds++;
- }
- }
- }
- }
-
- {
- int rest;
-
- if ((rest = (_iocs_ontime () - start) % 8640000) < 0)
- rest += 8640000;
-
- if (nfds != 0)
- {
- if (ticks >= 0)
- {
- int left;
-
- if ((left = ticks - rest) < 0)
- left = 0;
-
- timeout->tv_sec = left / 100;
- timeout->tv_usec = (left % 100) * 10000;
- }
-
- if (rfds)
- *rfds = oread;
- if (wfds)
- *wfds = owrite;
- if (efds)
- *efds = oexcept;
-
- return nfds;
- }
-
- if (ticks >= 0 && rest > ticks)
- return 0;
- }
-
- _dos_change_pr ();
- }
-}