summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
author(no author) <(no author)@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>1999-12-20 20:48:49 +0000
committer(no author) <(no author)@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>1999-12-20 20:48:49 +0000
commit90bec5557a7d2a7a1ca87bad5f334688384f9b9e (patch)
treec4f1cb7553f0617f509f8a87facddfe7ecfbbb82
parent47f58037b610ded89a4bbbc73501733558e7734e (diff)
downloadruby-90bec5557a7d2a7a1ca87bad5f334688384f9b9e.tar.gz
This commit was manufactured by cvs2svn to create tag 'V1-1-1'.
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/tags/V1-1-1@594 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
-rw-r--r--.cvsignore17
-rw-r--r--COPYING340
-rw-r--r--ChangeLog5655
-rw-r--r--MANIFEST242
-rw-r--r--Makefile.in265
-rw-r--r--README151
-rw-r--r--README.EXT992
-rw-r--r--README.EXT.jp1176
-rw-r--r--README.jp196
-rw-r--r--ToDo77
-rw-r--r--array.c1550
-rw-r--r--bignum.c1324
-rw-r--r--class.c666
-rw-r--r--compar.c118
-rw-r--r--config.guess961
-rw-r--r--config.sub969
-rw-r--r--config_h.dj71
-rw-r--r--config_s.dj56
-rw-r--r--configure5010
-rw-r--r--configure.bat24
-rw-r--r--configure.in793
-rw-r--r--cygwin/GNUmakefile.in9
-rw-r--r--defines.h67
-rw-r--r--dir.c805
-rw-r--r--dln.c1724
-rw-r--r--dln.h30
-rw-r--r--dmyext.c4
-rw-r--r--enum.c385
-rw-r--r--env.h52
-rw-r--r--error.c1088
-rw-r--r--eval.c7730
-rw-r--r--ext/Setup15
-rw-r--r--ext/Setup.dj14
-rw-r--r--ext/Setup.emx16
-rw-r--r--ext/Setup.nt19
-rw-r--r--ext/Setup.x6812
-rw-r--r--ext/Win32API/MANIFEST7
-rw-r--r--ext/Win32API/Win32API.c237
-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/curses/MANIFEST7
-rw-r--r--ext/curses/curses.c850
-rw-r--r--ext/curses/depend1
-rw-r--r--ext/curses/extconf.rb23
-rw-r--r--ext/curses/hello.rb30
-rw-r--r--ext/curses/rain.rb76
-rw-r--r--ext/curses/view.rb91
-rw-r--r--ext/dbm/MANIFEST4
-rw-r--r--ext/dbm/dbm.c584
-rw-r--r--ext/dbm/depend1
-rw-r--r--ext/dbm/extconf.rb12
-rw-r--r--ext/etc/MANIFEST6
-rw-r--r--ext/etc/depend1
-rw-r--r--ext/etc/etc.c271
-rw-r--r--ext/etc/etc.txt72
-rw-r--r--ext/etc/etc.txt.jp72
-rw-r--r--ext/etc/extconf.rb31
-rw-r--r--ext/extmk.rb.in680
-rw-r--r--ext/fcntl/MANIFEST3
-rw-r--r--ext/fcntl/depend1
-rw-r--r--ext/fcntl/fcntl.c107
-rw-r--r--ext/gdbm/MANIFEST5
-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.c594
-rw-r--r--ext/md5/MANIFEST7
-rw-r--r--ext/md5/depend2
-rw-r--r--ext/md5/md5.h86
-rw-r--r--ext/md5/md5.txt38
-rw-r--r--ext/md5/md5.txt.jp37
-rw-r--r--ext/md5/md5c.c337
-rw-r--r--ext/md5/md5init.c114
-rw-r--r--ext/mswin32_extmk.rb41
-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.c196
-rw-r--r--ext/nkf/nkf1.7/nkf.c1900
-rw-r--r--ext/nkf/test.rb318
-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.jp21
-rw-r--r--ext/pty/README.jp89
-rw-r--r--ext/pty/depend1
-rw-r--r--ext/pty/expect_sample.rb56
-rw-r--r--ext/pty/extconf.rb10
-rw-r--r--ext/pty/lib/expect.rb36
-rw-r--r--ext/pty/pty.c497
-rw-r--r--ext/pty/script.rb38
-rw-r--r--ext/pty/shl.rb96
-rw-r--r--ext/readline/MANIFEST5
-rw-r--r--ext/readline/README55
-rw-r--r--ext/readline/depend1
-rw-r--r--ext/readline/extconf.rb11
-rw-r--r--ext/readline/readline.c421
-rw-r--r--ext/sdbm/MANIFEST6
-rw-r--r--ext/sdbm/_sdbm.c977
-rw-r--r--ext/sdbm/depend2
-rw-r--r--ext/sdbm/extconf.rb3
-rw-r--r--ext/sdbm/init.c584
-rw-r--r--ext/sdbm/sdbm.h84
-rw-r--r--ext/socket/MANIFEST8
-rw-r--r--ext/socket/addrinfo.h172
-rw-r--r--ext/socket/depend3
-rw-r--r--ext/socket/extconf.rb287
-rw-r--r--ext/socket/getaddrinfo.c675
-rw-r--r--ext/socket/getnameinfo.c254
-rw-r--r--ext/socket/socket.c2214
-rw-r--r--ext/socket/sockport.h43
-rw-r--r--ext/tcltklib/MANIFEST15
-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/depend1
-rw-r--r--ext/tcltklib/extconf.rb49
-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/tcltklib.c521
-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/tk.rb2470
-rw-r--r--ext/tk/lib/tkafter.rb296
-rw-r--r--ext/tk/lib/tkbgerror.rb17
-rw-r--r--ext/tk/lib/tkcanvas.rb814
-rw-r--r--ext/tk/lib/tkclass.rb38
-rw-r--r--ext/tk/lib/tkdialog.rb141
-rw-r--r--ext/tk/lib/tkentry.rb73
-rw-r--r--ext/tk/lib/tkfont.rb966
-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.rb903
-rw-r--r--ext/tk/lib/tkvirtevent.rb66
-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.c2095
-rw-r--r--gc.c1220
-rw-r--r--hash.c1527
-rw-r--r--inits.c80
-rw-r--r--install-sh0
-rw-r--r--instruby.rb91
-rw-r--r--intern.h340
-rw-r--r--io.c3379
-rw-r--r--keywords42
-rw-r--r--lex.c132
-rw-r--r--lib/English.rb28
-rw-r--r--lib/Env.rb31
-rw-r--r--lib/README48
-rw-r--r--lib/base64.rb29
-rw-r--r--lib/cgi-lib.rb272
-rw-r--r--lib/cgi.rb1984
-rw-r--r--lib/cgi/session.rb157
-rw-r--r--lib/complex.rb498
-rw-r--r--lib/date.rb258
-rw-r--r--lib/date2.rb346
-rw-r--r--lib/debug.rb399
-rw-r--r--lib/delegate.rb120
-rw-r--r--lib/e2mmap.rb196
-rw-r--r--lib/eregex.rb36
-rw-r--r--lib/final.rb41
-rw-r--r--lib/finalize.rb201
-rw-r--r--lib/find.rb39
-rw-r--r--lib/ftools.rb182
-rw-r--r--lib/ftplib.rb629
-rw-r--r--lib/getoptlong.rb473
-rw-r--r--lib/getopts.rb141
-rw-r--r--lib/importenv.rb32
-rw-r--r--lib/jcode.rb206
-rw-r--r--lib/mailread.rb48
-rw-r--r--lib/mathn.rb309
-rw-r--r--lib/matrix.rb1022
-rw-r--r--lib/mkmf.rb474
-rw-r--r--lib/monitor.rb229
-rw-r--r--lib/mutex_m.rb111
-rw-r--r--lib/observer.rb42
-rw-r--r--lib/open3.rb55
-rw-r--r--lib/ostruct.rb55
-rw-r--r--lib/parsearg.rb83
-rw-r--r--lib/parsedate.rb93
-rw-r--r--lib/ping.rb62
-rw-r--r--lib/profile.rb55
-rw-r--r--lib/pstore.rb138
-rw-r--r--lib/rational.rb390
-rw-r--r--lib/readbytes.rb36
-rw-r--r--lib/shellwords.rb46
-rw-r--r--lib/singleton.rb43
-rw-r--r--lib/sync.rb313
-rw-r--r--lib/telnet.rb696
-rw-r--r--lib/tempfile.rb94
-rw-r--r--lib/thread.rb233
-rw-r--r--lib/thwait.rb133
-rw-r--r--lib/timeout.rb42
-rw-r--r--lib/tracer.rb163
-rw-r--r--lib/weakref.rb75
-rw-r--r--main.c41
-rw-r--r--marshal.c929
-rw-r--r--math.c145
-rw-r--r--misc/README5
-rw-r--r--misc/inf-ruby.el325
-rw-r--r--misc/ruby-mode.el721
-rw-r--r--misc/rubydb2x.el104
-rw-r--r--misc/rubydb3x.el115
-rw-r--r--missing/alloca.c189
-rw-r--r--missing/crypt.c276
-rw-r--r--missing/dir.h63
-rw-r--r--missing/dup2.c61
-rw-r--r--missing/file.h31
-rw-r--r--missing/finite.c6
-rw-r--r--missing/flock.c90
-rw-r--r--missing/isinf.c44
-rw-r--r--missing/isnan.c16
-rw-r--r--missing/memcmp.c21
-rw-r--r--missing/memmove.c24
-rw-r--r--missing/mkdir.c104
-rw-r--r--missing/os2.c111
-rw-r--r--missing/strcasecmp.c12
-rw-r--r--missing/strchr.c45
-rw-r--r--missing/strdup.c25
-rw-r--r--missing/strerror.c19
-rw-r--r--missing/strftime.c894
-rw-r--r--missing/strncasecmp.c18
-rw-r--r--missing/strstr.c73
-rw-r--r--missing/strtod.c266
-rw-r--r--missing/strtol.c84
-rw-r--r--missing/strtoul.c184
-rw-r--r--missing/vsnprintf.c1128
-rw-r--r--missing/x68.c36
-rw-r--r--mkconfig.rb98
-rw-r--r--node.h344
-rw-r--r--numeric.c1537
-rw-r--r--object.c1116
-rw-r--r--pack.c1691
-rw-r--r--parse.y4619
-rw-r--r--prec.c81
-rw-r--r--process.c1092
-rw-r--r--random.c152
-rw-r--r--range.c349
-rw-r--r--re.c1324
-rw-r--r--re.h43
-rw-r--r--regex.c4334
-rw-r--r--regex.h221
-rw-r--r--ruby.1291
-rw-r--r--ruby.c1009
-rw-r--r--ruby.h562
-rw-r--r--rubyio.h63
-rw-r--r--rubysig.h50
-rw-r--r--rubytest.rb37
-rw-r--r--sample/README52
-rw-r--r--sample/biorhythm.rb138
-rw-r--r--sample/cal.rb119
-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/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.pl10
-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/io.rb44
-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.rb14
-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/rbc.rb1015
-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/rename.rb297
-rw-r--r--sample/sieve.rb14
-rw-r--r--sample/svr.rb32
-rw-r--r--sample/test.rb1157
-rw-r--r--sample/time.rb8
-rw-r--r--sample/trojan.rb15
-rw-r--r--sample/tsvr.rb23
-rw-r--r--sample/uumerge.rb43
-rw-r--r--signal.c646
-rw-r--r--sprintf.c686
-rw-r--r--st.c500
-rw-r--r--st.h46
-rw-r--r--string.c2706
-rw-r--r--struct.c592
-rw-r--r--time.c1042
-rw-r--r--top.sed68
-rw-r--r--util.c811
-rw-r--r--util.h50
-rw-r--r--variable.c1305
-rw-r--r--version.c45
-rw-r--r--version.h4
-rw-r--r--win32/Makefile270
-rw-r--r--win32/config.h53
-rw-r--r--win32/config.status65
-rwxr-xr-xwin32/ntsetup.bat8
-rw-r--r--win32/ruby.def574
-rw-r--r--win32/win32.c2340
-rw-r--r--win32/win32.h395
-rw-r--r--x68/_dtos18.c250
-rw-r--r--x68/_round.c45
-rw-r--r--x68/fconvert.c81
-rw-r--r--x68/select.c167
340 files changed, 0 insertions, 117821 deletions
diff --git a/.cvsignore b/.cvsignore
deleted file mode 100644
index c1bdd084b3..0000000000
--- a/.cvsignore
+++ /dev/null
@@ -1,17 +0,0 @@
-parse.c
-newver.rb
-ruby
-miniruby
-README.fat-patch
-config.cache
-config.h
-config.log
-config.status
-Makefile
-ppack
-archive
-*.orig
-*.rej
-*.bak
-*.sav
-*~
diff --git a/COPYING b/COPYING
deleted file mode 100644
index eeb586b392..0000000000
--- a/COPYING
+++ /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) 19yy <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) 19yy 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/ChangeLog b/ChangeLog
deleted file mode 100644
index 1df3c184a1..0000000000
--- a/ChangeLog
+++ /dev/null
@@ -1,5655 +0,0 @@
-Mon Dec 13 15:15:31 1999 Yukihiro Matsumoto <matz@netlab.co.jp>
-
- * regex.c (re_adjust_startpos): separate startpos adjustment
- because of major performace drawback.
-
- * class.c (rb_singleton_class): tainted status of the singleton
- class must synchronize 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): recurseve 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 (shared variables).
-
- * 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,
- becase 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 systems'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.
-
-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 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 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.
-
-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 ommited for return statement.
-
-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 optimaize 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 granteed 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 maintaind 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 retrun 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 unsed 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 safty 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 happend 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 contant 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/sockt/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): aboid 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 shuould 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): intialize 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 preverse 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 ommited.
-
-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 superclasse method with the value from
- optinal 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 expandion moved to find_file.
-
- * eval.c (find_file): tilde expandion 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): nagative length raises exception now.
-
- * array.c (beg_len): if end == -1, it points end of the array.
-
- * array.c (rb_ary_subseq): nagative 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 shoule not be
- ommited 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 ommited.
-
-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
- insinf, 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): accessng $~ 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 supprt
- 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 realoc 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 classs. 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 iff __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__ iff 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 supprt 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 supprt 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
- splitted 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 variabls 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): comsume at leaset 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 bwetween 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
- comsuming 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 unkown 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): forwading 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 temination.
-
- * 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): imcomplete 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 baes 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 extention 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 multipe
- 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 extention 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-resitering 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 extentions 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 seuid.
-
- * 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 occured 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 initilialized.
-
- * 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 inifinite 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_anscestors): 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 (asignable): 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 extention.
-
- * 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/MANIFEST b/MANIFEST
deleted file mode 100644
index d67346f3ac..0000000000
--- a/MANIFEST
+++ /dev/null
@@ -1,242 +0,0 @@
-COPYING
-COPYING.LIB
-ChangeLog
-MANIFEST
-Makefile.in
-README
-README.jp
-README.EXT
-README.EXT.jp
-ToDo
-array.c
-bignum.c
-class.c
-compar.c
-configure
-configure.bat
-configure.in
-config_h.dj
-config_s.dj
-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
-top.sed
-util.h
-util.c
-variable.c
-version.c
-version.h
-beos/ruby.def.in
-cygwin/GNUmakefile.in
-ext/Setup
-ext/Setup.dj
-ext/Setup.emx
-ext/Setup.x68
-ext/aix_mksym.rb
-ext/mswin32_extmk.rb
-ext/extmk.rb.in
-lib/English.rb
-lib/Env.rb
-lib/README
-lib/base64.rb
-lib/cgi.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/ftplib.rb
-lib/ftools.rb
-lib/getopts.rb
-lib/getoptlong.rb
-lib/importenv.rb
-lib/irb/completion.rb
-lib/irb/frame.rb
-lib/irb/input-method.rb
-lib/irb/loader.rb
-lib/irb/main.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-binding-2.rb
-lib/irb/workspace-binding.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/pop.rb
-lib/net/session.rb
-lib/net/smtp.rb
-lib/observer.rb
-lib/open3.rb
-lib/ostruct.rb
-lib/parsearg.rb
-lib/parsedate.rb
-lib/ping.rb
-lib/profile.rb
-lib/pstore.rb
-lib/rational.rb
-lib/readbytes.rb
-lib/shellwords.rb
-lib/singleton.rb
-lib/sync.rb
-lib/telnet.rb
-lib/tempfile.rb
-lib/thread.rb
-lib/thwait.rb
-lib/timeout.rb
-lib/tracer.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/dir.h
-missing/dup2.c
-missing/file.h
-missing/finite.c
-missing/flock.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/strdup.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/rd2html.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
-win32/config.h
-win32/config.status
-win32/ntsetup.bat
-win32/ruby.def
-win32/win32.c
-win32/win32.h
-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 5b66caa96b..0000000000
--- a/Makefile.in
+++ /dev/null
@@ -1,265 +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@
-
-RUBY_INSTALL_NAME=@RUBY_INSTALL_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) rbconfig.rb
- @./miniruby$(EXEEXT) -Xext 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) $(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@
- $(LDSHARED) $(DLDFLAGS) $(SOLIBS) $(OBJS) dmyext.@OBJEXT@ -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$(EXEEXT) $(srcdir)/instruby.rb $(DESTDIR)
-
-clean:; @rm -f $(OBJS) $(LIBRUBY_A) $(LIBRUBY_SO) $(LIBRUBY_ALIASES) $(MAINOBJ) rbconfig.rb
- @rm -f ext/extinit.c ext/extinit.@OBJEXT@ dmyext.@OBJEXT@
- @-./miniruby$(EXEEXT) -Xext extmk.rb clean 2> /dev/null || true
- @rm -f $(PROGRAM) miniruby$(EXEEXT)
-
-distclean: clean
- @rm -f Makefile ext/extmk.rb config.h
- @rm -f ext/config.cache config.cache config.log config.status
- @rm -f *~ core *.core gmon.out y.tab.c y.output ruby.imp
-
-realclean: distclean
- @rm -f parse.c
- @rm -f lex.c
-
-test: miniruby$(EXEEXT)
- @./miniruby$(EXEEXT) $(srcdir)/rubytest.rb
-
-rbconfig.rb: miniruby$(EXEEXT)
- @./miniruby$(EXEEXT) $(srcdir)/mkconfig.rb rbconfig.rb
-
-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
-
-strdup.@OBJEXT@: @srcdir@/missing/strdup.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c @srcdir@/missing/strdup.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
-
-nt.@OBJEXT@: @srcdir@/missing/nt.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c @srcdir@/missing/nt.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
-
-# 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
-bignum.@OBJEXT@: bignum.c ruby.h config.h defines.h intern.h
-class.@OBJEXT@: class.c ruby.h config.h defines.h intern.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
-error.@OBJEXT@: error.c ruby.h config.h defines.h intern.h env.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
-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
-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 util.h
-ruby.@OBJEXT@: ruby.c ruby.h config.h defines.h intern.h dln.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 5ed6015be0..0000000000
--- a/README
+++ /dev/null
@@ -1,151 +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.netlab.co.jp/pub/lang/ruby/
-
-You can get it by anonymous CVS. How to check out is:
-
- $ cvs -d :pserver:anonymous@cvs.netlab.co.jp:/home/cvs login
- (Logging in to anonymous@cvs.netlab.co.jp)
- CVS password: guest
- $ cvs -d :pserver:anonymous@cvs.netlab.co.jp:/home/cvs checkout ruby
-
-* 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@netlab.co.jp>.
-
-* How to compile and install
-
-This is what you need to do to compile and install Ruby:
-
- 1. Run ./configure, which will generate config.h and Makefile.
-
- 2. Edit defines.h if you need. Probably this step will not need.
-
- 3. 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.
-
- 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'
-
- 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
-
-Ruby is copyrighted free software by Yukihiro Matsumoto <matz@netlab.co.jp>.
-You can redistribute it and/or modify it under either the terms of the GPL
-(see COPYING file), 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) rename any non-standard executables so the names do not conflict
- with standard executables, which must also be provided.
-
- d) make other distribution arrangements with the author.
-
- 3. You may distribute the software in object code or executable
- form, provided that you do at least ONE of the following:
-
- a) distribute the executables 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 executables 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 this terms.
- They are gc.c(partly), utils.c(partly), regex.[ch], st.[ch] and some
- files under the ./missing directory. See each file for the copying
- condition.
-
- 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 MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
- PURPOSE.
-
-* Ruby home-page
-
-The URL of the Ruby home-page is:
-
- http://www.ruby-lang.org/
-
-* The Author
-
-Feel free to send comments and bug reports to the author. Here is the
-author's latest mail address:
-
- matz@netlab.co.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 68726b793d..0000000000
--- a/README.EXT
+++ /dev/null
@@ -1,992 +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
-
-Otherwise, there are several other types used internally:
-
- T_ICLASS
- T_MATCH
- 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 */
- Fail("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(char *ptr, int len)
-
- Creates a new Ruby string.
-
- rb_str_new2(char *ptr)
-
- Creates a new Ruby string from C string. This is equivalent to
- rb_str_new(ptr, strlen(ptr)).
-
- rb_str_cat(VALUE str, char *ptr, int 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(int len)
-
- Creates an array with no element, with allocating internal buffer
- for len elements.
-
- rb_ary_new3(int n, ...)
-
- Creates an n-elements array from arguments.
-
- rb_ary_new4(int 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)
- rb_ary_entry(VALUE ary, int idx)
-
- 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(char *name, VALUE super)
- VALUE rb_define_module(char *name)
-
-These functions return the newly created class or module. You may
-want to save this reference into the variable to use later.
-
-2.1.2 Method/singleton method definition
-
-To define methods or singleton methods, use functions below:
-
- void rb_define_method(VALUE klass, char *name,
- VALUE (*func)(), int argc)
-
- void rb_define_singleton_method(VALUE object, 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, 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, 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(char *name, VALUE (*func)(), int argc)
-
-
-2.1.3 Constant definition
-
-We have 2 functions to define constants:
-
- void rb_define_const(VALUE klass, char *name, VALUE val)
- void rb_define_global_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(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(char *name)
-
-In addition, the symbols for one character operators (e.g +) is the
-code for that character.
-
-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(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(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(char *name, VALUE *var,
- VALUE (*getter)(), VALUE (*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(char *name,
- VALUE (*getter)(), VALUE (*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 class 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): 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
- fnmatch.c
- glob.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
- math.c
- numeric.c
- pack.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(char *name, VALUE super)
-
-Defines new Ruby class as subclass of super.
-
- VALUE rb_define_class_under(VALUE module, char *name, VALUE super)
-
-Creates new Ruby class as subclass of super, under the module's
-namespace.
-
- VALUE rb_define_module(char *name)
-
-Defines new Ruby module.
-
- VALUE rb_define_module_under(VALUE module, 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(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(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(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(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, char *name, VALUE val)
-
-Defines a new constant under the class/module.
-
- void rb_define_global_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, 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, 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, char *name, VALUE (*func)(), int argc)
-
-Defines a singleton method. Arguments are same as rb_define_method().
-
- rb_scan_args(int argc, VALUE *argv, 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(char *str)
-
-Compiles and executes the string as Ruby program.
-
- ID rb_intern(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 reponds to the message specified by id.
-
-** Instance Variables
-
- VALUE rb_iv_get(VALUE obj, 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, 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(char *fmt, ...)
-
-Prints warning message according to the printf-like format.
-
- void rb_warning(char *fmt, ...)
-
-Prints warning message according to the printf-like format, if
-$VERBOSE is true.
-
- void rb_raise(VALUE exception, char *fmt, ...)
-
-Raises an exception of class exception. The fmt is the format string
-just like printf().
-
- void rb_fatal(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(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 B. 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.
-
- have_func(func)
-
-Checks whether func exists. 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 for the header files. 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.
-
-/*
- * Local variables:
- * fill-column: 70
- * end:
- */
diff --git a/README.EXT.jp b/README.EXT.jp
deleted file mode 100644
index 6a049d0222..0000000000
--- a/README.EXT.jp
+++ /dev/null
@@ -1,1176 +0,0 @@
-.\" README.EXT - -*- 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_ICLASS
- T_MATCH
- 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:
- /* 例外を発生させる */
- TypeError("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(char *ptr, int len)
-
- 新しいRubyの文字列を生成する.
-
- rb_str_new2(char *ptr)
-
- Cの文字列からRubyの文字列を生成する.この関数の機能は
- rb_str_new(ptr, strlen(ptr))と同等である.
-
- rb_str_cat(VALUE str, char *ptr, int len)
-
- Rubyの文字列strにlenバイトの文字列ptrを追加する.
-
- 配列に対する関数
-
- rb_ary_new()
-
- 要素が0の配列を生成する.
-
- rb_ary_new2(int len)
-
- 要素が0の配列を生成する.len要素分の領域をあらかじめ割り
- 当てておく.
-
- rb_ary_new3(int n, ...)
-
- 引数で指定したn要素を含む配列を生成する.
-
- rb_ary_new4(int 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)
- rb_ary_entry(VALUE ary, int idx)
-
- Arrayの同名のメソッドと同じ働きをする関数.第1引数は必ず
- 配列でなければならない.
-
-2.Rubyの機能を使う
-
-原理的にRubyで書けることはCでも書けます.RubyそのものがCで記
-述されているんですから,当然といえば当然なんですけど.ここで
-はRubyの拡張に使うことが多いだろうと予測される機能を中心に紹
-介します.
-
-2.1 Rubyに機能を追加する
-
-Rubyで提供されている関数を使えばRubyインタプリタに新しい機能
-を追加することができます.Rubyでは以下の機能を追加する関数が
-提供されています.
-
- * クラス,モジュール
- * メソッド,特異メソッドなど
- * 定数
-
-では順に紹介します.
-
-2.1.1 クラス/モジュール定義
-
-クラスやモジュールを定義するためには,以下の関数を使います.
-
- VALUE rb_define_class(char *name, VALUE super)
- VALUE rb_define_module(char *name)
-
-これらの関数は新しく定義されたクラスやモジュールを返します.
-メソッドや定数の定義にこれらの値が必要なので,ほとんどの場合
-は戻り値を変数に格納しておく必要があるでしょう.
-
-クラスやモジュールを他のクラスの内部にネストして定義する時に
-は以下の関数を使います.
-
- VALUE rb_define_class_under(VALUE outer, char *name, VALUE super)
- VALUE rb_define_module_under(VALUE outer, char *name)
-
-2.1.2 メソッド/特異メソッド定義
-
-メソッドや特異メソッドを定義するには以下の関数を使います.
-
- void rb_define_method(VALUE class, char *name,
- VALUE (*func)(), int argc)
-
- void rb_define_singleton_method(VALUE object, 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 class, char *name,
- VALUE (*func)(), int argc)
-
-privateメソッドとは関数形式でしか呼び出すことの出来ないメソッ
-ドです.
-
-もうひとつはモジュール関数を定義するものです.モジュール関数
-とはモジュールの特異メソッドであり,同時にprivateメソッドで
-もあるものです.例をあげるとMathモジュールのsqrt()などがあげ
-られます.このメソッドは
-
- Math.sqrt(4)
-
-という形式でも
-
- include Math
- sqrt(4)
-
-という形式でも使えます.モジュール関数を定義する関数は以下の
-通りです.
-
- void rb_define_module_function(VALUE module, char *name,
- VALUE (*func)(), int argc)
-
-関数的メソッド(Kernelモジュールのprivate method)を定義するた
-めの関数は以下の通りです.
-
- void rb_define_global_function(char *name, VALUE (*func)(), int argc)
-
-
-2.1.3 定数定義
-
-拡張ライブラリが必要な定数はあらかじめ定義しておいた方が良い
-でしょう.定数を定義する関数は二つあります.
-
- void rb_define_const(VALUE class, char *name, VALUE val)
- void rb_define_global_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(char *str)
-
-この評価は現在の環境で行われます.つまり,現在のローカル変数
-などを受け継ぎます.
-
-2.2.2 IDまたはシンボル
-
-Cから文字列を経由せずにRubyのメソッドを呼び出すこともできま
-す.その前に,Rubyインタプリタ内でメソッドや変数名を指定する
-時に使われているIDについて説明しておきましょう.
-
-IDとは変数名,メソッド名を表す整数です.Rubyの中では
-
- :識別子
-
-でアクセスできます.Cからこの整数を得るためには関数
-
- rb_intern(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(char *name, VALUE *var)
-
-この関数はRubyとCとで共有する大域変数を定義します.変数名が
-`$'で始まらない時には自動的に追加されます.この変数の値を変
-更すると自動的にRubyの対応する変数の値も変わります.
-
-またRuby側からは更新できない変数もあります.このread onlyの
-変数は以下の関数で定義します.
-
- void rb_define_readonly_variable(char *name, VALUE *var)
-
-これら変数の他にhookをつけた大域変数を定義できます.hook付き
-の大域変数は以下の関数を用いて定義します.hook付き大域変数の
-値の参照や設定はhookで行う必要があります.
-
- void rb_define_hooked_variable(char *name, VALUE *var,
- VALUE (*getter)(), VALUE (*setter)())
-
-この関数はCの関数によってhookのつけられた大域変数を定義しま
-す.変数が参照された時には関数getterが,変数に値がセットされ
-た時には関数setterが呼ばれる.hookを指定しない場合はgetterや
-setterに0を指定します.
-
-# getterもsetterも0ならばrb_define_variable()と同じになる.
-
-それから,Cの関数によって実現されるRubyの大域変数を定義する
-関数があります.
-
- void rb_define_virtual_variable(char *name,
- VALUE (*getter)(), VALUE (*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(class,mark,free,ptr)
-
-このマクロの戻り値は生成されたDataオブジェクトです.
-
-classはこのDataオブジェクトのクラスです.ptrはカプセル化する
-Cの構造体へのポインタです.markはこの構造体がRubyのオブジェ
-クトへの参照がある時に使う関数です.そのような参照を含まない
-時には0を指定します.
-
-# そのような参照は勧められません.
-
-freeはこの構造体がもう不要になった時に呼ばれる関数です.この
-関数がガーベージコレクタから呼ばれます.
-
-Cの構造体の割当とDataオブジェクトの生成を同時に行うマクロと
-して以下のものが提供されています.
-
- Data_Make_Struct(class, type, mark, free, sval)
-
-このマクロの戻り値は生成されたDataオブジェクトです.
-
-class, 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) 設計する
-
-まあ,当然なんですけど,どういう機能を実現するかどうかまず設
-計する必要があります.どんなクラスをつくるか,そのクラスには
-どんなメソッドがあるか,クラスが提供する定数などについて設計
-します.dbmクラスについてはext/dbm.docを参照してください.
-
-(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(class,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, class)
- int argc;
- VALUE *argv;
- VALUE class;
-{
- :
- 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): 関数の存在チェック
- 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
- fnmatch.c
- glob.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
- 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 class, void (*mark)(), void (*free)(), void *sval)
-
- Cの任意のポインタをカプセル化したRubyオブジェクトを返す.こ
- のポインタがRubyからアクセスされなくなった時,freeで指定した
- 関数が呼ばれる.また,このポインタの指すデータが他のRubyオブ
- ジェクトを指している場合,markに指定する関数でマークする必要
- がある.
-
-Data_Make_Struct(class, 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(char *name, VALUE super)
-
- superのサブクラスとして新しいRubyクラスを定義する.
-
-VALUE rb_define_class_under(VALUE module, char *name, VALUE super)
-
- superのサブクラスとして新しいRubyクラスを定義し,moduleの
- 定数として定義する.
-
-VALUE rb_define_module(char *name)
-
- 新しいRubyモジュールを定義する.
-
-VALUE rb_define_module_under(VALUE module, char *name, VALUE super)
-
- 新しいRubyモジュールを定義し,moduleの定数として定義する.
-
-void rb_include_module(VALUE class, VALUE module)
-
- モジュールをインクルードする.classがすでにmoduleをインク
- ルードしている時には何もしない(多重インクルードの禁止).
-
-void rb_extend_object(VALUE object, VALUE module)
-
- オブジェクトをモジュール(で定義されているメソッド)で拡張する.
-
-** 大域変数定義
-
-void rb_define_variable(char *name, VALUE *var)
-
- RubyとCとで共有するグローバル変数を定義する.変数名が`$'で
- 始まらない時には自動的に追加される.nameとしてRubyの識別子
- として許されない文字(例えば` ')を含む場合にはRubyプログラ
- ムからは見えなくなる.
-
-void rb_define_readonly_variable(char *name, VALUE *var)
-
- RubyとCとで共有するread onlyのグローバル変数を定義する.
- read onlyであること以外はrb_define_variable()と同じ.
-
-void rb_define_virtual_variable(char *name,
- VALUE (*getter)(), VALUE (*setter)())
-
- 関数によって実現されるRuby変数を定義する.変数が参照された
- 時にはgetterが,変数に値がセットされた時にはsetterが呼ばれ
- る.
-
-void rb_define_hooked_variable(char *name, VALUE *var,
- VALUE (*getter)(), VALUE (*setter)())
-
- 関数によってhookのつけられたグローバル変数を定義する.変数
- が参照された時にはgetterが,関数に値がセットされた時には
- setterが呼ばれる.getterやsetterに0を指定した時にはhookを
- 指定しないのと同じ事になる.
-
-void rb_global_variable(VALUE *var)
-
- GCのため,Rubyプログラムからはアクセスされないが, Rubyオブ
- ジェクトを含む大域変数をマークする.
-
-** 定数
-
-void rb_define_const(VALUE klass, char *name, VALUE val)
-
- 定数を定義する.
-
-void rb_define_global_const(char *name, VALUE val)
-
- 大域定数を定義する.
-
- rb_define_const(cKernal, name, val)
-
- と同じ意味.
-
-** メソッド定義
-
-rb_define_method(VALUE class, 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 class, char *name, VALUE (*func)(), int argc)
-
- privateメソッドを定義する.引数はrb_define_method()と同じ.
-
-rb_define_singleton_method(VALUE class, char *name, VALUE (*func)(), int argc)
-
- 特異メソッドを定義する.引数はrb_define_method()と同じ.
-
-rb_scan_args(int argc, VALUE *argv, 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(char *str)
-
- 文字列をRubyスクリプトとしてコンパイル・実行する.
-
-ID rb_intern(char *name)
-
- 文字列に対応するIDを返す.
-
-char *rb_id2name(ID id)
-
- IDに対応する文字列を返す(デバッグ用).
-
-char *rb_class2name(VALUE class)
-
- classの名前を返す(デバッグ用).classが名前を持たない時には,
- 祖先を遡って名前を持つクラスの名前を返す.
-
-int rb_respond_to(VALUE obj, ID id)
-
- objがidで示されるメソッドを持つかどうかを返す。
-
-** インスタンス変数
-
-VALUE rb_iv_get(VALUE obj, char *name)
-
- objのインスタンス変数の値を得る.`@'で始まらないインスタン
- ス変数は Rubyプログラムからアクセスできない「隠れた」イン
- スタンス変数になる.定数は大文字の名前を持つクラス(または
- モジュール)のインスタンス変数として実装されている.
-
-VALUE rb_iv_set(VALUE obj, char *name, VALUE val)
-
- objのインスタンス変数をvalにセットする.
-
-** 制御構造
-
-VALUE rb_iterate(VALUE (*func1)(), void *arg1, VALUE (*func2)(), void *arg2)
-
- func2をブロックとして設定し, func1をイテレータとして呼ぶ.
- func1には arg1が引数として渡され, func2には第1引数にイテレー
- タから与えられた値, 第2引数にarg2が渡される.
-
-VALUE rb_yield(VALUE val)
-
- valを値としてイテレータブロックを呼び出す.
-
-VALUE rb_rescue(VALUE (*func1)(), void *arg1, VALUE (*func2)(), void *arg2)
-
- 関数func1をarg1を引数に呼び出す.func1の実行中に例外が発生
- した時には func2をarg2を引数として呼ぶ.戻り値は例外が発生
- しなかった時はfunc1の戻り値, 例外が発生した時にはfunc2の戻
- り値である.
-
-VALUE rb_ensure(VALUE (*func1)(), void *arg1, void (*func2)(), void *arg2)
-
- 関数func1をarg1を引数として実行し, 実行終了後(たとえ例外が
- 発生しても) func2をarg2を引数として実行する.戻り値はfunc1
- の戻り値である(例外が発生した時は戻らない).
-
-** 例外・エラー
-
-void rb_warning(char *fmt, ...)
-
- rb_verbose時に標準エラー出力に警告情報を表示する.引数は
- printf()と同じ.
-
-void rb_raise(rb_eRuntimeError, char *fmt, ...)
-
- RuntimeError例外を発生させる.引数はprintf()と同じ.
-
-void rb_raise(VALUE exception, char *fmt, ...)
-
- exceptionで指定した例外を発生させる.fmt以下の引数は
- printf()と同じ.
-
-void rb_fatal(char *fmt, ...)
-
- 致命的例外を発生させる.通常の例外処理は行なわれず, インター
- プリタが終了する(ただしensureで指定されたコードは終了前に
- 実行される).
-
-void rb_bug(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 B. extconf.rbで使える関数たち
-
-extconf.rbの中では利用可能なコンパイル条件チェックの関数は以
-下の通りである.
-
-have_library(lib, func)
-
- 関数funcを定義しているライブラリlibの存在をチェックする.
- ライブラリが存在する時,trueを返す.
-
-find_library(lib, func, path...)
-
- 関数funcを定義しているライブラリlibの存在を -Lpath を追加
- しながらチェックする.ライブラリが見付かった時,trueを返す.
- 結果をキャッシュしない.
-
-have_func(func)
-
- 関数funcの存在をチェックする.funcが標準ではリンクされない
- ライブラリ内のものである時には先にhave_libraryでそのライブ
- ラリをチェックしておく事.関数が存在する時trueを返す.
-
-have_header(header)
-
- ヘッダファイルの存在をチェックする.ヘッダファイルが存在す
- る時trueを返す.
-
-find_header(header)
-
- ヘッダファイルの存在を -Ipath を追加しながらチェックする.
- ヘッダファイルが見付かった時trueを返す.結果をキャッシュし
- ない.
-
-create_makefile(target)
-
- 拡張ライブラリ用のMakefileを生成する.この関数を呼ばなけれ
- ばそのライブラリはコンパイルされない.targetはモジュール名
- を表す.
-
-with_config(withval[, default=nil])
-
- --with-<withval>で指定されたオプション値を得る.
-
-dir_config(target)
-
- --with-<target>-dir, --with-<target>-include, --with-<target>-lib
- のいずれかで指定されるディレクトリを $CFLAGS や $LDFLAGS
- に追加する.
-
-/*
- * Local variables:
- * fill-column: 60
- * end:
- */
diff --git a/README.jp b/README.jp
deleted file mode 100644
index 515f658609..0000000000
--- a/README.jp
+++ /dev/null
@@ -1,196 +0,0 @@
-* Rubyとは
-
-Rubyはシンプルかつ強力なオブジェクト指向スクリプト言語です.
-Rubyは最初から純粋なオブジェクト指向言語として設計されていま
-すから,オブジェクト指向プログラミングを手軽に行う事が出来ま
-す.もちろん通常の手続き型のプログラミングも可能です.
-
-Rubyはテキスト処理関係の能力などに優れ,Perlと同じくらい強力
-です.さらにシンプルな文法と,例外処理やイテレータなどの機構
-によって,より分かりやすいプログラミングが出来ます.
-
-
-* Rubyの特長
-
- + シンプルな文法
- + 普通のオブジェクト指向機能(クラス,メソッドコールなど)
- + 特殊なオブジェクト指向機能(Mixin, 特異メソッドなど)
- + 演算子オーバーロード
- + 例外処理機能
- + イテレータとクロージャ
- + ガーベージコレクタ
- + ダイナミックローディング (アーキテクチャによる)
- + 移植性が高い.多くのUNIX上で動くだけでなく,DOSやWindows,
- Mac,BeOSなどの上でも動く
-
-
-* 入手法
-
-** ftpで
-
-以下の場所においてあります.
-
- ftp://ftp.netlab.co.jp/pub/lang/ruby/
-
-** CVSで
-
- $ cvs -d :pserver:anonymous@cvs.netlab.co.jp:/home/cvs login
- (Logging in to anonymous@cvs.netlab.co.jp)
- CVS password: guest
- $ cvs -d :pserver:anonymous@cvs.netlab.co.jp:/home/cvs checkout ruby
-
-
-* ホームページ
-
-RubyのホームページのURLは
-
- http://www.ruby-lang.org/
-
-です.
-
-
-* メーリングリスト
-
-Rubyのメーリングリストがあります。参加希望の方は
-
- ruby-list-ctl@netlab.co.jp
-
-まで本文に
-
- subscribe YourFirstName YourFamilyName
-
-と書いて送って下さい。
-
-Ruby開発者向けメーリングリストもあります。こちらではrubyのバ
-グ、将来の仕様拡張など実装上の問題について議論されています。
-参加希望の方は
-
- ruby-dev-ctl@netlab.co.jp
-
-までruby-listと同様の方法でメールしてください。
-
-Ruby拡張モジュールについて話し合うruby-extメーリングリストと
-英語で話し合うruby-talkメーリングリストもあります。参加方法
-はどれも同じです。
-
-
-* コンパイル・インストール
-
-以下の手順で行ってください.
-
- 1. configureを実行してMakefileなどを生成する
-
- 2. (必要ならば)defines.hを編集する
-
- 多分,必要無いと思います.
-
- 3. (必要ならば)ext/Setupに静的にリンクする拡張モジュールを
- 指定する
-
- ext/Setupに記述したモジュールは静的にリンクされます.
-
- ダイナミックローディングをサポートしていないアーキテク
- チャではSetupの1行目の「option nodynamic」という行のコ
- メントを外す必要があります.また,このアーキテクチャで
- 拡張モジュールを利用するためには,あらかじめ静的にリン
- クしておく必要があります.
-
- 4. makeを実行してコンパイルする
-
- 5. make testでテストを行う.
-
- 「test succeeded」と表示されれば成功です.ただしテスト
- に成功しても完璧だと保証されている訳ではありません.
-
- 6. make install
-
- rootで作業する必要があるかもしれません.
-
-もし,コンパイル時にエラーが発生した場合にはエラーのログとマ
-シン,OSの種類を含むできるだけ詳しいレポートを作者に送ってく
-ださると他の方のためにもなります.
-
-
-* 移植
-
-UNIXであればconfigureがほとんどの差異を吸収してくれるはずで
-すが,思わぬ見落としがあった場合(あるに違いない),作者にその
-ことをレポートすれば,解決できるかも知れません.
-
-アーキテクチャにもっとも依存するのはGC部です.RubyのGCは対象
-のアーキテクチャがsetjmp()によって全てのレジスタを jmp_bufに
-格納することと,jmp_bufとスタックが32bitアラインメントされて
-いることを仮定しています.特に前者が成立しない場合の対応は非
-常に困難でしょう.後者の解決は比較的簡単で,gc.cでスタックを
-マークしている部分にアラインメントのバイト数だけずらしてマー
-クするコードを追加するだけで済みます.「defined(THINK_C)」で
-括られている部分を参考にしてください
-
-# 実際にはRubyはThink Cではコンパイルできません.
-
-レジスタウィンドウを持つCPUでは,レジスタウィンドウをスタッ
-クにフラッシュするアセンブラコードを追加する必要があるかも知
-れません.
-
-
-* 配布条件
-
-Rubyはフリーソフトウェアです.GPL(the GNU General Public
-License)または以下に示す条件でRubyを再配布できます.GPLにつ
-いてはCOPYINGファイルを参照して下さい.
-
- 1. 複製は制限なく自由です.
-
- 2. 以下の条件のいずれかを満たす時に手元のRubyのソースを自
- 由に変更できます.
-
- (a) ネットニューズにポストしたり,作者に変更を送付する
- などの方法で,変更を公開する.
-
- (b) 変更したRubyを自分の所属する組織内部だけで使う.
-
- (c) 変更点を明示したうえ,ソフトウェアの名前を変更する.
- そのソフトウェアを配布する時には変更前のRubyも同時
- に配布する.または変更前のRubyのソースの入手法を明
- 示する.
-
- (d) その他の変更条件を作者と合意する.
-
- 3. 以下の条件のいずれかを満たす時にRubyをオブジェクトコー
- ドや実行形式でも配布できます.
-
- (a) バイナリを受け取った人がソースを入手できるように,
- ソースの入手法を明示する.
-
- (b) 機械可読なソースコードを添付する.
-
- (c) 変更を行ったバイナリは名前を変更したうえ,オリジナ
- ルのソースコードの入手法を明示する.
-
- (d) その他の配布条件を作者と合意する.
-
- 4. 他のプログラムへの引用はいかなる目的であれ自由です.た
- だし,Rubyに含まれる他の作者によるコードは,それぞれの
- 作者の意向による制限が加えられます.具体的にはgc.c(一部),
- util.c(一部),st.[ch],regex.[ch] および ./missingディ
- レクトリ下のファイル群が該当します.それぞれの配布条件
- などに付いては各ファイルを参照してください.
-
- 5. Rubyへの入力となるスクリプトおよび,Rubyからの出力の権
- 利はRubyの作者ではなく,それぞれの入出力を生成した人に
- 属します.また,Rubyに組み込むための拡張ライブラリにつ
- いても同様です.
-
- 6. Rubyは無保証です.作者はRubyをサポートする意志はありま
- すが,Ruby自身のバグあるいはRubyスクリプトのバグなどか
- ら発生するいかなる損害に対しても責任を持ちません.
-
-
-* 著者
-
-コメント,バグレポートその他は matz@netlab.co.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 8bc7ac58a2..0000000000
--- a/ToDo
+++ /dev/null
@@ -1,77 +0,0 @@
-Language Spec.
-
-- def foo; .. rescue .. end
-- compile time string concatenation, "hello" "world" => "helloworld"
-- assignable constant, which now should be called shared variable.
-- class variable (prefix?) -- done by shared variable
-- rescue modifier; a rescue b => begin a rescue; b end
-* operator !! for rescue.
-* objectify symbols
-* objectify characters
-* ../... outside condition invokes operator method too.
-* ... inside condition turns off just before right condition.???
-* %w(a\ b\ c abc) => ["a b c", "abc"]
-* package or access control for global variables??
-* named arguments like foo(nation:="german") or foo(nation: "german").
-* method to retrieve argument information (need 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 ??
-
-Hacking Interpreter
-
-- use eban's fnmatch
-- RUBYOPT environment variable
-- alias $defout $>
-* retrieve STACK_LEVEL_MAX from users' limit.
-* remove end_proc registered out of require only
-* non-blocking open (e.g. for named pipe) for thread
-* avoid blocking with gethostbyname/gethostbyaddr
-* objectify interpreters
-* remove rb_eval() recursions
-* syntax tree -> bytecode ???
-* scrambled script, or script filter
-* setuid ruby
-
-Standard Libraries
-
-- hash[key] = nil may not remove entry; hashes may have nil as the value.
-- hash.fetch(key) raises exception if key is not found.
-- Array#{first,last,at}
-- Dir.glob(pat){|f|...}
-- sprintf/printf's $ to specify argument order
-- Dir.glob("**/*.c") ala zsh
-- Remove Enumerable#{size,length}
-* SyntaxError and NameError should not be subclasses of StandardError, maybe.
-* debugger for thread programming
-* Struct::new([name,]member,...) ??
-* 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()
-
-Extension Libraries
-
-- FastCGI ruby
-* ptk.rb pTk wrapper that is compatible to tk.rb
-* Berkeley DB extension
-
-Ruby Libraries
-
-* httplib.rb, urllib.rb, nttplib.rb, etc.
-* format like perl's
-
-Tools
-
-- extension library maker like XS or SWIG
-* freeze or undump to bundle everything
-
-Misc
-
-- publish Ruby books
diff --git a/array.c b/array.c
deleted file mode 100644
index 6401bc4886..0000000000
--- a/array.c
+++ /dev/null
@@ -1,1550 +0,0 @@
-/************************************************
-
- array.c -
-
- $Author$
- $Date$
- created at: Fri Aug 6 09:46:12 JST 1993
-
- Copyright (C) 1993-1999 Yukihiro Matsumoto
-
-************************************************/
-
-#include "ruby.h"
-#include "util.h"
-
-VALUE rb_cArray;
-
-#define ARY_DEFAULT_SIZE 16
-
-void
-rb_mem_clear(mem, size)
- register VALUE *mem;
- register size_t size;
-{
- while (size--) {
- *mem++ = Qnil;
- }
-}
-
-static void
-memfill(mem, size, val)
- register VALUE *mem;
- register size_t size;
- register VALUE val;
-{
- while (size--) {
- *mem++ = val;
- }
-}
-
-#define ARY_FREEZE FL_USER1
-#define ARY_TMPLOCK FL_USER2
-
-static void
-rb_ary_modify(ary)
- VALUE ary;
-{
- if (FL_TEST(ary, ARY_FREEZE))
- rb_raise(rb_eTypeError, "can't modify 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");
-}
-
-VALUE
-rb_ary_freeze(ary)
- VALUE ary;
-{
- if (rb_safe_level() >= 4 && !OBJ_TAINTED(ary))
- rb_raise(rb_eSecurityError, "Insecure: can't freeze array");
-
- FL_SET(ary, ARY_FREEZE);
- return ary;
-}
-
-static VALUE
-rb_ary_frozen_p(ary)
- VALUE ary;
-{
- if (FL_TEST(ary, ARY_FREEZE|ARY_TMPLOCK))
- return Qtrue;
- return Qfalse;
-}
-
-VALUE
-rb_ary_new2(len)
- long len;
-{
- NEWOBJ(ary, struct RArray);
- OBJSETUP(ary, rb_cArray, T_ARRAY);
-
- 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");
- }
- ary->len = 0;
- ary->capa = len;
- ary->ptr = 0;
- if (len == 0) len++;
- ary->ptr = ALLOC_N(VALUE, len);
-
- return (VALUE)ary;
-}
-
-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 (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
-rb_ary_s_new(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- long len = 0;
- VALUE size, val;
- NEWOBJ(ary, struct RArray);
- OBJSETUP(ary, klass, T_ARRAY);
-
- ary->len = 0;
- ary->ptr = 0;
- if (rb_scan_args(argc, argv, "02", &size, &val) == 0) {
- ary->capa = ARY_DEFAULT_SIZE;
- }
- else {
- long capa = NUM2LONG(size);
-
- if (capa < 0) {
- rb_raise(rb_eArgError, "negative array size");
- }
- if (capa > 0 && capa*sizeof(VALUE) <= 0) {
- rb_raise(rb_eArgError, "array size too big");
- }
- ary->capa = capa;
- len = capa;
- }
- ary->ptr = ALLOC_N(VALUE, ary->capa);
- memfill(ary->ptr, len, val);
- ary->len = len;
-
- return (VALUE)ary;
-}
-
-static VALUE
-rb_ary_s_create(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- NEWOBJ(ary, struct RArray);
- OBJSETUP(ary, klass, T_ARRAY);
-
- ary->len = ary->capa = 0;
- if (argc == 0) {
- ary->ptr = 0;
- }
- else {
- ary->ptr = ALLOC_N(VALUE, argc);
- MEMCPY(ary->ptr, argv, VALUE, argc);
- }
- ary->len = ary->capa = argc;
-
- return (VALUE)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)->capa) {
- long capa_inc = RARRAY(ary)->capa / 2;
- if (capa_inc < ARY_DEFAULT_SIZE) {
- capa_inc = ARY_DEFAULT_SIZE;
- }
- RARRAY(ary)->capa = idx + capa_inc;
- REALLOC_N(RARRAY(ary)->ptr, VALUE, RARRAY(ary)->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_method(argc, argv, ary)
- int argc;
- VALUE *argv;
- VALUE ary;
-{
- while (argc--) {
- rb_ary_store(ary, RARRAY(ary)->len, *argv++);
- }
- return ary;
-}
-
-VALUE
-rb_ary_pop(ary)
- VALUE ary;
-{
- rb_ary_modify(ary);
- if (RARRAY(ary)->len == 0) return Qnil;
- if (RARRAY(ary)->len * 10 < RARRAY(ary)->capa && RARRAY(ary)->capa > ARY_DEFAULT_SIZE) {
- RARRAY(ary)->capa = RARRAY(ary)->len * 2;
- REALLOC_N(RARRAY(ary)->ptr, VALUE, RARRAY(ary)->capa);
- }
- return RARRAY(ary)->ptr[--RARRAY(ary)->len];
-}
-
-VALUE
-rb_ary_shift(ary)
- VALUE ary;
-{
- VALUE top;
-
- rb_ary_modify(ary);
- if (RARRAY(ary)->len == 0) return Qnil;
-
- top = RARRAY(ary)->ptr[0];
- RARRAY(ary)->len--;
-
- /* sliding items */
- MEMMOVE(RARRAY(ary)->ptr, RARRAY(ary)->ptr+1, VALUE, RARRAY(ary)->len);
- if (RARRAY(ary)->len * 10 < RARRAY(ary)->capa && RARRAY(ary)->capa > ARY_DEFAULT_SIZE) {
- RARRAY(ary)->capa = RARRAY(ary)->len * 2;
- REALLOC_N(RARRAY(ary)->ptr, VALUE, RARRAY(ary)->capa);
- }
-
- return top;
-}
-
-VALUE
-rb_ary_unshift(ary, item)
- VALUE ary, item;
-{
- rb_ary_modify(ary);
- if (RARRAY(ary)->len >= RARRAY(ary)->capa) {
- long capa_inc = RARRAY(ary)->capa / 2;
- if (capa_inc < ARY_DEFAULT_SIZE) {
- capa_inc = ARY_DEFAULT_SIZE;
- }
- RARRAY(ary)->capa+=capa_inc;
- REALLOC_N(RARRAY(ary)->ptr, VALUE, RARRAY(ary)->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;
-}
-
-VALUE
-rb_ary_entry(ary, offset)
- VALUE ary;
- long offset;
-{
- if (RARRAY(ary)->len == 0) return Qnil;
-
- if (offset < 0) {
- offset = RARRAY(ary)->len + offset;
- }
- if (offset < 0 || RARRAY(ary)->len <= offset) {
- return Qnil;
- }
-
- return RARRAY(ary)->ptr[offset];
-}
-
-static VALUE
-rb_ary_subary(ary, beg, len)
- VALUE ary;
- long beg, len;
-{
- VALUE ary2;
-
- if (beg > RARRAY(ary)->len) return Qnil;
- if (beg < 0) {
- len += beg;
- beg = 0;
- }
- if (len < 0) return Qnil;
- if (beg + len > RARRAY(ary)->len) {
- len = RARRAY(ary)->len - beg;
- }
- if (len < 0) {
- len = 0;
- }
- if (len == 0) return rb_ary_new2(0);
-
- ary2 = rb_ary_new2(len);
- MEMCPY(RARRAY(ary2)->ptr, RARRAY(ary)->ptr+beg, VALUE, len);
- RARRAY(ary2)->len = len;
-
- return ary2;
-}
-
-VALUE
-rb_ary_aref(argc, argv, ary)
- int argc;
- VALUE *argv;
- VALUE ary;
-{
- VALUE arg1, arg2;
- long beg, len;
-
- if (rb_scan_args(argc, argv, "11", &arg1, &arg2) == 2) {
- beg = NUM2LONG(arg1);
- len = NUM2LONG(arg2);
- if (beg < 0) {
- beg = RARRAY(ary)->len + beg;
- }
- return rb_ary_subary(ary, beg, len);
- }
-
- /* special case - speeding up */
- if (FIXNUM_P(arg1)) {
- return rb_ary_entry(ary, FIX2LONG(arg1));
- }
- else if (TYPE(arg1) == T_BIGNUM) {
- rb_raise(rb_eIndexError, "index too big");
- }
- else {
- /* check if idx is Range */
- switch (rb_range_beg_len(arg1, &beg, &len, RARRAY(ary)->len, 0)) {
- case Qfalse:
- break;
- case Qnil:
- return Qnil;
- default:
- return rb_ary_subary(ary, beg, len);
- }
- }
- return rb_ary_entry(ary, NUM2LONG(arg1));
-}
-
-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_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;
-
- 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;
-}
-
-static void
-rb_ary_replace(ary, beg, len, rpl)
- VALUE ary, rpl;
- long beg, 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;
- }
-
- if (TYPE(rpl) != T_ARRAY) {
- rpl = rb_Array(rpl);
- }
-
- rb_ary_modify(ary);
- if (beg >= RARRAY(ary)->len) {
- len = beg + RARRAY(rpl)->len;
- if (len >= RARRAY(ary)->capa) {
- RARRAY(ary)->capa=len;
- REALLOC_N(RARRAY(ary)->ptr, VALUE, RARRAY(ary)->capa);
- }
- rb_mem_clear(RARRAY(ary)->ptr+RARRAY(ary)->len, beg-RARRAY(ary)->len);
- MEMCPY(RARRAY(ary)->ptr+beg, RARRAY(rpl)->ptr, VALUE, RARRAY(rpl)->len);
- RARRAY(ary)->len = len;
- }
- else {
- long alen;
-
- if (beg + len > RARRAY(ary)->len) {
- len = RARRAY(ary)->len - beg;
- }
-
- alen = RARRAY(ary)->len + RARRAY(rpl)->len - len;
- if (alen >= RARRAY(ary)->capa) {
- RARRAY(ary)->capa=alen;
- REALLOC_N(RARRAY(ary)->ptr, VALUE, RARRAY(ary)->capa);
- }
-
- if (len != RARRAY(rpl)->len) {
- MEMMOVE(RARRAY(ary)->ptr+beg+RARRAY(rpl)->len, RARRAY(ary)->ptr+beg+len,
- VALUE, RARRAY(ary)->len-(beg+len));
- RARRAY(ary)->len = alen;
- }
- MEMCPY(RARRAY(ary)->ptr+beg, RARRAY(rpl)->ptr, VALUE, RARRAY(rpl)->len);
- }
-}
-
-static VALUE
-rb_ary_aset(argc, argv, ary)
- int argc;
- VALUE *argv;
- VALUE ary;
-{
- VALUE arg1, arg2, arg3;
- long offset, beg, len;
-
- if (rb_scan_args(argc, argv, "21", &arg1, &arg2, &arg3) == 3) {
- rb_ary_replace(ary, NUM2LONG(arg1), NUM2LONG(arg2), arg3);
- return arg3;
- }
- else if (FIXNUM_P(arg1)) {
- offset = FIX2LONG(arg1);
- goto fixnum;
- }
- else if (rb_range_beg_len(arg1, &beg, &len, RARRAY(ary)->len, 1)) {
- /* check if idx is Range */
- rb_ary_replace(ary, beg, len, arg2);
- return arg2;
- }
- if (TYPE(arg1) == T_BIGNUM) {
- rb_raise(rb_eIndexError, "index too big");
- }
-
- offset = NUM2LONG(arg1);
- fixnum:
- rb_ary_store(ary, offset, arg2);
- return arg2;
-}
-
-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
-rb_ary_clone(ary)
- VALUE ary;
-{
- VALUE ary2 = rb_ary_new2(RARRAY(ary)->len);
-
- CLONESETUP(ary2, ary);
- MEMCPY(RARRAY(ary2)->ptr, RARRAY(ary)->ptr, VALUE, RARRAY(ary)->len);
- RARRAY(ary2)->len = RARRAY(ary)->len;
- return ary2;
-}
-
-static VALUE
-rb_ary_dup(ary)
- VALUE ary;
-{
- return rb_ary_s_create(RARRAY(ary)->len, RARRAY(ary)->ptr, CLASS_OF(ary));
-}
-
-static VALUE
-to_ary(ary)
- VALUE ary;
-{
- return rb_convert_type(ary, T_ARRAY, "Array", "to_ary");
-}
-
-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 i;
- VALUE result, tmp;
- if (RARRAY(ary)->len == 0) return rb_str_new(0, 0);
-
- tmp = RARRAY(ary)->ptr[0];
- switch (TYPE(tmp)) {
- case T_STRING:
- result = rb_str_dup(tmp);
- break;
- case T_ARRAY:
- if (rb_inspecting_p(tmp)) {
- result = rb_str_new2("[...]");
- }
- else {
- VALUE args[2];
-
- args[0] = tmp;
- args[1] = sep;
- result = rb_protect_inspect(inspect_join, ary, (VALUE)args);
- }
- break;
- default:
- result = rb_obj_as_string(tmp);
- break;
- }
-
- for (i=1; 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 (!NIL_P(sep)) rb_str_concat(result, sep);
- rb_str_cat(result, RSTRING(tmp)->ptr, RSTRING(tmp)->len);
- if (OBJ_TAINTED(tmp)) OBJ_TAINT(result);
- }
-
- return result;
-}
-
-static VALUE
-rb_ary_join_method(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;
-
- if (RARRAY(ary)->len == 0) return rb_str_new(0, 0);
- str = rb_ary_join(ary, rb_output_fs);
- if (NIL_P(str)) return rb_str_new(0, 0);
- return str;
-}
-
-static ID inspect_key;
-
-struct inspect_arg {
- VALUE (*func)();
- VALUE arg1, arg2;
-};
-
-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)();
- VALUE obj, arg;
-{
- struct inspect_arg iarg;
-
- 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)) {
- inspect_tbl = rb_ary_new();
- rb_thread_local_aset(rb_thread_current(), inspect_key, inspect_tbl);
- }
- rb_ary_push(inspect_tbl, obj);
- 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) return Qfalse;
- inspect_tbl = rb_thread_local_aref(rb_thread_current(), inspect_key);
- if (NIL_P(inspect_tbl)) return Qfalse;
- return rb_ary_includes(inspect_tbl, obj);
-}
-
-static VALUE
-inspect_ary(ary)
- VALUE ary;
-{
- long i = 0;
- VALUE s, str;
-
- str = rb_str_new2("[");
-
- for (i=0; i<RARRAY(ary)->len; i++) {
- s = rb_inspect(RARRAY(ary)->ptr[i]);
- if (i > 0) rb_str_cat(str, ", ", 2);
- rb_str_cat(str, RSTRING(s)->ptr, RSTRING(s)->len);
- }
- rb_str_cat(str, "]", 1);
-
- 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;
-
- rb_ary_modify(ary);
- if (RARRAY(ary)->len == 0) return ary;
-
- p1 = RARRAY(ary)->ptr;
- p2 = p1 + RARRAY(ary)->len - 1; /* points last item */
-
- while (p1 < p2) {
- tmp = *p1;
- *p1 = *p2;
- *p2 = tmp;
- p1++; p2--;
- }
-
- return ary;
-}
-
-static VALUE
-rb_ary_reverse_method(ary)
- VALUE ary;
-{
- return rb_ary_reverse(rb_ary_dup(ary));
-}
-
-static ID cmp;
-
-static int
-sort_1(a, b)
- VALUE *a, *b;
-{
- VALUE retval = rb_yield(rb_assoc_new(*a, *b));
- return NUM2INT(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, cmp, 1, *b);
- return NUM2INT(retval);
-}
-
-static VALUE
-sort_internal(ary)
- VALUE ary;
-{
- qsort(RARRAY(ary)->ptr, RARRAY(ary)->len, sizeof(VALUE),
- rb_iterator_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 = rb_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_iterator_p()) {
- return rb_ary_dup(ary);
- }
-
- 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;
-}
-
-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_iterator_p()) {
- return rb_yield(item);
- }
- return Qnil;
- }
- else {
- RARRAY(ary)->len = i2;
- }
-
- return item;
-}
-
-VALUE
-rb_ary_delete_at(ary, at)
- VALUE ary;
- VALUE at;
-{
- long i, pos = NUM2LONG(at), 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_if(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++;
- }
- RARRAY(ary)->len = i2;
-
- return ary;
-}
-
-static VALUE
-rb_ary_filter(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_replace_method(ary, ary2)
- VALUE ary, ary2;
-{
- ary2 = to_ary(ary2);
- rb_ary_replace(ary, 0, RARRAY(ary)->len, ary2);
- return ary;
-}
-
-static VALUE
-rb_ary_clear(ary)
- VALUE ary;
-{
- rb_ary_modify(ary);
- RARRAY(ary)->len = 0;
- if (ARY_DEFAULT_SIZE*3 < RARRAY(ary)->capa) {
- RARRAY(ary)->capa = ARY_DEFAULT_SIZE * 2;
- REALLOC_N(RARRAY(ary)->ptr, VALUE, RARRAY(ary)->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;
-
- rb_scan_args(argc, argv, "12", &item, &arg1, &arg2);
- switch (argc) {
- case 1:
- beg = 0;
- len = RARRAY(ary)->len - beg;
- 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)->capa) {
- RARRAY(ary)->capa=end;
- REALLOC_N(RARRAY(ary)->ptr, VALUE, RARRAY(ary)->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;
-
- while (p < pend) {
- *p++ = item;
- }
- return ary;
-}
-
-VALUE
-rb_ary_plus(x, y)
- VALUE x, y;
-{
- VALUE z;
-
- if (TYPE(y) != T_ARRAY) {
- y = rb_Array(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;
-{
- VALUE *p, *pend;
-
- rb_ary_modify(x);
- if (TYPE(y) != T_ARRAY) {
- y = rb_Array(y);
- }
-
- p = RARRAY(y)->ptr;
- pend = p + RARRAY(y)->len;
- while (p < pend) {
- rb_ary_store(x, RARRAY(x)->len, *p);
- p++;
- }
- 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 = rb_ary_new2(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);
- }
-
- 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 > 1
- && 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 (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;
- int h;
-
- h = RARRAY(ary)->len;
- for (i=0; i<RARRAY(ary)->len; i++) {
- int 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;
-}
-
-static VALUE
-rb_ary_cmp(ary, ary2)
- VALUE ary;
- VALUE ary2;
-{
- long i, len;
-
- 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],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
-rb_ary_and(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])
- && !rb_ary_includes(ary3, RARRAY(ary1)->ptr[i])) {
- rb_ary_push(ary3, RARRAY(ary1)->ptr[i]);
- }
- }
- return ary3;
-}
-
-static VALUE
-rb_ary_or(ary1, ary2)
- VALUE ary1, ary2;
-{
- VALUE ary3;
- long i;
-
- if (TYPE(ary2) != T_ARRAY) {
- if (rb_ary_includes(ary1, ary2)) return ary1;
- else return rb_ary_plus(ary1, ary2);
- }
-
- ary3 = rb_ary_new();
- for (i=0; i<RARRAY(ary1)->len; i++) {
- if (!rb_ary_includes(ary3, RARRAY(ary1)->ptr[i]))
- rb_ary_push(ary3, RARRAY(ary1)->ptr[i]);
- }
- for (i=0; i<RARRAY(ary2)->len; i++) {
- if (!rb_ary_includes(ary3, RARRAY(ary2)->ptr[i]))
- rb_ary_push(ary3, RARRAY(ary2)->ptr[i]);
- }
- return ary3;
-}
-
-static VALUE
-rb_ary_uniq_bang(ary)
- VALUE ary;
-{
- VALUE *p, *q, *t, *end;
- VALUE v;
-
- rb_ary_modify(ary);
- p = RARRAY(ary)->ptr;
- end = p + RARRAY(ary)->len;
-
- while (p < end) {
- v = *p++;
- q = t = p;
- while (q < end) {
- if (rb_equal(*q, v)) q++;
- else *t++ = *q++;
- }
- end = t;
- }
- if (RARRAY(ary)->len == (end - RARRAY(ary)->ptr)) {
- return Qnil;
- }
-
- RARRAY(ary)->len = (end - RARRAY(ary)->ptr);
-
- return ary;
-}
-
-static VALUE
-rb_ary_uniq(ary)
- VALUE ary;
-{
- ary = rb_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)->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 = rb_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 VALUE
-rb_ary_flatten_bang(ary)
- VALUE ary;
-{
- long i;
- int mod = 0;
-
- rb_ary_modify(ary);
- for (i=0; i<RARRAY(ary)->len; i++) {
- VALUE ary2 = RARRAY(ary)->ptr[i];
- if (TYPE(ary2) == T_ARRAY) {
- rb_ary_replace(ary, i--, 1, ary2);
- mod = 1;
- }
- }
- if (mod == 0) return Qnil;
- return ary;
-}
-
-static VALUE
-rb_ary_flatten(ary)
- VALUE ary;
-{
- ary = rb_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, "new", rb_ary_s_new, -1);
- rb_define_singleton_method(rb_cArray, "[]", rb_ary_s_create, -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, "freeze", rb_ary_freeze, 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, "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_method, -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, 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_method, -1);
- rb_define_method(rb_cArray, "reverse", rb_ary_reverse_method, 0);
- rb_define_method(rb_cArray, "reverse!", rb_ary_reverse, 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, "delete", rb_ary_delete, 1);
- rb_define_method(rb_cArray, "delete_at", rb_ary_delete_at, 1);
- rb_define_method(rb_cArray, "delete_if", rb_ary_delete_if, 0);
- rb_define_method(rb_cArray, "reject!", rb_ary_delete_if, 0);
- rb_define_method(rb_cArray, "filter", rb_ary_filter, 0);
- rb_define_method(rb_cArray, "replace", rb_ary_replace_method, 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, "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);
-
- cmp = rb_intern("<=>");
-}
diff --git a/bignum.c b/bignum.c
deleted file mode 100644
index 828e0cb9aa..0000000000
--- a/bignum.c
+++ /dev/null
@@ -1,1324 +0,0 @@
-/************************************************
-
- bignum.c -
-
- $Author$
- $Date$
- created at: Fri Jun 10 00:48:55 JST 1994
-
-************************************************/
-
-#include "ruby.h"
-#include <math.h>
-#include <ctype.h>
-
-VALUE rb_cBignum;
-typedef unsigned short USHORT;
-
-#define BDIGITS(x) RBIGNUM(x)->digits
-#define BITSPERDIG (sizeof(short)*CHAR_BIT)
-#define BIGRAD (1L << BITSPERDIG)
-#define DIGSPERINT ((unsigned int)(sizeof(long)/sizeof(short)))
-#define BIGUP(x) ((unsigned long)(x) << BITSPERDIG)
-#define BIGDN(x) RSHIFT(x,BITSPERDIG)
-#define BIGLO(x) ((USHORT)((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;
- BDIGITS(big) = ALLOC_N(USHORT, 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), USHORT, RBIGNUM(x)->len);
- return z;
-}
-
-void
-rb_big_2comp(x) /* get 2's complement */
- VALUE x;
-{
- long i = RBIGNUM(x)->len;
- USHORT *ds = BDIGITS(x);
- long 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 (ds[0] == 1 || ds[0] == 0) {
- for (i=1; i<RBIGNUM(x)->len; i++) {
- if (ds[i] != 0) return;
- }
- REALLOC_N(BDIGITS(x), USHORT, RBIGNUM(x)->len++);
- ds = BDIGITS(x);
- ds[RBIGNUM(x)->len-1] = 1;
- }
-}
-
-static VALUE
-bignorm(x)
- VALUE x;
-{
- long len = RBIGNUM(x)->len;
- USHORT *ds = BDIGITS(x);
-
- while (len-- && !ds[len]) ;
- RBIGNUM(x)->len = ++len;
-
- if (len*sizeof(USHORT) <= 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;
-{
- unsigned int i = 0;
- USHORT *digits;
- VALUE big;
-
- i = 0;
- big = bignew(DIGSPERINT, 1);
- digits = BDIGITS(big);
- while (i < DIGSPERINT) {
- digits[i++] = BIGLO(n);
- n = BIGDN(n);
- }
-
- i = DIGSPERINT;
- 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);
-}
-
-VALUE
-rb_str2inum(str, base)
- const char *str;
- int base;
-{
- char sign = 1, c;
- unsigned long num;
- long len, blen = 1;
- long i;
- VALUE z;
- USHORT *zds;
-
- while (ISSPACE(*str)) str++;
-
- if (*str == '+') {
- str++;
- }
- else if (*str == '-') {
- str++;
- sign = 0;
- }
- if (base == 0) {
- if (*str == '0') {
- str++;
- if (*str == 'x' || *str == 'X') {
- str++;
- base = 16;
- }
- else if (*str == 'b' || *str == 'B') {
- str++;
- base = 2;
- }
- else {
- base = 8;
- }
- if (*str == '\0') return INT2FIX(0);
- }
- else {
- base = 10;
- }
- }
- if (base == 8) {
- while (str[0] == '0') str++;
- len = 3*strlen(str)*sizeof(char);
- }
- else { /* base == 10, 2 or 16 */
- if (base == 16 && str[0] == '0' && (str[1] == 'x'||str[1] == 'X')) {
- str += 2;
- }
- if (base == 2 && str[0] == '0' && (str[1] == 'b'||str[1] == 'B')) {
- str += 2;
- }
- while (str[0] == '0') str++;
- len = 4*strlen(str)*sizeof(char);
- }
-
- if (len <= (sizeof(VALUE)*CHAR_BIT)) {
- unsigned long val = strtoul((char*)str, 0, base);
-
- 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;
- }
- }
- len = (len/BITSPERDIG)+1;
-
- z = bignew(len, sign);
- zds = BDIGITS(z);
- for (i=len;i--;) zds[i]=0;
- while (c = *str++) {
- switch (c) {
- case '0': case '1': case '2': case '3': case '4':
- case '5': case '6': case '7': case '8': case '9':
- c = c - '0';
- break;
- case 'a': case 'b': case 'c':
- case 'd': case 'e': case 'f':
- c = c - 'a' + 10;
- break;
- case 'A': case 'B': case 'C':
- case 'D': case 'E': case 'F':
- c = c - 'A' + 10;
- break;
- default:
- c = base;
- break;
- }
- if (c >= base) break;
- i = 0;
- num = c;
- for (;;) {
- while (i<blen) {
- num += zds[i]*base;
- zds[i++] = BIGLO(num);
- num = BIGDN(num);
- }
- if (num) {
- blen++;
- continue;
- }
- break;
- }
- }
- return bignorm(z);
-}
-
-static char hexmap[] = "0123456789abcdef";
-VALUE
-rb_big2str(x, base)
- VALUE x;
- int base;
-{
- VALUE t;
- USHORT *ds;
- unsigned 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(USHORT)/sizeof(char)*CHAR_BIT*i*241L)/800+2;
- hbase = 10000;
- }
- else if (base == 16) {
- j = (sizeof(USHORT)/sizeof(char)*CHAR_BIT*i)/4+2;
- hbase = 0x10000;
- }
- else if (base == 8) {
- j = (sizeof(USHORT)/sizeof(char)*CHAR_BIT*i)+2;
- hbase = 010000;
- }
- else if (base == 2) {
- j = (sizeof(USHORT)*CHAR_BIT*i)+2;
- hbase = 020;
- }
- else {
- j = 0;
- hbase = 0;
- rb_raise(rb_eArgError, "bignum cannot treat base %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;
- unsigned long num = 0;
- while (k--) {
- num = BIGUP(num) + ds[k];
- ds[k] = (USHORT)(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(x)
- VALUE x;
-{
- return rb_big2str(x, 10);
-}
-
-unsigned long
-rb_big2ulong(x)
- VALUE x;
-{
- unsigned long num;
- long len = RBIGNUM(x)->len;
- USHORT *ds;
-
- if (len > sizeof(long)/sizeof(USHORT))
- rb_raise(rb_eArgError, "bignum too big to convert into `uint'");
- ds = BDIGITS(x);
- num = 0;
- while (len--) {
- num = BIGUP(num);
- num += ds[len];
- }
- return num;
-}
-
-long
-rb_big2long(x)
- VALUE x;
-{
- unsigned long num = rb_big2ulong(x);
-
- if ((long)num < 0) {
- rb_raise(rb_eArgError, "bignum too big to convert into `int'");
- }
- if (!RBIGNUM(x)->sign) return -(long)num;
- return num;
-}
-
-static VALUE
-rb_big_to_i(x)
- VALUE x;
-{
- return bignorm(x);
-}
-
-VALUE
-rb_dbl2big(d)
- double d;
-{
- unsigned long i = 0;
- long c;
- USHORT *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 = (long)u;
- u -= c;
- digits[i] = (USHORT)c;
- }
-
- return bignorm(z);
-}
-
-double
-rb_big2dbl(x)
- VALUE x;
-{
- double d = 0.0;
- long i = RBIGNUM(x)->len;
- USHORT *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;
-
- 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;
-{
- if (rb_big_cmp(x, y) == INT2FIX(0)) return Qtrue;
- return Qfalse;
-}
-
-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;
- USHORT *ds = BDIGITS(z);
-
- if (!RBIGNUM(x)->sign) rb_big_2comp(z);
- while (i--) ds[i] = ~ds[i];
- if (RBIGNUM(x)->sign) rb_big_2comp(z);
- RBIGNUM(z)->sign = !RBIGNUM(z)->sign;
-
- return bignorm(z);
-}
-
-static VALUE
-bigsub(x, y)
- VALUE x, y;
-{
- VALUE z = 0;
- USHORT *zds;
- long 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 += (long)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 bignorm(z);
-}
-
-static VALUE
-bigadd(x, y, sign)
- VALUE x, y;
- char sign;
-{
- VALUE z;
- long 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 += 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] = (USHORT)num;
-
- return bignorm(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 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 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;
- unsigned long n = 0;
- VALUE z;
- USHORT *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++) {
- unsigned long dd = BDIGITS(x)[i];
- if (dd == 0) continue;
- n = 0;
- for (j = 0; j < RBIGNUM(y)->len; j++) {
- int ee = n + 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
-bigdivmod(x, y, div, mod, modulo)
- VALUE x, y;
- VALUE *div, *mod;
- int modulo;
-{
- long nx = RBIGNUM(x)->len, ny = RBIGNUM(y)->len;
- long i, j;
- VALUE yy, z;
- USHORT *xds, *yds, *zds, *tds;
- unsigned long t2;
- long num;
- USHORT 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 (div) *div = INT2FIX(0);
- if (mod) *mod = bignorm(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] = (USHORT)(t2 / dd);
- t2 %= dd;
- }
- RBIGNUM(z)->sign = RBIGNUM(x)->sign==RBIGNUM(y)->sign;
- if (div) *div = bignorm(z);
- if (mod) {
- if (!RBIGNUM(y)->sign) t2 = -(long)t2;
- *mod = INT2NUM(t2);
- }
- 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--;
- if ((dd = BIGRAD/(int)(yds[ny-1]+1)) != 1) {
- yy = rb_big_clone(y);
- tds = BDIGITS(yy);
- j = 0;
- num = 0;
- while (j<ny) {
- num += (long)yds[j]*dd;
- tds[j++] = BIGLO(num);
- num = BIGDN(num);
- }
- yds = tds;
- j = 0;
- num = 0;
- while (j<nx) {
- num += (long)xds[j]*dd;
- zds[j++] = BIGLO(num);
- num = BIGDN(num);
- }
- zds[j] = (USHORT)num;
- }
- 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 = (USHORT)((BIGUP(zds[j]) + zds[j-1])/yds[ny-1]);
- if (q) {
- i = 0; num = 0; t2 = 0;
- do { /* multiply and subtract */
- int ee;
- t2 += (long)yds[i] * q;
- ee = num - BIGLO(t2);
- num = 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 {
- int ee = num + yds[i];
- num = (long) 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 (div) { /* move quotient down in z */
- *div = rb_big_clone(z);
- zds = BDIGITS(*div);
- j = (nx==ny ? nx+2 : nx+1) - ny;
- for (i = 0;i < j;i++) zds[i] = zds[i+ny];
- RBIGNUM(*div)->len = i;
- *div = bignorm(*div);
- }
- if (mod) { /* just normalize remainder */
- *mod = rb_big_clone(z);
- if (dd) {
- zds = BDIGITS(*mod);
- t2 = 0; i = ny;
- while(i--) {
- t2 = BIGUP(t2) + zds[i];
- zds[i] = (USHORT)(t2 / dd);
- t2 %= dd;
- }
- }
- RBIGNUM(*mod)->len = ny;
- RBIGNUM(*mod)->sign = RBIGNUM(x)->sign;
- if (modulo && RBIGNUM(x)->sign != RBIGNUM(y)->sign) {
- long len = ny;
- zds = BDIGITS(*mod);
- while (len-- && !zds[len]);
- if (len > 0) {
- *mod = bigadd(*mod, y, 1);
- return;
- }
- }
- *mod = bignorm(*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, 0);
-
- return z;
-}
-
-
-static VALUE
-rb_big_modulo(x, y, modulo)
- VALUE x, y;
- int modulo;
-{
- VALUE z;
-
- switch (TYPE(y)) {
- case T_FIXNUM:
- y = rb_int2big(FIX2LONG(y));
- break;
-
- case T_BIGNUM:
- break;
-
- case T_FLOAT:
- y = rb_dbl2big(RFLOAT(y)->value);
- break;
-
- default:
- return rb_num_coerce_bin(x, y);
- }
- bigdivmod(x, y, 0, &z, modulo);
-
- return z;
-}
-
-static VALUE
-rb_big_mod(x, y)
- VALUE x, y;
-{
- return rb_big_modulo(x, y, 1);
-}
-
-static VALUE
-rb_big_remainder(x, y)
- VALUE x, y;
-{
- return rb_big_modulo(x, y, 0);
-}
-
-static 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_FLOAT:
- y = rb_dbl2big(RFLOAT(y)->value);
- break;
-
- case T_BIGNUM:
- break;
-
- default:
- return rb_num_coerce_bin(x, y);
- }
- bigdivmod(x, y, &div, &mod, 1);
-
- return rb_assoc_new(div, 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;
- USHORT *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);
- rb_big_2comp(y);
- }
- if (!RBIGNUM(x)->sign) {
- x = rb_big_clone(x);
- rb_big_2comp(x);
- }
- 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) rb_big_2comp(z);
- return bignorm(z);
-}
-
-VALUE
-rb_big_or(x, y)
- VALUE x, y;
-{
- VALUE z;
- USHORT *ds1, *ds2, *zds;
- unsigned 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);
- rb_big_2comp(y);
- }
- if (!RBIGNUM(x)->sign) {
- x = rb_big_clone(x);
- rb_big_2comp(x);
- }
- 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) rb_big_2comp(z);
-
- return bignorm(z);
-}
-
-VALUE
-rb_big_xor(x, y)
- VALUE x, y;
-{
- VALUE z;
- USHORT *ds1, *ds2, *zds;
- unsigned int 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);
- rb_big_2comp(y);
- }
- if (!RBIGNUM(x)->sign) {
- x = rb_big_clone(x);
- rb_big_2comp(x);
- }
- 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) rb_big_2comp(z);
-
- return bignorm(z);
-}
-
-static VALUE rb_big_rshift _((VALUE,VALUE));
-
-VALUE
-rb_big_lshift(x, y)
- VALUE x, y;
-{
- USHORT *xds, *zds;
- int shift = NUM2INT(y);
- int s1 = shift/BITSPERDIG;
- int s2 = shift%BITSPERDIG;
- VALUE z;
- unsigned long num = 0;
- long len, i;
-
- if (shift < 0) return rb_big_rshift(x, INT2FIX(-shift));
- xds = BDIGITS(x);
- len = RBIGNUM(x)->len;
- z = bignew(len+s1+1, RBIGNUM(x)->sign);
- zds = BDIGITS(z);
- for (i=0; i<s1; i++) {
- *zds++ = 0;
- }
- for (i=0; i<len; i++) {
- num = num | *xds++<<s2;
- *zds++ = BIGLO(num);
- num = BIGDN(num);
- }
- *zds = BIGLO(num);
- return bignorm(z);
-}
-
-static VALUE
-rb_big_rshift(x, y)
- VALUE x, y;
-{
- USHORT *xds, *zds;
- int shift = NUM2INT(y);
- int s1 = shift/BITSPERDIG;
- int s2 = shift%BITSPERDIG;
- VALUE z;
- unsigned long 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);
- }
- 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]);
- }
- return bignorm(z);
-}
-
-static VALUE
-rb_big_aref(x, y)
- VALUE x, y;
-{
- USHORT *xds;
- int shift = NUM2INT(y);
- int s1, s2;
-
- 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);
- rb_big_2comp(x);
- }
- 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;
- int key;
- USHORT *digits;
-
- key = 0; digits = BDIGITS(x);
- for (i=0,len=RBIGNUM(x)->len; i<RBIGNUM(x)->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] = ((USHORT)~0) * rand;
- }
-
- return rb_big_mod((VALUE)v, max);
-}
-
-static VALUE
-rb_big_size(big)
- VALUE big;
-{
- return INT2FIX(RBIGNUM(big)->len*sizeof(USHORT));
-}
-
-static VALUE
-rb_big_zero_p(big)
- VALUE big;
-{
- return Qfalse;
-}
-
-void
-Init_Bignum()
-{
- rb_cBignum = rb_define_class("Bignum", rb_cInteger);
-
- rb_undef_method(CLASS_OF(rb_cBignum), "new");
-
- rb_define_method(rb_cBignum, "to_s", rb_big_to_s, 0);
- 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_mod, 1);
- rb_define_method(rb_cBignum, "divmod", rb_big_divmod, 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_eq, 1);
- rb_define_method(rb_cBignum, "hash", rb_big_hash, 0);
- rb_define_method(rb_cBignum, "to_i", rb_big_to_i, 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 46989474a8..0000000000
--- a/class.c
+++ /dev/null
@@ -1,666 +0,0 @@
-/************************************************
-
- class.c -
-
- $Author$
- $Date$
- created at: Tue Aug 10 15:05:44 JST 1993
-
- Copyright (C) 1993-1999 Yukihiro Matsumoto
-
-************************************************/
-
-#include "ruby.h"
-#include "node.h"
-#include "st.h"
-#include <ctype.h>
-
-#ifdef USE_CWGUSI
-#include <stdio.h>
-#endif
-
-extern st_table *rb_class_tbl;
-
-VALUE
-rb_class_new(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();
-
- return (VALUE)klass;
-}
-
-VALUE
-rb_singleton_class_new(super)
- VALUE super;
-{
- VALUE klass = rb_class_new(super);
-
- FL_SET(klass, FL_SINGLETON);
- return klass;
-}
-
-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_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;
- 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))
- rb_iv_set(klass, "__attached__", obj);
-}
-
-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);
- /* make metaclass */
- RBASIC(klass)->klass = rb_singleton_class_new(RBASIC(super)->klass);
- rb_singleton_class_attached(RBASIC(klass)->klass, klass);
- rb_funcall(super, rb_intern("inherited"), 1, klass);
-
- return klass;
-}
-
-VALUE
-rb_define_class(name, super)
- const char *name;
- VALUE super;
-{
- VALUE klass;
- ID id;
-
- id = rb_intern(name);
- klass = rb_define_class_id(id, super);
-
- 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);
- klass = rb_define_class_id(id, super);
- rb_const_set(outer, id, klass);
- rb_set_class_path(klass, outer, name);
-
- 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);
- 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);
- 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;
- }
-
- return (VALUE)klass;
-}
-
-void
-rb_include_module(klass, module)
- VALUE klass, module;
-{
- VALUE p;
-
- 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);
- }
-
- while (module) {
- /* ignore if the module included already in superclasses */
- for (p = RCLASS(klass)->super; p; p = RCLASS(p)->super) {
- if (BUILTIN_TYPE(p) == T_ICLASS &&
- RCLASS(p)->m_tbl == RCLASS(module)->m_tbl) {
- if (RCLASS(module)->super) {
- rb_include_module(p, RCLASS(module)->super);
- }
- return;
- }
- }
- RCLASS(klass)->super =
- include_class_new(module, RCLASS(klass)->super);
- klass = RCLASS(klass)->super;
- module = RCLASS(module)->super;
- }
- 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_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;
-
- if (!OBJ_TAINTED(mod) && rb_safe_level() >= 4)
- rb_raise(rb_eSecurityError, "Insecure: can't get metainfo");
- 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(obj)
- VALUE obj;
-{
- VALUE ary;
- VALUE klass;
- VALUE *p, *q, *pend;
-
- if (rb_safe_level() >= 4 && !OBJ_TAINTED(obj))
- rb_raise(rb_eSecurityError, "Insecure: can't get metainfo");
- 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;
- }
- 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);
-}
-
-VALUE
-rb_singleton_class(obj)
- VALUE obj;
-{
- VALUE klass;
- if (rb_special_const_p(obj)) {
- rb_raise(rb_eTypeError, "can't define singleton");
- }
- if (FL_TEST(RBASIC(obj)->klass, FL_SINGLETON)) {
- klass = RBASIC(obj)->klass;
- }
- else {
- klass = rb_singleton_class_new(RBASIC(obj)->klass);
- RBASIC(obj)->klass = klass;
- rb_singleton_class_attached(klass, obj);
- }
- if (OBJ_TAINTED(obj)) {
- OBJ_TAINT(klass);
- }
- else {
- FL_UNSET(klass, FL_TAINT);
- }
-
- 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;
- const char *p = fmt;
- VALUE *var;
- va_list vargs;
-
- va_init_list(vargs, fmt);
-
- if (*p == '*') {
- var = va_arg(vargs, VALUE*);
- *var = rb_ary_new4(argc, argv);
- return argc;
- }
-
- if (ISDIGIT(*p)) {
- n = *p - '0';
- if (n > argc)
- rb_raise(rb_eArgError, "wrong # 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 == '*') {
- var = va_arg(vargs, VALUE*);
- if (argc > i) {
- if (var) *var = rb_ary_new4(argc-i, argv+i);
- }
- else {
- if (var) *var = rb_ary_new();
- }
- }
- else if (*p == '\0') {
- if (argc > i) {
- rb_raise(rb_eArgError, "wrong # of arguments(%d for %d)", argc, i);
- }
- }
- else {
- goto error;
- }
-
- va_end(vargs);
- 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 677b6a3cbd..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-1999 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 7e23afe37b..0000000000
--- a/config.guess
+++ /dev/null
@@ -1,961 +0,0 @@
-#! /bin/sh
-# Attempt to guess a canonical system name.
-# Copyright (C) 1992, 93, 94, 95, 96, 97, 1998 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.
-
-# Written by Per Bothner <bothner@cygnus.com>.
-# The master version of this file is at the FSF in /home/gd/gnu/lib.
-#
-# 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 system type (host/target name).
-#
-# Only a few systems have been added to this list; please add others
-# (but try to keep the structure clean).
-#
-
-# 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
-
-trap 'rm -f dummy.c dummy.o dummy; exit 1' 1 2 15
-
-# Note: order is significant - the case branches are not exclusive.
-
-case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
- *:OS/2:*:*)
- echo "i386-pc-os2_emx"
- 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
- .globl main
- .ent main
-main:
- .frame \$30,0,\$26,0
- .prologue 0
- .long 0x47e03d80 # implver $0
- lda \$2,259
- .long 0x47e20c21 # amask $2,$1
- srl \$1,8,\$2
- sll \$2,2,\$2
- sll \$0,3,\$0
- addl \$1,\$0,\$0
- addl \$2,\$0,\$0
- ret \$31,(\$26),1
- .end main
-EOF
- ${CC-cc} dummy.s -o dummy 2>/dev/null
- if test "$?" = 0 ; then
- ./dummy
- case "$?" in
- 7)
- UNAME_MACHINE="alpha"
- ;;
- 15)
- UNAME_MACHINE="alphaev5"
- ;;
- 14)
- UNAME_MACHINE="alphaev56"
- ;;
- 10)
- UNAME_MACHINE="alphapca56"
- ;;
- 16)
- UNAME_MACHINE="alphaev6"
- ;;
- esac
- fi
- rm -f dummy.s dummy
- echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[VTX]//' | tr [[A-Z]] [[a-z]]`
- exit 0 ;;
- 21064:Windows_NT:50:3)
- echo alpha-dec-winnt3.5
- exit 0 ;;
- Amiga*:UNIX_System_V:4.0:*)
- echo m68k-cbm-sysv4
- exit 0;;
- amiga:NetBSD:*:*)
- echo m68k-cbm-netbsd${UNAME_RELEASE}
- 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 ;;
- arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*)
- echo arm-acorn-riscix${UNAME_RELEASE}
- exit 0;;
- arm32:NetBSD:*:*)
- echo arm-unknown-netbsd`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'`
- exit 0 ;;
- SR2?01: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*:NetBSD:*:*)
- echo m68k-atari-netbsd${UNAME_RELEASE}
- exit 0 ;;
- atari*:OpenBSD:*:*)
- echo m68k-unknown-openbsd${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:*:*)
- echo clipper-intergraph-clix${UNAME_RELEASE}
- exit 0 ;;
- mips:*:*:UMIPS | mips:*:*:RISCos)
- sed 's/^ //' << EOF >dummy.c
- int main (argc, argv) int argc; char **argv; {
- #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-cc} dummy.c -o dummy \
- && ./dummy `echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` \
- && rm dummy.c dummy && exit 0
- rm -f dummy.c dummy
- echo mips-mips-riscos${UNAME_RELEASE}
- 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 -o $UNAME_PROCESSOR = mc88110 ] ; then
- if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx \
- -o ${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 ;;
- *: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-cc} dummy.c -o dummy && ./dummy && rm 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:*:4)
- IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | head -1 | awk '{ print $1 }'`
- if /usr/sbin/lsattr -EHl ${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=4.${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 NetBSD 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:*:*)
- case "${UNAME_MACHINE}" in
- 9000/31? ) HP_ARCH=m68000 ;;
- 9000/[34]?? ) HP_ARCH=m68k ;;
- 9000/[678]?? )
- sed 's/^ //' << EOF >dummy.c
- #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
- (${CC-cc} dummy.c -o dummy 2>/dev/null ) && HP_ARCH=`./dummy`
- rm -f dummy.c dummy
- esac
- HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
- echo ${HP_ARCH}-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-cc} dummy.c -o dummy && ./dummy && rm 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 ;;
- 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 ;;
- 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}
- exit 0 ;;
- CRAY-2:*:*:*)
- echo cray2-cray-unicos
- exit 0 ;;
- F300:UNIX_System_V:*:*)
- FUJITSU_SYS=`uname -p | tr [A-Z] [a-z] | sed -e 's/\///'`
- FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'`
- echo "f300-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
- exit 0 ;;
- F301:UNIX_System_V:*:*)
- echo f301-fujitsu-uxpv`echo $UNAME_RELEASE | sed 's/ .*//'`
- exit 0 ;;
- hp3[0-9][05]:NetBSD:*:*)
- echo m68k-hp-netbsd${UNAME_RELEASE}
- exit 0 ;;
- hp300:OpenBSD:*:*)
- echo m68k-unknown-openbsd${UNAME_RELEASE}
- exit 0 ;;
- sparc*:BSD/OS:*:*)
- echo sparc-unknown-bsdi${UNAME_RELEASE}
- exit 0 ;;
- i?86:BSD/386:*:* | i?86:BSD/OS:*:*)
- echo ${UNAME_MACHINE}-pc-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 ;;
- *:NetBSD:*:*)
- echo ${UNAME_MACHINE}-unknown-netbsd`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'`
- exit 0 ;;
- *:OpenBSD:*:*)
- echo ${UNAME_MACHINE}-unknown-openbsd`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'`
- exit 0 ;;
- *:*:*BOW*:*)
- echo i386-pc-bow
- exit 0 ;;
- i*:CYGWIN*:*)
- echo ${UNAME_MACHINE}-pc-cygwin
- exit 0 ;;
- i*:MINGW*:*)
- echo ${UNAME_MACHINE}-pc-mingw32
- 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 ;;
- *:Linux:*:*)
- # uname on the ARM produces all sorts of strangeness, and we need to
- # filter it out.
- case "$UNAME_MACHINE" in
- arm* | sa110*) UNAME_MACHINE="arm" ;;
- esac
-
- # The BFD linker knows what the default object file format is, so
- # first see if it will tell us.
- ld_help_string=`ld --help 2>&1`
- ld_supported_emulations=`echo $ld_help_string \
- | 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 ;;
- i?86coff) echo "${UNAME_MACHINE}-pc-linux-coff" ; exit 0 ;;
- sparclinux) echo "${UNAME_MACHINE}-unknown-linux-aout" ; exit 0 ;;
- m68klinux) echo "${UNAME_MACHINE}-unknown-linux-aout" ; exit 0 ;;
- elf32ppc) echo "powerpc-unknown-linux" ; exit 0 ;;
- esac
-
- if test "${UNAME_MACHINE}" = "alpha" ; then
- sed 's/^ //' <<EOF >dummy.s
- .globl main
- .ent main
- main:
- .frame \$30,0,\$26,0
- .prologue 0
- .long 0x47e03d80 # implver $0
- lda \$2,259
- .long 0x47e20c21 # amask $2,$1
- srl \$1,8,\$2
- sll \$2,2,\$2
- sll \$0,3,\$0
- addl \$1,\$0,\$0
- addl \$2,\$0,\$0
- ret \$31,(\$26),1
- .end main
-EOF
- LIBC=""
- ${CC-cc} dummy.s -o dummy 2>/dev/null
- if test "$?" = 0 ; then
- ./dummy
- case "$?" in
- 7)
- UNAME_MACHINE="alpha"
- ;;
- 15)
- UNAME_MACHINE="alphaev5"
- ;;
- 14)
- UNAME_MACHINE="alphaev56"
- ;;
- 10)
- UNAME_MACHINE="alphapca56"
- ;;
- 16)
- UNAME_MACHINE="alphaev6"
- ;;
- 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
- elif test "${UNAME_MACHINE}" = "mips" ; then
- cat >dummy.c <<EOF
-main(argc, argv)
- int argc;
- char *argv[];
-{
-#ifdef __MIPSEB__
- printf ("%s-unknown-linux\n", argv[1]);
-#endif
-#ifdef __MIPSEL__
- printf ("%sel-unknown-linux\n", argv[1]);
-#endif
- return 0;
-}
-EOF
- ${CC-cc} dummy.c -o dummy 2>/dev/null && ./dummy "${UNAME_MACHINE}" && rm dummy.c dummy && exit 0
- rm -f dummy.c dummy
- else
- case "${UNAME_MACHINE}" in
- i?86)
- VENDOR=pc;
- ;;
- *)
- VENDOR=unknown;
- ;;
- esac
- echo ${UNAME_MACHINE}-${VENDOR}-linux
- exit 0
- fi ;;
-# 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.*:*)
- if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then
- echo ${UNAME_MACHINE}-univel-sysv${UNAME_RELEASE}
- 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
- echo ${UNAME_MACHINE}-pc-sco$UNAME_REL
- else
- echo ${UNAME_MACHINE}-pc-sysv32
- fi
- exit 0 ;;
- i?86:UnixWare:*:*)
- if /bin/uname -X 2>/dev/null >/dev/null ; then
- (/bin/uname -X|egrep '^Machine.*Pentium' >/dev/null) \
- && UNAME_MACHINE=i586
- fi
- echo ${UNAME_MACHINE}-unixware-${UNAME_RELEASE}-${UNAME_VERSION}
- exit 0 ;;
- pc:*:*:*)
- # 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]??,*:*: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.*:*)
- echo m68k-unknown-lynxos${UNAME_RELEASE}
- exit 0 ;;
- mc68030:UNIX_System_V:4.*:*)
- echo m68k-atari-sysv4
- exit 0 ;;
- i?86:LynxOS:2.*:*)
- echo i386-unknown-lynxos${UNAME_RELEASE}
- exit 0 ;;
- TSUNAMI:LynxOS:2.*:*)
- echo sparc-unknown-lynxos${UNAME_RELEASE}
- exit 0 ;;
- rs6000:LynxOS:2.*:* | PowerPC:LynxOS:2.*:*)
- echo rs6000-unknown-lynxos${UNAME_RELEASE}
- exit 0 ;;
- SM[BE]S:UNIX_SV:*:*)
- echo mips-dde-sysv${UNAME_RELEASE}
- 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:*:* | R4000:UNIX_SV:*:*)
- if [ -d /usr/nec ]; then
- echo mips-nec-sysv`echo ${UNAME_RELEASE} | sed -n 's/\([.0-9]*\).*/\1/p'`
- else
- echo mips-unknown-sysv${UNAME_RELEASE}
- fi
- exit 0 ;;
- DS/90*:*:*:V20*)
- echo sparc-fujitsu-uxpds
- 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 ;;
-
- *:Rhapsody:*:*)
- arch=`/usr/bin/arch`
- case "$arch" in
- ppc)
- echo powerpc-apple-rhapsody${UNAME_RELEASE}
- ;;
- i[3456]86)
- echo i386-apple-rhapsody${UNAME_RELEASE}
- ;;
- *)
- echo $arch-apple-rhapsody${UNAME_RELEASE}
- ;;
- esac
- 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)
- printf ("vax-dec-bsd\n"); exit (0);
-#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-cc} dummy.c -o dummy 2>/dev/null && ./dummy && rm 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
-
-#echo '(Unable to guess system type)' 1>&2
-
-exit 1
diff --git a/config.sub b/config.sub
deleted file mode 100644
index aa2241272b..0000000000
--- a/config.sub
+++ /dev/null
@@ -1,969 +0,0 @@
-#! /bin/sh
-# Configuration validation subroutine script, version 1.1.
-# Copyright (C) 1991, 92-97, 1998 Free Software Foundation, Inc.
-# 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.
-
-# 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.
-
-if [ x$1 = x ]
-then
- echo Configuration name missing. 1>&2
- echo "Usage: $0 CPU-MFR-OPSYS" 1>&2
- echo "or $0 ALIAS" 1>&2
- echo where ALIAS is a recognized configuration type. 1>&2
- exit 1
-fi
-
-# First pass through any local machine types.
-case $1 in
- *local*)
- echo $1
- exit 0
- ;;
- *)
- ;;
-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
- linux-gnu*)
- 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)
- os=
- 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/'`
- ;;
- -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
- ;;
-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 | m32r | m68k | m68000 | m88k | ns32k | arc | arm \
- | arme[lb] | pyramid | mn10200 | mn10300 | tron | a29k \
- | 580 | i960 | h8300 | hppa | hppa1.0 | hppa1.1 | hppa2.0 | hppa2.0w \
- | alpha | alphaev5 | alphaev56 | we32k | ns16k | clipper \
- | i370 | sh | powerpc | powerpcle | 1750a | dsp16xx | pdp11 \
- | mips64 | mipsel | mips64el | mips64orion | mips64orionel \
- | mipstx39 | mipstx39el \
- | sparc | sparclet | sparclite | sparc64 | v850)
- basic_machine=$basic_machine-unknown
- ;;
- # 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[34567]86)
- basic_machine=$basic_machine-pc
- ;;
- i[3456]86-TOWNS*)
- basic_machine=`echo $basic_machine | sed -e 's/-TOWNS.*/-TOWNS/'`
- ;;
- # 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.
- vax-* | tahoe-* | i[34567]86-* | i860-* | m32r-* | m68k-* | m68000-* \
- | m88k-* | sparc-* | ns32k-* | fx80-* | arc-* | arm-* | c[123]* \
- | mips-* | pyramid-* | tron-* | a29k-* | romp-* | rs6000-* \
- | power-* | none-* | 580-* | cray2-* | h8300-* | i960-* \
- | xmp-* | ymp-* | hppa-* | hppa1.0-* | hppa1.1-* | hppa2.0-* | hppa2.0w-* \
- | alpha-* | alphaev5-* | alphaev56-* | we32k-* | cydra-* \
- | ns16k-* | pn-* | np1-* | xps100-* | clipper-* | orion-* \
- | sparclite-* | pdp11-* | sh-* | powerpc-* | powerpcle-* \
- | sparc64-* | mips64-* | mipsel-* \
- | mips64el-* | mips64orion-* | mips64orionel-* \
- | mipstx39-* | mipstx39el-* \
- | f301-*)
- ;;
- # Recognize the various machine names and aliases which stand
- # for a CPU type and a company and sometimes even an OS.
- 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc)
- basic_machine=m68000-att
- ;;
- 3b*)
- basic_machine=we32k-att
- ;;
- 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-cbm
- ;;
- amigaos | amigados)
- basic_machine=m68k-cbm
- os=-amigaos
- ;;
- amigaunix | amix)
- basic_machine=m68k-cbm
- os=-sysv4
- ;;
- apollo68)
- basic_machine=m68k-apollo
- os=-sysv
- ;;
- 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
- ;;
- [ctj]90-cray)
- basic_machine=c90-cray
- os=-unicos
- ;;
- crds | unos)
- basic_machine=m68k-crds
- ;;
- 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
- ;;
- fx2800)
- basic_machine=i860-alliant
- ;;
- genix)
- basic_machine=ns32k-ns
- ;;
- gmicro)
- basic_machine=tron-gmicro
- os=-sysv
- ;;
- h3050r* | hiux*)
- basic_machine=hppa1.1-hitachi
- os=-hiuxwe2
- ;;
- h8300hms)
- basic_machine=h8300-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
- ;;
- hp9k2[0-9][0-9] | hp9k31[0-9])
- basic_machine=m68000-hp
- ;;
- hp9k3[2-9][0-9])
- basic_machine=m68k-hp
- ;;
- hp9k7[0-9][0-9] | hp7[0-9][0-9] | hp9k8[0-9]7 | hp8[0-9]7)
- basic_machine=hppa1.1-hp
- ;;
- hp9k8[0-9][0-9] | hp8[0-9][0-9])
- basic_machine=hppa1.0-hp
- ;;
- hppa-next)
- os=-nextstep3
- ;;
- i370-ibm* | ibm*)
- basic_machine=i370-ibm
- os=-mvs
- ;;
-# I'm not sure what "Sysv32" means. Should this be sysv3.2?
- i[34567]86v32)
- basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
- os=-sysv32
- ;;
- i[34567]86v4*)
- basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
- os=-sysv4
- ;;
- i[34567]86v)
- basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
- os=-sysv
- ;;
- i[34567]86sol2)
- basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
- os=-solaris2
- ;;
- 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
- ;;
- miniframe)
- basic_machine=m68000-convergent
- ;;
- 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
- ;;
- ncr3000)
- basic_machine=i486-ncr
- os=-sysv4
- ;;
- 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
- ;;
- 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
- ;;
- np1)
- basic_machine=np1-gould
- ;;
- 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 | nexen)
- basic_machine=i586-pc
- ;;
- pentiumpro | p6 | k6 | 6x86)
- basic_machine=i686-pc
- ;;
- pentiumii | pentium2)
- basic_machine=i786-pc
- ;;
- pentium-* | p5-* | k5-* | nexen-*)
- basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- pentiumpro-* | p6-* | k6-* | 6x86-*)
- basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- pentiumii-* | pentium2-*)
- basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- pn)
- basic_machine=pn-gould
- ;;
- power) basic_machine=rs6000-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
- ;;
- rm[46]00)
- basic_machine=mips-siemens
- ;;
- rtpc | rtpc-*)
- basic_machine=romp-ibm
- ;;
- sequent)
- basic_machine=i386-sequent
- ;;
- sh)
- basic_machine=sh-hitachi
- os=-hms
- ;;
- sps7)
- basic_machine=m68k-bull
- os=-sysv2
- ;;
- spur)
- basic_machine=spur-unknown
- ;;
- 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
- ;;
- symmetry)
- basic_machine=i386-sequent
- os=-dynix
- ;;
- 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
- ;;
- 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
- ;;
- xmp)
- basic_machine=xmp-cray
- os=-unicos
- ;;
- xps | xps100)
- basic_machine=xps100-honeywell
- ;;
- 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.
- 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
- ;;
- pdp11)
- basic_machine=pdp11-dec
- ;;
- we32k)
- basic_machine=we32k-att
- ;;
- sparc)
- basic_machine=sparc-sun
- ;;
- cydra)
- basic_machine=cydra-cydrome
- ;;
- orion)
- basic_machine=orion-highlevel
- ;;
- orion105)
- basic_machine=clipper-highlevel
- ;;
- *)
- 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/'`
- ;;
- human)
- basic_machine=m68k-sharp
- os=-human
- ;;
- *)
- ;;
-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-gnu|'`
- ;;
- -os2_emx)
- ;;
- # 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* \
- | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \
- | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \
- | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
- | -mingw32* | -linux* | -uxpv* | -beos* | -rhapsody* )
- # Remember, each alternative MUST END IN *, to match a version number.
- ;;
- -sunos5*)
- os=`echo $os | sed -e 's|sunos5|solaris2|'`
- ;;
- -sunos6*)
- os=`echo $os | sed -e 's|sunos6|solaris3|'`
- ;;
- -osfrose*)
- os=-osfrose
- ;;
- -osf*)
- os=-osf
- ;;
- -utek*)
- os=-bsd
- ;;
- -dynix*)
- os=-bsd
- ;;
- -acis*)
- os=-aos
- ;;
- -ctix* | -uts*)
- os=-sysv
- ;;
- -ns2 )
- os=-nextstep2
- ;;
- # 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*)
- ;;
- -xenix)
- os=-xenix
- ;;
- -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*-semi)
- os=-aout
- ;;
- 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
- ;;
- *-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
- ;;
- *-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
- ;;
- f301-fujitsu)
- os=-uxpv
- ;;
- *)
- 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
- ;;
- -hpux*)
- vendor=hp
- ;;
- -hiux*)
- vendor=hitachi
- ;;
- -unos*)
- vendor=crds
- ;;
- -dgux*)
- vendor=dg
- ;;
- -luna*)
- vendor=omron
- ;;
- -genix*)
- vendor=ns
- ;;
- -mvs*)
- vendor=ibm
- ;;
- -ptx*)
- vendor=sequent
- ;;
- -vxsim* | -vxworks*)
- vendor=wrs
- ;;
- -aux*)
- vendor=apple
- ;;
- esac
- basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"`
- ;;
-esac
-
-echo $basic_machine$os
diff --git a/config_h.dj b/config_h.dj
deleted file mode 100644
index 029da840c4..0000000000
--- a/config_h.dj
+++ /dev/null
@@ -1,71 +0,0 @@
-#define USE_THREAD 1
-#define SIZEOF_INT 4
-#define SIZEOF_SHORT 2
-#define SIZEOF_LONG 4
-#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 HAVE_ATTR_NORETURN 1
-#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)>>y)
-#define FILE_COUNT _cnt
-#define DLEXT ".o"
-#define RUBY_LIB "/usr/local/lib/ruby/1.5"
-#define RUBY_SITE_LIB "/usr/local/lib/ruby/1.5/site_ruby"
-#define RUBY_PLATFORM "i386-djgpp"
-#define RUBY_ARCHLIB "/usr/local/lib/ruby/1.5/i386-djgpp"
-#define RUBY_SITE_ARCHLIB "/usr/local/lib/ruby/1.5/site_ruby/i386-djgpp"
diff --git a/config_s.dj b/config_s.dj
deleted file mode 100644
index 7ba18e4376..0000000000
--- a/config_s.dj
+++ /dev/null
@@ -1,56 +0,0 @@
-s%@CFLAGS@%-O2%g
-s%@CPPFLAGS@%%g
-s%@CXXFLAGS@%%g
-s%@DEFS@% -DUSE_THREAD=1 -DSIZEOF_INT=4 -DSIZEOF_LONG=4 -DSIZEOF_VOIDP=4 -DHAVE_PROTOTYPES=1 -DHAVE_STDARG_PROTOTYPES=1 -DHAVE_ATTR_NORETURN=1 -DHAVE_DIRENT_H=1 -DSTDC_HEADERS=1 -DHAVE_STDLIB_H=1 -DHAVE_UNISTD_H=1 -DHAVE_LIMITS_H=1 -DHAVE_SYS_FILE_H=1 -DHAVE_SYS_IOCTL_H=1 -DHAVE_PWD_H=1 -DHAVE_SYS_TIME_H=1 -DHAVE_SYS_TIMES_H=1 -DHAVE_SYS_PARAM_H=1 -DHAVE_SYS_WAIT_H=1 -DHAVE_STRING_H=1 -DHAVE_UTIME_H=1 -DHAVE_MEMORY_H=1 -DHAVE_DIRECT_H=1 -DHAVE_ST_BLKSIZE=1 -DHAVE_ST_RDEV=1 -DGETGROUPS_T=gid_t -DRETSIGTYPE=void -DHAVE_ALLOCA=1 -Dvfork=fork -DHAVE_DUP2=1 -DHAVE_SETENV=1 -DHAVE_MEMMOVE=1 -DHAVE_MKDIR=1 -DHAVE_STRCASECMP=1 -DHAVE_STRERROR=1 -DHAVE_STRFTIME=1 -DHAVE_STRCHR=1 -DHAVE_STRSTR=1 -DHAVE_STRTOUL=1 -DHAVE_STRDUP=1 -DHAVE_FMOD=1 -DHAVE_RANDOM=1 -DHAVE_WAITPID=1 -DHAVE_GETCWD=1 -DHAVE_TRUNCATE=1 -DHAVE_CHSIZE=1 -DHAVE_TIMES=1 -DHAVE_UTIMES=1 -DHAVE_FCNTL=1 -DHAVE_SETITIMER=1 -DHAVE_GETGROUPS=1 -DHAVE_SIGPROCMASK=1 -DHAVE_SIGACTION=1 -DHAVE_SETSID=1 -DPOSIX_SIGNAL=1 -DBSD_SETPGRP=setpgrp -DRSHIFT=\(x,y\)\ \(\(x\)\>\>y\) -DFILE_COUNT=_cnt -DDLEXT=\".so\" -DRUBY_LIB=\"/usr/local/lib/ruby\" -DRUBY_SITE_LIB=\"/usr/local/lib/ruby/site_ruby\" -DRUBY_ARCHLIB=\"/usr/local/lib/ruby/i386-djgpp\" -DRUBY_SITE_ARCHLIB=\"/usr/local/lib/ruby/site_ruby/i386-djgpp\" -DRUBY_PLATFORM=\"i386-djgpp\" %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-djgpp%g
-s%@host_alias@%i386-djgpp%g
-s%@host_cpu@%i386%g
-s%@host_vendor@%pc%g
-s%@host_os@%djgpp%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 fnmatch.o snprintf.o%g
-s%@ALLOCA@%%g
-s%@DEFAULT_KCODE@%%g
-s%@EXEEXT@%.exe%g
-s%@OBJEXT@%o%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%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%@srcdir%.%g
-s%@arch@%i386-djgpp%g
-ac_given_srcdir=.
diff --git a/configure b/configure
deleted file mode 100644
index 0a63be065b..0000000000
--- a/configure
+++ /dev/null
@@ -1,5010 +0,0 @@
-#! /bin/sh
-
-# Guess values for system-dependent variables and create Makefiles.
-# Generated automatically using autoconf version 2.13
-# 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.
-
-# Defaults:
-ac_help=
-ac_default_prefix=/usr/local
-# Any additions from configure.in:
-ac_help="$ac_help
---without-gcc never use gcc"
-ac_help="$ac_help
---enable-fat-binary build a NeXT/Apple Multi Architecture Binary. "
-ac_help="$ac_help
---with-default-kcode=CODE specify default value for \$KCODE (utf8|euc|sjis|none)"
-ac_help="$ac_help
---with-dln-a-out use dln_a_out if possible"
-ac_help="$ac_help
---with-static-linked-ext link external modules statically"
-ac_help="$ac_help
---enable-shared build a shared library for Ruby. "
-ac_help="$ac_help
---with-search-path specify the additional search path"
-
-# Initialize some variables set by options.
-# The variables have the same names as the options, with
-# dashes changed to underlines.
-build=NONE
-cache_file=./config.cache
-exec_prefix=NONE
-host=NONE
-no_create=
-nonopt=NONE
-no_recursion=
-prefix=NONE
-program_prefix=NONE
-program_suffix=NONE
-program_transform_name=s,x,x,
-silent=
-site=
-srcdir=
-target=NONE
-verbose=
-x_includes=NONE
-x_libraries=NONE
-bindir='${exec_prefix}/bin'
-sbindir='${exec_prefix}/sbin'
-libexecdir='${exec_prefix}/libexec'
-datadir='${prefix}/share'
-sysconfdir='${prefix}/etc'
-sharedstatedir='${prefix}/com'
-localstatedir='${prefix}/var'
-libdir='${exec_prefix}/lib'
-includedir='${prefix}/include'
-oldincludedir='/usr/include'
-infodir='${prefix}/info'
-mandir='${prefix}/man'
-
-# Initialize some other variables.
-subdirs=
-MFLAGS= MAKEFLAGS=
-SHELL=${CONFIG_SHELL-/bin/sh}
-# Maximum number of lines to put in a shell here document.
-ac_max_here_lines=12
-
-ac_prev=
-for ac_option
-do
-
- # If the previous option needs an argument, assign it.
- if test -n "$ac_prev"; then
- eval "$ac_prev=\$ac_option"
- ac_prev=
- continue
- fi
-
- case "$ac_option" in
- -*=*) ac_optarg=`echo "$ac_option" | sed 's/[-_a-zA-Z0-9]*=//'` ;;
- *) ac_optarg= ;;
- esac
-
- # Accept the important Cygnus configure options, so we can diagnose typos.
-
- case "$ac_option" in
-
- -bindir | --bindir | --bindi | --bind | --bin | --bi)
- ac_prev=bindir ;;
- -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*)
- bindir="$ac_optarg" ;;
-
- -build | --build | --buil | --bui | --bu)
- ac_prev=build ;;
- -build=* | --build=* | --buil=* | --bui=* | --bu=*)
- build="$ac_optarg" ;;
-
- -cache-file | --cache-file | --cache-fil | --cache-fi \
- | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c)
- ac_prev=cache_file ;;
- -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \
- | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*)
- cache_file="$ac_optarg" ;;
-
- -datadir | --datadir | --datadi | --datad | --data | --dat | --da)
- ac_prev=datadir ;;
- -datadir=* | --datadir=* | --datadi=* | --datad=* | --data=* | --dat=* \
- | --da=*)
- datadir="$ac_optarg" ;;
-
- -disable-* | --disable-*)
- ac_feature=`echo $ac_option|sed -e 's/-*disable-//'`
- # Reject names that are not valid shell variable names.
- if test -n "`echo $ac_feature| sed 's/[-a-zA-Z0-9_]//g'`"; then
- { echo "configure: error: $ac_feature: invalid feature name" 1>&2; exit 1; }
- fi
- ac_feature=`echo $ac_feature| sed 's/-/_/g'`
- eval "enable_${ac_feature}=no" ;;
-
- -enable-* | --enable-*)
- ac_feature=`echo $ac_option|sed -e 's/-*enable-//' -e 's/=.*//'`
- # Reject names that are not valid shell variable names.
- if test -n "`echo $ac_feature| sed 's/[-_a-zA-Z0-9]//g'`"; then
- { echo "configure: error: $ac_feature: invalid feature name" 1>&2; exit 1; }
- fi
- ac_feature=`echo $ac_feature| sed 's/-/_/g'`
- case "$ac_option" in
- *=*) ;;
- *) ac_optarg=yes ;;
- esac
- eval "enable_${ac_feature}='$ac_optarg'" ;;
-
- -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
- | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
- | --exec | --exe | --ex)
- ac_prev=exec_prefix ;;
- -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \
- | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \
- | --exec=* | --exe=* | --ex=*)
- exec_prefix="$ac_optarg" ;;
-
- -gas | --gas | --ga | --g)
- # Obsolete; use --with-gas.
- with_gas=yes ;;
-
- -help | --help | --hel | --he)
- # Omit some internal or obsolete options to make the list less imposing.
- # This message is too long to be a string in the A/UX 3.1 sh.
- cat << EOF
-Usage: configure [options] [host]
-Options: [defaults in brackets after descriptions]
-Configuration:
- --cache-file=FILE cache test results in FILE
- --help print this message
- --no-create do not create output files
- --quiet, --silent do not print \`checking...' messages
- --version print the version of autoconf that created configure
-Directory and file names:
- --prefix=PREFIX install architecture-independent files in PREFIX
- [$ac_default_prefix]
- --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX
- [same as prefix]
- --bindir=DIR user executables in DIR [EPREFIX/bin]
- --sbindir=DIR system admin executables in DIR [EPREFIX/sbin]
- --libexecdir=DIR program executables in DIR [EPREFIX/libexec]
- --datadir=DIR read-only architecture-independent data in DIR
- [PREFIX/share]
- --sysconfdir=DIR read-only single-machine data in DIR [PREFIX/etc]
- --sharedstatedir=DIR modifiable architecture-independent data in DIR
- [PREFIX/com]
- --localstatedir=DIR modifiable single-machine data in DIR [PREFIX/var]
- --libdir=DIR object code libraries in DIR [EPREFIX/lib]
- --includedir=DIR C header files in DIR [PREFIX/include]
- --oldincludedir=DIR C header files for non-gcc in DIR [/usr/include]
- --infodir=DIR info documentation in DIR [PREFIX/info]
- --mandir=DIR man documentation in DIR [PREFIX/man]
- --srcdir=DIR find the sources in DIR [configure dir or ..]
- --program-prefix=PREFIX prepend PREFIX to installed program names
- --program-suffix=SUFFIX append SUFFIX to installed program names
- --program-transform-name=PROGRAM
- run sed PROGRAM on installed program names
-EOF
- cat << EOF
-Host type:
- --build=BUILD configure for building on BUILD [BUILD=HOST]
- --host=HOST configure for HOST [guessed]
- --target=TARGET configure for TARGET [TARGET=HOST]
-Features and packages:
- --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no)
- --enable-FEATURE[=ARG] include FEATURE [ARG=yes]
- --with-PACKAGE[=ARG] use PACKAGE [ARG=yes]
- --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no)
- --x-includes=DIR X include files are in DIR
- --x-libraries=DIR X library files are in DIR
-EOF
- if test -n "$ac_help"; then
- echo "--enable and --with options recognized:$ac_help"
- fi
- exit 0 ;;
-
- -host | --host | --hos | --ho)
- ac_prev=host ;;
- -host=* | --host=* | --hos=* | --ho=*)
- host="$ac_optarg" ;;
-
- -includedir | --includedir | --includedi | --included | --include \
- | --includ | --inclu | --incl | --inc)
- ac_prev=includedir ;;
- -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \
- | --includ=* | --inclu=* | --incl=* | --inc=*)
- includedir="$ac_optarg" ;;
-
- -infodir | --infodir | --infodi | --infod | --info | --inf)
- ac_prev=infodir ;;
- -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*)
- infodir="$ac_optarg" ;;
-
- -libdir | --libdir | --libdi | --libd)
- ac_prev=libdir ;;
- -libdir=* | --libdir=* | --libdi=* | --libd=*)
- libdir="$ac_optarg" ;;
-
- -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \
- | --libexe | --libex | --libe)
- ac_prev=libexecdir ;;
- -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \
- | --libexe=* | --libex=* | --libe=*)
- libexecdir="$ac_optarg" ;;
-
- -localstatedir | --localstatedir | --localstatedi | --localstated \
- | --localstate | --localstat | --localsta | --localst \
- | --locals | --local | --loca | --loc | --lo)
- ac_prev=localstatedir ;;
- -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \
- | --localstate=* | --localstat=* | --localsta=* | --localst=* \
- | --locals=* | --local=* | --loca=* | --loc=* | --lo=*)
- localstatedir="$ac_optarg" ;;
-
- -mandir | --mandir | --mandi | --mand | --man | --ma | --m)
- ac_prev=mandir ;;
- -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*)
- mandir="$ac_optarg" ;;
-
- -nfp | --nfp | --nf)
- # Obsolete; use --without-fp.
- with_fp=no ;;
-
- -no-create | --no-create | --no-creat | --no-crea | --no-cre \
- | --no-cr | --no-c)
- no_create=yes ;;
-
- -no-recursion | --no-recursion | --no-recursio | --no-recursi \
- | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r)
- no_recursion=yes ;;
-
- -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \
- | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \
- | --oldin | --oldi | --old | --ol | --o)
- ac_prev=oldincludedir ;;
- -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \
- | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \
- | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*)
- oldincludedir="$ac_optarg" ;;
-
- -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
- ac_prev=prefix ;;
- -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
- prefix="$ac_optarg" ;;
-
- -program-prefix | --program-prefix | --program-prefi | --program-pref \
- | --program-pre | --program-pr | --program-p)
- ac_prev=program_prefix ;;
- -program-prefix=* | --program-prefix=* | --program-prefi=* \
- | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*)
- program_prefix="$ac_optarg" ;;
-
- -program-suffix | --program-suffix | --program-suffi | --program-suff \
- | --program-suf | --program-su | --program-s)
- ac_prev=program_suffix ;;
- -program-suffix=* | --program-suffix=* | --program-suffi=* \
- | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*)
- program_suffix="$ac_optarg" ;;
-
- -program-transform-name | --program-transform-name \
- | --program-transform-nam | --program-transform-na \
- | --program-transform-n | --program-transform- \
- | --program-transform | --program-transfor \
- | --program-transfo | --program-transf \
- | --program-trans | --program-tran \
- | --progr-tra | --program-tr | --program-t)
- ac_prev=program_transform_name ;;
- -program-transform-name=* | --program-transform-name=* \
- | --program-transform-nam=* | --program-transform-na=* \
- | --program-transform-n=* | --program-transform-=* \
- | --program-transform=* | --program-transfor=* \
- | --program-transfo=* | --program-transf=* \
- | --program-trans=* | --program-tran=* \
- | --progr-tra=* | --program-tr=* | --program-t=*)
- program_transform_name="$ac_optarg" ;;
-
- -q | -quiet | --quiet | --quie | --qui | --qu | --q \
- | -silent | --silent | --silen | --sile | --sil)
- silent=yes ;;
-
- -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb)
- ac_prev=sbindir ;;
- -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
- | --sbi=* | --sb=*)
- sbindir="$ac_optarg" ;;
-
- -sharedstatedir | --sharedstatedir | --sharedstatedi \
- | --sharedstated | --sharedstate | --sharedstat | --sharedsta \
- | --sharedst | --shareds | --shared | --share | --shar \
- | --sha | --sh)
- ac_prev=sharedstatedir ;;
- -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \
- | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \
- | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \
- | --sha=* | --sh=*)
- sharedstatedir="$ac_optarg" ;;
-
- -site | --site | --sit)
- ac_prev=site ;;
- -site=* | --site=* | --sit=*)
- site="$ac_optarg" ;;
-
- -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
- ac_prev=srcdir ;;
- -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
- srcdir="$ac_optarg" ;;
-
- -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \
- | --syscon | --sysco | --sysc | --sys | --sy)
- ac_prev=sysconfdir ;;
- -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \
- | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*)
- sysconfdir="$ac_optarg" ;;
-
- -target | --target | --targe | --targ | --tar | --ta | --t)
- ac_prev=target ;;
- -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*)
- target="$ac_optarg" ;;
-
- -v | -verbose | --verbose | --verbos | --verbo | --verb)
- verbose=yes ;;
-
- -version | --version | --versio | --versi | --vers)
- echo "configure generated by autoconf version 2.13"
- exit 0 ;;
-
- -with-* | --with-*)
- ac_package=`echo $ac_option|sed -e 's/-*with-//' -e 's/=.*//'`
- # Reject names that are not valid shell variable names.
- if test -n "`echo $ac_package| sed 's/[-_a-zA-Z0-9]//g'`"; then
- { echo "configure: error: $ac_package: invalid package name" 1>&2; exit 1; }
- fi
- ac_package=`echo $ac_package| sed 's/-/_/g'`
- case "$ac_option" in
- *=*) ;;
- *) ac_optarg=yes ;;
- esac
- eval "with_${ac_package}='$ac_optarg'" ;;
-
- -without-* | --without-*)
- ac_package=`echo $ac_option|sed -e 's/-*without-//'`
- # Reject names that are not valid shell variable names.
- if test -n "`echo $ac_package| sed 's/[-a-zA-Z0-9_]//g'`"; then
- { echo "configure: error: $ac_package: invalid package name" 1>&2; exit 1; }
- fi
- ac_package=`echo $ac_package| sed 's/-/_/g'`
- eval "with_${ac_package}=no" ;;
-
- --x)
- # Obsolete; use --with-x.
- with_x=yes ;;
-
- -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \
- | --x-incl | --x-inc | --x-in | --x-i)
- ac_prev=x_includes ;;
- -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \
- | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*)
- x_includes="$ac_optarg" ;;
-
- -x-libraries | --x-libraries | --x-librarie | --x-librari \
- | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l)
- ac_prev=x_libraries ;;
- -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \
- | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*)
- x_libraries="$ac_optarg" ;;
-
- -*) { echo "configure: error: $ac_option: invalid option; use --help to show usage" 1>&2; exit 1; }
- ;;
-
- *)
- if test -n "`echo $ac_option| sed 's/[-a-z0-9.]//g'`"; then
- echo "configure: warning: $ac_option: invalid host type" 1>&2
- fi
- if test "x$nonopt" != xNONE; then
- { echo "configure: error: can only configure for one host and one target at a time" 1>&2; exit 1; }
- fi
- nonopt="$ac_option"
- ;;
-
- esac
-done
-
-if test -n "$ac_prev"; then
- { echo "configure: error: missing argument to --`echo $ac_prev | sed 's/_/-/g'`" 1>&2; exit 1; }
-fi
-
-trap 'rm -fr conftest* confdefs* core core.* *.core $ac_clean_files; exit 1' 1 2 15
-
-# File descriptor usage:
-# 0 standard input
-# 1 file creation
-# 2 errors and warnings
-# 3 some systems may open it to /dev/tty
-# 4 used on the Kubota Titan
-# 6 checking for... messages and results
-# 5 compiler messages saved in config.log
-if test "$silent" = yes; then
- exec 6>/dev/null
-else
- exec 6>&1
-fi
-exec 5>./config.log
-
-echo "\
-This file contains any messages produced by compilers while
-running configure, to aid debugging if configure makes a mistake.
-" 1>&5
-
-# Strip out --no-create and --no-recursion so they do not pile up.
-# Also quote any args containing shell metacharacters.
-ac_configure_args=
-for ac_arg
-do
- case "$ac_arg" in
- -no-create | --no-create | --no-creat | --no-crea | --no-cre \
- | --no-cr | --no-c) ;;
- -no-recursion | --no-recursion | --no-recursio | --no-recursi \
- | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) ;;
- *" "*|*" "*|*[\[\]\~\#\$\^\&\*\(\)\{\}\\\|\;\<\>\?]*)
- ac_configure_args="$ac_configure_args '$ac_arg'" ;;
- *) ac_configure_args="$ac_configure_args $ac_arg" ;;
- esac
-done
-
-# NLS nuisances.
-# Only set these to C if already set. These must not be set unconditionally
-# because not all systems understand e.g. LANG=C (notably SCO).
-# Fixing LC_MESSAGES prevents Solaris sh from translating var values in `set'!
-# Non-C LC_CTYPE values break the ctype check.
-if test "${LANG+set}" = set; then LANG=C; export LANG; fi
-if test "${LC_ALL+set}" = set; then LC_ALL=C; export LC_ALL; fi
-if test "${LC_MESSAGES+set}" = set; then LC_MESSAGES=C; export LC_MESSAGES; fi
-if test "${LC_CTYPE+set}" = set; then LC_CTYPE=C; export LC_CTYPE; fi
-
-# confdefs.h avoids OS command line length limits that DEFS can exceed.
-rm -rf conftest* confdefs.h
-# AIX cpp loses on an empty file, so make sure it contains at least a newline.
-echo > confdefs.h
-
-# A filename unique to this package, relative to the directory that
-# configure is in, which we can look for to find out if srcdir is correct.
-ac_unique_file=ruby.h
-
-# Find the source files, if location was not specified.
-if test -z "$srcdir"; then
- ac_srcdir_defaulted=yes
- # Try the directory containing this script, then its parent.
- ac_prog=$0
- ac_confdir=`echo $ac_prog|sed 's%/[^/][^/]*$%%'`
- test "x$ac_confdir" = "x$ac_prog" && ac_confdir=.
- srcdir=$ac_confdir
- if test ! -r $srcdir/$ac_unique_file; then
- srcdir=..
- fi
-else
- ac_srcdir_defaulted=no
-fi
-if test ! -r $srcdir/$ac_unique_file; then
- if test "$ac_srcdir_defaulted" = yes; then
- { echo "configure: error: can not find sources in $ac_confdir or .." 1>&2; exit 1; }
- else
- { echo "configure: error: can not find sources in $srcdir" 1>&2; exit 1; }
- fi
-fi
-srcdir=`echo "${srcdir}" | sed 's%\([^/]\)/*$%\1%'`
-
-# Prefer explicitly selected file to automatically selected ones.
-if test -z "$CONFIG_SITE"; then
- if test "x$prefix" != xNONE; then
- CONFIG_SITE="$prefix/share/config.site $prefix/etc/config.site"
- else
- CONFIG_SITE="$ac_default_prefix/share/config.site $ac_default_prefix/etc/config.site"
- fi
-fi
-for ac_site_file in $CONFIG_SITE; do
- if test -r "$ac_site_file"; then
- echo "loading site script $ac_site_file"
- . "$ac_site_file"
- fi
-done
-
-if test -r "$cache_file"; then
- echo "loading cache $cache_file"
- . $cache_file
-else
- echo "creating cache $cache_file"
- > $cache_file
-fi
-
-ac_ext=c
-# CFLAGS is not in ac_cpp because -g, -O, etc. are not valid cpp options.
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='${CC-cc} -c $CFLAGS $CPPFLAGS conftest.$ac_ext 1>&5'
-ac_link='${CC-cc} -o conftest${ac_exeext} $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS 1>&5'
-cross_compiling=$ac_cv_prog_cc_cross
-
-ac_exeext=
-ac_objext=o
-if (echo "testing\c"; echo 1,2,3) | grep c >/dev/null; then
- # Stardent Vistra SVR4 grep lacks -e, says ghazi@caip.rutgers.edu.
- if (echo -n testing; echo 1,2,3) | sed s/-n/xn/ | grep xn >/dev/null; then
- ac_n= ac_c='
-' ac_t=' '
- else
- ac_n=-n ac_c= ac_t=
- fi
-else
- ac_n= ac_c='\c' ac_t=
-fi
-
-
-
-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]*\)"'`
-
-
-
-# Check whether --with-gcc or --without-gcc was given.
-if test "${with_gcc+set}" = set; then
- withval="$with_gcc"
-
- case $withval in
- no) CC=cc
- without_gcc=yes;;
- yes) CC=gcc
- without_gcc=no;;
- *) CC=$withval
- without_gcc=$withval;;
- esac
-else
- without_gcc=no
-fi
-
-if test ! -z "$ac_cv_prog_CC" -a ! -z "$CC" -a "$CC" != "$ac_cv_prog_CC"
-then
- { echo "configure: error: cached CC is different -- throw away $cache_file
-(it is also a good idea to do 'make clean' before compiling)" 1>&2; exit 1; }
-fi
-
-ac_aux_dir=
-for ac_dir in $srcdir $srcdir/.. $srcdir/../..; do
- if test -f $ac_dir/install-sh; then
- ac_aux_dir=$ac_dir
- ac_install_sh="$ac_aux_dir/install-sh -c"
- break
- elif test -f $ac_dir/install.sh; then
- ac_aux_dir=$ac_dir
- ac_install_sh="$ac_aux_dir/install.sh -c"
- break
- fi
-done
-if test -z "$ac_aux_dir"; then
- { echo "configure: error: can not find install-sh or install.sh in $srcdir $srcdir/.. $srcdir/../.." 1>&2; exit 1; }
-fi
-ac_config_guess=$ac_aux_dir/config.guess
-ac_config_sub=$ac_aux_dir/config.sub
-ac_configure=$ac_aux_dir/configure # This should be Cygnus configure.
-
-
-# Make sure we can run config.sub.
-if ${CONFIG_SHELL-/bin/sh} $ac_config_sub sun4 >/dev/null 2>&1; then :
-else { echo "configure: error: can not run $ac_config_sub" 1>&2; exit 1; }
-fi
-
-echo $ac_n "checking host system type""... $ac_c" 1>&6
-echo "configure:595: checking host system type" >&5
-
-host_alias=$host
-case "$host_alias" in
-NONE)
- case $nonopt in
- NONE)
- if host_alias=`${CONFIG_SHELL-/bin/sh} $ac_config_guess`; then :
- else { echo "configure: error: can not guess host type; you must specify one" 1>&2; exit 1; }
- fi ;;
- *) host_alias=$nonopt ;;
- esac ;;
-esac
-
-host=`${CONFIG_SHELL-/bin/sh} $ac_config_sub $host_alias`
-host_cpu=`echo $host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\1/'`
-host_vendor=`echo $host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\2/'`
-host_os=`echo $host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\3/'`
-echo "$ac_t""$host" 1>&6
-
-
-fat_binary=no
-# Check whether --enable-fat-binary or --disable-fat-binary was given.
-if test "${enable_fat_binary+set}" = set; then
- enableval="$enable_fat_binary"
- fat_binary=$enableval
-fi
-
- if test "$fat_binary" = yes ; then
-
- echo $ac_n "checking target architecture""... $ac_c" 1>&6
-echo "configure:626: checking target architecture" >&5
-
- case "$host_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
- ;;
- 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
- cat >> confdefs.h <<\EOF
-#define NEXT_FAT_BINARY 1
-EOF
-
- echo "."
-fi
-
-if test "$program_transform_name" = s,x,x,; then
- program_transform_name=
-else
- # Double any \ or $. echo might interpret backslashes.
- cat <<\EOF_SED > conftestsed
-s,\\,\\\\,g; s,\$,$$,g
-EOF_SED
- program_transform_name="`echo $program_transform_name|sed -f conftestsed`"
- rm -f conftestsed
-fi
-test "$program_prefix" != NONE &&
- program_transform_name="s,^,${program_prefix},; $program_transform_name"
-# Use a double $ so make ignores it.
-test "$program_suffix" != NONE &&
- program_transform_name="s,\$\$,${program_suffix},; $program_transform_name"
-
-# sed with no file args requires a program.
-test "$program_transform_name" = "" && program_transform_name="s,x,x,"
-
-
-# Extract the first word of "gcc", so it can be a program name with args.
-set dummy gcc; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:682: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_CC'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- if test -n "$CC"; then
- ac_cv_prog_CC="$CC" # Let the user override the test.
-else
- IFS="${IFS= }"; ac_save_ifs="$IFS"; IFS=":"
- ac_dummy="$PATH"
- for ac_dir in $ac_dummy; do
- test -z "$ac_dir" && ac_dir=.
- if test -f $ac_dir/$ac_word; then
- ac_cv_prog_CC="gcc"
- break
- fi
- done
- IFS="$ac_save_ifs"
-fi
-fi
-CC="$ac_cv_prog_CC"
-if test -n "$CC"; then
- echo "$ac_t""$CC" 1>&6
-else
- echo "$ac_t""no" 1>&6
-fi
-
-if test -z "$CC"; then
- # Extract the first word of "cc", so it can be a program name with args.
-set dummy cc; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:712: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_CC'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- if test -n "$CC"; then
- ac_cv_prog_CC="$CC" # Let the user override the test.
-else
- IFS="${IFS= }"; ac_save_ifs="$IFS"; IFS=":"
- ac_prog_rejected=no
- ac_dummy="$PATH"
- for ac_dir in $ac_dummy; do
- test -z "$ac_dir" && ac_dir=.
- if test -f $ac_dir/$ac_word; then
- if test "$ac_dir/$ac_word" = "/usr/ucb/cc"; then
- ac_prog_rejected=yes
- continue
- fi
- ac_cv_prog_CC="cc"
- break
- fi
- done
- IFS="$ac_save_ifs"
-if test $ac_prog_rejected = yes; then
- # We found a bogon in the path, so make sure we never use it.
- set dummy $ac_cv_prog_CC
- shift
- if test $# -gt 0; then
- # We chose a different compiler from the bogus one.
- # However, it has the same basename, so the bogon will be chosen
- # first if we set CC to just the basename; use the full file name.
- shift
- set dummy "$ac_dir/$ac_word" "$@"
- shift
- ac_cv_prog_CC="$@"
- fi
-fi
-fi
-fi
-CC="$ac_cv_prog_CC"
-if test -n "$CC"; then
- echo "$ac_t""$CC" 1>&6
-else
- echo "$ac_t""no" 1>&6
-fi
-
- if test -z "$CC"; then
- case "`uname -s`" in
- *win32* | *WIN32*)
- # Extract the first word of "cl", so it can be a program name with args.
-set dummy cl; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:763: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_CC'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- if test -n "$CC"; then
- ac_cv_prog_CC="$CC" # Let the user override the test.
-else
- IFS="${IFS= }"; ac_save_ifs="$IFS"; IFS=":"
- ac_dummy="$PATH"
- for ac_dir in $ac_dummy; do
- test -z "$ac_dir" && ac_dir=.
- if test -f $ac_dir/$ac_word; then
- ac_cv_prog_CC="cl"
- break
- fi
- done
- IFS="$ac_save_ifs"
-fi
-fi
-CC="$ac_cv_prog_CC"
-if test -n "$CC"; then
- echo "$ac_t""$CC" 1>&6
-else
- echo "$ac_t""no" 1>&6
-fi
- ;;
- esac
- fi
- test -z "$CC" && { echo "configure: error: no acceptable cc found in \$PATH" 1>&2; exit 1; }
-fi
-
-echo $ac_n "checking whether the C compiler ($CC $CFLAGS $LDFLAGS) works""... $ac_c" 1>&6
-echo "configure:795: checking whether the C compiler ($CC $CFLAGS $LDFLAGS) works" >&5
-
-ac_ext=c
-# CFLAGS is not in ac_cpp because -g, -O, etc. are not valid cpp options.
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='${CC-cc} -c $CFLAGS $CPPFLAGS conftest.$ac_ext 1>&5'
-ac_link='${CC-cc} -o conftest${ac_exeext} $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS 1>&5'
-cross_compiling=$ac_cv_prog_cc_cross
-
-cat > conftest.$ac_ext << EOF
-
-#line 806 "configure"
-#include "confdefs.h"
-
-main(){return(0);}
-EOF
-if { (eval echo configure:811: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
- ac_cv_prog_cc_works=yes
- # If we can't run a trivial program, we are probably using a cross compiler.
- if (./conftest; exit) 2>/dev/null; then
- ac_cv_prog_cc_cross=no
- else
- ac_cv_prog_cc_cross=yes
- fi
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- ac_cv_prog_cc_works=no
-fi
-rm -fr conftest*
-ac_ext=c
-# CFLAGS is not in ac_cpp because -g, -O, etc. are not valid cpp options.
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='${CC-cc} -c $CFLAGS $CPPFLAGS conftest.$ac_ext 1>&5'
-ac_link='${CC-cc} -o conftest${ac_exeext} $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS 1>&5'
-cross_compiling=$ac_cv_prog_cc_cross
-
-echo "$ac_t""$ac_cv_prog_cc_works" 1>&6
-if test $ac_cv_prog_cc_works = no; then
- { echo "configure: error: installation or configuration problem: C compiler cannot create executables." 1>&2; exit 1; }
-fi
-echo $ac_n "checking whether the C compiler ($CC $CFLAGS $LDFLAGS) is a cross-compiler""... $ac_c" 1>&6
-echo "configure:837: checking whether the C compiler ($CC $CFLAGS $LDFLAGS) is a cross-compiler" >&5
-echo "$ac_t""$ac_cv_prog_cc_cross" 1>&6
-cross_compiling=$ac_cv_prog_cc_cross
-
-echo $ac_n "checking whether we are using GNU C""... $ac_c" 1>&6
-echo "configure:842: checking whether we are using GNU C" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_gcc'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.c <<EOF
-#ifdef __GNUC__
- yes;
-#endif
-EOF
-if { ac_try='${CC-cc} -E conftest.c'; { (eval echo configure:851: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }; } | egrep yes >/dev/null 2>&1; then
- ac_cv_prog_gcc=yes
-else
- ac_cv_prog_gcc=no
-fi
-fi
-
-echo "$ac_t""$ac_cv_prog_gcc" 1>&6
-
-if test $ac_cv_prog_gcc = yes; then
- GCC=yes
-else
- GCC=
-fi
-
-ac_test_CFLAGS="${CFLAGS+set}"
-ac_save_CFLAGS="$CFLAGS"
-CFLAGS=
-echo $ac_n "checking whether ${CC-cc} accepts -g""... $ac_c" 1>&6
-echo "configure:870: checking whether ${CC-cc} accepts -g" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_cc_g'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- echo 'void f(){}' > conftest.c
-if test -z "`${CC-cc} -g -c conftest.c 2>&1`"; then
- ac_cv_prog_cc_g=yes
-else
- ac_cv_prog_cc_g=no
-fi
-rm -f conftest*
-
-fi
-
-echo "$ac_t""$ac_cv_prog_cc_g" 1>&6
-if test "$ac_test_CFLAGS" = set; then
- CFLAGS="$ac_save_CFLAGS"
-elif test $ac_cv_prog_cc_g = yes; then
- if test "$GCC" = yes; then
- CFLAGS="-g -O2"
- else
- CFLAGS="-g"
- fi
-else
- if test "$GCC" = yes; then
- CFLAGS="-O2"
- else
- CFLAGS=
- fi
-fi
-
-echo $ac_n "checking how to run the C preprocessor""... $ac_c" 1>&6
-echo "configure:902: checking how to run the C preprocessor" >&5
-# On Suns, sometimes $CPP names a directory.
-if test -n "$CPP" && test -d "$CPP"; then
- CPP=
-fi
-if test -z "$CPP"; then
-if eval "test \"`echo '$''{'ac_cv_prog_CPP'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- # This must be in double quotes, not single quotes, because CPP may get
- # substituted into the Makefile and "${CC-cc}" will confuse make.
- CPP="${CC-cc} -E"
- # On the NeXT, cc -E runs the code through the compiler's parser,
- # not just through cpp.
- cat > conftest.$ac_ext <<EOF
-#line 917 "configure"
-#include "confdefs.h"
-#include <assert.h>
-Syntax Error
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:923: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
-if test -z "$ac_err"; then
- :
-else
- echo "$ac_err" >&5
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- CPP="${CC-cc} -E -traditional-cpp"
- cat > conftest.$ac_ext <<EOF
-#line 934 "configure"
-#include "confdefs.h"
-#include <assert.h>
-Syntax Error
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:940: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
-if test -z "$ac_err"; then
- :
-else
- echo "$ac_err" >&5
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- CPP="${CC-cc} -nologo -E"
- cat > conftest.$ac_ext <<EOF
-#line 951 "configure"
-#include "confdefs.h"
-#include <assert.h>
-Syntax Error
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:957: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
-if test -z "$ac_err"; then
- :
-else
- echo "$ac_err" >&5
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- CPP=/lib/cpp
-fi
-rm -f conftest*
-fi
-rm -f conftest*
-fi
-rm -f conftest*
- ac_cv_prog_CPP="$CPP"
-fi
- CPP="$ac_cv_prog_CPP"
-else
- ac_cv_prog_CPP="$CPP"
-fi
-echo "$ac_t""$CPP" 1>&6
-
-if test $ac_cv_prog_gcc = yes; then
- echo $ac_n "checking whether ${CC-cc} needs -traditional""... $ac_c" 1>&6
-echo "configure:983: checking whether ${CC-cc} needs -traditional" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_gcc_traditional'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- ac_pattern="Autoconf.*'x'"
- cat > conftest.$ac_ext <<EOF
-#line 989 "configure"
-#include "confdefs.h"
-#include <sgtty.h>
-Autoconf TIOCGETP
-EOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
- egrep "$ac_pattern" >/dev/null 2>&1; then
- rm -rf conftest*
- ac_cv_prog_gcc_traditional=yes
-else
- rm -rf conftest*
- ac_cv_prog_gcc_traditional=no
-fi
-rm -f conftest*
-
-
- if test $ac_cv_prog_gcc_traditional = no; then
- cat > conftest.$ac_ext <<EOF
-#line 1007 "configure"
-#include "confdefs.h"
-#include <termio.h>
-Autoconf TCGETA
-EOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
- egrep "$ac_pattern" >/dev/null 2>&1; then
- rm -rf conftest*
- ac_cv_prog_gcc_traditional=yes
-fi
-rm -f conftest*
-
- fi
-fi
-
-echo "$ac_t""$ac_cv_prog_gcc_traditional" 1>&6
- if test $ac_cv_prog_gcc_traditional = yes; then
- CC="$CC -traditional"
- fi
-fi
-
-for ac_prog in 'bison -y' byacc
-do
-# Extract the first word of "$ac_prog", so it can be a program name with args.
-set dummy $ac_prog; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:1033: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_YACC'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- if test -n "$YACC"; then
- ac_cv_prog_YACC="$YACC" # Let the user override the test.
-else
- IFS="${IFS= }"; ac_save_ifs="$IFS"; IFS=":"
- ac_dummy="$PATH"
- for ac_dir in $ac_dummy; do
- test -z "$ac_dir" && ac_dir=.
- if test -f $ac_dir/$ac_word; then
- ac_cv_prog_YACC="$ac_prog"
- break
- fi
- done
- IFS="$ac_save_ifs"
-fi
-fi
-YACC="$ac_cv_prog_YACC"
-if test -n "$YACC"; then
- echo "$ac_t""$YACC" 1>&6
-else
- echo "$ac_t""no" 1>&6
-fi
-
-test -n "$YACC" && break
-done
-test -n "$YACC" || YACC="yacc"
-
-# Extract the first word of "ranlib", so it can be a program name with args.
-set dummy ranlib; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:1066: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_RANLIB'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- if test -n "$RANLIB"; then
- ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test.
-else
- IFS="${IFS= }"; ac_save_ifs="$IFS"; IFS=":"
- ac_dummy="$PATH"
- for ac_dir in $ac_dummy; do
- test -z "$ac_dir" && ac_dir=.
- if test -f $ac_dir/$ac_word; then
- ac_cv_prog_RANLIB="ranlib"
- break
- fi
- done
- IFS="$ac_save_ifs"
- test -z "$ac_cv_prog_RANLIB" && ac_cv_prog_RANLIB=":"
-fi
-fi
-RANLIB="$ac_cv_prog_RANLIB"
-if test -n "$RANLIB"; then
- echo "$ac_t""$RANLIB" 1>&6
-else
- echo "$ac_t""no" 1>&6
-fi
-
-
-for ac_prog in ar aal
-do
-# Extract the first word of "$ac_prog", so it can be a program name with args.
-set dummy $ac_prog; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:1099: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_AR'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- if test -n "$AR"; then
- ac_cv_prog_AR="$AR" # Let the user override the test.
-else
- IFS="${IFS= }"; ac_save_ifs="$IFS"; IFS=":"
- ac_dummy="$PATH"
- for ac_dir in $ac_dummy; do
- test -z "$ac_dir" && ac_dir=.
- if test -f $ac_dir/$ac_word; then
- ac_cv_prog_AR="$ac_prog"
- break
- fi
- done
- IFS="$ac_save_ifs"
-fi
-fi
-AR="$ac_cv_prog_AR"
-if test -n "$AR"; then
- echo "$ac_t""$AR" 1>&6
-else
- echo "$ac_t""no" 1>&6
-fi
-
-test -n "$AR" && break
-done
-test -n "$AR" || AR="ar"
-
-
-echo $ac_n "checking whether ln -s works""... $ac_c" 1>&6
-echo "configure:1131: checking whether ln -s works" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_LN_S'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- rm -f conftestdata
-if ln -s X conftestdata 2>/dev/null
-then
- rm -f conftestdata
- ac_cv_prog_LN_S="ln -s"
-else
- ac_cv_prog_LN_S=ln
-fi
-fi
-LN_S="$ac_cv_prog_LN_S"
-if test "$ac_cv_prog_LN_S" = "ln -s"; then
- echo "$ac_t""yes" 1>&6
-else
- echo "$ac_t""no" 1>&6
-fi
-
-echo $ac_n "checking whether ${MAKE-make} sets \${MAKE}""... $ac_c" 1>&6
-echo "configure:1152: checking whether ${MAKE-make} sets \${MAKE}" >&5
-set dummy ${MAKE-make}; ac_make=`echo "$2" | sed 'y%./+-%__p_%'`
-if eval "test \"`echo '$''{'ac_cv_prog_make_${ac_make}_set'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftestmake <<\EOF
-all:
- @echo 'ac_maketemp="${MAKE}"'
-EOF
-# GNU make sometimes prints "make[1]: Entering...", which would confuse us.
-eval `${MAKE-make} -f conftestmake 2>/dev/null | grep temp=`
-if test -n "$ac_maketemp"; then
- eval ac_cv_prog_make_${ac_make}_set=yes
-else
- eval ac_cv_prog_make_${ac_make}_set=no
-fi
-rm -f conftestmake
-fi
-if eval "test \"`echo '$ac_cv_prog_make_'${ac_make}_set`\" = yes"; then
- echo "$ac_t""yes" 1>&6
- SET_MAKE=
-else
- echo "$ac_t""no" 1>&6
- SET_MAKE="MAKE=${MAKE-make}"
-fi
-
-
-# checks for UNIX variants that set C preprocessor variables
-ac_safe=`echo "minix/config.h" | sed 'y%./+-%__p_%'`
-echo $ac_n "checking for minix/config.h""... $ac_c" 1>&6
-echo "configure:1182: checking for minix/config.h" >&5
-if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 1187 "configure"
-#include "confdefs.h"
-#include <minix/config.h>
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:1192: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
-if test -z "$ac_err"; then
- rm -rf conftest*
- eval "ac_cv_header_$ac_safe=yes"
-else
- echo "$ac_err" >&5
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- eval "ac_cv_header_$ac_safe=no"
-fi
-rm -f conftest*
-fi
-if eval "test \"`echo '$ac_cv_header_'$ac_safe`\" = yes"; then
- echo "$ac_t""yes" 1>&6
- MINIX=yes
-else
- echo "$ac_t""no" 1>&6
-MINIX=
-fi
-
-if test "$MINIX" = yes; then
- cat >> confdefs.h <<\EOF
-#define _POSIX_SOURCE 1
-EOF
-
- cat >> confdefs.h <<\EOF
-#define _POSIX_1_SOURCE 2
-EOF
-
- cat >> confdefs.h <<\EOF
-#define _MINIX 1
-EOF
-
-fi
-
-
-echo $ac_n "checking for Cygwin environment""... $ac_c" 1>&6
-echo "configure:1231: checking for Cygwin environment" >&5
-if eval "test \"`echo '$''{'ac_cv_cygwin'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 1236 "configure"
-#include "confdefs.h"
-
-int main() {
-
-#ifndef __CYGWIN__
-#define __CYGWIN__ __CYGWIN32__
-#endif
-return __CYGWIN__;
-; return 0; }
-EOF
-if { (eval echo configure:1247: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
- rm -rf conftest*
- ac_cv_cygwin=yes
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- ac_cv_cygwin=no
-fi
-rm -f conftest*
-rm -f conftest*
-fi
-
-echo "$ac_t""$ac_cv_cygwin" 1>&6
-CYGWIN=
-test "$ac_cv_cygwin" = yes && CYGWIN=yes
-echo $ac_n "checking for mingw32 environment""... $ac_c" 1>&6
-echo "configure:1264: checking for mingw32 environment" >&5
-if eval "test \"`echo '$''{'ac_cv_mingw32'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 1269 "configure"
-#include "confdefs.h"
-
-int main() {
-return __MINGW32__;
-; return 0; }
-EOF
-if { (eval echo configure:1276: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
- rm -rf conftest*
- ac_cv_mingw32=yes
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- ac_cv_mingw32=no
-fi
-rm -f conftest*
-rm -f conftest*
-fi
-
-echo "$ac_t""$ac_cv_mingw32" 1>&6
-MINGW32=
-test "$ac_cv_mingw32" = yes && MINGW32=yes
-
-
-echo $ac_n "checking for executable suffix""... $ac_c" 1>&6
-echo "configure:1295: checking for executable suffix" >&5
-if eval "test \"`echo '$''{'ac_cv_exeext'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- if test "$CYGWIN" = yes || test "$MINGW32" = yes; then
- ac_cv_exeext=.exe
-else
- rm -f conftest*
- echo 'int main () { return 0; }' > conftest.$ac_ext
- ac_cv_exeext=
- if { (eval echo configure:1305: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; }; then
- for file in conftest.*; do
- case $file in
- *.c | *.o | *.obj) ;;
- *) ac_cv_exeext=`echo $file | sed -e s/conftest//` ;;
- esac
- done
- else
- { echo "configure: error: installation or configuration problem: compiler cannot create executables." 1>&2; exit 1; }
- fi
- rm -f conftest*
- test x"${ac_cv_exeext}" = x && ac_cv_exeext=no
-fi
-fi
-
-EXEEXT=""
-test x"${ac_cv_exeext}" != xno && EXEEXT=${ac_cv_exeext}
-echo "$ac_t""${ac_cv_exeext}" 1>&6
-ac_exeext=$EXEEXT
-
-echo $ac_n "checking for object suffix""... $ac_c" 1>&6
-echo "configure:1326: checking for object suffix" >&5
-if eval "test \"`echo '$''{'ac_cv_objext'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- rm -f conftest*
-echo 'int i = 1;' > conftest.$ac_ext
-if { (eval echo configure:1332: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
- for ac_file in conftest.*; do
- case $ac_file in
- *.c) ;;
- *) ac_cv_objext=`echo $ac_file | sed -e s/conftest.//` ;;
- esac
- done
-else
- { echo "configure: error: installation or configuration problem; compiler does not work" 1>&2; exit 1; }
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$ac_cv_objext" 1>&6
-OBJEXT=$ac_cv_objext
-ac_objext=$ac_cv_objext
-
-
-echo $ac_n "checking size of int""... $ac_c" 1>&6
-echo "configure:1351: checking size of int" >&5
-if eval "test \"`echo '$''{'ac_cv_sizeof_int'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- if test "$cross_compiling" = yes; then
- ac_cv_sizeof_int=4
-else
- cat > conftest.$ac_ext <<EOF
-#line 1359 "configure"
-#include "confdefs.h"
-#include <stdio.h>
-main()
-{
- FILE *f=fopen("conftestval", "w");
- if (!f) exit(1);
- fprintf(f, "%d\n", sizeof(int));
- exit(0);
-}
-EOF
-if { (eval echo configure:1370: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
-then
- ac_cv_sizeof_int=`cat conftestval`
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -fr conftest*
- ac_cv_sizeof_int=0
-fi
-rm -fr conftest*
-fi
-
-fi
-echo "$ac_t""$ac_cv_sizeof_int" 1>&6
-cat >> confdefs.h <<EOF
-#define SIZEOF_INT $ac_cv_sizeof_int
-EOF
-
-
-echo $ac_n "checking size of short""... $ac_c" 1>&6
-echo "configure:1390: checking size of short" >&5
-if eval "test \"`echo '$''{'ac_cv_sizeof_short'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- if test "$cross_compiling" = yes; then
- ac_cv_sizeof_short=2
-else
- cat > conftest.$ac_ext <<EOF
-#line 1398 "configure"
-#include "confdefs.h"
-#include <stdio.h>
-main()
-{
- FILE *f=fopen("conftestval", "w");
- if (!f) exit(1);
- fprintf(f, "%d\n", sizeof(short));
- exit(0);
-}
-EOF
-if { (eval echo configure:1409: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
-then
- ac_cv_sizeof_short=`cat conftestval`
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -fr conftest*
- ac_cv_sizeof_short=0
-fi
-rm -fr conftest*
-fi
-
-fi
-echo "$ac_t""$ac_cv_sizeof_short" 1>&6
-cat >> confdefs.h <<EOF
-#define SIZEOF_SHORT $ac_cv_sizeof_short
-EOF
-
-
-echo $ac_n "checking size of long""... $ac_c" 1>&6
-echo "configure:1429: checking size of long" >&5
-if eval "test \"`echo '$''{'ac_cv_sizeof_long'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- if test "$cross_compiling" = yes; then
- ac_cv_sizeof_long=4
-else
- cat > conftest.$ac_ext <<EOF
-#line 1437 "configure"
-#include "confdefs.h"
-#include <stdio.h>
-main()
-{
- FILE *f=fopen("conftestval", "w");
- if (!f) exit(1);
- fprintf(f, "%d\n", sizeof(long));
- exit(0);
-}
-EOF
-if { (eval echo configure:1448: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
-then
- ac_cv_sizeof_long=`cat conftestval`
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -fr conftest*
- ac_cv_sizeof_long=0
-fi
-rm -fr conftest*
-fi
-
-fi
-echo "$ac_t""$ac_cv_sizeof_long" 1>&6
-cat >> confdefs.h <<EOF
-#define SIZEOF_LONG $ac_cv_sizeof_long
-EOF
-
-
-echo $ac_n "checking size of void*""... $ac_c" 1>&6
-echo "configure:1468: checking size of void*" >&5
-if eval "test \"`echo '$''{'ac_cv_sizeof_voidp'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- if test "$cross_compiling" = yes; then
- ac_cv_sizeof_voidp=4
-else
- cat > conftest.$ac_ext <<EOF
-#line 1476 "configure"
-#include "confdefs.h"
-#include <stdio.h>
-main()
-{
- FILE *f=fopen("conftestval", "w");
- if (!f) exit(1);
- fprintf(f, "%d\n", sizeof(void*));
- exit(0);
-}
-EOF
-if { (eval echo configure:1487: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
-then
- ac_cv_sizeof_voidp=`cat conftestval`
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -fr conftest*
- ac_cv_sizeof_voidp=0
-fi
-rm -fr conftest*
-fi
-
-fi
-echo "$ac_t""$ac_cv_sizeof_voidp" 1>&6
-cat >> confdefs.h <<EOF
-#define SIZEOF_VOIDP $ac_cv_sizeof_voidp
-EOF
-
-
-echo $ac_n "checking size of float""... $ac_c" 1>&6
-echo "configure:1507: checking size of float" >&5
-if eval "test \"`echo '$''{'ac_cv_sizeof_float'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- if test "$cross_compiling" = yes; then
- ac_cv_sizeof_float=4
-else
- cat > conftest.$ac_ext <<EOF
-#line 1515 "configure"
-#include "confdefs.h"
-#include <stdio.h>
-main()
-{
- FILE *f=fopen("conftestval", "w");
- if (!f) exit(1);
- fprintf(f, "%d\n", sizeof(float));
- exit(0);
-}
-EOF
-if { (eval echo configure:1526: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
-then
- ac_cv_sizeof_float=`cat conftestval`
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -fr conftest*
- ac_cv_sizeof_float=0
-fi
-rm -fr conftest*
-fi
-
-fi
-echo "$ac_t""$ac_cv_sizeof_float" 1>&6
-cat >> confdefs.h <<EOF
-#define SIZEOF_FLOAT $ac_cv_sizeof_float
-EOF
-
-
-echo $ac_n "checking size of double""... $ac_c" 1>&6
-echo "configure:1546: checking size of double" >&5
-if eval "test \"`echo '$''{'ac_cv_sizeof_double'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- if test "$cross_compiling" = yes; then
- ac_cv_sizeof_double=8
-else
- cat > conftest.$ac_ext <<EOF
-#line 1554 "configure"
-#include "confdefs.h"
-#include <stdio.h>
-main()
-{
- FILE *f=fopen("conftestval", "w");
- if (!f) exit(1);
- fprintf(f, "%d\n", sizeof(double));
- exit(0);
-}
-EOF
-if { (eval echo configure:1565: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
-then
- ac_cv_sizeof_double=`cat conftestval`
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -fr conftest*
- ac_cv_sizeof_double=0
-fi
-rm -fr conftest*
-fi
-
-fi
-echo "$ac_t""$ac_cv_sizeof_double" 1>&6
-cat >> confdefs.h <<EOF
-#define SIZEOF_DOUBLE $ac_cv_sizeof_double
-EOF
-
-
-
-echo $ac_n "checking for prototypes""... $ac_c" 1>&6
-echo "configure:1586: checking for prototypes" >&5
-if eval "test \"`echo '$''{'rb_cv_have_prototypes'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 1591 "configure"
-#include "confdefs.h"
-int foo(int x) { return 0; }
-int main() {
-return foo(10);
-; return 0; }
-EOF
-if { (eval echo configure:1598: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
- rm -rf conftest*
- rb_cv_have_prototypes=yes
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- rb_cv_have_prototypes=no
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$rb_cv_have_prototypes" 1>&6
-if test "$rb_cv_have_prototypes" = yes; then
- cat >> confdefs.h <<\EOF
-#define HAVE_PROTOTYPES 1
-EOF
-
-fi
-
-echo $ac_n "checking token paste string""... $ac_c" 1>&6
-echo "configure:1619: checking token paste string" >&5
-if eval "test \"`echo '$''{'rb_cv_tokenpaste'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 1624 "configure"
-#include "confdefs.h"
-#define paste(a,b) a##b
-int main() {
-int xy = 1; return paste(x,y);
-; return 0; }
-EOF
-if { (eval echo configure:1631: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
- rm -rf conftest*
- rb_cv_tokenpaste=ansi
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- rb_cv_tokenpaste=knr
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$rb_cv_tokenpaste" 1>&6
-if test "$rb_cv_tokenpaste" = ansi; then
- cat >> confdefs.h <<\EOF
-#define TOKEN_PASTE(x,y) x##y
-EOF
-
-else
- cat >> confdefs.h <<\EOF
-#define TOKEN_PASTE(x,y) x/**/y
-EOF
-
-fi
-
-echo $ac_n "checking for variable length prototypes and stdarg.h""... $ac_c" 1>&6
-echo "configure:1657: checking for variable length prototypes and stdarg.h" >&5
-if eval "test \"`echo '$''{'rb_cv_stdarg'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 1662 "configure"
-#include "confdefs.h"
-
-#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;
-}
-
-int main() {
-return foo(10, "", 3.14);
-; return 0; }
-EOF
-if { (eval echo configure:1679: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
- rm -rf conftest*
- rb_cv_stdarg=yes
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- rb_cv_stdarg=no
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$rb_cv_stdarg" 1>&6
-if test "$rb_cv_stdarg" = yes; then
- cat >> confdefs.h <<\EOF
-#define HAVE_STDARG_PROTOTYPES 1
-EOF
-
-fi
-
-echo $ac_n "checking for gcc attribute noreturn""... $ac_c" 1>&6
-echo "configure:1700: checking for gcc attribute noreturn" >&5
-if eval "test \"`echo '$''{'rb_cv_have_attr_noreturn'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 1705 "configure"
-#include "confdefs.h"
-void exit(int x) __attribute__ ((noreturn));
-int main() {
-
-; return 0; }
-EOF
-if { (eval echo configure:1712: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
- rm -rf conftest*
- rb_cv_have_attr_noreturn=yes
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- rb_cv_have_attr_noreturn=no
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$rb_cv_have_attr_noreturn" 1>&6
-if test "$rb_cv_have_attr_noreturn" = yes; then
- cat >> confdefs.h <<\EOF
-#define HAVE_ATTR_NORETURN 1
-EOF
-
-fi
-
-case "$host_os" in
-nextstep*) ;;
-openstep*) ;;
-rhapsody*) ;;
-human*) ;;
-beos*) ;;
-cygwin*) ;;
-*) LIBS="-lm $LIBS";;
-esac
-echo $ac_n "checking for crypt in -lcrypt""... $ac_c" 1>&6
-echo "configure:1742: checking for crypt in -lcrypt" >&5
-ac_lib_var=`echo crypt'_'crypt | sed 'y%./+-%__p_%'`
-if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- ac_save_LIBS="$LIBS"
-LIBS="-lcrypt $LIBS"
-cat > conftest.$ac_ext <<EOF
-#line 1750 "configure"
-#include "confdefs.h"
-/* Override any gcc2 internal prototype to avoid an error. */
-/* We use char because int might match the return type of a gcc2
- builtin and then its argument prototype would still apply. */
-char crypt();
-
-int main() {
-crypt()
-; return 0; }
-EOF
-if { (eval echo configure:1761: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
- rm -rf conftest*
- eval "ac_cv_lib_$ac_lib_var=yes"
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- eval "ac_cv_lib_$ac_lib_var=no"
-fi
-rm -f conftest*
-LIBS="$ac_save_LIBS"
-
-fi
-if eval "test \"`echo '$ac_cv_lib_'$ac_lib_var`\" = yes"; then
- echo "$ac_t""yes" 1>&6
- ac_tr_lib=HAVE_LIB`echo crypt | sed -e 's/[^a-zA-Z0-9_]/_/g' \
- -e 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/'`
- cat >> confdefs.h <<EOF
-#define $ac_tr_lib 1
-EOF
-
- LIBS="-lcrypt $LIBS"
-
-else
- echo "$ac_t""no" 1>&6
-fi
-
-echo $ac_n "checking for dlopen in -ldl""... $ac_c" 1>&6
-echo "configure:1789: checking for dlopen in -ldl" >&5
-ac_lib_var=`echo dl'_'dlopen | sed 'y%./+-%__p_%'`
-if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- ac_save_LIBS="$LIBS"
-LIBS="-ldl $LIBS"
-cat > conftest.$ac_ext <<EOF
-#line 1797 "configure"
-#include "confdefs.h"
-/* Override any gcc2 internal prototype to avoid an error. */
-/* We use char because int might match the return type of a gcc2
- builtin and then its argument prototype would still apply. */
-char dlopen();
-
-int main() {
-dlopen()
-; return 0; }
-EOF
-if { (eval echo configure:1808: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
- rm -rf conftest*
- eval "ac_cv_lib_$ac_lib_var=yes"
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- eval "ac_cv_lib_$ac_lib_var=no"
-fi
-rm -f conftest*
-LIBS="$ac_save_LIBS"
-
-fi
-if eval "test \"`echo '$ac_cv_lib_'$ac_lib_var`\" = yes"; then
- echo "$ac_t""yes" 1>&6
- ac_tr_lib=HAVE_LIB`echo dl | sed -e 's/[^a-zA-Z0-9_]/_/g' \
- -e 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/'`
- cat >> confdefs.h <<EOF
-#define $ac_tr_lib 1
-EOF
-
- LIBS="-ldl $LIBS"
-
-else
- echo "$ac_t""no" 1>&6
-fi
- # Dynamic linking for SunOS/Solaris and SYSV
-echo $ac_n "checking for shl_load in -ldld""... $ac_c" 1>&6
-echo "configure:1836: checking for shl_load in -ldld" >&5
-ac_lib_var=`echo dld'_'shl_load | sed 'y%./+-%__p_%'`
-if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- ac_save_LIBS="$LIBS"
-LIBS="-ldld $LIBS"
-cat > conftest.$ac_ext <<EOF
-#line 1844 "configure"
-#include "confdefs.h"
-/* Override any gcc2 internal prototype to avoid an error. */
-/* We use char because int might match the return type of a gcc2
- builtin and then its argument prototype would still apply. */
-char shl_load();
-
-int main() {
-shl_load()
-; return 0; }
-EOF
-if { (eval echo configure:1855: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
- rm -rf conftest*
- eval "ac_cv_lib_$ac_lib_var=yes"
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- eval "ac_cv_lib_$ac_lib_var=no"
-fi
-rm -f conftest*
-LIBS="$ac_save_LIBS"
-
-fi
-if eval "test \"`echo '$ac_cv_lib_'$ac_lib_var`\" = yes"; then
- echo "$ac_t""yes" 1>&6
- ac_tr_lib=HAVE_LIB`echo dld | sed -e 's/[^a-zA-Z0-9_]/_/g' \
- -e 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/'`
- cat >> confdefs.h <<EOF
-#define $ac_tr_lib 1
-EOF
-
- LIBS="-ldld $LIBS"
-
-else
- echo "$ac_t""no" 1>&6
-fi
- # Dynamic linking for HP-UX
-echo $ac_n "checking for setlocale in -lxpg4""... $ac_c" 1>&6
-echo "configure:1883: checking for setlocale in -lxpg4" >&5
-ac_lib_var=`echo xpg4'_'setlocale | sed 'y%./+-%__p_%'`
-if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- ac_save_LIBS="$LIBS"
-LIBS="-lxpg4 $LIBS"
-cat > conftest.$ac_ext <<EOF
-#line 1891 "configure"
-#include "confdefs.h"
-/* Override any gcc2 internal prototype to avoid an error. */
-/* We use char because int might match the return type of a gcc2
- builtin and then its argument prototype would still apply. */
-char setlocale();
-
-int main() {
-setlocale()
-; return 0; }
-EOF
-if { (eval echo configure:1902: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
- rm -rf conftest*
- eval "ac_cv_lib_$ac_lib_var=yes"
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- eval "ac_cv_lib_$ac_lib_var=no"
-fi
-rm -f conftest*
-LIBS="$ac_save_LIBS"
-
-fi
-if eval "test \"`echo '$ac_cv_lib_'$ac_lib_var`\" = yes"; then
- echo "$ac_t""yes" 1>&6
- ac_tr_lib=HAVE_LIB`echo xpg4 | sed -e 's/[^a-zA-Z0-9_]/_/g' \
- -e 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/'`
- cat >> confdefs.h <<EOF
-#define $ac_tr_lib 1
-EOF
-
- LIBS="-lxpg4 $LIBS"
-
-else
- echo "$ac_t""no" 1>&6
-fi
- # FreeBSD needs this
-
-ac_header_dirent=no
-for ac_hdr in dirent.h sys/ndir.h sys/dir.h ndir.h
-do
-ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'`
-echo $ac_n "checking for $ac_hdr that defines DIR""... $ac_c" 1>&6
-echo "configure:1935: checking for $ac_hdr that defines DIR" >&5
-if eval "test \"`echo '$''{'ac_cv_header_dirent_$ac_safe'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 1940 "configure"
-#include "confdefs.h"
-#include <sys/types.h>
-#include <$ac_hdr>
-int main() {
-DIR *dirp = 0;
-; return 0; }
-EOF
-if { (eval echo configure:1948: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
- rm -rf conftest*
- eval "ac_cv_header_dirent_$ac_safe=yes"
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- eval "ac_cv_header_dirent_$ac_safe=no"
-fi
-rm -f conftest*
-fi
-if eval "test \"`echo '$ac_cv_header_dirent_'$ac_safe`\" = yes"; then
- echo "$ac_t""yes" 1>&6
- ac_tr_hdr=HAVE_`echo $ac_hdr | sed 'y%abcdefghijklmnopqrstuvwxyz./-%ABCDEFGHIJKLMNOPQRSTUVWXYZ___%'`
- cat >> confdefs.h <<EOF
-#define $ac_tr_hdr 1
-EOF
- ac_header_dirent=$ac_hdr; break
-else
- echo "$ac_t""no" 1>&6
-fi
-done
-# Two versions of opendir et al. are in -ldir and -lx on SCO Xenix.
-if test $ac_header_dirent = dirent.h; then
-echo $ac_n "checking for opendir in -ldir""... $ac_c" 1>&6
-echo "configure:1973: checking for opendir in -ldir" >&5
-ac_lib_var=`echo dir'_'opendir | sed 'y%./+-%__p_%'`
-if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- ac_save_LIBS="$LIBS"
-LIBS="-ldir $LIBS"
-cat > conftest.$ac_ext <<EOF
-#line 1981 "configure"
-#include "confdefs.h"
-/* Override any gcc2 internal prototype to avoid an error. */
-/* We use char because int might match the return type of a gcc2
- builtin and then its argument prototype would still apply. */
-char opendir();
-
-int main() {
-opendir()
-; return 0; }
-EOF
-if { (eval echo configure:1992: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
- rm -rf conftest*
- eval "ac_cv_lib_$ac_lib_var=yes"
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- eval "ac_cv_lib_$ac_lib_var=no"
-fi
-rm -f conftest*
-LIBS="$ac_save_LIBS"
-
-fi
-if eval "test \"`echo '$ac_cv_lib_'$ac_lib_var`\" = yes"; then
- echo "$ac_t""yes" 1>&6
- LIBS="$LIBS -ldir"
-else
- echo "$ac_t""no" 1>&6
-fi
-
-else
-echo $ac_n "checking for opendir in -lx""... $ac_c" 1>&6
-echo "configure:2014: checking for opendir in -lx" >&5
-ac_lib_var=`echo x'_'opendir | sed 'y%./+-%__p_%'`
-if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- ac_save_LIBS="$LIBS"
-LIBS="-lx $LIBS"
-cat > conftest.$ac_ext <<EOF
-#line 2022 "configure"
-#include "confdefs.h"
-/* Override any gcc2 internal prototype to avoid an error. */
-/* We use char because int might match the return type of a gcc2
- builtin and then its argument prototype would still apply. */
-char opendir();
-
-int main() {
-opendir()
-; return 0; }
-EOF
-if { (eval echo configure:2033: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
- rm -rf conftest*
- eval "ac_cv_lib_$ac_lib_var=yes"
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- eval "ac_cv_lib_$ac_lib_var=no"
-fi
-rm -f conftest*
-LIBS="$ac_save_LIBS"
-
-fi
-if eval "test \"`echo '$ac_cv_lib_'$ac_lib_var`\" = yes"; then
- echo "$ac_t""yes" 1>&6
- LIBS="$LIBS -lx"
-else
- echo "$ac_t""no" 1>&6
-fi
-
-fi
-
-echo $ac_n "checking for ANSI C header files""... $ac_c" 1>&6
-echo "configure:2056: checking for ANSI C header files" >&5
-if eval "test \"`echo '$''{'ac_cv_header_stdc'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 2061 "configure"
-#include "confdefs.h"
-#include <stdlib.h>
-#include <stdarg.h>
-#include <string.h>
-#include <float.h>
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:2069: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
-if test -z "$ac_err"; then
- rm -rf conftest*
- ac_cv_header_stdc=yes
-else
- echo "$ac_err" >&5
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- ac_cv_header_stdc=no
-fi
-rm -f conftest*
-
-if test $ac_cv_header_stdc = yes; then
- # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
-cat > conftest.$ac_ext <<EOF
-#line 2086 "configure"
-#include "confdefs.h"
-#include <string.h>
-EOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
- egrep "memchr" >/dev/null 2>&1; then
- :
-else
- rm -rf conftest*
- ac_cv_header_stdc=no
-fi
-rm -f conftest*
-
-fi
-
-if test $ac_cv_header_stdc = yes; then
- # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
-cat > conftest.$ac_ext <<EOF
-#line 2104 "configure"
-#include "confdefs.h"
-#include <stdlib.h>
-EOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
- egrep "free" >/dev/null 2>&1; then
- :
-else
- rm -rf conftest*
- ac_cv_header_stdc=no
-fi
-rm -f conftest*
-
-fi
-
-if test $ac_cv_header_stdc = yes; then
- # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.
-if test "$cross_compiling" = yes; then
- :
-else
- cat > conftest.$ac_ext <<EOF
-#line 2125 "configure"
-#include "confdefs.h"
-#include <ctype.h>
-#define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
-#define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
-#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))
-int main () { int i; for (i = 0; i < 256; i++)
-if (XOR (islower (i), ISLOWER (i)) || toupper (i) != TOUPPER (i)) exit(2);
-exit (0); }
-
-EOF
-if { (eval echo configure:2136: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
-then
- :
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -fr conftest*
- ac_cv_header_stdc=no
-fi
-rm -fr conftest*
-fi
-
-fi
-fi
-
-echo "$ac_t""$ac_cv_header_stdc" 1>&6
-if test $ac_cv_header_stdc = yes; then
- cat >> confdefs.h <<\EOF
-#define STDC_HEADERS 1
-EOF
-
-fi
-
-echo $ac_n "checking for sys/wait.h that is POSIX.1 compatible""... $ac_c" 1>&6
-echo "configure:2160: checking for sys/wait.h that is POSIX.1 compatible" >&5
-if eval "test \"`echo '$''{'ac_cv_header_sys_wait_h'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 2165 "configure"
-#include "confdefs.h"
-#include <sys/types.h>
-#include <sys/wait.h>
-#ifndef WEXITSTATUS
-#define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
-#endif
-#ifndef WIFEXITED
-#define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
-#endif
-int main() {
-int s;
-wait (&s);
-s = WIFEXITED (s) ? WEXITSTATUS (s) : 1;
-; return 0; }
-EOF
-if { (eval echo configure:2181: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
- rm -rf conftest*
- ac_cv_header_sys_wait_h=yes
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- ac_cv_header_sys_wait_h=no
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$ac_cv_header_sys_wait_h" 1>&6
-if test $ac_cv_header_sys_wait_h = yes; then
- cat >> confdefs.h <<\EOF
-#define HAVE_SYS_WAIT_H 1
-EOF
-
-fi
-
-for ac_hdr in 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
-do
-ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'`
-echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6
-echo "configure:2207: checking for $ac_hdr" >&5
-if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 2212 "configure"
-#include "confdefs.h"
-#include <$ac_hdr>
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:2217: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
-if test -z "$ac_err"; then
- rm -rf conftest*
- eval "ac_cv_header_$ac_safe=yes"
-else
- echo "$ac_err" >&5
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- eval "ac_cv_header_$ac_safe=no"
-fi
-rm -f conftest*
-fi
-if eval "test \"`echo '$ac_cv_header_'$ac_safe`\" = yes"; then
- echo "$ac_t""yes" 1>&6
- ac_tr_hdr=HAVE_`echo $ac_hdr | sed 'y%abcdefghijklmnopqrstuvwxyz./-%ABCDEFGHIJKLMNOPQRSTUVWXYZ___%'`
- cat >> confdefs.h <<EOF
-#define $ac_tr_hdr 1
-EOF
-
-else
- echo "$ac_t""no" 1>&6
-fi
-done
-
-
-echo $ac_n "checking for uid_t in sys/types.h""... $ac_c" 1>&6
-echo "configure:2245: checking for uid_t in sys/types.h" >&5
-if eval "test \"`echo '$''{'ac_cv_type_uid_t'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 2250 "configure"
-#include "confdefs.h"
-#include <sys/types.h>
-EOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
- egrep "uid_t" >/dev/null 2>&1; then
- rm -rf conftest*
- ac_cv_type_uid_t=yes
-else
- rm -rf conftest*
- ac_cv_type_uid_t=no
-fi
-rm -f conftest*
-
-fi
-
-echo "$ac_t""$ac_cv_type_uid_t" 1>&6
-if test $ac_cv_type_uid_t = no; then
- cat >> confdefs.h <<\EOF
-#define uid_t int
-EOF
-
- cat >> confdefs.h <<\EOF
-#define gid_t int
-EOF
-
-fi
-
-echo $ac_n "checking for size_t""... $ac_c" 1>&6
-echo "configure:2279: checking for size_t" >&5
-if eval "test \"`echo '$''{'ac_cv_type_size_t'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 2284 "configure"
-#include "confdefs.h"
-#include <sys/types.h>
-#if STDC_HEADERS
-#include <stdlib.h>
-#include <stddef.h>
-#endif
-EOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
- egrep "(^|[^a-zA-Z_0-9])size_t[^a-zA-Z_0-9]" >/dev/null 2>&1; then
- rm -rf conftest*
- ac_cv_type_size_t=yes
-else
- rm -rf conftest*
- ac_cv_type_size_t=no
-fi
-rm -f conftest*
-
-fi
-echo "$ac_t""$ac_cv_type_size_t" 1>&6
-if test $ac_cv_type_size_t = no; then
- cat >> confdefs.h <<\EOF
-#define size_t unsigned
-EOF
-
-fi
-
-echo $ac_n "checking for st_blksize in struct stat""... $ac_c" 1>&6
-echo "configure:2312: checking for st_blksize in struct stat" >&5
-if eval "test \"`echo '$''{'ac_cv_struct_st_blksize'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 2317 "configure"
-#include "confdefs.h"
-#include <sys/types.h>
-#include <sys/stat.h>
-int main() {
-struct stat s; s.st_blksize;
-; return 0; }
-EOF
-if { (eval echo configure:2325: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
- rm -rf conftest*
- ac_cv_struct_st_blksize=yes
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- ac_cv_struct_st_blksize=no
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$ac_cv_struct_st_blksize" 1>&6
-if test $ac_cv_struct_st_blksize = yes; then
- cat >> confdefs.h <<\EOF
-#define HAVE_ST_BLKSIZE 1
-EOF
-
-fi
-
-save_LIBOJBS="$LIBOBJS"
-echo $ac_n "checking for st_blocks in struct stat""... $ac_c" 1>&6
-echo "configure:2347: checking for st_blocks in struct stat" >&5
-if eval "test \"`echo '$''{'ac_cv_struct_st_blocks'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 2352 "configure"
-#include "confdefs.h"
-#include <sys/types.h>
-#include <sys/stat.h>
-int main() {
-struct stat s; s.st_blocks;
-; return 0; }
-EOF
-if { (eval echo configure:2360: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
- rm -rf conftest*
- ac_cv_struct_st_blocks=yes
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- ac_cv_struct_st_blocks=no
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$ac_cv_struct_st_blocks" 1>&6
-if test $ac_cv_struct_st_blocks = yes; then
- cat >> confdefs.h <<\EOF
-#define HAVE_ST_BLOCKS 1
-EOF
-
-else
- LIBOBJS="$LIBOBJS fileblocks.${ac_objext}"
-fi
-
-LIBOBJS="$save_LIBOBJS"
-echo $ac_n "checking for st_rdev in struct stat""... $ac_c" 1>&6
-echo "configure:2384: checking for st_rdev in struct stat" >&5
-if eval "test \"`echo '$''{'ac_cv_struct_st_rdev'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 2389 "configure"
-#include "confdefs.h"
-#include <sys/types.h>
-#include <sys/stat.h>
-int main() {
-struct stat s; s.st_rdev;
-; return 0; }
-EOF
-if { (eval echo configure:2397: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
- rm -rf conftest*
- ac_cv_struct_st_rdev=yes
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- ac_cv_struct_st_rdev=no
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$ac_cv_struct_st_rdev" 1>&6
-if test $ac_cv_struct_st_rdev = yes; then
- cat >> confdefs.h <<\EOF
-#define HAVE_ST_RDEV 1
-EOF
-
-fi
-
-
-echo $ac_n "checking type of array argument to getgroups""... $ac_c" 1>&6
-echo "configure:2419: checking type of array argument to getgroups" >&5
-if eval "test \"`echo '$''{'ac_cv_type_getgroups'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- if test "$cross_compiling" = yes; then
- ac_cv_type_getgroups=cross
-else
- cat > conftest.$ac_ext <<EOF
-#line 2427 "configure"
-#include "confdefs.h"
-
-/* Thanks to Mike Rendell for this test. */
-#include <sys/types.h>
-#define NGID 256
-#undef MAX
-#define MAX(x, y) ((x) > (y) ? (x) : (y))
-main()
-{
- gid_t gidset[NGID];
- int i, n;
- union { gid_t gval; long lval; } val;
-
- val.lval = -1;
- for (i = 0; i < NGID; i++)
- gidset[i] = val.gval;
- n = getgroups (sizeof (gidset) / MAX (sizeof (int), sizeof (gid_t)) - 1,
- gidset);
- /* Exit non-zero if getgroups seems to require an array of ints. This
- happens when gid_t is short but getgroups modifies an array of ints. */
- exit ((n > 0 && gidset[n] != val.gval) ? 1 : 0);
-}
-
-EOF
-if { (eval echo configure:2452: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
-then
- ac_cv_type_getgroups=gid_t
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -fr conftest*
- ac_cv_type_getgroups=int
-fi
-rm -fr conftest*
-fi
-
-if test $ac_cv_type_getgroups = cross; then
- cat > conftest.$ac_ext <<EOF
-#line 2466 "configure"
-#include "confdefs.h"
-#include <unistd.h>
-EOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
- egrep "getgroups.*int.*gid_t" >/dev/null 2>&1; then
- rm -rf conftest*
- ac_cv_type_getgroups=gid_t
-else
- rm -rf conftest*
- ac_cv_type_getgroups=int
-fi
-rm -f conftest*
-
-fi
-fi
-
-echo "$ac_t""$ac_cv_type_getgroups" 1>&6
-cat >> confdefs.h <<EOF
-#define GETGROUPS_T $ac_cv_type_getgroups
-EOF
-
-
-echo $ac_n "checking return type of signal handlers""... $ac_c" 1>&6
-echo "configure:2490: checking return type of signal handlers" >&5
-if eval "test \"`echo '$''{'ac_cv_type_signal'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 2495 "configure"
-#include "confdefs.h"
-#include <sys/types.h>
-#include <signal.h>
-#ifdef signal
-#undef signal
-#endif
-#ifdef __cplusplus
-extern "C" void (*signal (int, void (*)(int)))(int);
-#else
-void (*signal ()) ();
-#endif
-
-int main() {
-int i;
-; return 0; }
-EOF
-if { (eval echo configure:2512: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
- rm -rf conftest*
- ac_cv_type_signal=void
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- ac_cv_type_signal=int
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$ac_cv_type_signal" 1>&6
-cat >> confdefs.h <<EOF
-#define RETSIGTYPE $ac_cv_type_signal
-EOF
-
-
-# The Ultrix 4.2 mips builtin alloca declared by alloca.h only works
-# for constant arguments. Useless!
-echo $ac_n "checking for working alloca.h""... $ac_c" 1>&6
-echo "configure:2533: checking for working alloca.h" >&5
-if eval "test \"`echo '$''{'ac_cv_header_alloca_h'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 2538 "configure"
-#include "confdefs.h"
-#include <alloca.h>
-int main() {
-char *p = alloca(2 * sizeof(int));
-; return 0; }
-EOF
-if { (eval echo configure:2545: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
- rm -rf conftest*
- ac_cv_header_alloca_h=yes
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- ac_cv_header_alloca_h=no
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$ac_cv_header_alloca_h" 1>&6
-if test $ac_cv_header_alloca_h = yes; then
- cat >> confdefs.h <<\EOF
-#define HAVE_ALLOCA_H 1
-EOF
-
-fi
-
-echo $ac_n "checking for alloca""... $ac_c" 1>&6
-echo "configure:2566: checking for alloca" >&5
-if eval "test \"`echo '$''{'ac_cv_func_alloca_works'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 2571 "configure"
-#include "confdefs.h"
-
-#ifdef __GNUC__
-# define alloca __builtin_alloca
-#else
-# ifdef _MSC_VER
-# include <malloc.h>
-# define alloca _alloca
-# else
-# if HAVE_ALLOCA_H
-# include <alloca.h>
-# else
-# ifdef _AIX
- #pragma alloca
-# else
-# ifndef alloca /* predefined by HP cc +Olibcalls */
-char *alloca ();
-# endif
-# endif
-# endif
-# endif
-#endif
-
-int main() {
-char *p = (char *) alloca(1);
-; return 0; }
-EOF
-if { (eval echo configure:2599: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
- rm -rf conftest*
- ac_cv_func_alloca_works=yes
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- ac_cv_func_alloca_works=no
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$ac_cv_func_alloca_works" 1>&6
-if test $ac_cv_func_alloca_works = yes; then
- cat >> confdefs.h <<\EOF
-#define HAVE_ALLOCA 1
-EOF
-
-fi
-
-if test $ac_cv_func_alloca_works = no; then
- # The SVR3 libPW and SVR4 libucb both contain incompatible functions
- # that cause trouble. Some versions do not even contain alloca or
- # contain a buggy version. If you still want to use their alloca,
- # use ar to extract alloca.o from them instead of compiling alloca.c.
- ALLOCA=alloca.${ac_objext}
- cat >> confdefs.h <<\EOF
-#define C_ALLOCA 1
-EOF
-
-
-echo $ac_n "checking whether alloca needs Cray hooks""... $ac_c" 1>&6
-echo "configure:2631: checking whether alloca needs Cray hooks" >&5
-if eval "test \"`echo '$''{'ac_cv_os_cray'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 2636 "configure"
-#include "confdefs.h"
-#if defined(CRAY) && ! defined(CRAY2)
-webecray
-#else
-wenotbecray
-#endif
-
-EOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
- egrep "webecray" >/dev/null 2>&1; then
- rm -rf conftest*
- ac_cv_os_cray=yes
-else
- rm -rf conftest*
- ac_cv_os_cray=no
-fi
-rm -f conftest*
-
-fi
-
-echo "$ac_t""$ac_cv_os_cray" 1>&6
-if test $ac_cv_os_cray = yes; then
-for ac_func in _getb67 GETB67 getb67; do
- echo $ac_n "checking for $ac_func""... $ac_c" 1>&6
-echo "configure:2661: checking for $ac_func" >&5
-if eval "test \"`echo '$''{'ac_cv_func_$ac_func'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 2666 "configure"
-#include "confdefs.h"
-/* System header to define __stub macros and hopefully few prototypes,
- which can conflict with char $ac_func(); below. */
-#include <assert.h>
-/* Override any gcc2 internal prototype to avoid an error. */
-/* We use char because int might match the return type of a gcc2
- builtin and then its argument prototype would still apply. */
-char $ac_func();
-
-int main() {
-
-/* The GNU C library defines this for functions which it implements
- to always fail with ENOSYS. Some functions are actually named
- something starting with __ and the normal name is an alias. */
-#if defined (__stub_$ac_func) || defined (__stub___$ac_func)
-choke me
-#else
-$ac_func();
-#endif
-
-; return 0; }
-EOF
-if { (eval echo configure:2689: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
- rm -rf conftest*
- eval "ac_cv_func_$ac_func=yes"
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- eval "ac_cv_func_$ac_func=no"
-fi
-rm -f conftest*
-fi
-
-if eval "test \"`echo '$ac_cv_func_'$ac_func`\" = yes"; then
- echo "$ac_t""yes" 1>&6
- cat >> confdefs.h <<EOF
-#define CRAY_STACKSEG_END $ac_func
-EOF
-
- break
-else
- echo "$ac_t""no" 1>&6
-fi
-
-done
-fi
-
-echo $ac_n "checking stack direction for C alloca""... $ac_c" 1>&6
-echo "configure:2716: checking stack direction for C alloca" >&5
-if eval "test \"`echo '$''{'ac_cv_c_stack_direction'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- if test "$cross_compiling" = yes; then
- ac_cv_c_stack_direction=0
-else
- cat > conftest.$ac_ext <<EOF
-#line 2724 "configure"
-#include "confdefs.h"
-find_stack_direction ()
-{
- static char *addr = 0;
- auto char dummy;
- if (addr == 0)
- {
- addr = &dummy;
- return find_stack_direction ();
- }
- else
- return (&dummy > addr) ? 1 : -1;
-}
-main ()
-{
- exit (find_stack_direction() < 0);
-}
-EOF
-if { (eval echo configure:2743: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
-then
- ac_cv_c_stack_direction=1
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -fr conftest*
- ac_cv_c_stack_direction=-1
-fi
-rm -fr conftest*
-fi
-
-fi
-
-echo "$ac_t""$ac_cv_c_stack_direction" 1>&6
-cat >> confdefs.h <<EOF
-#define STACK_DIRECTION $ac_cv_c_stack_direction
-EOF
-
-fi
-
-echo $ac_n "checking for pid_t""... $ac_c" 1>&6
-echo "configure:2765: checking for pid_t" >&5
-if eval "test \"`echo '$''{'ac_cv_type_pid_t'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 2770 "configure"
-#include "confdefs.h"
-#include <sys/types.h>
-#if STDC_HEADERS
-#include <stdlib.h>
-#include <stddef.h>
-#endif
-EOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
- egrep "(^|[^a-zA-Z_0-9])pid_t[^a-zA-Z_0-9]" >/dev/null 2>&1; then
- rm -rf conftest*
- ac_cv_type_pid_t=yes
-else
- rm -rf conftest*
- ac_cv_type_pid_t=no
-fi
-rm -f conftest*
-
-fi
-echo "$ac_t""$ac_cv_type_pid_t" 1>&6
-if test $ac_cv_type_pid_t = no; then
- cat >> confdefs.h <<\EOF
-#define pid_t int
-EOF
-
-fi
-
-ac_safe=`echo "vfork.h" | sed 'y%./+-%__p_%'`
-echo $ac_n "checking for vfork.h""... $ac_c" 1>&6
-echo "configure:2799: checking for vfork.h" >&5
-if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 2804 "configure"
-#include "confdefs.h"
-#include <vfork.h>
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:2809: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
-if test -z "$ac_err"; then
- rm -rf conftest*
- eval "ac_cv_header_$ac_safe=yes"
-else
- echo "$ac_err" >&5
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- eval "ac_cv_header_$ac_safe=no"
-fi
-rm -f conftest*
-fi
-if eval "test \"`echo '$ac_cv_header_'$ac_safe`\" = yes"; then
- echo "$ac_t""yes" 1>&6
- cat >> confdefs.h <<\EOF
-#define HAVE_VFORK_H 1
-EOF
-
-else
- echo "$ac_t""no" 1>&6
-fi
-
-echo $ac_n "checking for working vfork""... $ac_c" 1>&6
-echo "configure:2834: checking for working vfork" >&5
-if eval "test \"`echo '$''{'ac_cv_func_vfork_works'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- if test "$cross_compiling" = yes; then
- echo $ac_n "checking for vfork""... $ac_c" 1>&6
-echo "configure:2840: checking for vfork" >&5
-if eval "test \"`echo '$''{'ac_cv_func_vfork'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 2845 "configure"
-#include "confdefs.h"
-/* System header to define __stub macros and hopefully few prototypes,
- which can conflict with char vfork(); below. */
-#include <assert.h>
-/* Override any gcc2 internal prototype to avoid an error. */
-/* We use char because int might match the return type of a gcc2
- builtin and then its argument prototype would still apply. */
-char vfork();
-
-int main() {
-
-/* The GNU C library defines this for functions which it implements
- to always fail with ENOSYS. Some functions are actually named
- something starting with __ and the normal name is an alias. */
-#if defined (__stub_vfork) || defined (__stub___vfork)
-choke me
-#else
-vfork();
-#endif
-
-; return 0; }
-EOF
-if { (eval echo configure:2868: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
- rm -rf conftest*
- eval "ac_cv_func_vfork=yes"
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- eval "ac_cv_func_vfork=no"
-fi
-rm -f conftest*
-fi
-
-if eval "test \"`echo '$ac_cv_func_'vfork`\" = yes"; then
- echo "$ac_t""yes" 1>&6
- :
-else
- echo "$ac_t""no" 1>&6
-fi
-
-ac_cv_func_vfork_works=$ac_cv_func_vfork
-else
- cat > conftest.$ac_ext <<EOF
-#line 2890 "configure"
-#include "confdefs.h"
-/* Thanks to Paul Eggert for this test. */
-#include <stdio.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-#ifdef HAVE_VFORK_H
-#include <vfork.h>
-#endif
-/* On some sparc systems, changes by the child to local and incoming
- argument registers are propagated back to the parent.
- The compiler is told about this with #include <vfork.h>,
- but some compilers (e.g. gcc -O) don't grok <vfork.h>.
- Test for this by using a static variable whose address
- is put into a register that is clobbered by the vfork. */
-static
-#ifdef __cplusplus
-sparc_address_test (int arg)
-#else
-sparc_address_test (arg) int arg;
-#endif
-{
- static pid_t child;
- if (!child) {
- child = vfork ();
- if (child < 0) {
- perror ("vfork");
- _exit(2);
- }
- if (!child) {
- arg = getpid();
- write(-1, "", 0);
- _exit (arg);
- }
- }
-}
-main() {
- pid_t parent = getpid ();
- pid_t child;
-
- sparc_address_test ();
-
- child = vfork ();
-
- if (child == 0) {
- /* Here is another test for sparc vfork register problems.
- This test uses lots of local variables, at least
- as many local variables as main has allocated so far
- including compiler temporaries. 4 locals are enough for
- gcc 1.40.3 on a Solaris 4.1.3 sparc, but we use 8 to be safe.
- A buggy compiler should reuse the register of parent
- for one of the local variables, since it will think that
- parent can't possibly be used any more in this routine.
- Assigning to the local variable will thus munge parent
- in the parent process. */
- pid_t
- p = getpid(), p1 = getpid(), p2 = getpid(), p3 = getpid(),
- p4 = getpid(), p5 = getpid(), p6 = getpid(), p7 = getpid();
- /* Convince the compiler that p..p7 are live; otherwise, it might
- use the same hardware register for all 8 local variables. */
- if (p != p1 || p != p2 || p != p3 || p != p4
- || p != p5 || p != p6 || p != p7)
- _exit(1);
-
- /* On some systems (e.g. IRIX 3.3),
- vfork doesn't separate parent from child file descriptors.
- If the child closes a descriptor before it execs or exits,
- this munges the parent's descriptor as well.
- Test for this by closing stdout in the child. */
- _exit(close(fileno(stdout)) != 0);
- } else {
- int status;
- struct stat st;
-
- while (wait(&status) != child)
- ;
- exit(
- /* Was there some problem with vforking? */
- child < 0
-
- /* Did the child fail? (This shouldn't happen.) */
- || status
-
- /* Did the vfork/compiler bug occur? */
- || parent != getpid()
-
- /* Did the file descriptor bug occur? */
- || fstat(fileno(stdout), &st) != 0
- );
- }
-}
-EOF
-if { (eval echo configure:2985: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
-then
- ac_cv_func_vfork_works=yes
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -fr conftest*
- ac_cv_func_vfork_works=no
-fi
-rm -fr conftest*
-fi
-
-fi
-
-echo "$ac_t""$ac_cv_func_vfork_works" 1>&6
-if test $ac_cv_func_vfork_works = no; then
- cat >> confdefs.h <<\EOF
-#define vfork fork
-EOF
-
-fi
-
-echo $ac_n "checking for 8-bit clean memcmp""... $ac_c" 1>&6
-echo "configure:3008: checking for 8-bit clean memcmp" >&5
-if eval "test \"`echo '$''{'ac_cv_func_memcmp_clean'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- if test "$cross_compiling" = yes; then
- ac_cv_func_memcmp_clean=no
-else
- cat > conftest.$ac_ext <<EOF
-#line 3016 "configure"
-#include "confdefs.h"
-
-main()
-{
- char c0 = 0x40, c1 = 0x80, c2 = 0x81;
- exit(memcmp(&c0, &c2, 1) < 0 && memcmp(&c1, &c2, 1) < 0 ? 0 : 1);
-}
-
-EOF
-if { (eval echo configure:3026: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
-then
- ac_cv_func_memcmp_clean=yes
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -fr conftest*
- ac_cv_func_memcmp_clean=no
-fi
-rm -fr conftest*
-fi
-
-fi
-
-echo "$ac_t""$ac_cv_func_memcmp_clean" 1>&6
-test $ac_cv_func_memcmp_clean = no && LIBOBJS="$LIBOBJS memcmp.${ac_objext}"
-
-for ac_func in dup2 memmove mkdir strcasecmp strncasecmp strerror strftime\
- strchr strstr strtoul strdup crypt flock vsnprintf\
- isinf isnan finite
-do
-echo $ac_n "checking for $ac_func""... $ac_c" 1>&6
-echo "configure:3048: checking for $ac_func" >&5
-if eval "test \"`echo '$''{'ac_cv_func_$ac_func'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 3053 "configure"
-#include "confdefs.h"
-/* System header to define __stub macros and hopefully few prototypes,
- which can conflict with char $ac_func(); below. */
-#include <assert.h>
-/* Override any gcc2 internal prototype to avoid an error. */
-/* We use char because int might match the return type of a gcc2
- builtin and then its argument prototype would still apply. */
-char $ac_func();
-
-int main() {
-
-/* The GNU C library defines this for functions which it implements
- to always fail with ENOSYS. Some functions are actually named
- something starting with __ and the normal name is an alias. */
-#if defined (__stub_$ac_func) || defined (__stub___$ac_func)
-choke me
-#else
-$ac_func();
-#endif
-
-; return 0; }
-EOF
-if { (eval echo configure:3076: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
- rm -rf conftest*
- eval "ac_cv_func_$ac_func=yes"
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- eval "ac_cv_func_$ac_func=no"
-fi
-rm -f conftest*
-fi
-
-if eval "test \"`echo '$ac_cv_func_'$ac_func`\" = yes"; then
- echo "$ac_t""yes" 1>&6
- ac_tr_func=HAVE_`echo $ac_func | tr 'abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'`
- cat >> confdefs.h <<EOF
-#define $ac_tr_func 1
-EOF
-
-else
- echo "$ac_t""no" 1>&6
-LIBOBJS="$LIBOBJS ${ac_func}.${ac_objext}"
-fi
-done
-
-
-for ac_func in fmod killpg drand48 random wait4 waitpid syscall getcwd\
- truncate chsize times utimes fcntl lockf setitimer\
- setruid seteuid setreuid setrgid setegid setregid\
- getpgrp setpgrp getpgid setpgid getgroups getpriority\
- dlopen sigprocmask sigaction _setjmp setsid getrlimit
-do
-echo $ac_n "checking for $ac_func""... $ac_c" 1>&6
-echo "configure:3109: checking for $ac_func" >&5
-if eval "test \"`echo '$''{'ac_cv_func_$ac_func'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 3114 "configure"
-#include "confdefs.h"
-/* System header to define __stub macros and hopefully few prototypes,
- which can conflict with char $ac_func(); below. */
-#include <assert.h>
-/* Override any gcc2 internal prototype to avoid an error. */
-/* We use char because int might match the return type of a gcc2
- builtin and then its argument prototype would still apply. */
-char $ac_func();
-
-int main() {
-
-/* The GNU C library defines this for functions which it implements
- to always fail with ENOSYS. Some functions are actually named
- something starting with __ and the normal name is an alias. */
-#if defined (__stub_$ac_func) || defined (__stub___$ac_func)
-choke me
-#else
-$ac_func();
-#endif
-
-; return 0; }
-EOF
-if { (eval echo configure:3137: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
- rm -rf conftest*
- eval "ac_cv_func_$ac_func=yes"
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- eval "ac_cv_func_$ac_func=no"
-fi
-rm -f conftest*
-fi
-
-if eval "test \"`echo '$ac_cv_func_'$ac_func`\" = yes"; then
- echo "$ac_t""yes" 1>&6
- ac_tr_func=HAVE_`echo $ac_func | tr 'abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'`
- cat >> confdefs.h <<EOF
-#define $ac_tr_func 1
-EOF
-
-else
- echo "$ac_t""no" 1>&6
-fi
-done
-
-echo $ac_n "checking whether struct tm is in sys/time.h or time.h""... $ac_c" 1>&6
-echo "configure:3162: checking whether struct tm is in sys/time.h or time.h" >&5
-if eval "test \"`echo '$''{'ac_cv_struct_tm'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 3167 "configure"
-#include "confdefs.h"
-#include <sys/types.h>
-#include <time.h>
-int main() {
-struct tm *tp; tp->tm_sec;
-; return 0; }
-EOF
-if { (eval echo configure:3175: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
- rm -rf conftest*
- ac_cv_struct_tm=time.h
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- ac_cv_struct_tm=sys/time.h
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$ac_cv_struct_tm" 1>&6
-if test $ac_cv_struct_tm = sys/time.h; then
- cat >> confdefs.h <<\EOF
-#define TM_IN_SYS_TIME 1
-EOF
-
-fi
-
-echo $ac_n "checking for tm_zone in struct tm""... $ac_c" 1>&6
-echo "configure:3196: checking for tm_zone in struct tm" >&5
-if eval "test \"`echo '$''{'ac_cv_struct_tm_zone'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 3201 "configure"
-#include "confdefs.h"
-#include <sys/types.h>
-#include <$ac_cv_struct_tm>
-int main() {
-struct tm tm; tm.tm_zone;
-; return 0; }
-EOF
-if { (eval echo configure:3209: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
- rm -rf conftest*
- ac_cv_struct_tm_zone=yes
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- ac_cv_struct_tm_zone=no
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$ac_cv_struct_tm_zone" 1>&6
-if test "$ac_cv_struct_tm_zone" = yes; then
- cat >> confdefs.h <<\EOF
-#define HAVE_TM_ZONE 1
-EOF
-
-else
- echo $ac_n "checking for tzname""... $ac_c" 1>&6
-echo "configure:3229: checking for tzname" >&5
-if eval "test \"`echo '$''{'ac_cv_var_tzname'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 3234 "configure"
-#include "confdefs.h"
-#include <time.h>
-#ifndef tzname /* For SGI. */
-extern char *tzname[]; /* RS6000 and others reject char **tzname. */
-#endif
-int main() {
-atoi(*tzname);
-; return 0; }
-EOF
-if { (eval echo configure:3244: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
- rm -rf conftest*
- ac_cv_var_tzname=yes
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- ac_cv_var_tzname=no
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$ac_cv_var_tzname" 1>&6
- if test $ac_cv_var_tzname = yes; then
- cat >> confdefs.h <<\EOF
-#define HAVE_TZNAME 1
-EOF
-
- fi
-fi
-
-if test "$ac_cv_func_strftime" = no; then
- cat > conftest.$ac_ext <<EOF
-#line 3267 "configure"
-#include "confdefs.h"
-
-int main() {
-extern int daylight; int i = daylight;
-; return 0; }
-EOF
-if { (eval echo configure:3274: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
- rm -rf conftest*
- cat >> confdefs.h <<\EOF
-#define HAVE_DAYLIGHT 1
-EOF
-
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
-fi
-rm -f conftest*
-fi
-
-if test "$ac_cv_func_sigprocmask" = yes && test "$ac_cv_func_sigaction" = yes; then
- cat >> confdefs.h <<\EOF
-#define POSIX_SIGNAL 1
-EOF
-
-else
- echo $ac_n "checking for BSD signal semantics""... $ac_c" 1>&6
-echo "configure:3294: checking for BSD signal semantics" >&5
-if eval "test \"`echo '$''{'rb_cv_bsd_signal'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- if test "$cross_compiling" = yes; then
- rb_cv_bsd_signal=no
-else
- cat > conftest.$ac_ext <<EOF
-#line 3302 "configure"
-#include "confdefs.h"
-
-#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;
-}
-
-EOF
-if { (eval echo configure:3324: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
-then
- rb_cv_bsd_signal=yes
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -fr conftest*
- rb_cv_bsd_signal=no
-fi
-rm -fr conftest*
-fi
-
-fi
-
-echo "$ac_t""$rb_cv_bsd_signal" 1>&6
- if test "$rb_cv_bsd_signal" = yes; then
- cat >> confdefs.h <<\EOF
-#define BSD_SIGNAL 1
-EOF
-
- fi
-fi
-
-echo $ac_n "checking whether getpgrp takes no argument""... $ac_c" 1>&6
-echo "configure:3348: checking whether getpgrp takes no argument" >&5
-if eval "test \"`echo '$''{'ac_cv_func_getpgrp_void'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- if test "$cross_compiling" = yes; then
- { echo "configure: error: cannot check getpgrp if cross compiling" 1>&2; exit 1; }
-else
- cat > conftest.$ac_ext <<EOF
-#line 3356 "configure"
-#include "confdefs.h"
-
-/*
- * If this system has a BSD-style getpgrp(),
- * which takes a pid argument, exit unsuccessfully.
- *
- * Snarfed from Chet Ramey's bash pgrp.c test program
- */
-#include <stdio.h>
-#include <sys/types.h>
-
-int pid;
-int pg1, pg2, pg3, pg4;
-int ng, np, s, child;
-
-main()
-{
- pid = getpid();
- pg1 = getpgrp(0);
- pg2 = getpgrp();
- pg3 = getpgrp(pid);
- pg4 = getpgrp(1);
-
- /*
- * If all of these values are the same, it's pretty sure that
- * we're on a system that ignores getpgrp's first argument.
- */
- if (pg2 == pg4 && pg1 == pg3 && pg2 == pg3)
- exit(0);
-
- child = fork();
- if (child < 0)
- exit(1);
- else if (child == 0) {
- np = getpid();
- /*
- * If this is Sys V, this will not work; pgrp will be
- * set to np because setpgrp just changes a pgrp to be
- * the same as the pid.
- */
- setpgrp(np, pg1);
- ng = getpgrp(0); /* Same result for Sys V and BSD */
- if (ng == pg1) {
- exit(1);
- } else {
- exit(0);
- }
- } else {
- wait(&s);
- exit(s>>8);
- }
-}
-
-EOF
-if { (eval echo configure:3411: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
-then
- ac_cv_func_getpgrp_void=yes
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -fr conftest*
- ac_cv_func_getpgrp_void=no
-fi
-rm -fr conftest*
-fi
-
-
-fi
-
-echo "$ac_t""$ac_cv_func_getpgrp_void" 1>&6
-if test $ac_cv_func_getpgrp_void = yes; then
- cat >> confdefs.h <<\EOF
-#define GETPGRP_VOID 1
-EOF
-
-fi
-
-echo $ac_n "checking whether setpgrp takes no argument""... $ac_c" 1>&6
-echo "configure:3435: checking whether setpgrp takes no argument" >&5
-if eval "test \"`echo '$''{'ac_cv_func_setpgrp_void'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- if test "$cross_compiling" = yes; then
- { echo "configure: error: cannot check setpgrp if cross compiling" 1>&2; exit 1; }
-else
- cat > conftest.$ac_ext <<EOF
-#line 3443 "configure"
-#include "confdefs.h"
-
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-
-/*
- * If this system has a BSD-style setpgrp, which takes arguments, exit
- * successfully.
- */
-main()
-{
- if (setpgrp(1,1) == -1)
- exit(0);
- else
- exit(1);
-}
-
-EOF
-if { (eval echo configure:3463: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
-then
- ac_cv_func_setpgrp_void=no
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -fr conftest*
- ac_cv_func_setpgrp_void=yes
-fi
-rm -fr conftest*
-fi
-
-
-fi
-
-echo "$ac_t""$ac_cv_func_setpgrp_void" 1>&6
-if test $ac_cv_func_setpgrp_void = yes; then
- cat >> confdefs.h <<\EOF
-#define SETPGRP_VOID 1
-EOF
-
-fi
-
-
-echo $ac_n "checking for working strtod""... $ac_c" 1>&6
-echo "configure:3488: checking for working strtod" >&5
-if eval "test \"`echo '$''{'rb_cv_func_strtod'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- if test "$cross_compiling" = yes; then
- rb_cv_func_strtod=no
-else
- cat > conftest.$ac_ext <<EOF
-#line 3496 "configure"
-#include "confdefs.h"
-
-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);
-}
-
-EOF
-if { (eval echo configure:3526: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
-then
- rb_cv_func_strtod=yes
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -fr conftest*
- rb_cv_func_strtod=no
-fi
-rm -fr conftest*
-fi
-
-fi
-
-echo "$ac_t""$rb_cv_func_strtod" 1>&6
-test $rb_cv_func_strtod = no && LIBOBJS="$LIBOBJS strtod.o"
-
-echo $ac_n "checking whether byte ordering is bigendian""... $ac_c" 1>&6
-echo "configure:3544: checking whether byte ordering is bigendian" >&5
-if eval "test \"`echo '$''{'ac_cv_c_bigendian'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- ac_cv_c_bigendian=unknown
-# See if sys/param.h defines the BYTE_ORDER macro.
-cat > conftest.$ac_ext <<EOF
-#line 3551 "configure"
-#include "confdefs.h"
-#include <sys/types.h>
-#include <sys/param.h>
-int main() {
-
-#if !BYTE_ORDER || !BIG_ENDIAN || !LITTLE_ENDIAN
- bogus endian macros
-#endif
-; return 0; }
-EOF
-if { (eval echo configure:3562: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
- rm -rf conftest*
- # It does; now see whether it defined to BIG_ENDIAN or not.
-cat > conftest.$ac_ext <<EOF
-#line 3566 "configure"
-#include "confdefs.h"
-#include <sys/types.h>
-#include <sys/param.h>
-int main() {
-
-#if BYTE_ORDER != BIG_ENDIAN
- not big endian
-#endif
-; return 0; }
-EOF
-if { (eval echo configure:3577: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
- rm -rf conftest*
- ac_cv_c_bigendian=yes
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- ac_cv_c_bigendian=no
-fi
-rm -f conftest*
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
-fi
-rm -f conftest*
-if test $ac_cv_c_bigendian = unknown; then
-if test "$cross_compiling" = yes; then
- { echo "configure: error: can not run test program while cross compiling" 1>&2; exit 1; }
-else
- cat > conftest.$ac_ext <<EOF
-#line 3597 "configure"
-#include "confdefs.h"
-main () {
- /* Are we little or big endian? From Harbison&Steele. */
- union
- {
- long l;
- char c[sizeof (long)];
- } u;
- u.l = 1;
- exit (u.c[sizeof (long) - 1] == 1);
-}
-EOF
-if { (eval echo configure:3610: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
-then
- ac_cv_c_bigendian=no
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -fr conftest*
- ac_cv_c_bigendian=yes
-fi
-rm -fr conftest*
-fi
-
-fi
-fi
-
-echo "$ac_t""$ac_cv_c_bigendian" 1>&6
-if test $ac_cv_c_bigendian = yes; then
- cat >> confdefs.h <<\EOF
-#define WORDS_BIGENDIAN 1
-EOF
-
-fi
-
-echo $ac_n "checking for working const""... $ac_c" 1>&6
-echo "configure:3634: checking for working const" >&5
-if eval "test \"`echo '$''{'ac_cv_c_const'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 3639 "configure"
-#include "confdefs.h"
-
-int main() {
-
-/* Ultrix mips cc rejects this. */
-typedef int charset[2]; const charset x = {0,0};
-/* SunOS 4.1.1 cc rejects this. */
-char const *const *ccp;
-char **p;
-/* NEC SVR4.0.2 mips cc rejects this. */
-struct point {int x, y;};
-static struct point const zero = {0,0};
-/* AIX XL C 1.02.0.0 rejects this.
- It does not let you subtract one const X* pointer from another in an arm
- of an if-expression whose if-part is not a constant expression */
-const char *g = "string";
-ccp = &g + (g ? g-g : 0);
-/* HPUX 7.0 cc rejects these. */
-++ccp;
-p = (char**) ccp;
-ccp = (char const *const *) p;
-{ /* SCO 3.2v4 cc rejects this. */
- char *t;
- char const *s = 0 ? (char *) 0 : (char const *) 0;
-
- *t++ = 0;
-}
-{ /* Someone thinks the Sun supposedly-ANSI compiler will reject this. */
- int x[] = {25, 17};
- const int *foo = &x[0];
- ++foo;
-}
-{ /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */
- typedef const int *iptr;
- iptr p = 0;
- ++p;
-}
-{ /* AIX XL C 1.02.0.0 rejects this saying
- "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */
- struct s { int j; const int *ap[3]; };
- struct s *b; b->j = 5;
-}
-{ /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */
- const int foo = 10;
-}
-
-; return 0; }
-EOF
-if { (eval echo configure:3688: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
- rm -rf conftest*
- ac_cv_c_const=yes
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- ac_cv_c_const=no
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$ac_cv_c_const" 1>&6
-if test $ac_cv_c_const = no; then
- cat >> confdefs.h <<\EOF
-#define const
-EOF
-
-fi
-
-echo $ac_n "checking whether char is unsigned""... $ac_c" 1>&6
-echo "configure:3709: checking whether char is unsigned" >&5
-if eval "test \"`echo '$''{'ac_cv_c_char_unsigned'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- if test "$GCC" = yes; then
- # GCC predefines this symbol on systems where it applies.
-cat > conftest.$ac_ext <<EOF
-#line 3716 "configure"
-#include "confdefs.h"
-#ifdef __CHAR_UNSIGNED__
- yes
-#endif
-
-EOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
- egrep "yes" >/dev/null 2>&1; then
- rm -rf conftest*
- ac_cv_c_char_unsigned=yes
-else
- rm -rf conftest*
- ac_cv_c_char_unsigned=no
-fi
-rm -f conftest*
-
-else
-if test "$cross_compiling" = yes; then
- { echo "configure: error: can not run test program while cross compiling" 1>&2; exit 1; }
-else
- cat > conftest.$ac_ext <<EOF
-#line 3738 "configure"
-#include "confdefs.h"
-/* volatile prevents gcc2 from optimizing the test away on sparcs. */
-#if !defined(__STDC__) || __STDC__ != 1
-#define volatile
-#endif
-main() {
- volatile char c = 255; exit(c < 0);
-}
-EOF
-if { (eval echo configure:3748: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
-then
- ac_cv_c_char_unsigned=yes
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -fr conftest*
- ac_cv_c_char_unsigned=no
-fi
-rm -fr conftest*
-fi
-
-fi
-fi
-
-echo "$ac_t""$ac_cv_c_char_unsigned" 1>&6
-if test $ac_cv_c_char_unsigned = yes && test "$GCC" != yes; then
- cat >> confdefs.h <<\EOF
-#define __CHAR_UNSIGNED__ 1
-EOF
-
-fi
-
-
-echo $ac_n "checking whether right shift preserve sign bit""... $ac_c" 1>&6
-echo "configure:3773: checking whether right shift preserve sign bit" >&5
-if eval "test \"`echo '$''{'rb_cv_rshift_sign'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- if test "$cross_compiling" = yes; then
- rb_cv_rshift_sign=yes
-else
- cat > conftest.$ac_ext <<EOF
-#line 3781 "configure"
-#include "confdefs.h"
-
-int
-main()
-{
- if (-1==(-1>>1))
- return 0;
- return 1;
-}
-
-EOF
-if { (eval echo configure:3793: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
-then
- rb_cv_rshift_sign=yes
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -fr conftest*
- rb_cv_rshift_sign=no
-fi
-rm -fr conftest*
-fi
-
-fi
-
-echo "$ac_t""$rb_cv_rshift_sign" 1>&6
-if test "$rb_cv_rshift_sign" = yes; then
- cat >> confdefs.h <<\EOF
-#define RSHIFT(x,y) ((x)>>(int)y)
-EOF
-
-else
- cat >> confdefs.h <<\EOF
-#define RSHIFT(x,y) (((x)<0) ? ~((~(x))>>y) : (x)>>y)
-EOF
-
-fi
-
-echo $ac_n "checking count field in FILE structures""... $ac_c" 1>&6
-echo "configure:3821: checking count field in FILE structures" >&5
-if eval "test \"`echo '$''{'rb_cv_fcnt'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 3826 "configure"
-#include "confdefs.h"
-#include <stdio.h>
-int main() {
-FILE *f = stdin; f->_cnt = 0;
-; return 0; }
-EOF
-if { (eval echo configure:3833: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
- rm -rf conftest*
- rb_cv_fcnt="_cnt"
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
-fi
-rm -f conftest*
-if test "$rb_cv_fcnt" = ""; then
- cat > conftest.$ac_ext <<EOF
-#line 3843 "configure"
-#include "confdefs.h"
-#include <stdio.h>
-int main() {
-FILE *f = stdin; f->__cnt = 0;
-; return 0; }
-EOF
-if { (eval echo configure:3850: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
- rm -rf conftest*
- rb_cv_fcnt="__cnt"
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
-fi
-rm -f conftest*
-fi
-if test "$rb_cv_fcnt" = ""; then
- cat > conftest.$ac_ext <<EOF
-#line 3861 "configure"
-#include "confdefs.h"
-#include <stdio.h>
-int main() {
-FILE *f = stdin; f->_r = 0;
-; return 0; }
-EOF
-if { (eval echo configure:3868: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
- rm -rf conftest*
- rb_cv_fcnt="_r"
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
-fi
-rm -f conftest*
-fi
-if test "$rb_cv_fcnt" = ""; then
- cat > conftest.$ac_ext <<EOF
-#line 3879 "configure"
-#include "confdefs.h"
-#include <stdio.h>
-int main() {
-FILE *f = stdin; f->readCount = 0;
-; return 0; }
-EOF
-if { (eval echo configure:3886: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
- rm -rf conftest*
- rb_cv_fcnt="readCount"
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
-fi
-rm -f conftest*
-fi
-if test "$rb_cv_fcnt" = ""; then
- cat > conftest.$ac_ext <<EOF
-#line 3897 "configure"
-#include "confdefs.h"
-#include <stdio.h>
-int main() {
-FILE *f = stdin; f->_rcount = 0;
-; return 0; }
-EOF
-if { (eval echo configure:3904: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
- rm -rf conftest*
- rb_cv_fcnt="_rcount"
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- rb_cv_fcnt="not found"
-fi
-rm -f conftest*
-fi
-fi
-
-if test "$rb_cv_fcnt" = "not found"; then
- echo "$ac_t""not found(OK if using GNU libc)" 1>&6
-else
- echo "$ac_t""$rb_cv_fcnt" 1>&6
- cat >> confdefs.h <<EOF
-#define FILE_COUNT $rb_cv_fcnt
-EOF
-
-fi
-
-
-# Check whether --with-default-kcode or --without-default-kcode was given.
-if test "${with_default_kcode+set}" = set; then
- withval="$with_default_kcode"
- case $withval in
- utf8) cat >> confdefs.h <<\EOF
-#define DEFAULT_KCODE KCODE_UTF8
-EOF
-;;
- euc) cat >> confdefs.h <<\EOF
-#define DEFAULT_KCODE KCODE_EUC
-EOF
-;;
- sjis) cat >> confdefs.h <<\EOF
-#define DEFAULT_KCODE KCODE_SJIS
-EOF
-;;
- none) cat >> confdefs.h <<\EOF
-#define DEFAULT_KCODE KCODE_NONE
-EOF
-;;
- *) echo "configure: warning: $withval is not valid kcode; ignored" 1>&2;;
- esac
-fi
-
-
-# Check whether --with-dln-a-out or --without-dln-a-out was given.
-if test "${with_dln_a_out+set}" = set; then
- withval="$with_dln_a_out"
-
- case $withval in
- yes) with_dln_a_out=yes;;
- *) with_dln_a_out=no;;
- esac
-else
- with_dln_a_out=no
-fi
-
-
-
-case "$host_os" in
- linux*)
- echo $ac_n "checking whether ELF binaries are produced""... $ac_c" 1>&6
-echo "configure:3970: checking whether ELF binaries are produced" >&5
-if eval "test \"`echo '$''{'rb_cv_binary_elf'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- if test "$cross_compiling" = yes; then
- rb_cv_binary_elf=yes
-else
- cat > conftest.$ac_ext <<EOF
-#line 3978 "configure"
-#include "confdefs.h"
-
-/* 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) */
-}
-
-EOF
-if { (eval echo configure:3998: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
-then
- rb_cv_binary_elf=yes
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -fr conftest*
- rb_cv_binary_elf=no
-fi
-rm -fr conftest*
-fi
-
-fi
-
-echo "$ac_t""$rb_cv_binary_elf" 1>&6
- if test "$rb_cv_binary_elf" = no; then
- with_dln_a_out=yes
- host_os=${host_os}-a_out
- else
- LDFLAGS="-rdynamic"
- fi;;
-esac
-
-
-
-STATIC=
-
-if test "$with_dln_a_out" != yes; then
- rb_cv_dlopen=unknown
- echo $ac_n "checking whether OS depend dynamic link works""... $ac_c" 1>&6
-echo "configure:4028: checking whether OS depend dynamic link works" >&5
- if test "$GCC" = yes; then
- case "$host_os" in
- nextstep*) ;;
- openstep*) ;;
- rhapsody*) ;;
- human*) ;;
- bsdi*) ;;
- cygwin*) ;;
- netbsd*) CCDLFLAGS=-fpic
- case "$host_cpu" in
- mips*) CCDLFLAGS=-fPIC ;;
- *) ;;
- esac ;;
- *) CCDLFLAGS=-fPIC;;
- esac
- else
- case "$host_os" in
- hpux*) CCDLFLAGS='+z';;
- solaris*|irix*) CCDLFLAGS='-K PIC' ;;
- sunos*) CCDLFLAGS='-PIC' ;;
- esix*|uxpds*) CCDLFLAGS='-KPIC' ;;
- *) CCDLFLAGS='' ;;
- esac
- fi
-
- case "$host_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'
- `$CC --print-prog-name=ld` -v 2>&1 | grep "GNU ld" > /dev/null && LDFLAGS="-Wl,-E"
- else
- LDSHARED='ld -G'
- fi
- rb_cv_dlopen=yes;;
- sunos*) LDSHARED='ld -assert nodefinitions'
- rb_cv_dlopen=yes;;
- irix*) LDSHARED='ld -ignore_unresolved'
- rb_cv_dlopen=yes;;
- sysv4*) LDSHARED='ld -G'
- 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 ;;
- freebsd*) LDSHARED="$CC -shared"
- if test -x /usr/bin/objformat && \
- test `/usr/bin/objformat` = "elf" ; then
- LDFLAGS="-rdynamic"
- DLDFLAGS='-Wl,-soname,$(.TARGET)'
- rb_cv_freebsd_elf=yes
- 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="ld -shared"
- case "$host_cpu" in
- alpha)
- LDFLAGS="-export-dynamic" ;;
- esac
- 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 ;;
- aix*) LDSHARED='/usr/ccs/bin/ld'
- XLDFLAGS='-Wl,-bE:ruby.imp'
- DLDFLAGS='-eInit_$(TARGET) -bI:$(topdir)/ruby.imp -bM:SRE -T512 -H512 -lc'
- rb_cv_dlopen=yes ;;
-
- human*) DLDFLAGS=''
- LDSHARED=''
- LDFLAGS=''
- rb_cv_dlopen=yes ;;
- beos*) case "$host_cpu" in
- powerpc*)
- LDSHARED="ld -xms"
- DLDFLAGS="-f ruby.exp -lbe -lroot glue-noinit.a init_term_dyn.o start_dyn.o"
- ;;
- i586*)
- LDSHARED="ld -shared"
- DLDFLAGS="-L/boot/develop/lib/x86 -lbe -lroot"
- ;;
- *)
- DLDFLAGS="ruby.def -lbe -lroot glue-noinit.a init_term_dyn.o start_dyn.o"
- esac
- rb_cv_dlopen=yes ;;
- cygwin*) LDSHARED='dllwrap --export-all -s'
- rb_cv_dlopen=yes ;;
- *) LDSHARED='ld' ;;
- esac
- echo "$ac_t""$rb_cv_dlopen" 1>&6
-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
- echo $ac_n "checking whether matz's dln works""... $ac_c" 1>&6
-echo "configure:4149: checking whether matz's dln works" >&5
-if eval "test \"`echo '$''{'rb_cv_dln_a_out'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 4154 "configure"
-#include "confdefs.h"
-
-#define USE_DLN_A_OUT
-#include "dln.c"
-
-int main() {
-
-; return 0; }
-EOF
-if { (eval echo configure:4164: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
- rm -rf conftest*
- rb_cv_dln_a_out=yes
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- rb_cv_dln_a_out=no
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$rb_cv_dln_a_out" 1>&6
- if test "$rb_cv_dln_a_out" = yes; then
- dln_a_out_works=yes
- cat >> confdefs.h <<\EOF
-#define USE_DLN_A_OUT 1
-EOF
-
- fi
- fi
-fi
-
-if test "$dln_a_out_works" = yes; then
- if test "$GCC" = yes; then
- STATIC=-static
- else
- STATIC=-Bstatic
- fi
- DLEXT=so
- cat >> confdefs.h <<\EOF
-#define DLEXT ".so"
-EOF
-
- CCDLFLAGS=
-else
- case "$host_os" in
- hpux*) DLEXT=sl
- cat >> confdefs.h <<\EOF
-#define DLEXT ".sl"
-EOF
-;;
- nextstep*) DLEXT=bundle
- cat >> confdefs.h <<\EOF
-#define DLEXT ".bundle"
-EOF
-;;
- openstep*) DLEXT=bundle
- cat >> confdefs.h <<\EOF
-#define DLEXT ".bundle"
-EOF
-;;
- rhapsody*) DLEXT=bundle
- cat >> confdefs.h <<\EOF
-#define DLEXT ".bundle"
-EOF
-;;
- cygwin*) DLEXT=dll
- cat >> confdefs.h <<\EOF
-#define DLEXT ".dll"
-EOF
-;;
- os2_emx) DLEXT=o
- cat >> confdefs.h <<\EOF
-#define DLEXT ".so"
-EOF
-;;
- *) DLEXT=so
- cat >> confdefs.h <<\EOF
-#define DLEXT ".so"
-EOF
-;;
- esac
-fi
-
-if test "$with_dln_a_out" = yes; then
- STRIP=true
-else
- STRIP=strip
-fi
-
-case "$host_os" in
- linux*)
- STRIP='strip -S -x';;
- nextstep*)
- STRIP='strip -A -n';;
- openstep*)
- STRIP='strip -A -n';;
- rhapsody*)
- STRIP='strip -A -n';;
-esac
-
-EXTSTATIC=
-# Check whether --with-static-linked-ext or --without-static-linked-ext was given.
-if test "${with_static_linked_ext+set}" = set; then
- withval="$with_static_linked_ext"
- case $withval in
- yes) STATIC=
- EXTSTATIC=static;;
- *) ;;
- esac
-fi
-
-
-case "$host_os" in
- human*)
- echo $ac_n "checking for _harderr in -lsignal""... $ac_c" 1>&6
-echo "configure:4271: checking for _harderr in -lsignal" >&5
-ac_lib_var=`echo signal'_'_harderr | sed 'y%./+-%__p_%'`
-if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- ac_save_LIBS="$LIBS"
-LIBS="-lsignal $LIBS"
-cat > conftest.$ac_ext <<EOF
-#line 4279 "configure"
-#include "confdefs.h"
-/* Override any gcc2 internal prototype to avoid an error. */
-/* We use char because int might match the return type of a gcc2
- builtin and then its argument prototype would still apply. */
-char _harderr();
-
-int main() {
-_harderr()
-; return 0; }
-EOF
-if { (eval echo configure:4290: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
- rm -rf conftest*
- eval "ac_cv_lib_$ac_lib_var=yes"
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- eval "ac_cv_lib_$ac_lib_var=no"
-fi
-rm -f conftest*
-LIBS="$ac_save_LIBS"
-
-fi
-if eval "test \"`echo '$ac_cv_lib_'$ac_lib_var`\" = yes"; then
- echo "$ac_t""yes" 1>&6
- ac_tr_lib=HAVE_LIB`echo signal | sed -e 's/[^a-zA-Z0-9_]/_/g' \
- -e 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/'`
- cat >> confdefs.h <<EOF
-#define $ac_tr_lib 1
-EOF
-
- LIBS="-lsignal $LIBS"
-
-else
- echo "$ac_t""no" 1>&6
-fi
-
- echo $ac_n "checking for hmemset in -lhmem""... $ac_c" 1>&6
-echo "configure:4318: checking for hmemset in -lhmem" >&5
-ac_lib_var=`echo hmem'_'hmemset | sed 'y%./+-%__p_%'`
-if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- ac_save_LIBS="$LIBS"
-LIBS="-lhmem $LIBS"
-cat > conftest.$ac_ext <<EOF
-#line 4326 "configure"
-#include "confdefs.h"
-/* Override any gcc2 internal prototype to avoid an error. */
-/* We use char because int might match the return type of a gcc2
- builtin and then its argument prototype would still apply. */
-char hmemset();
-
-int main() {
-hmemset()
-; return 0; }
-EOF
-if { (eval echo configure:4337: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
- rm -rf conftest*
- eval "ac_cv_lib_$ac_lib_var=yes"
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- eval "ac_cv_lib_$ac_lib_var=no"
-fi
-rm -f conftest*
-LIBS="$ac_save_LIBS"
-
-fi
-if eval "test \"`echo '$ac_cv_lib_'$ac_lib_var`\" = yes"; then
- echo "$ac_t""yes" 1>&6
- ac_tr_lib=HAVE_LIB`echo hmem | sed -e 's/[^a-zA-Z0-9_]/_/g' \
- -e 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/'`
- cat >> confdefs.h <<EOF
-#define $ac_tr_lib 1
-EOF
-
- LIBS="-lhmem $LIBS"
-
-else
- echo "$ac_t""no" 1>&6
-fi
-
- for ac_func in select
-do
-echo $ac_n "checking for $ac_func""... $ac_c" 1>&6
-echo "configure:4367: checking for $ac_func" >&5
-if eval "test \"`echo '$''{'ac_cv_func_$ac_func'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- cat > conftest.$ac_ext <<EOF
-#line 4372 "configure"
-#include "confdefs.h"
-/* System header to define __stub macros and hopefully few prototypes,
- which can conflict with char $ac_func(); below. */
-#include <assert.h>
-/* Override any gcc2 internal prototype to avoid an error. */
-/* We use char because int might match the return type of a gcc2
- builtin and then its argument prototype would still apply. */
-char $ac_func();
-
-int main() {
-
-/* The GNU C library defines this for functions which it implements
- to always fail with ENOSYS. Some functions are actually named
- something starting with __ and the normal name is an alias. */
-#if defined (__stub_$ac_func) || defined (__stub___$ac_func)
-choke me
-#else
-$ac_func();
-#endif
-
-; return 0; }
-EOF
-if { (eval echo configure:4395: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
- rm -rf conftest*
- eval "ac_cv_func_$ac_func=yes"
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -rf conftest*
- eval "ac_cv_func_$ac_func=no"
-fi
-rm -f conftest*
-fi
-
-if eval "test \"`echo '$ac_cv_func_'$ac_func`\" = yes"; then
- echo "$ac_t""yes" 1>&6
- ac_tr_func=HAVE_`echo $ac_func | tr 'abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'`
- cat >> confdefs.h <<EOF
-#define $ac_tr_func 1
-EOF
-
-else
- echo "$ac_t""no" 1>&6
-fi
-done
-
- echo $ac_n "checking whether PD libc _dtos18 fail to convert big number""... $ac_c" 1>&6
-echo "configure:4420: checking whether PD libc _dtos18 fail to convert big number" >&5
-if eval "test \"`echo '$''{'rb_cv_missing__dtos18'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- if test "$cross_compiling" = yes; then
- rb_cv_missing__dtos18=no
-else
- cat > conftest.$ac_ext <<EOF
-#line 4428 "configure"
-#include "confdefs.h"
-
-#include <stdio.h>
-main ()
-{
- char buf[256];
- sprintf (buf, "%g", 1e+300);
- exit (strcmp (buf, "1e+300") ? 0 : 1);
-}
-
-EOF
-if { (eval echo configure:4440: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
-then
- rb_cv_missing__dtos18=yes
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -fr conftest*
- rb_cv_missing__dtos18=no
-fi
-rm -fr conftest*
-fi
-
-fi
-
-echo "$ac_t""$rb_cv_missing__dtos18" 1>&6
- if test "$rb_cv_missing__dtos18" = yes; then
- cat >> confdefs.h <<\EOF
-#define MISSING__DTOS18 1
-EOF
-
- fi
- echo $ac_n "checking whether PD libc fconvert fail to round""... $ac_c" 1>&6
-echo "configure:4462: checking whether PD libc fconvert fail to round" >&5
-if eval "test \"`echo '$''{'rb_cv_missing_fconvert'+set}'`\" = set"; then
- echo $ac_n "(cached) $ac_c" 1>&6
-else
- if test "$cross_compiling" = yes; then
- rb_cv_missing_fconvert=no
-else
- cat > conftest.$ac_ext <<EOF
-#line 4470 "configure"
-#include "confdefs.h"
-
-#include <stdio.h>
-#include <math.h>
-main ()
-{
- char buf[256];
- sprintf (buf, "%f", log(exp(1.0)));
- exit (strcmp (buf, "1.000000") ? 0 : 1);
-}
-
-EOF
-if { (eval echo configure:4483: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
-then
- rb_cv_missing_fconvert=yes
-else
- echo "configure: failed program was:" >&5
- cat conftest.$ac_ext >&5
- rm -fr conftest*
- rb_cv_missing_fconvert=no
-fi
-rm -fr conftest*
-fi
-
-fi
-
-echo "$ac_t""$rb_cv_missing_fconvert" 1>&6
- if test "$rb_cv_missing_fconvert" = yes; then
- cat >> confdefs.h <<\EOF
-#define MISSING_FCONVERT 1
-EOF
-
- fi
- LIBOBJS="$LIBOBJS x68.o"
- CFLAGS="$CFLAGS -fansi-only -cc1-stack=196608 -cpp-stack=2694144"
- EXEEXT=.x
- OBJEXT=o
- setup=Setup.x68
- ;;
- os2_emx)
- LIBOBJS="$LIBOBJS os2.o"
- setup=Setup.emx
- ;;
- cygwin*)
- setup=Setup
- ;;
- *)
- setup=Setup
- ;;
-esac
-
-
-
-if test "$prefix" = NONE; then
- prefix=$ac_default_prefix
-fi
-
-if test "$fat_binary" = yes ; then
- CFLAGS="$CFLAGS $ARCH_FLAG"
-fi
-
-LIBRUBY_A='lib$(RUBY_INSTALL_NAME).a'
-LIBRUBY='$(LIBRUBY_A)'
-LIBRUBYARG='$(LIBRUBY_A)'
-SOLIBS=
-if test "$host_os" = "beos"; then
- LIBRUBY='$(LIBRUBY_SO)'
- LIBRUBYARG='-l$(RUBY_INSTALL_NAME)'
- SOLIBS='-lnet'
- echo creating ruby.def
- case "$host_cpu" in
- powerpc*)
- cp beos/ruby.def.in ruby.exp
- CFLAGS="$CFLAGS -relax_pointers"
- ;;
- i586*)
- LDFLAGS="$LDFLAGS -L."
- ;;
- *)
- echo EXPORTS > ruby.def
- cat beos/ruby.def.in >> ruby.def
- ;;
- esac
-fi
-
-FIRSTMAKEFILE=""
-LIBRUBY_LDSHARED=$LDSHARED
-LIBRUBY_DLDFLAGS=$DLDFLAGS
-LIBRUBY_SO='lib$(RUBY_INSTALL_NAME).so.$(MAJOR).$(MINOR).$(TEENY)'
-LIBRUBY_ALIASES='lib$(RUBY_INSTALL_NAME).so'
-# Check whether --enable-enable-shared or --disable-enable-shared was given.
-if test "${enable_enable_shared+set}" = set; then
- enableval="$enable_enable_shared"
- enable_shared=$enableval
-fi
-
-if test "$enable_shared" = 'yes'; then
- LIBRUBY='$(LIBRUBY_SO)'
- LIBRUBYARG='-L. -l$(RUBY_INSTALL_NAME)'
- CFLAGS="$CFLAGS $CCDLFLAGS"
- case "$host_os" in
- sunos4*)
- LIBRUBY_ALIASES='lib$(RUBY_INSTALL_NAME).so.$(MAJOR).$(MINOR) lib$(RUBY_INSTALL_NAME).so'
- ;;
- linux*)
- XLDFLAGS='-Wl,-rpath,${prefix}/lib':/usr/lib:/lib
- LIBRUBY_ALIASES='lib$(RUBY_INSTALL_NAME).so.$(MAJOR).$(MINOR) lib$(RUBY_INSTALL_NAME).so'
- ;;
- freebsd*)
- LIBRUBY_SO='lib$(RUBY_INSTALL_NAME).so.$(MAJOR)$(MINOR)'
- if test "$rb_cv_freebsd_elf" != "yes" ; then
- LIBRUBY_SO="$LIBRUBY_SO.\$(TEENY)"
- LIBRUBY_ALIASES=''
- fi
- ;;
- netbsd*)
- LIBRUBY_SO='lib$(RUBY_INSTALL_NAME).so.$(MAJOR).$(MINOR)'
- case "$host_cpu" in
- alpha|mipsel|mipseb|powerpc|sparc64) # ELF platforms
- LIBRUBY_ALIASES='lib$(RUBY_INSTALL_NAME).so.$(MAJOR) lib$(RUBY_INSTALL_NAME).so' ;;
- *) LIBRUBY_ALIASES= ;; # a.out platforms
- esac
- ;;
- 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'
- ;;
- cygwin*)
- LIBRUBY_SO='lib$(RUBY_INSTALL_NAME).a'
- LIBRUBY_ALIASES=''
- LIBRUBY_A='lib$(RUBY_INSTALL_NAME)s.a'
- LIBRUBYARG='-L. -l$(RUBY_INSTALL_NAME)'
- FIRSTMAKEFILE=GNUmakefile:cygwin/GNUmakefile.in
- LIBOBJS="$LIBOBJS strftime.o"
- CCDLFLAGS=-DUSEIMPORTLIB
- ;;
- *)
- ;;
- esac
-fi
-
-case "$host_os" in
- nextstep*)
- CFLAGS="$CFLAGS -pipe"
- ;;
- openstep*)
- CFLAGS="$CFLAGS -pipe"
- ;;
- rhasody*)
- CFLAGS="$CFLAGS -pipe -no-precomp"
- ;;
- *)
- ;;
-esac
-
-
-
-
-
-
-
-
-
-
-
-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}"
-RUBY_LIB_PATH="${prefix}/lib/ruby/${MAJOR}.${MINOR}"
-cat >> confdefs.h <<EOF
-#define RUBY_LIB "${RUBY_LIB_PATH}"
-EOF
-
-RUBY_SITE_LIB_PATH="${RUBY_LIB_PATH}/site_ruby"
-cat >> confdefs.h <<EOF
-#define RUBY_SITE_LIB "${RUBY_SITE_LIB_PATH}"
-EOF
-
-
-configure_args=$ac_configure_args
-
-if test "$fat_binary" = yes ; then
- arch="fat-${host_os}"
-
- cat >> confdefs.h <<EOF
-#define RUBY_THIN_ARCHLIB "${RUBY_LIB_PATH}/" __ARCHITECTURE__ "-${host_os}"
-EOF
-
-
- cat >> confdefs.h <<EOF
-#define RUBY_SITE_THIN_ARCHLIB "${RUBY_SITE_LIB_PATH}/" __ARCHITECTURE__ "-${host_os}"
-EOF
-
- cat >> confdefs.h <<EOF
-#define RUBY_PLATFORM __ARCHITECTURE__ "-${host_os}"
-EOF
-
-else
- arch="${host_cpu}-${host_os}"
- cat >> confdefs.h <<EOF
-#define RUBY_PLATFORM "${arch}"
-EOF
-
-fi
-cat >> confdefs.h <<EOF
-#define RUBY_ARCHLIB "${RUBY_LIB_PATH}/${arch}"
-EOF
-
-cat >> confdefs.h <<EOF
-#define RUBY_SITE_ARCHLIB "${RUBY_SITE_LIB_PATH}/${arch}"
-EOF
-
-
-# Check whether --with-search-path or --without-search-path was given.
-if test "${with_search_path+set}" = set; then
- withval="$with_search_path"
- search_path=$withval
-fi
-
-if test "$search_path" != ""; then
- cat >> confdefs.h <<EOF
-#define RUBY_SEARCH_PATH "$search_path"
-EOF
-
-fi
-
-echo "creating config.h"
-cat confdefs.h > config.h
-
-trap '' 1 2 15
-cat > confcache <<\EOF
-# This file is a shell script that caches the results of configure
-# tests run on this system so they can be shared between configure
-# scripts and configure runs. It is not useful on other systems.
-# If it contains results you don't want to keep, you may remove or edit it.
-#
-# By default, configure uses ./config.cache as the cache file,
-# creating it if it does not exist already. You can give configure
-# the --cache-file=FILE option to use a different cache file; that is
-# what configure does when it calls configure scripts in
-# subdirectories, so they share the cache.
-# Giving --cache-file=/dev/null disables caching, for debugging configure.
-# config.status only pays attention to the cache file if you give it the
-# --recheck option to rerun configure.
-#
-EOF
-# The following way of writing the cache mishandles newlines in values,
-# but we know of no workaround that is simple, portable, and efficient.
-# So, don't put newlines in cache variables' values.
-# Ultrix sh set writes to stderr and can't be redirected directly,
-# and sets the high bit in the cache file unless we assign to the vars.
-(set) 2>&1 |
- case `(ac_space=' '; set | grep ac_space) 2>&1` in
- *ac_space=\ *)
- # `set' does not quote correctly, so add quotes (double-quote substitution
- # turns \\\\ into \\, and sed turns \\ into \).
- sed -n \
- -e "s/'/'\\\\''/g" \
- -e "s/^\\([a-zA-Z0-9_]*_cv_[a-zA-Z0-9_]*\\)=\\(.*\\)/\\1=\${\\1='\\2'}/p"
- ;;
- *)
- # `set' quotes correctly as required by POSIX, so do not add quotes.
- sed -n -e 's/^\([a-zA-Z0-9_]*_cv_[a-zA-Z0-9_]*\)=\(.*\)/\1=${\1=\2}/p'
- ;;
- esac >> confcache
-if cmp -s $cache_file confcache; then
- :
-else
- if test -w $cache_file; then
- echo "updating cache $cache_file"
- cat confcache > $cache_file
- else
- echo "not updating unwritable cache $cache_file"
- fi
-fi
-rm -f confcache
-
-trap 'rm -fr conftest* confdefs* core core.* *.core $ac_clean_files; exit 1' 1 2 15
-
-test "x$prefix" = xNONE && prefix=$ac_default_prefix
-# Let make expand exec_prefix.
-test "x$exec_prefix" = xNONE && exec_prefix='${prefix}'
-
-# Any assignment to VPATH causes Sun make to only execute
-# the first set of double-colon rules, so remove it if not needed.
-# If there is a colon in the path, we need to keep it.
-if test "x$srcdir" = x.; then
- ac_vpsub='/^[ ]*VPATH[ ]*=[^:]*$/d'
-fi
-
-trap 'rm -f $CONFIG_STATUS conftest*; exit 1' 1 2 15
-
-# Transform confdefs.h into DEFS.
-# Protect against shell expansion while executing Makefile rules.
-# Protect against Makefile macro expansion.
-cat > conftest.defs <<\EOF
-s%#define \([A-Za-z_][A-Za-z0-9_]*\) *\(.*\)%-D\1=\2%g
-s%[ `~#$^&*(){}\\|;'"<>?]%\\&%g
-s%\[%\\&%g
-s%\]%\\&%g
-s%\$%$$%g
-EOF
-DEFS=`sed -f conftest.defs confdefs.h | tr '\012' ' '`
-rm -f conftest.defs
-
-
-# Without the "./", some shells look in PATH for config.status.
-: ${CONFIG_STATUS=./config.status}
-
-echo creating $CONFIG_STATUS
-rm -f $CONFIG_STATUS
-cat > $CONFIG_STATUS <<EOF
-#! /bin/sh
-# Generated automatically by configure.
-# Run this file to recreate the current configuration.
-# This directory was configured as follows,
-# on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
-#
-# $0 $ac_configure_args
-#
-# Compiler output produced by configure, useful for debugging
-# configure, is in ./config.log if it exists.
-
-ac_cs_usage="Usage: $CONFIG_STATUS [--recheck] [--version] [--help]"
-for ac_option
-do
- case "\$ac_option" in
- -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
- echo "running \${CONFIG_SHELL-/bin/sh} $0 $ac_configure_args --no-create --no-recursion"
- exec \${CONFIG_SHELL-/bin/sh} $0 $ac_configure_args --no-create --no-recursion ;;
- -version | --version | --versio | --versi | --vers | --ver | --ve | --v)
- echo "$CONFIG_STATUS generated by autoconf version 2.13"
- exit 0 ;;
- -help | --help | --hel | --he | --h)
- echo "\$ac_cs_usage"; exit 0 ;;
- *) echo "\$ac_cs_usage"; exit 1 ;;
- esac
-done
-
-ac_given_srcdir=$srcdir
-
-trap 'rm -fr `echo "$FIRSTMAKEFILE Makefile ext/extmk.rb" | sed "s/:[^ ]*//g"` conftest*; exit 1' 1 2 15
-EOF
-cat >> $CONFIG_STATUS <<EOF
-
-# Protect against being on the right side of a sed subst in config.status.
-sed 's/%@/@@/; s/@%/@@/; s/%g\$/@g/; /@g\$/s/[\\\\&%]/\\\\&/g;
- s/@@/%@/; s/@@/@%/; s/@g\$/%g/' > conftest.subs <<\\CEOF
-$ac_vpsub
-$extrasub
-s%@SHELL@%$SHELL%g
-s%@CFLAGS@%$CFLAGS%g
-s%@CPPFLAGS@%$CPPFLAGS%g
-s%@CXXFLAGS@%$CXXFLAGS%g
-s%@FFLAGS@%$FFLAGS%g
-s%@DEFS@%$DEFS%g
-s%@LDFLAGS@%$LDFLAGS%g
-s%@LIBS@%$LIBS%g
-s%@exec_prefix@%$exec_prefix%g
-s%@prefix@%$prefix%g
-s%@program_transform_name@%$program_transform_name%g
-s%@bindir@%$bindir%g
-s%@sbindir@%$sbindir%g
-s%@libexecdir@%$libexecdir%g
-s%@datadir@%$datadir%g
-s%@sysconfdir@%$sysconfdir%g
-s%@sharedstatedir@%$sharedstatedir%g
-s%@localstatedir@%$localstatedir%g
-s%@libdir@%$libdir%g
-s%@includedir@%$includedir%g
-s%@oldincludedir@%$oldincludedir%g
-s%@infodir@%$infodir%g
-s%@mandir@%$mandir%g
-s%@MAJOR@%$MAJOR%g
-s%@MINOR@%$MINOR%g
-s%@TEENY@%$TEENY%g
-s%@host@%$host%g
-s%@host_alias@%$host_alias%g
-s%@host_cpu@%$host_cpu%g
-s%@host_vendor@%$host_vendor%g
-s%@host_os@%$host_os%g
-s%@CC@%$CC%g
-s%@CPP@%$CPP%g
-s%@YACC@%$YACC%g
-s%@RANLIB@%$RANLIB%g
-s%@AR@%$AR%g
-s%@LN_S@%$LN_S%g
-s%@SET_MAKE@%$SET_MAKE%g
-s%@EXEEXT@%$EXEEXT%g
-s%@OBJEXT@%$OBJEXT%g
-s%@LIBOBJS@%$LIBOBJS%g
-s%@ALLOCA@%$ALLOCA%g
-s%@DEFAULT_KCODE@%$DEFAULT_KCODE%g
-s%@XLDFLAGS@%$XLDFLAGS%g
-s%@DLDFLAGS@%$DLDFLAGS%g
-s%@STATIC@%$STATIC%g
-s%@CCDLFLAGS@%$CCDLFLAGS%g
-s%@LDSHARED@%$LDSHARED%g
-s%@DLEXT@%$DLEXT%g
-s%@STRIP@%$STRIP%g
-s%@EXTSTATIC@%$EXTSTATIC%g
-s%@setup@%$setup%g
-s%@LIBRUBY_LDSHARED@%$LIBRUBY_LDSHARED%g
-s%@LIBRUBY_DLDFLAGS@%$LIBRUBY_DLDFLAGS%g
-s%@RUBY_INSTALL_NAME@%$RUBY_INSTALL_NAME%g
-s%@LIBRUBY_A@%$LIBRUBY_A%g
-s%@LIBRUBY_SO@%$LIBRUBY_SO%g
-s%@LIBRUBY_ALIASES@%$LIBRUBY_ALIASES%g
-s%@LIBRUBY@%$LIBRUBY%g
-s%@LIBRUBYARG@%$LIBRUBYARG%g
-s%@SOLIBS@%$SOLIBS%g
-s%@arch@%$arch%g
-s%@configure_args@%$configure_args%g
-
-CEOF
-EOF
-
-cat >> $CONFIG_STATUS <<\EOF
-
-# Split the substitutions into bite-sized pieces for seds with
-# small command number limits, like on Digital OSF/1 and HP-UX.
-ac_max_sed_cmds=90 # Maximum number of lines to put in a sed script.
-ac_file=1 # Number of current file.
-ac_beg=1 # First line for current file.
-ac_end=$ac_max_sed_cmds # Line after last line for current file.
-ac_more_lines=:
-ac_sed_cmds=""
-while $ac_more_lines; do
- if test $ac_beg -gt 1; then
- sed "1,${ac_beg}d; ${ac_end}q" conftest.subs > conftest.s$ac_file
- else
- sed "${ac_end}q" conftest.subs > conftest.s$ac_file
- fi
- if test ! -s conftest.s$ac_file; then
- ac_more_lines=false
- rm -f conftest.s$ac_file
- else
- if test -z "$ac_sed_cmds"; then
- ac_sed_cmds="sed -f conftest.s$ac_file"
- else
- ac_sed_cmds="$ac_sed_cmds | sed -f conftest.s$ac_file"
- fi
- ac_file=`expr $ac_file + 1`
- ac_beg=$ac_end
- ac_end=`expr $ac_end + $ac_max_sed_cmds`
- fi
-done
-if test -z "$ac_sed_cmds"; then
- ac_sed_cmds=cat
-fi
-EOF
-
-cat >> $CONFIG_STATUS <<EOF
-
-CONFIG_FILES=\${CONFIG_FILES-"$FIRSTMAKEFILE Makefile ext/extmk.rb"}
-EOF
-cat >> $CONFIG_STATUS <<\EOF
-for ac_file in .. $CONFIG_FILES; do if test "x$ac_file" != x..; then
- # Support "outfile[:infile[:infile...]]", defaulting infile="outfile.in".
- case "$ac_file" in
- *:*) ac_file_in=`echo "$ac_file"|sed 's%[^:]*:%%'`
- ac_file=`echo "$ac_file"|sed 's%:.*%%'` ;;
- *) ac_file_in="${ac_file}.in" ;;
- esac
-
- # Adjust a relative srcdir, top_srcdir, and INSTALL for subdirectories.
-
- # Remove last slash and all that follows it. Not all systems have dirname.
- ac_dir=`echo $ac_file|sed 's%/[^/][^/]*$%%'`
- if test "$ac_dir" != "$ac_file" && test "$ac_dir" != .; then
- # The file is in a subdirectory.
- test ! -d "$ac_dir" && mkdir "$ac_dir"
- ac_dir_suffix="/`echo $ac_dir|sed 's%^\./%%'`"
- # A "../" for each directory in $ac_dir_suffix.
- ac_dots=`echo $ac_dir_suffix|sed 's%/[^/]*%../%g'`
- else
- ac_dir_suffix= ac_dots=
- fi
-
- case "$ac_given_srcdir" in
- .) srcdir=.
- if test -z "$ac_dots"; then top_srcdir=.
- else top_srcdir=`echo $ac_dots|sed 's%/$%%'`; fi ;;
- /*) srcdir="$ac_given_srcdir$ac_dir_suffix"; top_srcdir="$ac_given_srcdir" ;;
- *) # Relative path.
- srcdir="$ac_dots$ac_given_srcdir$ac_dir_suffix"
- top_srcdir="$ac_dots$ac_given_srcdir" ;;
- esac
-
-
- echo creating "$ac_file"
- rm -f "$ac_file"
- configure_input="Generated automatically from `echo $ac_file_in|sed 's%.*/%%'` by configure."
- case "$ac_file" in
- *Makefile*) ac_comsub="1i\\
-# $configure_input" ;;
- *) ac_comsub= ;;
- esac
-
- ac_file_inputs=`echo $ac_file_in|sed -e "s%^%$ac_given_srcdir/%" -e "s%:% $ac_given_srcdir/%g"`
- sed -e "$ac_comsub
-s%@configure_input@%$configure_input%g
-s%@srcdir@%$srcdir%g
-s%@top_srcdir@%$top_srcdir%g
-" $ac_file_inputs | (eval "$ac_sed_cmds") > $ac_file
-fi; done
-rm -f conftest.s*
-
-EOF
-cat >> $CONFIG_STATUS <<EOF
-
-EOF
-cat >> $CONFIG_STATUS <<\EOF
-
-exit 0
-EOF
-chmod +x $CONFIG_STATUS
-rm -fr confdefs* $ac_clean_files
-test "$no_create" = yes || ${CONFIG_SHELL-/bin/sh} $CONFIG_STATUS || exit 1
-
diff --git a/configure.bat b/configure.bat
deleted file mode 100644
index ce0aa8bd9f..0000000000
--- a/configure.bat
+++ /dev/null
@@ -1,24 +0,0 @@
-@echo off
-grep -qs MAJOR top.sed
-if errorlevel 1 goto seen
-if errorlevel 0 goto not_seen
-:seen
- sed -n "/VERSION /s/[^0-9.]//gp" < version.h > version.out
- cut -d. -f1 version.out > major.out
- cut -d. -f2 version.out > minor.out
- cut -d. -f3 version.out > teeny.out
- sed "s/^/s,@MAJOR@,/;s/$/,/g" major.out >> top.sed
- sed "s/^/s,@MINOR@,/;s/$/,/g" minor.out >> top.sed
- sed "s/^/s,@TEENY@,/;s/$/,/g" teeny.out >> top.sed
- rm version.out major.out minor.out teeny.out
-:not_seen
-sed -f top.sed < Makefile.in > Makefile
-sed -f top.sed < ext\extmk.rb.in > ext\extmk.rb
-copy config_h.dj config.h
-if not (%OS%) == (Windows_NT) goto LFN
- copy missing\vsnprintf.c missing\vsnprint.c
- copy config_s.dj config.sta
-goto end
-:LFN
- copy config_s.dj config.status
-:end
diff --git a/configure.in b/configure.in
deleted file mode 100644
index e4ac66aeec..0000000000
--- a/configure.in
+++ /dev/null
@@ -1,793 +0,0 @@
-dnl Process this file with autoconf to produce a configure script.
-AC_INIT(ruby.h)
-
-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
- without_gcc=yes;;
- yes) CC=gcc
- without_gcc=no;;
- *) CC=$withval
- without_gcc=$withval;;
- esac], [without_gcc=no])
-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_CANONICAL_HOST
-
-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 "$host_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
- ;;
- 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
-
-AC_ARG_PROGRAM
-
-dnl Checks for programs.
-AC_PROG_CC
-AC_PROG_GCC_TRADITIONAL
-AC_PROG_YACC
-AC_PROG_RANLIB
-AC_SUBST(AR)
-AC_CHECK_PROGS(AR, ar aal, ar)
-
-AC_PROG_LN_S
-AC_PROG_MAKE_SET
-
-# checks for UNIX variants that set C preprocessor variables
-AC_MINIX
-
-AC_EXEEXT
-AC_OBJEXT
-
-AC_CHECK_SIZEOF(int, 4)
-AC_CHECK_SIZEOF(short, 2)
-AC_CHECK_SIZEOF(long, 4)
-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 gcc attribute noreturn, rb_cv_have_attr_noreturn,
- [AC_TRY_COMPILE([void exit(int x) __attribute__ ((noreturn));], [],
- rb_cv_have_attr_noreturn=yes,
- rb_cv_have_attr_noreturn=no)])
-if test "$rb_cv_have_attr_noreturn" = yes; then
- AC_DEFINE(HAVE_ATTR_NORETURN)
-fi
-
-dnl Checks for libraries.
-case "$host_os" in
-nextstep*) ;;
-openstep*) ;;
-rhapsody*) ;;
-human*) ;;
-beos*) ;;
-cygwin*) ;;
-*) 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
-AC_CHECK_LIB(xpg4, setlocale) # FreeBSD needs this
-
-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)
-
-dnl Checks for typedefs, structures, and compiler characteristics.
-AC_TYPE_UID_T
-AC_TYPE_SIZE_T
-AC_STRUCT_ST_BLKSIZE
-save_LIBOJBS="$LIBOBJS"
-AC_STRUCT_ST_BLOCKS
-LIBOBJS="$save_LIBOBJS"
-AC_STRUCT_ST_RDEV
-
-dnl Checks for library functions.
-AC_TYPE_GETGROUPS
-AC_TYPE_SIGNAL
-AC_FUNC_ALLOCA
-AC_FUNC_VFORK
-AC_FUNC_MEMCMP
-AC_REPLACE_FUNCS(dup2 memmove mkdir strcasecmp strncasecmp strerror strftime\
- strchr strstr strtoul strdup crypt flock vsnprintf\
- isinf isnan finite)
-AC_CHECK_FUNCS(fmod killpg drand48 random wait4 waitpid syscall getcwd\
- truncate chsize times utimes fcntl lockf setitimer\
- setruid seteuid setreuid setrgid setegid setregid\
- getpgrp setpgrp getpgid setpgid getgroups getpriority\
- dlopen sigprocmask sigaction _setjmp setsid getrlimit)
-AC_STRUCT_TIMEZONE
-if test "$ac_cv_func_strftime" = no; then
- AC_TRY_LINK([],
- [extern int daylight; int i = daylight;], AC_DEFINE(HAVE_DAYLIGHT))
-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 && LIBOBJS="$LIBOBJS strtod.o"
-
-AC_C_BIGENDIAN
-AC_C_CONST
-AC_C_CHAR_UNSIGNED
-
-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
-AC_SUBST(DEFAULT_KCODE)
-AC_ARG_WITH(default-kcode,
- [--with-default-kcode=CODE specify default value for \$KCODE (utf8|euc|sjis|none)],
- [case $withval in
- utf8) AC_DEFINE(DEFAULT_KCODE, KCODE_UTF8);;
- euc) AC_DEFINE(DEFAULT_KCODE, KCODE_EUC);;
- sjis) AC_DEFINE(DEFAULT_KCODE, KCODE_SJIS);;
- none) AC_DEFINE(DEFAULT_KCODE, KCODE_NONE);;
- *) AC_MSG_WARN($withval is not valid kcode; ignored);;
- esac])
-
-dnl wheather use dln_a_out ot 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
-
-case "$host_os" in
- linux*)
- 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" = no; then
- with_dln_a_out=yes
- host_os=${host_os}-a_out
- else
- LDFLAGS="-rdynamic"
- fi;;
-esac
-
-AC_SUBST(DLDFLAGS)dnl
-
-AC_SUBST(STATIC)dnl
-AC_SUBST(CCDLFLAGS)dnl
-AC_SUBST(LDSHARED)dnl
-AC_SUBST(DLEXT)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 "$host_os" in
- nextstep*) ;;
- openstep*) ;;
- rhapsody*) ;;
- human*) ;;
- bsdi*) ;;
- cygwin*) ;;
- netbsd*) CCDLFLAGS=-fpic
- case "$host_cpu" in
- mips*) CCDLFLAGS=-fPIC ;;
- *) ;;
- esac ;;
- *) CCDLFLAGS=-fPIC;;
- esac
- else
- case "$host_os" in
- hpux*) CCDLFLAGS='+z';;
- solaris*|irix*) CCDLFLAGS='-K PIC' ;;
- sunos*) CCDLFLAGS='-PIC' ;;
- esix*|uxpds*) CCDLFLAGS='-KPIC' ;;
- *) CCDLFLAGS='' ;;
- esac
- fi
-
- case "$host_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'
- `$CC --print-prog-name=ld` -v 2>&1 | grep "GNU ld" > /dev/null && LDFLAGS="-Wl,-E"
- else
- LDSHARED='ld -G'
- fi
- rb_cv_dlopen=yes;;
- sunos*) LDSHARED='ld -assert nodefinitions'
- rb_cv_dlopen=yes;;
- irix*) LDSHARED='ld -ignore_unresolved'
- rb_cv_dlopen=yes;;
- sysv4*) LDSHARED='ld -G'
- 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 ;;
- freebsd*) LDSHARED="$CC -shared"
- if test -x /usr/bin/objformat && \
- test `/usr/bin/objformat` = "elf" ; then
- LDFLAGS="-rdynamic"
- DLDFLAGS='-Wl,-soname,$(.TARGET)'
- rb_cv_freebsd_elf=yes
- 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="ld -shared"
- case "$host_cpu" in
- alpha)
- LDFLAGS="-export-dynamic" ;;
- esac
- 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 ;;
- aix*) LDSHARED='/usr/ccs/bin/ld'
- XLDFLAGS='-Wl,-bE:ruby.imp'
- DLDFLAGS='-eInit_$(TARGET) -bI:$(topdir)/ruby.imp -bM:SRE -T512 -H512 -lc'
- rb_cv_dlopen=yes ;;
-
- human*) DLDFLAGS=''
- LDSHARED=''
- LDFLAGS=''
- rb_cv_dlopen=yes ;;
- beos*) case "$host_cpu" in
- powerpc*)
- LDSHARED="ld -xms"
- DLDFLAGS="-f ruby.exp -lbe -lroot glue-noinit.a init_term_dyn.o start_dyn.o"
- ;;
- i586*)
- LDSHARED="ld -shared"
- DLDFLAGS="-L/boot/develop/lib/x86 -lbe -lroot"
- ;;
- *)
- DLDFLAGS="ruby.def -lbe -lroot glue-noinit.a init_term_dyn.o start_dyn.o"
- esac
- rb_cv_dlopen=yes ;;
- cygwin*) LDSHARED='dllwrap --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 "$host_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");;
- cygwin*) DLEXT=dll
- AC_DEFINE(DLEXT, ".dll");;
- os2_emx) DLEXT=o
- AC_DEFINE(DLEXT, ".so");;
- *) 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 "$host_os" in
- linux*)
- STRIP='strip -S -x';;
- nextstep*)
- STRIP='strip -A -n';;
- openstep*)
- STRIP='strip -A -n';;
- rhapsody*)
- 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 "$host_os" in
- human*)
- AC_CHECK_LIB(signal, _harderr)
- AC_CHECK_LIB(hmem, hmemset)
- AC_CHECK_FUNCS(select)
- 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
- LIBOBJS="$LIBOBJS x68.o"
- CFLAGS="$CFLAGS -fansi-only -cc1-stack=196608 -cpp-stack=2694144"
- EXEEXT=.x
- OBJEXT=o
- setup=Setup.x68
- ;;
- dnl OS/2 environment w/ Autoconf 2.1x for EMX
- os2_emx)
- LIBOBJS="$LIBOBJS os2.o"
- setup=Setup.emx
- ;;
- cygwin*)
- setup=Setup
- ;;
- *)
- 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
-
-LIBRUBY_A='lib$(RUBY_INSTALL_NAME).a'
-LIBRUBY='$(LIBRUBY_A)'
-LIBRUBYARG='$(LIBRUBY_A)'
-SOLIBS=
-if test "$host_os" = "beos"; then
- LIBRUBY='$(LIBRUBY_SO)'
- LIBRUBYARG='-l$(RUBY_INSTALL_NAME)'
- SOLIBS='-lnet'
- echo creating ruby.def
- case "$host_cpu" in
- powerpc*)
- cp beos/ruby.def.in ruby.exp
- CFLAGS="$CFLAGS -relax_pointers"
- ;;
- i586*)
- LDFLAGS="$LDFLAGS -L."
- ;;
- *)
- echo EXPORTS > ruby.def
- cat beos/ruby.def.in >> ruby.def
- ;;
- esac
-fi
-
-FIRSTMAKEFILE=""
-LIBRUBY_LDSHARED=$LDSHARED
-LIBRUBY_DLDFLAGS=$DLDFLAGS
-LIBRUBY_SO='lib$(RUBY_INSTALL_NAME).so.$(MAJOR).$(MINOR).$(TEENY)'
-LIBRUBY_ALIASES='lib$(RUBY_INSTALL_NAME).so'
-AC_ARG_ENABLE(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"
- case "$host_os" in
- sunos4*)
- LIBRUBY_ALIASES='lib$(RUBY_INSTALL_NAME).so.$(MAJOR).$(MINOR) lib$(RUBY_INSTALL_NAME).so'
- ;;
- linux*)
- XLDFLAGS='-Wl,-rpath,${prefix}/lib':/usr/lib:/lib
- LIBRUBY_ALIASES='lib$(RUBY_INSTALL_NAME).so.$(MAJOR).$(MINOR) lib$(RUBY_INSTALL_NAME).so'
- ;;
- freebsd*)
- LIBRUBY_SO='lib$(RUBY_INSTALL_NAME).so.$(MAJOR)$(MINOR)'
- if test "$rb_cv_freebsd_elf" != "yes" ; then
- LIBRUBY_SO="$LIBRUBY_SO.\$(TEENY)"
- LIBRUBY_ALIASES=''
- fi
- ;;
- netbsd*)
- LIBRUBY_SO='lib$(RUBY_INSTALL_NAME).so.$(MAJOR).$(MINOR)'
- case "$host_cpu" in
- alpha|mipsel|mipseb|powerpc|sparc64) # ELF platforms
- LIBRUBY_ALIASES='lib$(RUBY_INSTALL_NAME).so.$(MAJOR) lib$(RUBY_INSTALL_NAME).so' ;;
- *) LIBRUBY_ALIASES= ;; # a.out platforms
- esac
- ;;
- 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'
- ;;
- cygwin*)
- LIBRUBY_SO='lib$(RUBY_INSTALL_NAME).a'
- LIBRUBY_ALIASES=''
- LIBRUBY_A='lib$(RUBY_INSTALL_NAME)s.a'
- LIBRUBYARG='-L. -l$(RUBY_INSTALL_NAME)'
- FIRSTMAKEFILE=GNUmakefile:cygwin/GNUmakefile.in
- LIBOBJS="$LIBOBJS strftime.o"
- CCDLFLAGS=-DUSEIMPORTLIB
- ;;
- *)
- ;;
- esac
-fi
-
-case "$host_os" in
- nextstep*)
- CFLAGS="$CFLAGS -pipe"
- ;;
- openstep*)
- CFLAGS="$CFLAGS -pipe"
- ;;
- rhasody*)
- CFLAGS="$CFLAGS -pipe -no-precomp"
- ;;
- *)
- ;;
-esac
-
-AC_SUBST(LIBRUBY_LDSHARED)
-AC_SUBST(LIBRUBY_DLDFLAGS)
-AC_SUBST(RUBY_INSTALL_NAME)
-AC_SUBST(LIBRUBY_A)
-AC_SUBST(LIBRUBY_SO)
-AC_SUBST(LIBRUBY_ALIASES)
-AC_SUBST(LIBRUBY)
-AC_SUBST(LIBRUBYARG)
-AC_SUBST(SOLIBS)
-
-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}"
-RUBY_LIB_PATH="${prefix}/lib/ruby/${MAJOR}.${MINOR}"
-AC_DEFINE_UNQUOTED(RUBY_LIB, "${RUBY_LIB_PATH}")
-RUBY_SITE_LIB_PATH="${RUBY_LIB_PATH}/site_ruby"
-AC_DEFINE_UNQUOTED(RUBY_SITE_LIB, "${RUBY_SITE_LIB_PATH}")
-AC_SUBST(arch)dnl
-
-configure_args=$ac_configure_args
-AC_SUBST(configure_args)dnl
-
-if test "$fat_binary" = yes ; then
- arch="fat-${host_os}"
-
- AC_DEFINE_UNQUOTED(RUBY_THIN_ARCHLIB,
- "${RUBY_LIB_PATH}/" __ARCHITECTURE__ "-${host_os}")
-
- AC_DEFINE_UNQUOTED(RUBY_SITE_THIN_ARCHLIB,
- "${RUBY_SITE_LIB_PATH}/" __ARCHITECTURE__ "-${host_os}")
- AC_DEFINE_UNQUOTED(RUBY_PLATFORM, __ARCHITECTURE__ "-${host_os}")
-else
- arch="${host_cpu}-${host_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_PATH}/${arch}")
-
-AC_ARG_WITH(search-path,
- [--with-search-path specify the additional search path],
- [search_path=$withval])
-if test "$search_path" != ""; then
- AC_DEFINE_UNQUOTED(RUBY_SEARCH_PATH,"$search_path")
-fi
-
-echo "creating config.h"
-cat confdefs.h > config.h
-
-AC_OUTPUT($FIRSTMAKEFILE Makefile ext/extmk.rb)
diff --git a/cygwin/GNUmakefile.in b/cygwin/GNUmakefile.in
deleted file mode 100644
index 970e90e24a..0000000000
--- a/cygwin/GNUmakefile.in
+++ /dev/null
@@ -1,9 +0,0 @@
-include Makefile
-
-RUBYCWDLL=rubycw.dll
-
-miniruby$(EXEEXT): $(RUBYCWDLL)
-
-$(RUBYCWDLL): $(OBJS) dmyext.o
- dllwrap -o $(RUBYCWDLL) --export-all --output-lib=$(LIBRUBY_SO) --dllname=$(RUBYCWDLL) -Wl,-e,__cygwin_noncygwin_dll_entry@12 --add-stdcall-alias -s $(OBJS) dmyext.o
- nm --extern-only $(OBJS) dmyext.o | sed -n '/^........ [CD] _\(.*\)$$/s//#define \1 (*__imp_\1)/p' >import.h
diff --git a/defines.h b/defines.h
deleted file mode 100644
index 6485fd7a59..0000000000
--- a/defines.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/************************************************
-
- defines.h -
-
- $Author$
- $Date$
- created at: Wed May 18 00:21:44 JST 1994
-
-************************************************/
-#ifndef DEFINES_H
-#define DEFINES_H
-
-#define RUBY
-
-/* define RUBY_USE_EUC/SJIS for default kanji-code */
-#ifndef DEFAULT_KCODE
-#if defined(MSDOS) || defined(__CYGWIN32__) || 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 */
-#endif /* NeXT */
-
-#ifdef NT
-#include "win32/win32.h"
-#endif
-
-#ifndef EXTERN
-#define EXTERN extern
-#endif
-
-#ifdef sparc
-#define FLUSH_REGISTER_WINDOWS asm("ta 3")
-#else
-#define FLUSH_REGISTER_WINDOWS /* empty */
-#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 ";"
-#else
-#define PATH_SEP ":"
-#endif
-#define PATH_SEP_CHAR PATH_SEP[0]
-
-#if defined(__human68k__) || defined(__CYGWIN32__)
-#undef HAVE_RANDOM
-#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 3c0581c777..0000000000
--- a/dir.c
+++ /dev/null
@@ -1,805 +0,0 @@
-/************************************************
-
- dir.c -
-
- $Author$
- $Date$
- created at: Wed Jan 5 09:51:01 JST 1994
-
- Copyright (C) 1993-1999 Yukihiro Matsumoto
-
-************************************************/
-
-#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 HAVE_DIRENT_H
-# include <dirent.h>
-# define NAMLEN(dirent) strlen((dirent)->d_name)
-#elif HAVE_DIRECT_H
-# 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) && defined(_MSC_VER)
-# include "missing/dir.h"
-# endif
-#endif
-
-#include <errno.h>
-#ifdef USE_CWGUSI
-# include <sys/errno.h>
-#endif
-
-#ifndef HAVE_STDLIB_H
-char *getenv();
-#endif
-
-#ifndef HAVE_STRING_H
-char *strchr _((char*,char));
-#endif
-
-#include <ctype.h>
-
-#define FNM_NOESCAPE 0x01
-#define FNM_PATHNAME 0x02
-#define FNM_PERIOD 0x04
-#define FNM_NOCASE 0x08
-
-#define FNM_NOMATCH 1
-#define FNM_ERROR 2
-
-#define downcase(c) (nocase && isupper(c) ? tolower(c) : (c))
-
-#if defined DOSISH
-#define isdirsep(c) ((c) == '/' || (c) == '\\')
-static char *
-find_dirsep(s)
- char *s;
-{
- while (*s) {
- if (isdirsep(*s))
- return s;
- 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_NOCASE;
- 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 PERIOD(s) (period && *(s) == '.' && \
- ((s) == string || pathname && isdirsep(*(s))))
-static int
-fnmatch(pat, string, flags)
- char *pat;
- char *string;
- int flags;
-{
- int c;
- int test;
- char *s = string;
- int escape = !(flags & FNM_NOESCAPE);
- int pathname = flags & FNM_PATHNAME;
- int period = flags & FNM_PERIOD;
- int nocase = flags & FNM_NOCASE;
-
- while (c = *pat++) {
- switch (c) {
- case '?':
- if (!*s || pathname && 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 (pathname && 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_PERIOD))
- return 0;
- else if (pathname && isdirsep(*s))
- break;
- s++;
- }
- return FNM_NOMATCH;
-
- case '[':
- if (!*s || pathname && 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 (pathname && isdirsep(c) && isdirsep(*s))
- ;
- else
-#endif
- if(downcase(c) != downcase(*s))
- return FNM_NOMATCH;
- s++;
- break;
- }
- }
- return !*s ? 0 : FNM_NOMATCH;
-}
-
-VALUE rb_cDir;
-
-static void
-free_dir(dir)
- DIR *dir;
-{
- if (dir) closedir(dir);
-}
-
-static VALUE dir_close _((VALUE));
-
-static VALUE
-dir_s_open(dir_class, dirname)
- VALUE dir_class, dirname;
-{
- VALUE obj;
- DIR *dirp;
-
- Check_SafeStr(dirname);
-
- dirp = opendir(RSTRING(dirname)->ptr);
- if (dirp == NULL) {
- if (errno == EMFILE || errno == ENFILE) {
- rb_gc();
- dirp = opendir(RSTRING(dirname)->ptr);
- }
- if (dirp == NULL) {
- rb_sys_fail(RSTRING(dirname)->ptr);
- }
- }
-
- obj = Data_Wrap_Struct(dir_class, 0, free_dir, dirp);
-
- if (rb_iterator_p()) {
- return rb_ensure(rb_yield, obj, dir_close, obj);
- }
-
- return obj;
-}
-
-static void
-dir_closed()
-{
- rb_raise(rb_eIOError, "closed directory");
-}
-
-#define GetDIR(obj, dirp) {\
- Data_Get_Struct(obj, DIR, dirp);\
- if (dirp == NULL) dir_closed();\
-}
-
-static VALUE
-dir_read(dir)
- VALUE dir;
-{
- DIR *dirp;
- struct dirent *dp;
-
- GetDIR(dir, dirp);
- errno = 0;
- dp = readdir(dirp);
- 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;
-{
- DIR *dirp;
- struct dirent *dp;
- VALUE file;
-
- GetDIR(dir, dirp);
- for (dp = readdir(dirp); dp != NULL; dp = readdir(dirp)) {
- file = rb_tainted_str_new(dp->d_name, NAMLEN(dp));
- rb_yield(file);
- }
- return dir;
-}
-
-static VALUE
-dir_tell(dir)
- VALUE dir;
-{
-#if !defined(__CYGWIN32__) && !defined(__BEOS__)
- DIR *dirp;
- long pos;
-
- GetDIR(dir, dirp);
- pos = telldir(dirp);
- return rb_int2inum(pos);
-#else
- rb_notimplement();
-#endif
-}
-
-static VALUE
-dir_seek(dir, pos)
- VALUE dir, pos;
-{
- DIR *dirp;
-
-#if !defined(__CYGWIN32__) && !defined(__BEOS__)
- GetDIR(dir, dirp);
- seekdir(dirp, NUM2INT(pos));
- return dir;
-#else
- rb_notimplement();
-#endif
-}
-
-static VALUE
-dir_rewind(dir)
- VALUE dir;
-{
- DIR *dirp;
-
- GetDIR(dir, dirp);
- rewinddir(dirp);
- return dir;
-}
-
-static VALUE
-dir_close(dir)
- VALUE dir;
-{
- DIR *dirp;
-
- Data_Get_Struct(dir, DIR, dirp);
- if (dirp == NULL) dir_closed();
- closedir(dirp);
- DATA_PTR(dir) = NULL;
-
- return Qnil;
-}
-
-static VALUE
-dir_s_chdir(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- VALUE path;
- char *dist = "";
-
- rb_secure(2);
- if (rb_scan_args(argc, argv, "01", &path) == 1) {
- Check_SafeStr(path);
- dist = RSTRING(path)->ptr;
- }
- else {
- dist = getenv("HOME");
- if (!dist) {
- dist = getenv("LOGDIR");
- }
- }
-
- if (chdir(dist) < 0)
- rb_sys_fail(dist);
-
- return INT2FIX(0);
-}
-
-static VALUE
-dir_s_getwd(dir)
- VALUE dir;
-{
- char path[MAXPATHLEN];
-
-#ifdef HAVE_GETCWD
- if (getcwd(path, sizeof(path)) == 0) rb_sys_fail(path);
-#else
- extern char *getwd();
- if (getwd(path) == 0) rb_sys_fail(path);
-#endif
-
- return rb_tainted_str_new2(path);
-}
-
-static VALUE
-dir_s_chroot(dir, path)
- VALUE dir, path;
-{
-#if !defined(DJGPP) && !defined(NT) && !defined(__human68k__) && !defined(USE_CWGUSI) && !defined(__BEOS__) && !defined(__EMX__)
- rb_secure(2);
- Check_SafeStr(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;
- }
-
- Check_SafeStr(path);
- rb_secure(2);
-#if !defined(NT) && !defined(USE_CWGUSI)
- 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;
-{
- Check_SafeStr(dir);
- rb_secure(2);
- if (rmdir(RSTRING(dir)->ptr) < 0)
- rb_sys_fail(RSTRING(dir)->ptr);
-
- return Qtrue;
-}
-
-/* Return nonzero if S has any special globbing chars in it. */
-static int
-has_magic(s, send)
- char *s, *send;
-{
- register char *p = s;
- register char c;
- int open = 0;
-
- 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 (*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 > 0 && pend[-1] == '/') {
- 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);
-}
-
-#ifndef S_ISDIR
-# define S_ISDIR(m) ((m & S_IFMT) == S_IFDIR)
-#endif
-
-static void
-glob(path, func, arg)
- char *path;
- void (*func)();
- VALUE arg;
-{
- struct stat st;
- char *p, *m;
-
- if (!has_magic(path, 0)) {
- if (stat(path, &st) == 0) {
- (*func)(path, arg);
- }
- return;
- }
-
- p = path;
- while (p) {
- if (*p == '/') p++;
- m = strchr(p, '/');
- if (has_magic(p, m)) {
- 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 (strcmp(magic, "**") == 0) {
- recursive = 1;
- buf = ALLOC_N(char, strlen(base)+strlen(m)+3);
- sprintf(buf, "%s%s%s", base, (*base)?"":".", m);
- glob(buf, func, arg);
- free(buf);
- }
- dirp = opendir(dir);
- if (dirp == NULL) {
- free(base);
- break;
- }
- 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/**%s", base, (*base)?"/":"", dp->d_name, m);
- glob(buf, func, arg);
- free(buf);
- continue;
- }
- if (fnmatch(magic, dp->d_name, FNM_PERIOD|FNM_PATHNAME) == 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);
- while (link) {
- stat(link->path, &st); /* should success */
- 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(t, func, arg);
- free(t);
- }
- tmp = link;
- link = link->next;
- free(tmp->path);
- free(tmp);
- }
- }
- p = m;
- }
-}
-
-static void
-push_pattern(path, ary)
- char *path;
- VALUE ary;
-{
- rb_ary_push(ary, rb_tainted_str_new2(path));
-}
-
-static void
-push_globs(ary, s)
- VALUE ary;
- char *s;
-{
- glob(s, push_pattern, ary);
-}
-
-static void
-push_braces(ary, s)
- VALUE ary;
- char *s;
-{
- char buffer[MAXPATHLEN], *buf = buffer;
- 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);
- if (len >= MAXPATHLEN)
- 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);
- }
- if (buf != buffer)
- free(buf);
- }
- else {
- push_globs(ary, s);
- }
-}
-
-#define isdelim(c) ((c)==' '||(c)=='\t'||(c)=='\n'||(c)=='\0')
-
-static VALUE
-dir_s_glob(dir, str)
- VALUE dir, str;
-{
- char *p, *pend;
- char buffer[MAXPATHLEN], *buf = buffer;
- char *t;
- int nest;
- VALUE ary;
-
- Check_SafeStr(str);
- ary = rb_ary_new();
- if (RSTRING(str)->len >= MAXPATHLEN)
- 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+=2;
- if (*p == '}') nest+=3;
- *t++ = *p++;
- }
- *t = '\0';
- if (nest == 0) {
- push_globs(ary, buf);
- }
- else if (nest % 5 == 0) {
- push_braces(ary, buf);
- }
- /* else unmatched braces */
- }
- if (buf != buffer)
- free(buf);
- if (rb_iterator_p()) {
- long len = RARRAY(ary)->len;
- VALUE *ptr = RARRAY(ary)->ptr;
-
- while (len--) {
- rb_yield(*ptr++);
- }
- }
- return ary;
-}
-
-static VALUE
-dir_foreach(io, dirname)
- VALUE io, dirname;
-{
- VALUE dir;
-
- dir = rb_funcall(rb_cDir, rb_intern("open"), 1, dirname);
- return rb_ensure(dir_each, dir, dir_close, dir);
-}
-
-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);
-}
-
-void
-Init_Dir()
-{
- rb_cDir = rb_define_class("Dir", rb_cObject);
-
- rb_include_module(rb_cDir, rb_mEnumerable);
-
- rb_define_singleton_method(rb_cDir, "new", dir_s_open, 1);
- 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,"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,"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_glob, 1);
-}
diff --git a/dln.c b/dln.c
deleted file mode 100644
index 02ef484b36..0000000000
--- a/dln.c
+++ /dev/null
@@ -1,1724 +0,0 @@
-/************************************************
-
- dln.c -
-
- $Author$
- $Date$
- created at: Tue Jan 18 17:05:06 JST 1994
-
- Copyright (C) 1993-1999 Yukihiro Matsumoto
-
-************************************************/
-
-#include "config.h"
-#include "defines.h"
-#include "dln.h"
-
-char *dln_argv0;
-
-#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>
-#ifndef NT
-# ifndef USE_CWGUSI
-# include <sys/file.h>
-# endif
-#else
-#include "missing/file.h"
-#endif
-#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
-
-#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(__CYGWIN32__) && !defined(_AIX)
-/* dynamic load with dlopen() */
-# define USE_DLN_DLOPEN
-#endif
-
-#ifndef FUNCNAME_PATTERN
-# if defined(__hp9000s300) || (defined(__NetBSD__) && (!defined(__alpha__) && !defined(__mips__))) || defined(__BORLANDC__) || (defined(__FreeBSD__) && __FreeBSD__ < 3) || defined(__OpenBSD__) || defined(NeXT) || defined(__WATCOMC__) || defined(__APPLE__)
-# define FUNCNAME_PATTERN "_Init_%.200s"
-# else
-# define FUNCNAME_PATTERN "Init_%.200s"
-# 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
-
- sprintf(buf, FUNCNAME_PATTERN, slash + 1);
- 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 201 /* Symbol name conflict */
-#define DLN_ENOINIT 202 /* No inititalizer given */
-#define DLN_EUNDEF 203 /* Undefine symbol remains */
-#define DLN_ENOTLIB 204 /* Not a library file */
-#define DLN_EBADLIB 205 /* Malformed library file */
-#define DLN_EINIT 206 /* Not initialized */
-
-static int dln_init_p = 0;
-
-#include "st.h"
-#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)
-
-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++;
- }
- *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;
- char buf[256];
-
- 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;
-
- 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)();
- }
- }
- }
- 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;
-{
- int 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
-
-
-#ifdef _WIN32
-#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
-
-#ifdef _WIN32
- static char message[1024];
- int error = GetLastError();
- char *p = message;
- p += sprintf(message, "%d: ", error);
- FormatMessage(
- FORMAT_MESSAGE_FROM_SYSTEM,
- 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)
-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)
-
- sprintf(errbuf, "load failed - %.200s ", 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;
-{
-#ifdef _WIN32
- HINSTANCE handle;
- char winfile[255];
- void (*init_fct)();
- char buf[MAXPATHLEN];
-
- /* Load the file as an object one */
- init_funcname(buf, file);
-
-#ifdef __CYGWIN32__
- cygwin32_conv_to_win32_path(file, winfile);
-#else
- strcpy(winfile, file);
-#endif
-
- /* Load file */
- if ((handle =
- LoadLibraryExA(winfile, NULL, LOAD_WITH_ALTERED_SEARCH_PATH)) == NULL) {
- printf("LoadLibraryExA: %s\n", winfile);
- goto failed;
- }
-
-#ifdef __CYGWIN32__
- init_fct = (void(*)())GetProcAddress(handle, "impure_setup");
-
- if (init_fct)
- init_fct(_impure_ptr);
-#endif
-
- if ((init_fct = (void(*)())GetProcAddress(handle, buf)) == NULL) {
- printf("GetProcAddress %s\n", buf);
- goto failed;
- }
- /* Call the init code */
- (*init_fct)();
- return;
-#else
-#ifdef USE_DLN_A_OUT
- if (load(file) == -1) {
- goto failed;
- }
- return;
-#else
-
- char buf[MAXPATHLEN];
- /* 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;
- }
-
- if ((init_fct = (void(*)())dlsym(handle, buf)) == NULL) {
- goto failed;
- }
- /* Call the init code */
- (*init_fct)();
- return;
- }
-#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);
- 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;
- }
-#endif /* hpux */
-
-#if defined(_AIX)
-#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;
- }
-#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);
- }
-
- /* Cannot call *init_address directory, so copy this value to
- funtion pointer */
-
- init_fct = (void(*)())init_address;
- (*init_fct)();
- return;
- }
-#else/* OPENSTEP dyld functions */
- {
- int dyld_result;
- NSObjectFileImage obj_file; /* handle, but not use it */
- /* "file" is module file name .
- "buf" is 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, TRUE);
-
- /* 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));
- (*init_fct)();
-
- return;
- }
-#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[1024];
- 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);
- 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);
- rb_loaderror(errmsg, strerror(err_stat), buf);
- }
-
- /* call module initialize function. */
- (*init_fct)();
- return;
- }
-#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);
- if (err) {
- rb_loaderror("Unresolved symbols - %s" , file);
- }
-
- init_fct = (void (*)())symAddr;
- (*init_fct)();
- return;
- }
-#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
-}
-
-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;
-#ifndef __MACOS__
- struct stat st;
-#else
- 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 (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 (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 6e4f606212..0000000000
--- a/dln.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/************************************************
-
- dln.h -
-
- $Author$
- $Date$
- created at: Wed Jan 19 16:53:09 JST 1994
-
-************************************************/
-#ifndef DLN_H
-#define DLN_H
-
-#ifndef _
-#ifndef __STDC__
-# define _(args) ()
-# define const
-#else
-# define _(args) args
-#endif
-#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/enum.c b/enum.c
deleted file mode 100644
index 054c59786d..0000000000
--- a/enum.c
+++ /dev/null
@@ -1,385 +0,0 @@
-/************************************************
-
- enum.c -
-
- $Author$
- $Date$
- created at: Fri Oct 1 15:15:19 JST 1993
-
- Copyright (C) 1993-1999 Yukihiro Matsumoto
-
-************************************************/
-
-#include "ruby.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_iterator_p()) {
- rb_iterate(rb_each, obj, grep_iter_i, (VALUE)arg);
- }
- else {
- rb_iterate(rb_each, obj, grep_i, (VALUE)arg);
- }
- return tmp;
-}
-
-struct find_arg {
- int found;
- VALUE val;
-};
-
-static VALUE
-find_i(i, arg)
- VALUE i;
- struct find_arg *arg;
-{
- if (RTEST(rb_yield(i))) {
- arg->found = Qtrue;
- arg->val = i;
- rb_iter_break();
- }
- return Qnil;
-}
-
-static VALUE
-enum_find(argc, argv, obj)
- int argc;
- VALUE* argv;
- VALUE obj;
-{
- struct find_arg arg;
- VALUE if_none;
-
- rb_scan_args(argc, argv, "01", &if_none);
- arg.found = Qfalse;
- rb_iterate(rb_each, obj, find_i, (VALUE)&arg);
- if (arg.found) {
- return arg.val;
- }
- if (!NIL_P(if_none)) {
- rb_eval_cmd(if_none, Qnil);
- }
- 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
-enum_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, enum_all, ary);
-
- return ary;
-}
-
-static VALUE
-enum_collect(obj)
- VALUE obj;
-{
- VALUE tmp;
-
- tmp = rb_ary_new();
- rb_iterate(rb_each, obj, rb_iterator_p() ? collect_i : enum_all, tmp);
-
- return tmp;
-}
-
-static VALUE
-enum_sort(obj)
- VALUE obj;
-{
- return rb_ary_sort(enum_to_a(obj));
-}
-
-static VALUE
-min_i(i, min)
- VALUE i, *min;
-{
- VALUE cmp;
-
- if (NIL_P(*min))
- *min = i;
- else {
- cmp = rb_funcall(i, id_cmp, 1, *min);
- if (NUM2LONG(cmp) < 0)
- *min = i;
- }
- return Qnil;
-}
-
-static VALUE
-min_ii(i, min)
- VALUE i, *min;
-{
- VALUE cmp;
-
- if (NIL_P(*min))
- *min = i;
- else {
- cmp = rb_yield(rb_assoc_new(i, *min));
- if (NUM2LONG(cmp) < 0)
- *min = i;
- }
- return Qnil;
-}
-
-static VALUE
-enum_min(obj)
- VALUE obj;
-{
- VALUE min = Qnil;
-
- rb_iterate(rb_each, obj, rb_iterator_p()?min_ii:min_i, (VALUE)&min);
- return min;
-}
-
-static VALUE
-max_i(i, max)
- VALUE i, *max;
-{
- VALUE cmp;
-
- if (NIL_P(*max))
- *max = i;
- else {
- cmp = rb_funcall(i, id_cmp, 1, *max);
- if (NUM2LONG(cmp) > 0)
- *max = i;
- }
- return Qnil;
-}
-
-static VALUE
-max_ii(i, max)
- VALUE i, *max;
-{
- VALUE cmp;
-
- if (NIL_P(*max))
- *max = i;
- else {
- cmp = rb_yield(rb_assoc_new(i, *max));
- if (NUM2LONG(cmp) > 0)
- *max = i;
- }
- return Qnil;
-}
-
-static VALUE
-enum_max(obj)
- VALUE obj;
-{
- VALUE max = Qnil;
-
- rb_iterate(rb_each, obj, rb_iterator_p()?max_ii:max_i, (VALUE)&max);
- return max;
-}
-
-struct i_v_pair {
- int i;
- VALUE v;
- int found;
-};
-
-static VALUE
-index_i(item, iv)
- VALUE item;
- struct i_v_pair *iv;
-{
- if (rb_equal(item, iv->v)) {
- iv->found = 1;
- rb_iter_break();
- }
- else {
- iv->i++;
- }
- return Qnil;
-}
-
-static VALUE
-enum_index(obj, val)
- VALUE obj, val;
-{
- struct i_v_pair iv;
-
- iv.i = 0;
- iv.v = val;
- iv.found = 0;
- rb_iterate(rb_each, obj, index_i, (VALUE)&iv);
- if (iv.found) return INT2FIX(iv.i);
- return Qnil; /* not found */
-}
-
-static VALUE
-member_i(item, iv)
- VALUE item;
- struct i_v_pair *iv;
-{
- if (rb_equal(item, iv->v)) {
- iv->i = 1;
- rb_iter_break();
- }
- return Qnil;
-}
-
-static VALUE
-enum_member(obj, val)
- VALUE obj, val;
-{
- struct i_v_pair iv;
-
- iv.i = 0;
- iv.v = val;
- rb_iterate(rb_each, obj, member_i, (VALUE)&iv);
- if (iv.i) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-each_with_index_i(val, indexp)
- VALUE val;
- int *indexp;
-{
-#if 1
- rb_yield(rb_assoc_new(val, INT2FIX(*indexp)));
-#else
- rb_yield(rb_ary_concat(rb_Array(val), INT2FIX(*indexp)));
-#endif
- (*indexp)++;
- return Qnil;
-}
-
-static VALUE
-enum_each_with_index(obj)
- VALUE obj;
-{
- int index = 0;
-
- rb_iterate(rb_each, obj, each_with_index_i, (VALUE)&index);
- return Qnil;
-}
-
-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,"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,"min", enum_min, 0);
- rb_define_method(rb_mEnumerable,"max", enum_max, 0);
- rb_define_method(rb_mEnumerable,"index", enum_index, 1);
- 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 6c38d4cbb1..0000000000
--- a/env.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/************************************************
-
- env.h -
-
- $Author$
- $Date$
- created at: Mon Jul 11 11:53:03 JST 1994
-
-************************************************/
-#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;
-} *ruby_frame;
-
-void rb_gc_mark_frame _((struct FRAME *));
-
-extern struct SCOPE {
- struct RBasic super;
- ID *local_tbl;
- VALUE *local_vars;
- int flag;
-} *ruby_scope;
-
-#define SCOPE_ALLOCA 0
-#define SCOPE_MALLOC 1
-#define SCOPE_NOSTACK 2
-
-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 762151cc79..0000000000
--- a/error.c
+++ /dev/null
@@ -1,1088 +0,0 @@
-/************************************************
-
- error.c -
-
- $Author$
- $Date$
- created at: Mon Aug 9 16:11:34 JST 1993
-
- Copyright (C) 1993-1999 Yukihiro Matsumoto
-
-************************************************/
-
-#include "ruby.h"
-#include "env.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
-
-#ifdef USE_CWGUSI
-#include <sys/errno.h>
-int sys_nerr = 256;
-#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);
-}
-
-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);
- err_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);
- err_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);
- err_print(buf, args);
- va_end(args);
- 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_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 */
- -1, 0,
-};
-
-void
-rb_check_type(x, t)
- VALUE x;
- int t;
-{
- struct types *type = builtin_types;
- int tt = TYPE(x);
-
- if (tt != 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_eSyntaxError;
-VALUE rb_eTypeError;
-VALUE rb_eArgError;
-VALUE rb_eNameError;
-VALUE rb_eIndexError;
-VALUE rb_eLoadError;
-VALUE rb_eSecurityError;
-VALUE rb_eNotImpError;
-VALUE rb_eNoMemError;
-
-VALUE rb_eSystemCallError;
-VALUE rb_mErrno;
-
-VALUE
-rb_exc_new(etype, ptr, len)
- VALUE etype;
- const char *ptr;
- long len;
-{
- VALUE exc = rb_obj_alloc(etype);
-
- rb_iv_set(exc, "mesg", rb_str_new(ptr, len));
- return exc;
-}
-
-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;
-{
- char *s;
- int len;
-
- s = str2cstr(str, &len);
- return rb_exc_new(etype, s, 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) {
- STR2CSTR(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 etype, exc;
-
- if (argc == 0) return self;
- if (argc == 1 && self == argv[0]) return self;
- etype = CLASS_OF(self);
- while (FL_TEST(etype, FL_SINGLETON)) {
- etype = RCLASS(etype)->super;
- }
- exc = rb_obj_alloc(etype);
- rb_obj_call_init(exc, argc, argv);
-
- 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_new2("#<");
- klass = rb_class_path(klass);
- rb_str_concat(str, klass);
- rb_str_cat(str, ": ", 2);
- rb_str_concat(str, exc);
- rb_str_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));
-}
-
-#ifdef __BEOS__
-typedef struct {
- VALUE *list;
- int n;
-} syserr_list_entry;
-
-typedef struct {
- int ix;
- int n;
-} syserr_index_entry;
-
-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 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", INT2FIX(i));
-#ifdef __BEOS__
- 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");
-}
-
-#ifdef __BEOS__
-static VALUE
-get_syserr(int i)
-{
- VALUE *list;
- int ix, offset;
-
- 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_eFatal = rb_define_class("fatal", rb_eException);
- rb_eInterrupt = rb_define_class("Interrupt", rb_eException);
- rb_eSignal = rb_define_class("SignalException", rb_eException);
-
- rb_eStandardError = rb_define_class("StandardError", rb_eException);
- rb_eSyntaxError = rb_define_class("SyntaxError", rb_eStandardError);
- rb_eTypeError = rb_define_class("TypeError", rb_eStandardError);
- rb_eArgError = rb_define_class("ArgumentError", rb_eStandardError);
- rb_eNameError = rb_define_class("NameError", rb_eStandardError);
- rb_eIndexError = rb_define_class("IndexError", rb_eStandardError);
- rb_eLoadError = rb_define_class("LoadError", rb_eStandardError);
-
- rb_eRuntimeError = rb_define_class("RuntimeError", rb_eStandardError);
- rb_eSecurityError = rb_define_class("SecurityError", rb_eStandardError);
- rb_eNotImpError = rb_define_class("NotImplementError", rb_eException);
- 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;
-
- err = strerror(errno);
- if (mesg) {
- buf = ALLOCA_N(char, strlen(err)+strlen(mesg)+4);
- sprintf(buf, "%s - %s", err, mesg);
- }
- else {
- buf = ALLOCA_N(char, strlen(err)+1);
- strcpy(buf, err);
- }
-
- errno = 0;
-#ifdef __BEOS__
- ee = get_syserr(n);
- if (!ee) {
- char name[6];
-
- sprintf(name, "E%03d", n);
- ee = set_syserr(n, name);
- }
-#else
-# ifdef USE_CWGUSI
- if (n < 0) {
- int macoserr_index = sys_nerr - 1;
- if (!syserr_list[macoserr_index]) {
- char name[6];
- sprintf(name, "E%03d", macoserr_index);
- ee = set_syserr(macoserr_index, name);
- }
- }
- else
-#endif /* USE_CWGUSI */
- if (n > sys_nerr || !syserr_list[n]) {
- char name[6];
-
- sprintf(name, "E%03d", n);
- ee = set_syserr(n, name);
- }
- else {
- ee = syserr_list[n];
- }
- ee = rb_exc_new2(ee, buf);
-#endif
- rb_iv_set(ee, "errno", INT2FIX(n));
- rb_exc_raise(ee);
-}
-
-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_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);
- }
- }
-#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_cat(str, "\n", 1);
- rb_str_cat(str, s, strlen(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 0e16db765a..0000000000
--- a/eval.c
+++ /dev/null
@@ -1,7730 +0,0 @@
-/************************************************
-
- eval.c -
-
- $Author$
- $Date$
- created at: Thu Jun 10 14:22:17 JST 1993
-
- Copyright (C) 1993-1999 Yukihiro Matsumoto
-
-************************************************/
-
-#include "ruby.h"
-#include "node.h"
-#include "env.h"
-#include "rubysig.h"
-
-#include <stdio.h>
-#include <setjmp.h>
-#include "st.h"
-#include "dln.h"
-
-#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 USE_CWGUSI
-#include <sys/stat.h>
-#include <sys/errno.h>
-#include <compat.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
-
-#ifdef HAVE_SYS_RESOURCE_H
-#include <sys/resource.h>
-#endif
-
-VALUE rb_cProc;
-static VALUE rb_cBinding;
-static VALUE proc_call _((VALUE,VALUE));
-static VALUE rb_f_binding _((VALUE));
-static void rb_f_END _((void));
-static VALUE rb_f_iterator_p _((void));
-static VALUE block_pass _((VALUE,NODE*));
-static VALUE rb_cMethod;
-static VALUE method_proc _((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))
-
-static int safe_level = 0;
-/* safe-level:
- 0 - strings from streams/environment/ARGV are tainted (default)
- 1 - no dangerous operation by tainted string
- 2 - process/file operations prohibited
- 3 - all genetated strings are tainted
- 4 - no global (non-tainted) variable modification/no direct output
-*/
-
-int
-rb_safe_level()
-{
- return safe_level;
-}
-
-void
-rb_set_safe_level(level)
- int level;
-{
- if (level > safe_level) {
- safe_level = level;
- }
-}
-
-static VALUE
-safe_getter()
-{
- return INT2FIX(safe_level);
-}
-
-static void
-safe_setter(val)
- VALUE val;
-{
- int level = NUM2INT(val);
-
- if (level < safe_level) {
- rb_raise(rb_eSecurityError, "tried to downgrade safe level from %d to %d",
- safe_level, level);
- }
- safe_level = level;
-}
-
-void
-rb_check_safe_str(x)
- VALUE x;
-{
- if (safe_level > 0 && OBJ_TAINTED(x)){
- rb_raise(rb_eSecurityError, "Insecure operation - %s",
- rb_id2name(ruby_frame->last_func));
- }
- if (TYPE(x)!= T_STRING) {
- rb_raise(rb_eTypeError, "wrong argument type %s (expected String)",
- rb_class2name(CLASS_OF(x)));
- }
-}
-
-void
-rb_secure(level)
- int level;
-{
- if (level <= safe_level) {
- rb_raise(rb_eSecurityError, "Insecure operation `%s' for level %d",
- rb_id2name(ruby_frame->last_func), safe_level);
- }
-}
-
-static void print_undef _((VALUE, ID)) NORETURN;
-static void
-print_undef(klass, id)
- VALUE klass;
- ID id;
-{
- rb_raise(rb_eNameError, "undefined method `%s' for %s `%s'",
- rb_id2name(id),
- (TYPE(klass) == T_MODULE)?"module":"class",
- rb_class2name(klass));
-}
-
-
-#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 (klass == rb_cObject) {
- rb_secure(4);
- }
- if (safe_level >= 4 && !OBJ_TAINTED(klass)) {
- rb_raise(rb_eSecurityError, "Insecure: can't define method");
- }
- 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;
-
- 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 (safe_level >= 4 && !OBJ_TAINTED(klass)) {
- rb_raise(rb_eSecurityError, "Insecure: can't remove method");
- }
- if (!st_delete(RCLASS(klass)->m_tbl, &mid, &body)) {
- rb_raise(rb_eNameError, "method `%s' not defined in %s",
- rb_id2name(mid), rb_class2name(klass));
- }
- rb_clear_cache_by_id(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_clear_cache_by_id(mid);
- rb_add_method(ruby_class, 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_clear_cache_by_id(name);
- 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;
-}
-
-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("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);
- }
- sprintf(buf, "%s=", name);
- id = rb_intern(buf);
- if (write) {
- rb_add_method(klass, id, NEW_ATTRSET(attriv), noex);
- }
-}
-
-static ID init, eqq, each, aref, aset, match, missing;
-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; \
- ruby_frame = &_frame; \
-
-#define POP_FRAME() \
- ruby_sourcefile = _frame.file; \
- ruby_sourceline = _frame.line; \
- ruby_frame = _frame.prev; }
-
-struct BLOCK {
- NODE *var;
- NODE *body;
- VALUE self;
- struct FRAME frame;
- struct SCOPE *scope;
- VALUE klass;
- struct tag *tag;
- int iter;
- int vmode;
- int flags;
- struct RVarmap *d_vars;
- VALUE orig_thread;
- struct BLOCK *prev;
-};
-
-#define BLOCK_D_SCOPE 1
-#define BLOCK_DYNAMIC 2
-
-static struct BLOCK *ruby_block;
-
-#define PUSH_BLOCK(v,b) { \
- struct BLOCK _block; \
- _block.tag = prot_tag; \
- _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.d_vars = ruby_dyna_vars; \
- ruby_block = &_block;
-
-#define POP_BLOCK() \
- ruby_block = _block.prev; \
-}
-
-#define PUSH_BLOCK2(b) { \
- struct BLOCK * volatile _old; \
- _old = ruby_block; \
- ruby_block = b;
-
-#define POP_BLOCK2() \
- ruby_block = _old; \
-}
-
-struct RVarmap *ruby_dyna_vars;
-#define PUSH_VARS() { \
- struct RVarmap * volatile _old; \
- _old = ruby_dyna_vars; \
- ruby_dyna_vars = 0;
-
-#define POP_VARS() \
- ruby_dyna_vars = _old; \
-}
-
-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_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(id, value, push)
- ID id;
- VALUE value;
- int push;
-{
- struct RVarmap *vars = ruby_dyna_vars;
-
- while (vars) {
- if (push && vars->id == 0) break;
- if (vars->id == id) {
- vars->val = value;
- return;
- }
- vars = vars->next;
- }
- rb_dvar_push(id, value);
-}
-
-void
-rb_dvar_asgn(id, value)
- ID id;
- VALUE value;
-{
- dvar_asgn(id, value, 0);
-}
-
-static void
-dvar_asgn_push(id, value)
- ID id;
- VALUE value;
-{
- struct RVarmap* vars = 0;
-
- if (ruby_dyna_vars && ruby_dyna_vars->id == 0) {
- vars = ruby_dyna_vars;
- ruby_dyna_vars = ruby_dyna_vars->next;
- }
- dvar_asgn(id, value, 1);
- if (vars) {
- vars->next = ruby_dyna_vars;
- ruby_dyna_vars = vars;
- }
-}
-
-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.retval = Qnil; \
- _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; }
-
-#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->flag = 0; \
- _old = ruby_scope; \
- ruby_scope = _scope; \
- scope_vmode = SCOPE_PUBLIC;
-
-#define SCOPE_DONT_RECYCLE FL_USER2
-#define POP_SCOPE() \
- if (FL_TEST(ruby_scope, SCOPE_DONT_RECYCLE)) {\
- FL_SET(_old, SCOPE_DONT_RECYCLE);\
- } \
- else { \
- if (ruby_scope->flag == SCOPE_ALLOCA) {\
- ruby_scope->local_vars = 0; \
- ruby_scope->local_tbl = 0; \
- if (ruby_scope != top_scope)\
- rb_gc_force_recycle((VALUE)ruby_scope);\
- } \
- else { \
- ruby_scope->flag |= 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 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;
- 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)) {
- 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) {
- einfo = str2cstr(rb_obj_as_string(ruby_errinfo), &elen);
- }
- 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;
- ruby_frame->cbase = (VALUE)rb_node_newnode(NODE_CREF,rb_cObject,0,0);
- 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;
-}
-
-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;
- error_print();
- exit(1);
- }
-}
-
-static VALUE
-eval_node(self)
- VALUE self;
-{
- NODE *beg_tree, *tree;
-
- beg_tree = ruby_eval_tree_begin;
- tree = ruby_eval_tree;
- if (beg_tree) {
- ruby_eval_tree_begin = 0;
- rb_eval(self, beg_tree);
- }
-
- if (!tree) return Qnil;
- ruby_eval_tree = 0;
-
- return rb_eval(self, tree);
-}
-
-int ruby_in_eval;
-
-static void rb_thread_cleanup _((void));
-static void rb_thread_wait_other_threads _((void));
-
-static int exit_status;
-
-void
-ruby_run()
-{
- int state;
- static int ex;
- volatile NODE *tmp;
-
- if (ruby_nerrs > 0) exit(ruby_nerrs);
-
- Init_stack(&tmp);
- PUSH_TAG(PROT_NONE);
- PUSH_ITER(ITER_NOT);
- if ((state = EXEC_TAG()) == 0) {
- eval_node(ruby_top_self);
- }
- POP_ITER();
- POP_TAG();
-
- if (state && !ex) ex = state;
- PUSH_TAG(PROT_NONE);
- PUSH_ITER(ITER_NOT);
- if ((state = EXEC_TAG()) == 0) {
- rb_trap_exit();
- rb_thread_cleanup();
- rb_thread_wait_other_threads();
- }
- else {
- ex = state;
- }
- POP_ITER();
- POP_TAG();
-
- switch (ex & 0xf) {
- 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;
- }
- rb_exec_end_proc();
- rb_gc_call_finalizer_at_exit();
- exit(ex);
-}
-
-static void
-compile_error(at)
- const char *at;
-{
- VALUE str;
- char *mesg;
- int len;
-
- mesg = str2cstr(ruby_errinfo, &len);
- ruby_nerrs = 0;
- str = rb_str_new2("compile error");
- if (at) {
- rb_str_cat(str, " in ", 4);
- rb_str_cat(str, at, strlen(at));
- }
- rb_str_cat(str, "\n", 1);
- rb_str_cat(str, mesg, len);
- 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 = "(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 val;
-
- PUSH_CLASS();
- ruby_class = ruby_wrapper = rb_module_new();
- ruby_top_self = rb_obj_clone(ruby_top_self);
- rb_extend_object(self, ruby_class);
-
- val = rb_eval_string_protect(str, &status);
- ruby_top_self = self;
-
- POP_CLASS();
- if (state) {
- *state = status;
- }
- else if (status) {
- JUMP_TAG(status);
- }
- return val;
-}
-
-VALUE
-rb_eval_cmd(cmd, arg)
- VALUE cmd, arg;
-{
- int state;
- VALUE val; /* OK */
- struct SCOPE *saved_scope;
- volatile int safe = safe_level;
-
- if (TYPE(cmd) != T_STRING) {
- return rb_funcall2(cmd, rb_intern("call"),
- RARRAY(arg)->len, RARRAY(arg)->ptr);
- }
-
- PUSH_CLASS();
- PUSH_TAG(PROT_NONE);
- saved_scope = ruby_scope;
- ruby_scope = top_scope;
-
- ruby_class = rb_cObject;
- if (OBJ_TAINTED(cmd)) {
- safe_level = 4;
- }
-
- if ((state = EXEC_TAG()) == 0) {
- val = eval(ruby_top_self, cmd, Qnil, 0, 0);
- }
-
- if (FL_TEST(ruby_scope, SCOPE_DONT_RECYCLE))
- FL_SET(saved_scope, SCOPE_DONT_RECYCLE);
- ruby_scope = saved_scope;
- safe_level = safe;
- POP_TAG();
- POP_CLASS();
-
- switch (state) {
- case 0:
- break;
- case TAG_RETURN:
- rb_raise(rb_eLocalJumpError, "unexpected return");
- break;
- case TAG_NEXT:
- rb_raise(rb_eLocalJumpError, "unexpected next");
- break;
- case TAG_BREAK:
- rb_raise(rb_eLocalJumpError, "unexpected break");
- break;
- case TAG_REDO:
- rb_raise(rb_eLocalJumpError, "unexpected redo");
- break;
- case TAG_RETRY:
- rb_raise(rb_eLocalJumpError, "retry outside of rescue clause");
- break;
- default:
- JUMP_TAG(state);
- break;
- }
- return val;
-}
-
-static VALUE
-rb_trap_eval(cmd, sig)
- VALUE cmd;
- int sig;
-{
- int state;
- VALUE val; /* OK */
-
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- val = rb_eval_cmd(cmd, rb_ary_new3(1, INT2FIX(sig)));
- }
- 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_CVAR:
- rb_raise(rb_eTypeError, "undefined superclass `%s'",
- rb_id2name(node->nd_vid));
- default:
- rb_raise(rb_eTypeError, "superclass undefined");
- }
- 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;
-}
-
-static VALUE
-ev_const_defined(cref, id)
- NODE *cref;
- ID id;
-{
- NODE *cbase = cref;
-
- while (cbase && cbase->nd_clss != rb_cObject) {
- struct RClass *klass = RCLASS(cbase->nd_clss);
-
- 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)
- NODE *cref;
- ID id;
-{
- NODE *cbase = cref;
- VALUE result;
-
- while (cbase && cbase->nd_clss != rb_cObject) {
- struct RClass *klass = RCLASS(cbase->nd_clss);
-
- if (klass->iv_tbl && st_lookup(klass->iv_tbl, id, &result)) {
- return result;
- }
- cbase = cbase->nd_next;
- }
- return rb_const_get(cref->nd_clss, id);
-}
-
-static VALUE
-ev_const_set(cref, id, val)
- NODE *cref;
- ID id;
- VALUE val;
-{
- NODE *cbase = cref;
- VALUE tmp;
-
- while (cbase && cbase->nd_clss != rb_cObject) {
- struct RClass *klass = RCLASS(cbase->nd_clss);
-
- if (klass->iv_tbl && st_lookup(klass->iv_tbl, id, 0)) {
- st_insert(klass->iv_tbl, id, val);
- return val;
- }
- cbase = cbase->nd_next;
- }
- rb_const_assign(cbase->nd_clss, id, val);
- return val;
-}
-
-static VALUE
-rb_mod_nesting()
-{
- NODE *cbase = (NODE*)ruby_frame->cbase;
- VALUE ary = rb_ary_new();
-
- while (cbase && cbase->nd_clss != rb_cObject) {
- rb_ary_push(ary, cbase->nd_clss);
- cbase = cbase->nd_next;
- }
- return ary;
-}
-
-static VALUE
-rb_mod_s_constants()
-{
- NODE *cbase = (NODE*)ruby_frame->cbase;
- VALUE ary = rb_ary_new();
-
- while (cbase && cbase->nd_clss != rb_cObject) {
- rb_mod_const_at(cbase->nd_clss, ary);
- cbase = cbase->nd_next;
- }
-
- rb_mod_const_of(((NODE*)ruby_frame->cbase)->nd_clss, ary);
- return ary;
-}
-
-void
-rb_undef(klass, id)
- VALUE klass;
- ID id;
-{
- VALUE origin;
- NODE *body;
-
- if (safe_level >= 4 && !OBJ_TAINTED(klass)) {
- rb_raise(rb_eSecurityError, "Insecure: can't undef");
- }
- 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_raise(rb_eNameError, "undefined method `%s' for%s `%s'",
- rb_id2name(id),s0,rb_class2name(c));
- }
- rb_clear_cache_by_id(id);
- rb_add_method(klass, id, 0, NOEX_PUBLIC);
- rb_clear_cache_by_id(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;
-
- 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;
- if (nd_type(body) == NODE_FBODY) { /* was alias */
- def = body->nd_mid;
- origin = body->nd_orig;
- body = body->nd_head;
- }
-
- st_insert(RCLASS(klass)->m_tbl, name,
- NEW_METHOD(NEW_FBODY(body, def, origin), orig->nd_noex));
- rb_clear_cache_by_id(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;
-}
-
-#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_Array(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 ruby_scope->local_vars[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;
-
- 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 = CLASS_OF(self);
- goto check_bound;
-
- case NODE_CALL:
- if (!is_defined(self, node->nd_recv, buf)) return 0;
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- val = rb_eval(self, node->nd_recv);
- val = CLASS_OF(val);
- }
- POP_TAG();
- if (state) return 0;
- check_bound:
- if (rb_method_boundp(val, node->nd_mid, nd_type(node)== NODE_CALL)) {
- return arg_defined(self, node->nd_args, buf, "method");
- }
- break;
-
- case NODE_MATCH2:
- case NODE_MATCH3:
- return "method";
-
- case NODE_YIELD:
- if (rb_iterator_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_PUSH:
- case NODE_GASGN:
- case NODE_IASGN:
- case NODE_CASGN:
- 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_CVAR:
- if (ev_const_defined((NODE*)ruby_frame->cbase, node->nd_vid)) {
- return "constant";
- }
- break;
-
- case NODE_COLON2:
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- val = rb_eval(self, node->nd_head);
- }
- POP_TAG();
- if (state) return 0;
- else {
- switch (TYPE(val)) {
- case T_CLASS:
- case T_MODULE:
- if (rb_const_defined_at(val, node->nd_mid))
- return "constant";
- default:
- if (rb_method_boundp(val, node->nd_mid, 1)) {
- return "method";
- }
- }
- }
- break;
-
- case NODE_NTH_REF:
- if (rb_reg_nth_defined(node->nd_nth, MATCH_DATA)) {
- sprintf(buf, "$%d", node->nd_nth);
- return buf;
- }
- break;
-
- case NODE_BACK_REF:
- if (rb_reg_nth_defined(0, MATCH_DATA)) {
- sprintf(buf, "$%c", node->nd_nth);
- return buf;
- }
- break;
-
- default:
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- rb_eval(self, node);
- }
- POP_TAG();
- if (!state) {
- return "expression";
- }
- 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 == 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;
- volatile VALUE trace;
- struct FRAME *prev;
- char *file_save = ruby_sourcefile;
- int line_save = ruby_sourceline;
- VALUE srcfile;
-
- if (!trace_func) return;
-
- trace = trace_func;
- trace_func = 0;
- rb_thread_critical++;
-
- prev = ruby_frame;
- PUSH_FRAME();
- *ruby_frame = *prev;
- ruby_frame->prev = prev;
-
- if (file) {
- ruby_frame->line = ruby_sourceline = line;
- ruby_frame->file = ruby_sourcefile = file;
- }
- if (klass) {
- if (TYPE(klass) == T_ICLASS || 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_call(trace, rb_ary_new3(6, rb_str_new2(event),
- srcfile,
- INT2FIX(ruby_sourceline),
- INT2FIX(id),
- self?rb_f_binding(self):Qnil,
- klass));
- }
- POP_TMPTAG(); /* do not propagate retval */
- POP_FRAME();
-
- rb_thread_critical--;
- if (!trace_func) trace_func = trace;
- ruby_sourceline = line_save;
- ruby_sourcefile = file_save;
- if (state) JUMP_TAG(state);
-}
-
-static void return_check _((void));
-#define return_value(v) prot_tag->retval = (v)
-
-static VALUE
-rb_eval(self, node)
- VALUE self;
- NODE * volatile node;
-{
- 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_head->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(r) == T_STRING) {
- result = rb_reg_match(l, r);
- }
- else {
- result = rb_funcall(r, match, 1, l);
- }
- }
- 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 (RTEST(rb_eval(self, node->nd_cond))) {
- node = node->nd_body;
- }
- else {
- node = node->nd_else;
- }
- goto again;
-
- case NODE_CASE:
- {
- VALUE val;
-
- if (node->nd_head) {
- val = rb_eval(self, node->nd_head);
- }
- else {
- val = Qtrue;
- }
- 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_Array(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);
- 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;
- default:
- break;
- }
- while_out:
- POP_TAG();
- if (state) JUMP_TAG(state);
- RETURN(Qnil);
-
- case NODE_UNTIL:
- PUSH_TAG(PROT_NONE);
- switch (state = EXEC_TAG()) {
- case 0:
- 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;
- default:
- break;
- }
- until_out:
- POP_TAG();
- if (state) JUMP_TAG(state);
- RETURN(Qnil);
-
- case NODE_BLOCK_PASS:
- result = block_pass(self, node);
- break;
-
- case NODE_ITER:
- case NODE_FOR:
- {
- iter_retry:
- PUSH_BLOCK(node->nd_var, node->nd_body);
- PUSH_TAG(PROT_FUNC);
-
- state = EXEC_TAG();
- if (state == 0) {
- if (nd_type(node) == NODE_ITER) {
- PUSH_ITER(ITER_PRE);
- result = rb_eval(self, node->nd_iter);
- POP_ITER();
- }
- else {
- VALUE recv;
- char *file = ruby_sourcefile;
- int line = ruby_sourceline;
-
- _block.flags &= ~BLOCK_D_SCOPE;
- recv = rb_eval(self, node->nd_iter);
- PUSH_ITER(ITER_PRE);
- 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) {
- result = prot_tag->retval;
- }
- }
- POP_TAG();
- POP_BLOCK();
- switch (state) {
- case 0:
- break;
-
- case TAG_RETRY:
- goto iter_retry;
-
- case TAG_BREAK:
- result = Qnil;
- break;
- case TAG_RETURN:
- return_value(result);
- /* fall through */
- default:
- JUMP_TAG(state);
- }
- }
- break;
-
- case NODE_BREAK:
- JUMP_TAG(TAG_BREAK);
- break;
-
- case NODE_NEXT:
- JUMP_TAG(TAG_NEXT);
- break;
-
- case NODE_REDO:
- JUMP_TAG(TAG_REDO);
- break;
-
- case NODE_RETRY:
- JUMP_TAG(TAG_RETRY);
- break;
-
- case NODE_RESTARGS:
- result = rb_eval(self, node->nd_head);
- if (TYPE(result) != T_ARRAY) {
- result = rb_Array(result);
- }
- break;
-
- case NODE_YIELD:
- if (node->nd_stts) {
- result = rb_eval(self, node->nd_stts);
- if (nd_type(node->nd_stts) == NODE_RESTARGS &&
- RARRAY(result)->len == 1)
- {
- result = RARRAY(result)->ptr[0];
- }
- }
- else {
- result = Qnil;
- }
- result = rb_yield_0(result, 0, 0, Qfalse);
- 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;
-
- 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 == 0) {
- ruby_errinfo = e_info;
- }
- else if (state == TAG_RETRY) {
- state = 0;
- goto retry_entry;
- }
- 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 */
-
- rb_eval(self, node->nd_ensr);
- return_value(retval);
- }
- 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 */
- if (ruby_scope->local_vars == 0) {
- rb_bug("unexpected local variable");
- }
- if (!RTEST(ruby_scope->local_vars[node->nd_cnt])) {
- if (RTEST(rb_eval(self, node->nd_beg))) {
- ruby_scope->local_vars[node->nd_cnt] =
- RTEST(rb_eval(self, node->nd_end))?Qfalse:Qtrue;
- result = Qtrue;
- }
- else {
- result = Qfalse;
- }
- }
- else {
- if (RTEST(rb_eval(self, node->nd_end))) {
- ruby_scope->local_vars[node->nd_cnt] = Qfalse;
- }
- result = Qtrue;
- }
- break;
-
- case NODE_FLIP3: /* like SED */
- if (ruby_scope->local_vars == 0) {
- rb_bug("unexpected local variable");
- }
- if (!RTEST(ruby_scope->local_vars[node->nd_cnt])) {
- result = RTEST(rb_eval(self, node->nd_beg));
- ruby_scope->local_vars[node->nd_cnt] = result;
- }
- else {
- if (RTEST(rb_eval(self, node->nd_end))) {
- ruby_scope->local_vars[node->nd_cnt] = Qfalse;
- }
- result = Qtrue;
- }
- break;
-
- case NODE_RETURN:
- if (node->nd_stts) {
- return_value(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_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_raise(rb_eNameError, "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;
-
- frame = *ruby_frame;
- frame.tmp = ruby_frame;
- ruby_frame = &frame;
-
- PUSH_SCOPE();
- PUSH_TAG(PROT_NONE);
- if (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 (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;
- 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:
- result = rb_eval(self, node->nd_head);
- if (RTEST(result)) break;
- node = node->nd_value;
- goto again;
-
- 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);
- rb_dvar_asgn(node->nd_vid, result);
- break;
-
- case NODE_DASGN_PUSH:
- result = rb_eval(self, node->nd_value);
- dvar_asgn_push(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_CASGN:
- if (NIL_P(ruby_class)) {
- rb_raise(rb_eTypeError, "no class/module to define constant");
- }
- result = rb_eval(self, node->nd_value);
- ev_const_set((NODE*)ruby_frame->cbase, 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_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_CVAR:
- result = ev_const_get((NODE*)ruby_frame->cbase, node->nd_vid);
- break;
-
- case NODE_BLOCK_ARG:
- if (ruby_scope->local_vars == 0)
- rb_bug("unexpected block argument");
- if (rb_iterator_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(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:
- 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");
- }
- /* fall through */
- default:
- str2 = rb_eval(self, list->nd_head);
- str2 = rb_obj_as_string(str2);
- break;
- }
- rb_str_cat(str, RSTRING(str2)->ptr, RSTRING(str2)->len);
- if (OBJ_TAINTED(str2)) OBJ_TAINT(str);
- }
- 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 # 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;
- VALUE origin;
- int noex;
-
- if (NIL_P(ruby_class)) {
- rb_raise(rb_eTypeError, "no class to add method");
- }
- if (ruby_class == rb_cObject && node->nd_mid == init) {
- rb_warn("re-defining Object#initialize may cause infinite loop");
- }
- body = search_method(ruby_class, node->nd_mid, &origin);
- if (body){
- if (RTEST(ruby_verbose)) {
- rb_warning("discarding old %s", rb_id2name(node->nd_mid));
- }
- rb_clear_cache_by_id(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 {
- noex = NOEX_PUBLIC;
- }
- if (body && origin == ruby_class && body->nd_noex & NOEX_UNDEF) {
- noex |= NOEX_UNDEF;
- }
- rb_add_method(ruby_class, node->nd_mid, node->nd_defn, noex);
- if (scope_vmode == SCOPE_MODFUNC) {
- rb_add_method(rb_singleton_class(ruby_class),
- node->nd_mid, node->nd_defn, NOEX_PUBLIC);
- rb_funcall(ruby_class, rb_intern("singleton_method_added"),
- 1, INT2FIX(node->nd_mid));
- }
- if (FL_TEST(ruby_class, FL_SINGLETON)) {
- rb_funcall(rb_iv_get(ruby_class, "__attached__"),
- rb_intern("singleton_method_added"),
- 1, INT2FIX(node->nd_mid));
- }
- else {
- rb_funcall(ruby_class, rb_intern("method_added"),
- 1, INT2FIX(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;
-
- if (rb_special_const_p(recv)) {
- rb_raise(rb_eTypeError,
- "can't define method \"%s\" for %s",
- rb_id2name(node->nd_mid),
- rb_class2name(CLASS_OF(recv)));
- }
-
- if (safe_level >= 4 && !OBJ_TAINTED(recv)) {
- rb_raise(rb_eSecurityError, "can't define singleton method");
- }
- klass = rb_singleton_class(recv);
- if (st_lookup(RCLASS(klass)->m_tbl, node->nd_mid, &body)) {
- if (safe_level >= 4) {
- rb_raise(rb_eSecurityError, "re-defining method prohibited");
- }
- if (RTEST(ruby_verbose)) {
- rb_warning("redefine %s", rb_id2name(node->nd_mid));
- }
- }
- rb_clear_cache_by_id(node->nd_mid);
- rb_add_method(klass, node->nd_mid, node->nd_defn,
- NOEX_PUBLIC|(body?body->nd_noex&NOEX_UNDEF:0));
- rb_funcall(recv, rb_intern("singleton_method_added"),
- 1, INT2FIX(node->nd_mid));
- result = Qnil;
- }
- break;
-
- case NODE_UNDEF:
- if (NIL_P(ruby_class)) {
- rb_raise(rb_eTypeError, "no class to undef method");
- }
- if (ruby_class == rb_cObject) {
- rb_secure(4);
- }
- 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);
- rb_funcall(ruby_class, rb_intern("method_added"),
- 1, INT2FIX(node->nd_mid));
- 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 || ruby_class == ruby_wrapper) &&
- 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 && ruby_class == ruby_wrapper &&
- rb_const_defined_at(rb_cObject, node->nd_cname)) {
- klass = rb_const_get(rb_cObject, 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 = RCLASS(klass)->super;
- if (FL_TEST(tmp, FL_SINGLETON)) {
- tmp = RCLASS(tmp)->super;
- }
- while (TYPE(tmp) == T_ICLASS) {
- tmp = RCLASS(tmp)->super;
- }
- if (tmp != super) {
- rb_raise(rb_eTypeError, "superclass mismatch for %s",
- rb_id2name(node->nd_cname));
- }
- }
- if (safe_level >= 4) {
- rb_raise(rb_eSecurityError, "extending class prohibited");
- }
- rb_clear_cache();
- }
- else {
- if (!super) super = rb_cObject;
- klass = rb_define_class_id(node->nd_cname, super);
- rb_const_set(ruby_class, node->nd_cname, klass);
- rb_set_class_path(klass,ruby_class,rb_id2name(node->nd_cname));
- }
- 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 || ruby_class == ruby_wrapper) &&
- 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 && ruby_class == ruby_wrapper &&
- rb_const_defined_at(rb_cObject, node->nd_cname)) {
- module = rb_const_get(rb_cObject, 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 (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;
-
- klass = rb_eval(self, node->nd_recv);
- if (rb_special_const_p(klass)) {
- rb_raise(rb_eTypeError, "no virtual class for %s",
- rb_class2name(CLASS_OF(klass)));
- }
- if (safe_level >= 4 && !OBJ_TAINTED(klass))
- rb_raise(rb_eSecurityError, "Insecure: can't extend object");
- if (FL_TEST(CLASS_OF(klass), FL_SINGLETON)) {
- rb_clear_cache();
- }
- klass = rb_singleton_class(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_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, node)
- VALUE module;
- NODE * volatile node;
-{
- 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;
-
- /* fill c-ref */
- node->nd_clss = module;
- node = node->nd_body;
-
- PUSH_CLASS();
- ruby_class = module;
- PUSH_SCOPE();
- PUSH_VARS();
-
- if (node->nd_rval) ruby_frame->cbase = node->nd_rval;
- 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_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_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) {
- exit_status = status;
- rb_exc_raise(rb_exc_new(rb_eSystemExit, 0, 0));
- }
- rb_exec_end_proc();
- rb_gc_call_finalizer_at_exit();
- 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 (ruby_errinfo) {
- error_print();
- }
- rb_exit(1);
-}
-
-static VALUE
-rb_f_abort()
-{
- rb_secure(4);
- rb_abort();
- return Qnil; /* not reached */
-}
-
-void
-rb_iter_break()
-{
- JUMP_TAG(TAG_BREAK);
-}
-
-static void rb_longjmp _((int, VALUE)) NORETURN;
-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)) {
- fprintf(stderr, "Exception `%s' at %s:%d\n",
- rb_class2name(CLASS_OF(ruby_errinfo)),
- ruby_sourcefile, ruby_sourceline);
- }
-
- 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;
-
- 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;
- }
- mesg = rb_funcall(argv[0], rb_intern("exception"), 0, 0);
- break;
- case 3:
- case 2:
- mesg = rb_funcall(argv[0], rb_intern("exception"), 1, argv[1]);
- break;
- default:
- rb_raise(rb_eArgError, "wrong # of arguments");
- break;
- }
- if (!NIL_P(mesg)) {
- if (!rb_obj_is_kind_of(mesg, rb_eException))
- rb_raise(rb_eTypeError, "exception object expected");
- set_backtrace(mesg, (argc>2)?argv[2]:Qnil);
- }
-
- PUSH_FRAME(); /* fake frame */
- *ruby_frame = *_frame.prev->prev;
- rb_longjmp(TAG_RAISE, mesg);
- POP_FRAME();
-
- return Qnil; /* not reached */
-}
-
-void
-rb_jump_tag(tag)
- int tag;
-{
- JUMP_TAG(tag);
-}
-
-int
-rb_iterator_p()
-{
- if (ruby_frame->iter) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-rb_f_iterator_p()
-{
- if (ruby_frame->prev && ruby_frame->prev->iter) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-rb_yield_0(val, self, klass, acheck)
- VALUE val, self, klass; /* OK */
- int acheck;
-{
- NODE *node;
- volatile VALUE result = Qnil;
- struct BLOCK *block;
- struct SCOPE *old_scope;
- struct FRAME frame;
- int state;
- static unsigned serial = 1;
-
- if (!ruby_frame->iter || !ruby_block) {
- rb_raise(rb_eLocalJumpError, "yield called out of iterator");
- }
-
- PUSH_VARS();
- PUSH_CLASS();
- block = ruby_block;
- frame = block->frame;
- frame.prev = ruby_frame;
- ruby_frame = &(frame);
- 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->d_vars);
- }
- else {
- /* FOR does not introduce new scope */
- ruby_dyna_vars = block->d_vars;
- }
- ruby_class = klass?klass:block->klass;
- if (!self) self = block->self;
- node = block->body;
- if (block->var) {
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- if (nd_type(block->var) == NODE_MASGN)
- massign(self, block->var, val, acheck);
- else
- assign(self, block->var, val, acheck);
- }
- POP_TAG();
- if (state) goto pop_state;
- }
- 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) {
- result = (*node->nd_cfnc)(val, node->nd_tval, self);
- }
- else {
- result = rb_eval(self, node);
- }
- }
- else {
- switch (state) {
- case TAG_REDO:
- state = 0;
- goto redo;
- case TAG_NEXT:
- state = 0;
- result = Qnil;
- 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();
- POP_VARS();
- ruby_block = block;
- ruby_frame = ruby_frame->prev;
- if (FL_TEST(ruby_scope, SCOPE_DONT_RECYCLE))
- FL_SET(old_scope, SCOPE_DONT_RECYCLE);
- ruby_scope = old_scope;
- if (state) JUMP_TAG(state);
- return result;
-}
-
-VALUE
-rb_yield(val)
- VALUE val;
-{
- return rb_yield_0(val, 0, 0, Qfalse);
-}
-
-static VALUE
-rb_f_loop()
-{
- for (;;) { rb_yield_0(Qnil, 0, 0, Qfalse); }
- return Qnil; /* dummy */
-}
-
-static VALUE
-massign(self, node, val, check)
- VALUE self;
- NODE *node;
- VALUE val;
- int check;
-{
- NODE *list;
- int i = 0, len;
-
- list = node->nd_head;
-
- if (val) {
- if (TYPE(val) != T_ARRAY) {
- val = rb_Array(val);
- }
- len = RARRAY(val)->len;
- for (i=0; list && i<len; i++) {
- assign(self, list->nd_head, RARRAY(val)->ptr[i], check);
- list = list->nd_next;
- }
- if (check && list) goto arg_error;
- if (node->nd_args) {
- if (node->nd_args == (NODE*)-1) {
- /* ignore rest args */
- }
- else if (!list && i<len) {
- assign(self, node->nd_args, rb_ary_new4(len-i, RARRAY(val)->ptr+i), check);
- }
- else {
- assign(self, node->nd_args, rb_ary_new2(0), check);
- }
- }
- else if (check && i<len) goto arg_error;
- }
- else if (node->nd_args && node->nd_args != (NODE*)-1) {
- assign(self, node->nd_args, Qnil, check);
- }
-
- if (check && list) goto arg_error;
- while (list) {
- i++;
- assign(self, list->nd_head, Qnil, check);
- list = list->nd_next;
- }
- return val;
-
- arg_error:
- while (list) {
- i++;
- list = list->nd_next;
- }
- rb_raise(rb_eArgError, "wrong # of arguments (%d for %d)", len, i);
-}
-
-static void
-assign(self, lhs, val, check)
- VALUE self;
- NODE *lhs;
- VALUE val;
- int check;
-{
- 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 iterator variable assignment");
- ruby_scope->local_vars[lhs->nd_cnt] = val;
- break;
-
- case NODE_DASGN:
- rb_dvar_asgn(lhs->nd_vid, val);
- break;
-
- case NODE_DASGN_PUSH:
- dvar_asgn_push(lhs->nd_vid, val);
- break;
-
- case NODE_CASGN:
- ev_const_set((NODE*)ruby_frame->cbase, lhs->nd_vid, val);
- break;
-
- case NODE_CDECL:
- rb_const_set(ruby_class, lhs->nd_vid, val);
- break;
-
- case NODE_MASGN:
- massign(self, lhs, val, check);
- 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)(), (*bl_proc)();
- VALUE data1, data2;
-{
- int state;
- volatile VALUE retval = Qnil;
- NODE *node = NEW_CFUNC(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) {
- retval = prot_tag->retval;
- }
- }
- POP_TAG();
- POP_BLOCK();
- POP_ITER();
-
- switch (state) {
- case 0:
- break;
-
- case TAG_RETRY:
- goto iter_retry;
-
- case TAG_BREAK:
- retval = Qnil;
- 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 (rb_obj_is_kind_of(ruby_errinfo, argv[0])) return 1;
- argv++;
- }
- return 0;
-}
-
-VALUE
-rb_rescue(b_proc, data1, r_proc, data2)
- VALUE (*b_proc)(), (*r_proc)();
- VALUE data1, data2;
-{
- int state;
- volatile VALUE result;
- volatile VALUE e_info = ruby_errinfo;
-
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- retry_entry:
- result = (*b_proc)(data1);
- }
- else if (state == TAG_RAISE && rb_obj_is_kind_of(ruby_errinfo, rb_eStandardError)) {
- 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;
- 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_protect(proc, data, state)
- VALUE (*proc)();
- 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 (*e_proc)();
- VALUE data1, 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->retval; /* save retval */
- (*e_proc)(data2);
- 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 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;
- volatile VALUE d = 0;
- char *format = 0;
- char *desc = "";
- char *file = ruby_sourcefile;
- int line = ruby_sourceline;
-
- if (argc == 0) rb_raise(rb_eArgError, "no id given");
-
- id = FIX2INT(argv[0]);
- argc--; argv++;
-
- switch (TYPE(obj)) {
- case T_NIL:
- format = "undefined method `%s' for nil";
- break;
- case T_TRUE:
- format = "undefined method `%s' for true";
- break;
- case T_FALSE:
- format = "undefined method `%s' for false";
- break;
- case T_OBJECT:
- d = rb_any_to_s(obj);
- break;
- default:
- d = rb_inspect(obj);
- break;
- }
- if (d) {
- 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";
- }
- }
- if (!format) {
- format = "undefined method `%s' for %s%s%s";
- }
- if (RSTRING(d)->len > 65) {
- d = rb_any_to_s(obj);
- }
- desc = RSTRING(d)->ptr;
- }
-
- ruby_sourcefile = file;
- ruby_sourceline = line;
- PUSH_FRAME(); /* fake frame */
- *ruby_frame = *_frame.prev->prev;
-
- rb_raise(rb_eNameError, format, rb_id2name(id),
- desc, desc[0]=='#'?"":":",
- desc[0]=='#'?"":rb_class2name(CLASS_OF(obj)));
- 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;
-
- nargv = ALLOCA_N(VALUE, argc+1);
- nargv[0] = INT2FIX(id);
- MEMCPY(nargv+1, argv, VALUE, argc);
-
- last_call_status = call_status;
-
- return rb_funcall2(obj, missing, argc+1, nargv);
-}
-
-#ifdef DJGPP
-# define STACK_LEVEL_MAX 65535
-#else
-#ifdef __human68k__
-extern int _stacksize;
-# define STACK_LEVEL_MAX (_stacksize - 4096)
-#else
-#ifdef HAVE_GETRLIMIT
-static int STACK_LEVEL_MAX = 655300;
-#else
-# define STACK_LEVEL_MAX 655300
-#endif
-#endif
-#endif
-
-extern VALUE *rb_gc_stack_start;
-static int
-stack_length()
-{
- VALUE pos;
-
-#ifdef sparc
- return rb_gc_stack_start - &pos + 0x80;
-#else
- return (&pos < rb_gc_stack_start) ? rb_gc_stack_start - &pos
- : &pos - rb_gc_stack_start;
-#endif
-}
-
-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 # 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 */
- if (stack_length() > STACK_LEVEL_MAX) {
- rb_raise(rb_eSysStackError, "stack level too deep");
- }
- }
- 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, 0, 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 re-scoped/renamed method */
- case NODE_ZSUPER:
- /* for attr get/set */
- case NODE_ATTRSET:
- case NODE_IVAR:
- result = rb_eval(recv, body);
- break;
-
- default:
- {
- int state;
- VALUE *local_vars; /* OK */
-
- PUSH_SCOPE();
-
- if (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 # 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 # 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;
- }
- rb_eval(recv, opt);
- }
- if (node->nd_rest >= 0) {
- if (argc > 0)
- local_vars[node->nd_rest]=rb_ary_new4(argc,argv);
- else
- local_vars[node->nd_rest]=rb_ary_new2(0);
- }
- }
- }
-
- 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();
- 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_NEXT:
- rb_raise(rb_eLocalJumpError, "unexpected next");
- break;
- case TAG_BREAK:
- rb_raise(rb_eLocalJumpError, "unexpected break");
- break;
- case TAG_REDO:
- rb_raise(rb_eLocalJumpError, "unexpected redo");
- break;
- case TAG_RETRY:
- if (!rb_iterator_p()) {
- rb_raise(rb_eLocalJumpError, "retry outside of rescue clause");
- }
- default:
- JUMP_TAG(state);
- }
- }
- }
- 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;
-
- /* 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_raise(rb_eNameError, "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;
- while (TYPE(defined_class) == T_ICLASS)
- defined_class = RBASIC(defined_class)->klass;
- if (!rb_obj_is_kind_of(ruby_frame->self, 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_iterator_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);
-}
-
-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, lev;
- VALUE ary;
-
- lev = INT2FIX(0);
- 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()
-{
- VALUE lev;
-
- lev = INT2FIX(0);
- 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;
-
- 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_d_vars;
- int volatile old_vmode;
- struct FRAME frame;
- char *filesave = ruby_sourcefile;
- int linesave = ruby_sourceline;
- volatile int iter = ruby_frame->iter;
- int state;
-
- if (file == 0) {
- file = ruby_sourcefile;
- line = ruby_sourceline;
- }
- 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_d_vars = ruby_dyna_vars;
- ruby_dyna_vars = data->d_vars;
- old_vmode = scope_vmode;
- scope_vmode = data->vmode;
-
- self = data->self;
- ruby_frame->iter = data->iter;
- }
- else {
- if (ruby_frame->prev) {
- ruby_frame->iter = ruby_frame->prev->iter;
- }
- }
- PUSH_CLASS();
- ruby_class = ((NODE*)ruby_frame->cbase)->nd_clss;
-
- ruby_in_eval++;
- if (TYPE(ruby_class) == T_ICLASS) {
- ruby_class = RBASIC(ruby_class)->klass;
- }
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- compile(src, file, line);
- if (ruby_nerrs > 0) {
- compile_error(0);
- }
- result = eval_node(self);
- }
- POP_TAG();
- POP_CLASS();
- ruby_in_eval--;
- if (!NIL_P(scope)) {
- ruby_frame = frame.tmp;
- if (FL_TEST(ruby_scope, SCOPE_DONT_RECYCLE))
- FL_SET(old_scope, SCOPE_DONT_RECYCLE);
- ruby_scope = old_scope;
- ruby_block = old_block;
- ruby_dyna_vars = old_d_vars;
- data->vmode = scope_vmode; /* write back visibility mode */
- scope_vmode = old_vmode;
- }
- else {
- ruby_frame->iter = iter;
- }
- ruby_sourcefile = filesave;
- ruby_sourceline = linesave;
- if (state) {
- if (state == TAG_RAISE) {
- VALUE err;
- VALUE errat;
-
- errat = get_backtrace(ruby_errinfo);
- if (strcmp(file, "(eval)") == 0) {
- if (ruby_sourceline > 1) {
- err = RARRAY(errat)->ptr[0];
- rb_str_cat(err, ": ", 2);
- rb_str_concat(err, ruby_errinfo);
- }
- else {
- err = rb_str_dup(ruby_errinfo);
- }
- errat = Qnil;
- rb_exc_raise(rb_exc_new3(CLASS_OF(ruby_errinfo), 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, val;
- char *file = "(eval)";
- int line = 1;
-
- rb_scan_args(argc, argv, "13", &src, &scope, &vfile, &vline);
- if (argc >= 3) {
- Check_Type(vfile, T_STRING);
- file = RSTRING(vfile)->ptr;
- }
- if (argc >= 4) {
- line = NUM2INT(vline);
- }
-
- Check_SafeStr(src);
- 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;
- VALUE cbase = ruby_frame->cbase;
-
- PUSH_CLASS();
- ruby_class = under;
- PUSH_FRAME();
- 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;
- ruby_frame->cbase = (VALUE)rb_node_newnode(NODE_CREF,under,0,cbase);
- mode = scope_vmode;
- SCOPE_SET(SCOPE_PUBLIC);
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- val = (*func)(args);
- }
- POP_TAG();
- 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];
-
- Check_SafeStr(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;
- volatile VALUE cbase = ruby_block->frame.cbase;
- /* cbase should be pointed from volatile local variable */
- /* to be protected from GC. */
- VALUE result;
- int state;
-
- block = *ruby_block;
- /* copy the block to avoid modifying global data. */
- 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, Qfalse);
- }
- 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, Qfalse);
-}
-
-/* block eval under the class/module context */
-static VALUE
-yield_under(under, self)
- VALUE under, self;
-{
- if (safe_level >= 4 && !OBJ_TAINTED(self))
- rb_raise(rb_eSecurityError, "Insecure: can't eval");
- return exec_under(yield_under_i, under, self);
-}
-
-static VALUE
-specific_eval(argc, argv, klass, self)
- int argc;
- VALUE *argv;
- VALUE klass, self;
-{
- char *file = "(eval)";
- int line = 1;
- int iter = rb_iterator_p();
-
- if (argc > 0) {
- Check_SafeStr(argv[0]);
- if (argc > 3) {
- rb_raise(rb_eArgError, "wrong # of arguments: %s(src) or %s{..}",
- rb_id2name(ruby_frame->last_func),
- rb_id2name(ruby_frame->last_func));
- }
- if (argc > 1) file = STR2CSTR(argv[1]);
- if (argc > 2) line = NUM2INT(argv[2]);
- }
- else if (!iter) {
- rb_raise(rb_eArgError, "block not supplied");
- }
-
- if (iter) {
- return yield_under(klass, self);
- }
- else {
- 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);
-}
-
-static 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;
-
-static int
-is_absolute_path(path)
- const char *path;
-{
- if (path[0] == '/') return 1;
-# if defined(MSDOS) || defined(NT) || defined(__human68k__) || defined(__EMX__)
- if (path[0] == '\\') return 1;
- if (strlen(path) > 2 && path[1] == ':') return 1;
-# endif
- return 0;
-}
-
-#ifdef __MACOS__
-static int
-is_macos_native_path(path)
- const char *path;
-{
- if (strchr(path, ':')) return 1;
- return 0;
-}
-#endif
-
-static char*
-find_file(file)
- char *file;
-{
- volatile VALUE vpath;
- char *path;
-
-#ifdef __MACOS__
- if (is_macos_native_path(file)) {
- FILE *f = fopen(file, "r");
-
- if (f == NULL) return 0;
- fclose(f);
- return file;
- }
-#endif
-
- if (is_absolute_path(file)) {
- FILE *f = fopen(file, "r");
-
- if (f == NULL) return 0;
- fclose(f);
- return file;
- }
-
- if (file[0] == '~') {
- VALUE argv[1];
- argv[0] = rb_str_new2(file);
- file = STR2CSTR(rb_file_s_expand_path(1, argv));
- }
-
- if (rb_load_path) {
- int i;
-
- Check_Type(rb_load_path, T_ARRAY);
- vpath = rb_ary_new();
- for (i=0;i<RARRAY(rb_load_path)->len;i++) {
- VALUE str = RARRAY(rb_load_path)->ptr[i];
- Check_SafeStr(str);
- if (RSTRING(str)->len > 0) {
- rb_ary_push(vpath, str);
- }
- }
- vpath = rb_ary_join(vpath, rb_str_new2(PATH_SEP));
- path = STR2CSTR(vpath);
- if (safe_level >= 2 && !rb_path_check(path)) {
- rb_raise(rb_eSecurityError, "loading from unsafe path %s", path);
- }
- }
- else {
- path = 0;
- }
-
- return dln_find_file(file, path);
-}
-
-void
-rb_load(fname, wrap)
- VALUE fname;
- int wrap;
-{
- int state;
- char *file;
- volatile ID last_func;
- volatile VALUE wrapper = 0;
- VALUE self = ruby_top_self;
- TMP_PROTECT;
-
- if (wrap) {
- Check_Type(fname, T_STRING);
- }
- else {
- Check_SafeStr(fname);
- }
- file = find_file(RSTRING(fname)->ptr);
- if (!file) {
- rb_raise(rb_eLoadError, "No such file to load -- %s", RSTRING(fname)->ptr);
- }
-
- PUSH_VARS();
- PUSH_CLASS();
- wrapper = ruby_wrapper;
- 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_FRAME();
- ruby_frame->last_func = 0;
- ruby_frame->self = ruby_top_self;
- ruby_frame->cbase = (VALUE)rb_node_newnode(NODE_CREF,ruby_class,0,0);
- PUSH_SCOPE();
- if (ruby_class == rb_cObject && top_scope->local_tbl) {
- int len = top_scope->local_tbl[0]+1;
- ID *tbl = ALLOC_N(ID, len);
- VALUE *vars = TMP_ALLOC(len);
- *vars++ = 0;
- MEMCPY(tbl, top_scope->local_tbl, ID, len);
- MEMCPY(vars, top_scope->local_vars, VALUE, len-1);
- ruby_scope->local_tbl = tbl; /* copy toplevel scope */
- ruby_scope->local_vars = vars; /* will not alter toplevel variables */
- }
- /* 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) {
- ruby_in_eval++;
- rb_load_file(file);
- ruby_in_eval--;
- if (ruby_nerrs == 0) {
- eval_node(self);
- }
- }
- ruby_frame->last_func = last_func;
- if (ruby_scope->flag == SCOPE_ALLOCA && ruby_class == rb_cObject) {
- if (ruby_scope->local_tbl) /* toplevel was empty */
- free(ruby_scope->local_tbl);
- }
- POP_TAG();
- 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(state);
-}
-
-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;
-}
-
-static VALUE rb_features;
-
-static int
-rb_provided(feature)
- const char *feature;
-{
- VALUE *p, *pend;
- char *f;
- int len;
-
- p = RARRAY(rb_features)->ptr;
- pend = p + RARRAY(rb_features)->len;
- while (p < pend) {
- f = STR2CSTR(*p);
- if (strcmp(f, feature) == 0) return Qtrue;
- len = strlen(feature);
- if (strncmp(f, feature, len) == 0
- && (strcmp(f+len, ".rb") == 0 ||strcmp(f+len, ".so") == 0)) {
- return Qtrue;
- }
- p++;
- }
- return Qfalse;
-}
-
-static int rb_thread_loading _((const char*));
-static void rb_thread_loading_done _((const char*));
-
-void
-rb_provide(feature)
- const char *feature;
-{
- char *buf, *ext;
-
- if (!rb_provided(feature)) {
- ext = strrchr(feature, '.');
- if (ext && strcmp(DLEXT, ext) == 0) {
- buf = ALLOCA_N(char, strlen(feature)+4);
- strcpy(buf, feature);
- ext = strrchr(buf, '.');
- strcpy(ext, ".so");
- feature = buf;
- }
- rb_ary_push(rb_features, rb_str_new2(feature));
- }
-}
-
-VALUE
-rb_f_require(obj, fname)
- VALUE obj, fname;
-{
- char *ext, *file, *feature, *buf; /* OK */
- volatile VALUE load;
- int state;
- volatile int safe = safe_level;
-
- Check_SafeStr(fname);
- if (rb_provided(RSTRING(fname)->ptr))
- return Qfalse;
-
- ext = strrchr(RSTRING(fname)->ptr, '.');
- if (ext) {
- if (strcmp(".rb", ext) == 0) {
- feature = file = RSTRING(fname)->ptr;
- file = find_file(file);
- if (file) goto load_rb;
- }
- else if (strcmp(".so", ext) == 0 || strcmp(".o", ext) == 0) {
- file = feature = RSTRING(fname)->ptr;
- if (strcmp(ext, DLEXT) != 0) {
- buf = ALLOCA_N(char, strlen(file)+sizeof(DLEXT)+1);
- strcpy(buf, feature);
- ext = strrchr(buf, '.');
- strcpy(ext, DLEXT);
- file = feature = buf;
- if (rb_provided(feature)) return Qfalse;
- }
- file = find_file(file);
- if (file) goto load_dyna;
- }
- else if (strcmp(DLEXT, ext) == 0) {
- feature = RSTRING(fname)->ptr;
- file = find_file(feature);
- if (file) goto load_dyna;
- }
- }
- buf = ALLOCA_N(char, strlen(RSTRING(fname)->ptr) + 5);
- strcpy(buf, RSTRING(fname)->ptr);
- strcat(buf, ".rb");
- file = find_file(buf);
- if (file) {
- fname = rb_str_new2(file);
- feature = buf;
- goto load_rb;
- }
- strcpy(buf, RSTRING(fname)->ptr);
- strcat(buf, DLEXT);
- file = find_file(buf);
- if (file) {
- feature = buf;
- goto load_dyna;
- }
- rb_raise(rb_eLoadError, "No such file to load -- %s",
- RSTRING(fname)->ptr);
-
- load_dyna:
- if (rb_thread_loading(feature)) return Qfalse;
-
- rb_provide(feature);
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- load = rb_str_new2(file);
- file = RSTRING(load)->ptr;
- dln_load(file);
- }
- POP_TAG();
- rb_thread_loading_done(feature);
- if (state) JUMP_TAG(state);
-
- return Qtrue;
-
- load_rb:
- safe_level = 0;
- if (rb_thread_loading(feature)) return Qfalse;
- rb_provide(feature);
-
- PUSH_TAG(PROT_NONE);
- if ((state = EXEC_TAG()) == 0) {
- rb_load(fname, 0);
- }
- POP_TAG();
- rb_thread_loading_done(feature);
- 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
-set_method_visibility(self, argc, argv, ex)
- VALUE self;
- int argc;
- VALUE *argv;
- ID ex;
-{
- int i;
-
- 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;
-{
- 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;
-{
- 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;
-{
- 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 (argc == 0) {
- SCOPE_SET(SCOPE_MODFUNC);
- return module;
- }
-
- set_method_visibility(module, argc, argv, NOEX_PRIVATE);
- for (i=0; i<argc; i++) {
- id = rb_to_id(argv[i]);
- body = search_method(module, id, 0);
- if (body == 0 || body->nd_body == 0) {
- rb_bug("undefined method `%s'; can't happen", rb_id2name(id));
- }
- rb_clear_cache_by_id(id);
- rb_add_method(rb_singleton_class(module), id, body->nd_body, NOEX_PUBLIC);
- }
- 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;
-{
- int i;
-
- for (i=0; i<argc; i++) {
- Check_Type(argv[i], T_MODULE);
- rb_funcall(argv[i], rb_intern("append_features"), 1, module);
- }
- return module;
-}
-
-void
-rb_obj_call_init(obj, argc, argv)
- VALUE obj;
- int argc;
- VALUE *argv;
-{
- PUSH_ITER(rb_iterator_p()?ITER_PRE:ITER_NOT);
- rb_funcall2(obj, init, argc, argv);
- POP_ITER();
-}
-
-VALUE
-rb_class_new_instance(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- VALUE obj;
-
- if (FL_TEST(klass, FL_SINGLETON)) {
- rb_raise(rb_eTypeError, "can't create instance of virtual class");
- }
- obj = rb_obj_alloc(klass);
- rb_obj_call_init(obj, argc, argv);
-
- return obj;
-}
-
-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;
-
- for (i=0; i<argc; i++) Check_Type(argv[i], T_MODULE);
- for (i=0; i<argc; i++) {
- rb_funcall(argv[i], 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);
-}
-
-VALUE rb_f_global_variables();
-VALUE f_instance_variables();
-
-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 (tbl[i] == 0) 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));
-static VALUE rb_f_throw _((int,VALUE*)) NORETURN;
-
-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 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(data)
- VALUE data;
-{
- proc_call(data, Qnil);
-}
-
-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;
- int status;
-
- link = end_procs;
- while (link) {
- rb_protect((VALUE(*)())link->func, link->data, &status);
- link = link->next;
- }
- while (ephemeral_end_procs) {
- link = ephemeral_end_procs;
- ephemeral_end_procs = link->next;
- rb_protect((VALUE(*)())link->func, link->data, &status);
- free(link);
- }
-}
-
-void
-Init_eval()
-{
- init = rb_intern("initialize");
- eqq = rb_intern("===");
- each = rb_intern("each");
-
- aref = rb_intern("[]");
- aset = rb_intern("[]=");
- match = rb_intern("=~");
- missing = rb_intern("method_missing");
-
- 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_iterator_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, 0);
-
- 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_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_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);
-
-#ifdef HAVE_GETRLIMIT
- {
- struct rlimit rlim;
-
- if (getrlimit(RLIMIT_STACK, &rlim) == 0) {
- double space = (double)rlim.rlim_cur*0.2;
-
- if (space > 256*1024) space = 256*1024;
- STACK_LEVEL_MAX = (rlim.rlim_cur - space) / 4;
- }
- }
-#endif
-}
-
-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);
-}
-
-static void
-scope_dup(scope)
- struct SCOPE *scope;
-{
- ID *tbl;
- VALUE *vars;
-
- if (scope->flag & 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->flag = SCOPE_MALLOC;
- }
- else {
- scope->flag = SCOPE_NOSTACK;
- }
-}
-
-static void
-blk_mark(data)
- struct BLOCK *data;
-{
- while (data) {
- rb_gc_mark_frame(&data->frame);
- rb_gc_mark(data->scope);
- rb_gc_mark(data->var);
- rb_gc_mark(data->body);
- rb_gc_mark(data->self);
- rb_gc_mark(data->d_vars);
- rb_gc_mark(data->klass);
- 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)
- 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;
-
- 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);
- }
- scope_dup(tmp->scope);
- 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->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;
- 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->iter = rb_f_iterator_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;
- }
-
- scope_dup(data->scope);
- POP_BLOCK();
-
- return bind;
-}
-
-#define PROC_T3 FL_USER1
-#define PROC_T4 FL_USER2
-#define PROC_T5 (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 (safe_level) {
- case 3:
- FL_SET(data, PROC_T3);
- break;
- case 4:
- FL_SET(data, PROC_T4);
- break;
- case 5:
- FL_SET(data, PROC_T5);
- break;
- }
- }
-}
-
-static void
-proc_set_safe_level(data)
- VALUE data;
-{
- if (OBJ_TAINTED(data)) {
- switch (RBASIC(data)->flags & PROC_TMASK) {
- case PROC_T3:
- safe_level = 3;
- break;
- case PROC_T4:
- safe_level = 4;
- break;
- case PROC_T5:
- safe_level = 5;
- break;
- }
- }
-}
-
-static VALUE
-proc_s_new(klass)
- VALUE klass;
-{
- volatile VALUE proc;
- struct BLOCK *data;
-
- if (!rb_iterator_p() && !rb_f_iterator_p()) {
- rb_raise(rb_eArgError, "tried to create Procedure-Object out of iterator");
- }
-
- proc = Data_Make_Struct(klass, struct BLOCK, blk_mark, blk_free, data);
- *data = *ruby_block;
-
- data->orig_thread = rb_thread_current();
- data->iter = data->prev?Qtrue:Qfalse;
- data->tag = 0; /* should not point into stack */
- frame_dup(&data->frame);
- if (data->iter) {
- blk_copy_prev(data);
- }
- else {
- data->prev = 0;
- }
- data->flags |= BLOCK_DYNAMIC;
-
- scope_dup(data->scope);
- proc_save_safe_level(proc);
-
- return proc;
-}
-
-VALUE
-rb_f_lambda()
-{
- return proc_s_new(rb_cProc);
-}
-
-static int
-blk_orphan(data)
- struct BLOCK *data;
-{
- if (data->scope && data->scope != top_scope &&
- (data->scope->flag & SCOPE_NOSTACK)) {
- return 1;
- }
- if (data->orig_thread != rb_thread_current()) {
- return 1;
- }
- return 0;
-}
-
-static VALUE
-proc_call(proc, args)
- VALUE proc, args; /* OK */
-{
- struct BLOCK * volatile old_block;
- struct BLOCK _block;
- struct BLOCK *data;
- volatile VALUE result = Qnil;
- int state;
- volatile int orphan;
- volatile int safe = safe_level;
-
- Data_Get_Struct(proc, struct BLOCK, data);
- orphan = blk_orphan(data);
-
- /* PUSH BLOCK from data */
- old_block = ruby_block;
- _block = *data;
- ruby_block = &_block;
- PUSH_ITER(ITER_CUR);
- ruby_frame->iter = ITER_CUR;
-
- if (TYPE(args) == T_ARRAY) {
- switch (RARRAY(args)->len) {
- case 0:
- args = Qnil;
- break;
- case 1:
- args = RARRAY(args)->ptr[0];
- break;
- }
- }
-
- if (orphan) {/* orphan procedure */
- if (rb_iterator_p()) {
- ruby_block->frame.iter = ITER_CUR;
- }
- else {
- ruby_block->frame.iter = ITER_NOT;
- }
- }
-
- PUSH_TAG(PROT_NONE);
- _block.tag = prot_tag;
- state = EXEC_TAG();
- if (state == 0) {
- proc_set_safe_level(proc);
- result = rb_yield_0(args, 0, 0, Qtrue);
- }
- POP_TAG();
-
- POP_ITER();
- if (ruby_block->tag->dst == state) {
- state &= TAG_MASK;
- }
- ruby_block = old_block;
- safe_level = safe;
-
- if (state) {
- if (orphan) {/* orphan procedure */
- switch (state) {
- case TAG_BREAK:
- rb_raise(rb_eLocalJumpError, "break from proc-closure");
- break;
- case TAG_RETRY:
- rb_raise(rb_eLocalJumpError, "retry from proc-closure");
- break;
- case TAG_RETURN:
- rb_raise(rb_eLocalJumpError, "return from proc-closure");
- break;
- }
- }
- JUMP_TAG(state);
- }
- return result;
-}
-
-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 FIX2INT(-1);
- switch (nd_type(data->var)) {
- default:
- return INT2FIX(-2);
- 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
-block_pass(self, node)
- VALUE self;
- NODE *node;
-{
- VALUE block = rb_eval(self, node->nd_body);
- struct BLOCK * volatile old_block;
- struct BLOCK _block;
- struct BLOCK *data;
- volatile VALUE result = Qnil;
- int state;
- volatile int orphan;
- volatile int safe = safe_level;
-
- if (NIL_P(block)) {
- return rb_eval(self, node->nd_iter);
- }
- 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)));
- }
-
- Data_Get_Struct(block, struct BLOCK, data);
- orphan = blk_orphan(data);
-
- /* 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);
- _block.tag = prot_tag;
- state = EXEC_TAG();
- if (state == 0) {
- proc_set_safe_level(block);
- result = rb_eval(self, node->nd_iter);
- }
- POP_TAG();
- POP_ITER();
- if (_block.tag->dst == state) {
- state &= TAG_MASK;
- orphan = 2;
- }
- ruby_block = old_block;
- safe_level = safe;
-
- if (state) {
- if (orphan == 2) {/* escape from orphan procedure */
- switch (state) {
- case TAG_BREAK:
- rb_raise(rb_eLocalJumpError, "break from proc-closure");
- break;
- case TAG_RETRY:
- rb_raise(rb_eLocalJumpError, "retry from proc-closure");
- break;
- case TAG_RETURN:
- rb_raise(rb_eLocalJumpError, "return from proc-closure");
- break;
- }
- }
- JUMP_TAG(state);
- }
- return result;
-}
-
-struct METHOD {
- VALUE klass, oklass;
- VALUE recv;
- ID id, oid;
- NODE *body;
-};
-
-static void
-bm_mark(data)
- struct METHOD *data;
-{
- rb_gc_mark(data->oklass);
- rb_gc_mark(data->klass);
- rb_gc_mark(data->recv);
- rb_gc_mark(data->body);
-}
-
-static VALUE
-rb_obj_method(obj, vid)
- VALUE obj;
- VALUE vid;
-{
- VALUE method;
- VALUE klass = CLASS_OF(obj);
- ID id;
- NODE *body;
- int noex;
- struct METHOD *data;
-
- id = rb_to_id(vid);
-
- again:
- if ((body = rb_get_method_body(&klass, &id, &noex)) == 0) {
- return rb_undefined(obj, rb_to_id(vid), 0, 0, 0);
- }
-
- if (nd_type(body) == NODE_ZSUPER) {
- klass = RCLASS(klass)->super;
- goto again;
- }
-
- method = Data_Make_Struct(rb_cMethod, struct METHOD, bm_mark, free, data);
- data->klass = klass;
- data->recv = obj;
- data->id = id;
- data->body = body;
- data->oklass = CLASS_OF(obj);
- data->oid = rb_to_id(vid);
- if (OBJ_TAINTED(obj)) {
- OBJ_TAINT(method);
- }
-
- return method;
-}
-
-static VALUE
-method_call(argc, argv, method)
- int argc;
- VALUE *argv;
- VALUE method;
-{
- VALUE result;
- struct METHOD *data;
- int state;
- volatile int safe = safe_level;
-
- Data_Get_Struct(method, struct METHOD, data);
- PUSH_ITER(rb_iterator_p()?ITER_PRE:ITER_NOT);
- PUSH_TAG(PROT_NONE);
- if (OBJ_TAINTED(data->recv) || OBJ_TAINTED(method)) {
- OBJ_TAINT(method);
- if (safe_level < 4) 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();
- safe_level = safe;
- if (state) JUMP_TAG(state);
- return result;
-}
-
-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_rest) n = -n-1;
- return INT2FIX(n);
- }
-}
-
-static VALUE
-method_inspect(method)
- VALUE method;
-{
- struct METHOD *data;
- VALUE str;
- const char *s;
-
- Data_Get_Struct(method, struct METHOD, data);
- str = rb_str_new2("#<");
- s = rb_class2name(CLASS_OF(method));
- rb_str_cat(str, s, strlen(s));
- rb_str_cat(str, ": ", 2);
- s = rb_class2name(data->oklass);
- rb_str_cat(str, s, strlen(s));
- rb_str_cat(str, "#", 1);
- s = rb_id2name(data->oid);
- rb_str_cat(str, s, strlen(s));
- rb_str_cat(str, ">", 1);
-
- 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
-mcall(args, method)
- VALUE args, method;
-{
- if (TYPE(args) == T_ARRAY) {
- return method_call(RARRAY(args)->len, RARRAY(args)->ptr, method);
- }
- return method_call(1, &args, method);
-}
-
-static VALUE
-method_proc(method)
- VALUE method;
-{
- return rb_iterate(mproc, 0, mcall, method);
-}
-
-void
-Init_Proc()
-{
- rb_eLocalJumpError = rb_define_class("LocalJumpError", rb_eStandardError);
- rb_eSysStackError = rb_define_class("SystemStackError", rb_eStandardError);
-
- rb_cProc = rb_define_class("Proc", rb_cObject);
- rb_define_singleton_method(rb_cProc, "new", proc_s_new, 0);
-
- rb_define_method(rb_cProc, "call", proc_call, -2);
- rb_define_method(rb_cProc, "arity", proc_arity, 0);
- rb_define_method(rb_cProc, "[]", proc_call, -2);
- 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), "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), "new");
- 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_mKernel, "method", rb_obj_method, 1);
-}
-
-static VALUE rb_eThreadError;
-
-int rb_thread_pending = 0;
-
-VALUE rb_cThread;
-
-extern VALUE rb_last_status;
-
-enum thread_status {
- THREAD_RUNNABLE,
- THREAD_STOPPED,
- THREAD_TO_KILL,
- THREAD_KILLED,
-};
-
-#define WAIT_FD (1<<0)
-#define WAIT_TIME (1<<1)
-#define WAIT_JOIN (1<<2)
-
-/* +infty, for this purpose */
-#define DELAY_INFTY 1E30
-
-typedef struct thread * 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;
-
- VALUE trace;
- int flags; /* misc. states (vmode/rb_trap_immediate/raised) */
-
- char *file;
- int line;
-
- VALUE errinfo;
- VALUE last_status;
- VALUE last_line;
- VALUE last_match;
-
- int safe;
-
- enum thread_status status;
- int wait_for;
- int fd;
- double delay;
- thread_t join;
-
- int abort;
- int priority;
-
- st_table *locals;
-
- VALUE thread;
-};
-
-#define THREAD_RAISED 0x200
-
-static thread_t curr_thread = 0;
-static int num_waiting_on_fd = 0;
-static int num_waiting_on_timer = 0;
-static int num_waiting_on_join = 0;
-
-#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)
-
-/* 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;
-}
-
-static thread_t main_thread;
-
-#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)
- 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(th->scope);
- rb_gc_mark(th->dyna_vars);
- rb_gc_mark(th->errinfo);
- rb_gc_mark(th->last_line);
- rb_gc_mark(th->last_match);
- rb_gc_mark(th->trace);
- 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()
-{
- thread_t th;
-
- if (!curr_thread) return;
- FOREACH_THREAD(th) {
- rb_gc_mark(th->thread);
- } END_FOREACH(th);
-}
-
-static void
-thread_free(th)
- 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 != main_thread) free(th);
-}
-
-static thread_t
-rb_thread_check(data)
- VALUE data;
-{
- if (TYPE(data) != T_DATA || RDATA(data)->dfree != thread_free) {
- rb_raise(rb_eTypeError, "wrong argument type %s (expected Thread)",
- rb_class2name(CLASS_OF(data)));
- }
- return (thread_t)RDATA(data)->data;
-}
-
-static void
-rb_thread_save_context(th)
- thread_t th;
-{
- VALUE v;
-
- int len = stack_length();
- th->stk_len = 0;
- th->stk_pos = (rb_gc_stack_start<(VALUE*)&v)?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->dyna_vars = ruby_dyna_vars;
- th->block = ruby_block;
- th->flags = scope_vmode | (rb_trap_immediate<<8);
- th->iter = ruby_iter;
- th->tag = prot_tag;
- th->errinfo = ruby_errinfo;
- th->last_status = rb_last_status;
- th->last_line = rb_lastline_get();
- th->last_match = rb_backref_get();
- th->safe = safe_level;
-
- th->trace = trace_func;
- th->file = ruby_sourcefile;
- th->line = ruby_sourceline;
-}
-
-static void rb_thread_restore_context _((thread_t,int));
-
-static void
-stack_extend(th, exit)
- thread_t th;
- int exit;
-{
- VALUE space[1024];
-
- memset(space, 0, 1); /* prevent array from optimization */
- rb_thread_restore_context(th, exit);
-}
-
-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 0
-#define RESTORE_FATAL 1
-#define RESTORE_INTERRUPT 2
-#define RESTORE_TRAP 3
-#define RESTORE_RAISE 4
-#define RESTORE_SIGNAL 5
-
-static void
-rb_thread_restore_context(th, exit)
- thread_t th;
- int exit;
-{
- VALUE v;
- static thread_t tmp;
- static int ex;
-
- 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_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;
- ruby_errinfo = th->errinfo;
- rb_last_status = th->last_status;
- safe_level = th->safe;
-
- trace_func = th->trace;
- 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);
-
- rb_lastline_set(tmp->last_line);
- rb_backref_set(tmp->last_match);
-
- switch (ex) {
- 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_SIGNAL:
- rb_raise(rb_eSignal, "SIG%s", th_signm);
- 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_NORMAL:
- default:
- longjmp(tmp->context, 1);
- }
-}
-
-static void
-rb_thread_ready(th)
- thread_t th;
-{
- /* The thread is no longer waiting on anything */
- if (th->wait_for & WAIT_FD) {
- num_waiting_on_fd--;
- }
- if (th->wait_for & WAIT_TIME) {
- num_waiting_on_timer--;
- }
- if (th->wait_for & WAIT_JOIN) {
- num_waiting_on_join--;
- }
- th->wait_for = 0;
- th->status = THREAD_RUNNABLE;
-}
-
-static void
-rb_thread_remove()
-{
- rb_thread_ready(curr_thread);
- curr_thread->status = THREAD_KILLED;
- curr_thread->prev->next = curr_thread->next;
- curr_thread->next->prev = curr_thread->prev;
-}
-
-static int
-rb_thread_dead(th)
- thread_t th;
-{
- return th->status == THREAD_KILLED;
-}
-
-void
-rb_thread_fd_close(fd)
- int fd;
-{
- thread_t th;
-
- FOREACH_THREAD(th) {
- if ((th->wait_for & WAIT_FD) && th->fd == fd) {
- th_raise_argc = 1;
- th_raise_argv[0] = rb_exc_new2(rb_eIOError, "stream closed");
- th_raise_file = ruby_sourcefile;
- th_raise_line = ruby_sourceline;
- curr_thread = th;
- rb_thread_ready(th);
- rb_thread_restore_context(curr_thread, RESTORE_RAISE);
- }
- }
- END_FOREACH(th);
-}
-
-static void
-rb_thread_deadlock()
-{
-#if 1
- 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);
-#else
- static int invoked = 0;
-
- if (invoked) return;
- invoked = 1;
- rb_prohibit_interrupt = 1;
- ruby_errinfo = rb_exc_new2(rb_eFatal, "Thread: deadlock");
- set_backtrace(ruby_errinfo, make_backtrace());
- rb_abort();
-#endif
-}
-
-void
-rb_thread_schedule()
-{
- thread_t next; /* OK */
- thread_t th;
- thread_t curr;
-
- select_err:
- 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;
- }
-
- FOREACH_THREAD_FROM(curr, th) {
- if (th->status != THREAD_STOPPED && th->status != THREAD_KILLED) {
- if (!next || next->priority < th->priority)
- next = th;
- }
- }
- END_FOREACH_FROM(curr, th);
-
- if (num_waiting_on_join) {
- FOREACH_THREAD_FROM(curr, th) {
- if ((th->wait_for&WAIT_JOIN) && rb_thread_dead(th->join)) {
- th->join = 0;
- th->wait_for &= ~WAIT_JOIN;
- th->status = THREAD_RUNNABLE;
- num_waiting_on_join--;
- if (!next || next->priority < th->priority)
- next = th;
- }
- }
- END_FOREACH_FROM(curr, th);
- }
-
- if (num_waiting_on_fd > 0 || num_waiting_on_timer > 0) {
- fd_set readfds;
- struct timeval delay_tv, *delay_ptr;
- double delay, now; /* OK */
- int n, max;
-
- do {
- max = 0;
- FD_ZERO(&readfds);
- if (num_waiting_on_fd > 0) {
- FOREACH_THREAD_FROM(curr, th) {
- if (th->wait_for & WAIT_FD) {
- FD_SET(th->fd, &readfds);
- if (th->fd > max) max = th->fd;
- }
- }
- END_FOREACH_FROM(curr, th);
- }
-
- delay = DELAY_INFTY;
- if (num_waiting_on_timer > 0) {
- now = timeofday();
- FOREACH_THREAD_FROM(curr, th) {
- if (th->wait_for & WAIT_TIME) {
- if (th->delay <= now) {
- th->delay = 0.0;
- th->wait_for &= ~WAIT_TIME;
- th->status = THREAD_RUNNABLE;
- num_waiting_on_timer--;
- next = th;
- } else if (th->delay < delay) {
- delay = th->delay;
- }
- }
- }
- END_FOREACH_FROM(curr, th);
- }
- /* Do the select if needed */
- if (num_waiting_on_fd > 0 || !next) {
- /* Convert delay to a timeval */
- /* If a thread is runnable, just poll */
- if (next) {
- delay_tv.tv_sec = 0;
- delay_tv.tv_usec = 0;
- delay_ptr = &delay_tv;
- }
- else if (delay == DELAY_INFTY) {
- delay_ptr = 0;
- }
- else {
- delay -= now;
- delay_tv.tv_sec = (unsigned int)delay;
- delay_tv.tv_usec = (long)((delay-(double)delay_tv.tv_sec)*1e6);
- delay_ptr = &delay_tv;
- }
-
- n = select(max+1, &readfds, 0, 0, delay_ptr);
- if (n < 0) {
- if (rb_trap_pending) rb_trap_exec();
- switch (errno) {
- case EBADF:
- case ENOMEM:
- n = 0;
- break;
- default:
- goto select_err;
- }
- }
- if (n > 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 &= ~WAIT_FD;
- num_waiting_on_fd--;
- if (!next || next->priority < th->priority)
- next = th; /* Found one. */
- }
- }
- 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. */
- } while (!next && delay != DELAY_INFTY);
- }
-
- if (!next) {
- curr_thread->file = ruby_sourcefile;
- curr_thread->line = ruby_sourceline;
- FOREACH_THREAD_FROM(curr, th) {
- fprintf(stderr, "%s:%d:deadlock 0x%lx: %d:%d %s\n",
- th->file, th->line, th->thread, th->status,
- th->wait_for, th==main_thread?"(main)":"");
- if (th->status == THREAD_STOPPED) {
- next = th;
- }
- }
- END_FOREACH_FROM(curr, th);
- /* raise fatal error to main thread */
- rb_thread_deadlock();
- rb_thread_ready(next);
- next->status = THREAD_TO_KILL;
- }
- if (next->status == THREAD_RUNNABLE && next == curr_thread) {
- return;
- }
-
- /* context switch */
- if (curr == curr_thread) {
- rb_thread_save_context(curr);
- if (setjmp(curr->context)) {
- return;
- }
- }
-
- curr_thread = next;
- if (next->status == THREAD_TO_KILL) {
- /* 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 (curr_thread == curr_thread->next) return;
-
- curr_thread->status = THREAD_STOPPED;
- curr_thread->fd = fd;
- num_waiting_on_fd++;
- curr_thread->wait_for |= WAIT_FD;
- rb_thread_schedule();
-}
-
-int
-rb_thread_fd_writable(fd)
- int fd;
-{
- struct timeval zero;
- fd_set fds;
-
- if (curr_thread == curr_thread->next) return 1;
-
- zero.tv_sec = zero.tv_usec = 0;
- for (;;) {
- FD_ZERO(&fds);
- FD_SET(fd, &fds);
- if (select(fd+1, 0, &fds, 0, &zero) == 1) return 0;
- rb_thread_schedule();
- }
-}
-
-void
-rb_thread_wait_for(time)
- struct timeval time;
-{
- double date;
-
- if (curr_thread == curr_thread->next) {
- 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;
-
-#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;
- num_waiting_on_timer++;
- 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;
- struct timeval zero;
- fd_set r, *rp, w, *wp, x, *xp;
- 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 (curr_thread == curr_thread->next) { /* no other thread */
-#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 && errno == EINTR) {
- if (timeout) {
- double d = timeofday() - limit;
-
- tv.tv_sec = (unsigned int)d;
- tv.tv_usec = (long)((d-(double)tv.tv_sec)*1e6);
- }
- continue;
- }
- return n;
- }
-#else
- for (;;) {
- TRAP_BEG;
- n = select(max, read, write, except, timeout);
- TRAP_END;
- if (n < 0 && errno == EINTR) {
- continue;
- }
- return n;
- }
-#endif
-
- }
-
- for (;;) {
- zero.tv_sec = zero.tv_usec = 0;
- if (read) {rp = &r; r = *read;} else {rp = 0;}
- if (write) {wp = &w; w = *write;} else {wp = 0;}
- if (except) {xp = &x; x = *except;} else {xp = 0;}
- n = select(max, rp, wp, xp, &zero);
- if (n > 0) {
- /* write back fds */
- if (read) {*read = r;}
- if (write) {*write = w;}
- if (except) {*except = x;}
- return n;
- }
- if (n < 0 && errno != EINTR) {
- return n;
- }
- if (timeout) {
- if (timeout->tv_sec == 0 && timeout->tv_usec == 0) return 0;
- if (limit <= timeofday()) return 0;
- }
-
- rb_thread_schedule();
- CHECK_INTS;
- }
-}
-
-static VALUE
-rb_thread_join(thread)
- VALUE thread;
-{
- thread_t th = rb_thread_check(thread);
-
- if (!rb_thread_dead(th)) {
- if (th == curr_thread)
- rb_raise(rb_eThreadError, "recursive join");
- if ((th->wait_for & WAIT_JOIN) && th->join == curr_thread)
- rb_raise(rb_eThreadError, "Thread#join: deadlock - mutual join");
- curr_thread->status = THREAD_STOPPED;
- curr_thread->join = th;
- num_waiting_on_join++;
- curr_thread->wait_for |= WAIT_JOIN;
- rb_thread_schedule();
- }
-
- 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;
-}
-
-static VALUE
-rb_thread_s_join(dmy, thread) /* will be removed in 1.4 */
- VALUE dmy;
- VALUE thread;
-{
- rb_warn("Thread::join is obsolete; use Thread#join instead");
- return rb_thread_join(thread);
-}
-
-VALUE
-rb_thread_current()
-{
- return curr_thread->thread;
-}
-
-VALUE
-rb_thread_main()
-{
- return main_thread->thread;
-}
-
-VALUE
-rb_thread_wakeup(thread)
- VALUE thread;
-{
- 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;
-{
- thread_t th = rb_thread_check(thread);
-
- 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->status = THREAD_TO_KILL;
- rb_thread_schedule();
- return Qnil; /* not reached */
-}
-
-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()
-{
- rb_thread_critical = 0;
- if (curr_thread == curr_thread->next) {
- rb_raise(rb_eThreadError, "stopping only thread");
- }
- curr_thread->status = THREAD_STOPPED;
- rb_thread_schedule();
-
- return Qnil;
-}
-
-struct timeval rb_time_timeval();
-
-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)));
-}
-
-void
-rb_thread_sleep_forever()
-{
- if (curr_thread == curr_thread->next) {
- TRAP_BEG;
- sleep((32767L<<16)+32767);
- TRAP_END;
- return;
- }
-
- num_waiting_on_timer++;
- 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;
-{
- thread_t th = rb_thread_check(thread);;
-
- if (safe_level >= 4 && th != curr_thread) {
- rb_raise(rb_eSecurityError, "Insecure: can't get priority");
- }
- return INT2NUM(th->priority);
-}
-
-static VALUE
-rb_thread_priority_set(thread, prio)
- VALUE thread, prio;
-{
- thread_t th;
-
- rb_secure(4);
- th = rb_thread_check(thread);
-
- th->priority = NUM2INT(prio);
- return thread;
-}
-
-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;
-{
- thread_t th = rb_thread_check(thread);
-
- return th->abort?Qtrue:Qfalse;
-}
-
-static VALUE
-rb_thread_abort_exc_set(thread, val)
- VALUE thread, val;
-{
- thread_t th = rb_thread_check(thread);
-
- rb_secure(4);
- th->abort = RTEST(val);
- return val;
-}
-
-#define THREAD_ALLOC(th) do {\
- th = ALLOC(struct thread);\
-\
- th->status = 0;\
- th->result = 0;\
- th->errinfo = Qnil;\
-\
- th->stk_ptr = 0;\
- th->stk_len = 0;\
- th->stk_max = 0;\
- th->wait_for = 0;\
- th->fd = 0;\
- th->delay = 0.0;\
- th->join = 0;\
-\
- th->frame = 0;\
- th->scope = 0;\
- th->klass = 0;\
- th->wrapper = 0;\
- th->dyna_vars = 0;\
- th->block = 0;\
- th->iter = 0;\
- th->tag = 0;\
- th->errinfo = 0;\
- th->last_status = 0;\
- th->last_line = 0;\
- th->last_match = 0;\
- th->abort = 0;\
- th->priority = 0;\
- th->locals = 0;\
-} while(0)
-
-static thread_t
-rb_thread_alloc(klass)
- VALUE klass;
-{
- thread_t th;
-
- THREAD_ALLOC(th);
- th->thread = Data_Wrap_Struct(klass, thread_mark, thread_free, th);
-
- if (curr_thread) {
- th->prev = curr_thread;
- curr_thread->next->prev = th;
- th->next = curr_thread->next;
- curr_thread->next = th;
- th->priority = curr_thread->priority;
- }
- else {
- curr_thread = th->prev = th->next = th;
- th->status = THREAD_RUNNABLE;
- }
-
- return th;
-}
-
-#if defined(HAVE_SETITIMER) && !defined(__BOW__)
-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
-
-static VALUE rb_thread_raise _((int, VALUE*, VALUE));
-
-#define SCOPE_SHARED FL_USER1
-
-#if defined(HAVE_SETITIMER) && !defined(__BOW__)
-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 = 50000;
- 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_create_0(fn, arg, klass)
- VALUE (*fn)();
- void *arg;
- VALUE klass;
-{
- thread_t th = rb_thread_alloc(klass);
- volatile VALUE thread = th->thread;
- enum thread_status status;
- int state;
-
-#if defined(HAVE_SETITIMER) && !defined(__BOW__)
- 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
-
- FL_SET(ruby_scope, SCOPE_SHARED);
- rb_thread_save_context(curr_thread);
- if (setjmp(curr_thread->context)) {
- return thread;
- }
-
- PUSH_TAG(PROT_THREAD);
- if ((state = EXEC_TAG()) == 0) {
- rb_thread_save_context(th);
- if (setjmp(th->context) == 0) {
- curr_thread = th;
- th->result = (*fn)(arg, th);
- }
- }
- POP_TAG();
- status = th->status;
- rb_thread_remove();
- 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)) {
- /* delegate exception to main_thread */
- rb_thread_raise(1, &ruby_errinfo, main_thread->thread);
- }
- else if (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->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_create_0(fn, arg, rb_cThread);
-}
-
-int
-rb_thread_scope_shared_p()
-{
- return FL_TEST(ruby_scope, SCOPE_SHARED);
-}
-
-static VALUE
-rb_thread_yield(arg, th)
- int arg;
- thread_t th;
-{
- scope_dup(ruby_block->scope);
- return rb_yield_0(th->thread, 0, 0, Qfalse);
-}
-
-static VALUE
-rb_thread_start(klass)
- VALUE klass;
-{
- if (!rb_iterator_p()) {
- rb_raise(rb_eThreadError, "must be called as iterator");
- }
- return rb_thread_create_0(rb_thread_yield, 0, klass);
-}
-
-static VALUE
-rb_thread_value(thread)
- VALUE thread;
-{
- thread_t th = rb_thread_check(thread);
-
- rb_thread_join(thread);
-
- return th->result;
-}
-
-static VALUE
-rb_thread_status(thread)
- VALUE thread;
-{
- thread_t th = rb_thread_check(thread);
-
- if (rb_thread_dead(th)) {
- if (NIL_P(th->errinfo) && (th->flags & THREAD_RAISED))
- return Qfalse;
- return Qnil;
- }
-
- return Qtrue;
-}
-
-static VALUE
-rb_thread_stop_p(thread)
- VALUE thread;
-{
- 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()
-{
- /* wait other threads to terminate */
- while (curr_thread != curr_thread->next) {
- rb_thread_schedule();
- }
-}
-
-static void
-rb_thread_cleanup()
-{
- thread_t th;
-
- if (curr_thread != curr_thread->next->prev) {
- curr_thread = curr_thread->prev;
- }
-
- FOREACH_THREAD(th) {
- if (th != curr_thread && th->status != THREAD_KILLED) {
- rb_thread_ready(th);
- th->status = THREAD_TO_KILL;
- }
- }
- 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();
- }
- rb_thread_save_context(curr_thread);
- if (setjmp(curr_thread->context)) {
- 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);
- rb_thread_save_context(curr_thread);
- if (setjmp(curr_thread->context)) {
- 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;
-{
- 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);
- rb_thread_save_context(curr_thread);
- if (setjmp(curr_thread->context)) {
- return;
- }
- th_cmd = cmd;
- th_sig = sig;
- curr_thread = main_thread;
- rb_thread_restore_context(curr_thread, RESTORE_TRAP);
-}
-
-static VALUE
-rb_thread_raise(argc, argv, thread)
- int argc;
- VALUE *argv;
- VALUE thread;
-{
- thread_t th = rb_thread_check(thread);
-
- if (rb_thread_dead(th)) return thread;
- if (curr_thread == th) {
- rb_f_raise(argc, argv);
- }
-
- if (curr_thread->status != THREAD_KILLED)
- rb_thread_save_context(curr_thread);
- if (setjmp(curr_thread->context)) {
- return 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 st_table *loading_tbl;
-
-static int
-rb_thread_loading(feature)
- const char *feature;
-{
- if (!loading_tbl) {
- loading_tbl = st_init_strtable();
- }
- if (!rb_provided(feature)) {
- st_insert(loading_tbl, feature, 0);
- return Qfalse; /* need to load */
- }
- while (st_lookup(loading_tbl, feature, 0)) {
- CHECK_INTS;
- rb_thread_schedule();
- }
- return Qtrue;
-}
-
-static void
-rb_thread_loading_done(feature)
- const char *feature;
-{
- if (loading_tbl) {
- st_delete(loading_tbl, &feature, 0);
- }
-}
-
-VALUE
-rb_thread_local_aref(thread, id)
- VALUE thread;
- ID id;
-{
- thread_t th;
- VALUE val;
-
- th = rb_thread_check(thread);
- if (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;
-{
- thread_t th = rb_thread_check(thread);
-
- if (safe_level >= 4 && th != curr_thread) {
- rb_raise(rb_eSecurityError, "Insecure: can't modify 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;
-{
- 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 VALUE rb_cContinuation;
-
-static VALUE
-rb_callcc(self)
- VALUE self;
-{
- volatile VALUE cont;
- thread_t th;
- struct tag *tag;
-
- THREAD_ALLOC(th);
- th->thread = cont = Data_Wrap_Struct(rb_cContinuation, thread_mark,
- thread_free, th);
-
- FL_SET(ruby_scope, SCOPE_DONT_RECYCLE);
- for (tag=prot_tag; tag; tag=tag->prev) {
- scope_dup(tag->scope);
- }
- rb_thread_save_context(th);
- if (setjmp(th->context)) {
- return th->result;
- }
- else {
- return rb_yield(th->thread);
- }
-}
-
-static VALUE
-rb_continuation_call(argc, argv, cont)
- int argc;
- VALUE *argv;
- VALUE cont;
-{
- thread_t th = rb_thread_check(cont);
-
- 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;
-}
-
-void
-Init_Thread()
-{
- rb_eThreadError = rb_define_class("ThreadError", rb_eStandardError);
- rb_cThread = rb_define_class("Thread", rb_cObject);
-
- rb_define_singleton_method(rb_cThread, "new", rb_thread_start, 0);
- rb_define_singleton_method(rb_cThread, "start", rb_thread_start, 0);
- rb_define_singleton_method(rb_cThread, "fork", rb_thread_start, 0);
-
- 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, "join", rb_thread_s_join, 1);
- 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, "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, "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_status, 0);
- rb_define_method(rb_cThread, "stop?", rb_thread_stop_p, 0);
- rb_define_method(rb_cThread, "raise", rb_thread_raise, -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, "[]", rb_thread_aref, 1);
- rb_define_method(rb_cThread, "[]=", rb_thread_aset, 2);
- rb_define_method(rb_cThread, "key?", rb_thread_key_p, 1);
-
- /* allocate main thread */
- main_thread = rb_thread_alloc(rb_cThread);
-
- rb_cContinuation = rb_define_class("Continuation", rb_cObject);
- rb_undef_method(CLASS_OF(rb_cContinuation), "new");
- rb_define_method(rb_cContinuation, "call", rb_continuation_call, -1);
- rb_define_global_function("callcc", rb_callcc, 0);
-}
-
-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, Qfalse);
- }
- 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_f_catch(0, FIX2INT(tag));
-}
-
-VALUE
-rb_catch(tag, proc, data)
- const char *tag;
- VALUE (*proc)();
- VALUE data;
-{
- return rb_iterate(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_raise(rb_eNameError, "uncaught throw `%s'", rb_id2name(t));
- }
- return_value(value);
- rb_trap_restore_mask();
- JUMP_TAG(TAG_THROW);
- /* not reached */
-}
-
-void
-rb_throw(tag, val)
- const char *tag;
- VALUE val;
-{
- VALUE argv[2];
- ID t = rb_intern(tag);
-
- argv[0] = FIX2INT(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/Setup b/ext/Setup
deleted file mode 100644
index 830a5095ca..0000000000
--- a/ext/Setup
+++ /dev/null
@@ -1,15 +0,0 @@
-#option nodynamic
-
-#GD
-#curses
-#dbm
-#etc
-#fcntl
-#kconv
-#md5
-#pty
-#sdbm
-#socket
-#tkutil
-#tcltklib
-#gtk
diff --git a/ext/Setup.dj b/ext/Setup.dj
deleted file mode 100644
index cf25c07e6b..0000000000
--- a/ext/Setup.dj
+++ /dev/null
@@ -1,14 +0,0 @@
-option nodynamic
-
-#GD
-#curses
-dbm
-gdbm
-#etc
-fcntl
-nkf
-marshal
-md5
-sdbm
-#socket
-#tkutil
diff --git a/ext/Setup.emx b/ext/Setup.emx
deleted file mode 100644
index dbb4b7a61c..0000000000
--- a/ext/Setup.emx
+++ /dev/null
@@ -1,16 +0,0 @@
-option nodynamic
-
-#Win32API
-curses
-#dbm
-etc
-fcntl
-#gdbm
-md5
-nkf
-#pty
-#readline
-#sdbm
-socket
-#tcltklib
-#tk
diff --git a/ext/Setup.nt b/ext/Setup.nt
deleted file mode 100644
index cd7969bb73..0000000000
--- a/ext/Setup.nt
+++ /dev/null
@@ -1,19 +0,0 @@
-#option nodynamic
-
-#GD
-Win32API
-#curses
-#dbm
-#etc
-fcntl
-#gdbm
-#gtk
-marshal
-md5
-nkf
-#pty
-#readline
-sdbm
-socket
-#tcltklib
-#tk
diff --git a/ext/Setup.x68 b/ext/Setup.x68
deleted file mode 100644
index 25adea2035..0000000000
--- a/ext/Setup.x68
+++ /dev/null
@@ -1,12 +0,0 @@
-option nodynamic
-
-#GD
-#curses
-dbm
-#etc
-fcntl
-kconv
-marshal
-md5
-#socket
-#tkutil
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 8efb3ddad6..0000000000
--- a/ext/Win32API/Win32API.c
+++ /dev/null
@@ -1,237 +0,0 @@
-/*
- Win32API - Ruby Win32 API Import Facility
-*/
-
-#ifndef _MSC_VER
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#include <stdio.h>
-#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;
- int i;
- int len;
- int ex;
-
- hdll = GetModuleHandle(RSTRING(dllname)->ptr);
- if (!hdll) {
- hdll = LoadLibrary(RSTRING(dllname)->ptr);
- if (!hdll)
- rb_raise(rb_eRuntimeError, "LoadLibrary: %s\n", RSTRING(dllname)->ptr);
- 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__", INT2NUM((int)hdll));
- rb_iv_set(self, "__dllname__", dllname);
- rb_iv_set(self, "__proc__", INT2NUM((int)hproc));
-
- a_import = rb_ary_new();
- ptr = RARRAY(import)->ptr;
- for (i = 0, len = RARRAY(import)->len; i < len; i++) {
- int c = *(char *)RSTRING(ptr[i])->ptr;
- switch (c) {
- 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;
- }
- }
- rb_iv_set(self, "__import__", a_import);
-
- 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;
-
- 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__)
- _asm {
- mov eax, lParam
- push eax
- }
-#elif defined(__CYGWIN32__) || defined(__MINGW32__)
- 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 {
- Check_Type(str, T_STRING);
- rb_str_modify(str);
- pParam = RSTRING(str)->ptr;
- }
-#if defined(_MSC_VER) || defined(__LCC__)
- _asm {
- mov eax, dword ptr pParam
- push eax
- }
-#elif defined(__CYGWIN32__) || defined(__MINGW32__)
- asm volatile ("pushl %0" :: "g" (pParam));
-#else
-#error
-#endif
- break;
- }
- }
-
- }
-
- 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;
- }
- 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");
-}
-
-void
-Init_win32api()
-{
- Init_Win32API();
-}
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 5af3243d96..0000000000
--- a/ext/Win32API/extconf.rb
+++ /dev/null
@@ -1,7 +0,0 @@
-case PLATFORM
-when /cygwin/,/mingw/
- $CFLAGS = "-fno-defer-pop"
- 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/curses/MANIFEST b/ext/curses/MANIFEST
deleted file mode 100644
index e1a25d962d..0000000000
--- a/ext/curses/MANIFEST
+++ /dev/null
@@ -1,7 +0,0 @@
-MANIFEST
-curses.c
-depend
-extconf.rb
-hello.rb
-rain.rb
-view.rb
diff --git a/ext/curses/curses.c b/ext/curses/curses.c
deleted file mode 100644
index 202a0f9244..0000000000
--- a/ext/curses/curses.c
+++ /dev/null
@@ -1,850 +0,0 @@
-/*
- * ext/curses/curses.c
- *
- * by MAEDA Shugo (ender@pic-internet.or.jp)
- * modified by Yukihiro Matsumoto (matz@netlab.co.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(_maxx)
-# define _maxx maxx
-# endif
-# if (defined(__bsdi__) || defined(__NetBSD__)) && !defined(_maxy)
-# define _maxy maxy
-# endif
-# if (defined(__bsdi__) || defined(__NetBSD__)) && !defined(_begx)
-# define _begx begx
-# endif
-# if (defined(__bsdi__) || defined(__NetBSD__)) && !defined(_begy)
-# define _begy begy
-# endif
-# endif
-#endif
-#endif
-
-#include "stdio.h"
-#include "ruby.h"
-#include "rubyio.h"
-
-static VALUE mCurses;
-static VALUE cWindow;
-
-VALUE rb_stdscr;
-
-struct windata {
- WINDOW *window;
-};
-
-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();\
-}
-
-#define CHECK(c) c
-
-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 Qnil;
-}
-
-/* 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 CHR2FIX(getch());
-}
-
-/* def getstr */
-static VALUE
-curses_getstr(obj)
- VALUE obj;
-{
- char rtn[1024]; /* This should be big enough.. I hope */
-
- rb_read_check(stdin);
- getstr(rtn);
- 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;
-{
-#ifdef HAVE_DELETELN
- deleteln();
-#endif
- return Qnil;
-}
-
-static VALUE
-curses_lines()
-{
- return INT2FIX(LINES);
-}
-
-static VALUE
-curses_cols()
-{
- return INT2FIX(COLS);
-}
-
-/*-------------------------- class Window --------------------------*/
-
-/* def new(lines, cols, top, left) */
-static VALUE
-window_s_new(class, lines, cols, top, left)
- VALUE class;
- VALUE lines;
- VALUE cols;
- VALUE top;
- VALUE left;
-{
- VALUE w;
- WINDOW *window;
- VALUE args[4];
-
- window = newwin(NUM2INT(lines), NUM2INT(cols), NUM2INT(top), NUM2INT(left));
- wclear(window);
- w = prep_window(class, window);
- args[0] = lines; args[1] = cols; args[2] = top; args[3] = left;
- rb_obj_call_init(w, 4, args);
-
- return w;
-}
-
-/* def subwin(lines, cols, top, left) */
-static VALUE
-window_subwin(obj, lines, cols, top, left)
- VALUE obj;
- VALUE lines;
- VALUE cols;
- VALUE top;
- VALUE left;
-{
- struct windata *winp;
- WINDOW *window;
- VALUE w;
- VALUE args[4];
-
- GetWINDOW(obj, winp);
- window = subwin(winp->window, NUM2INT(lines), NUM2INT(cols),
- NUM2INT(top), NUM2INT(left));
- w = prep_window(cWindow, window);
- args[0] = lines; args[1] = cols; args[2] = top; args[3] = left;
- rb_obj_call_init(w, 4, args);
-
- return w;
-}
-
-/* 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 box(vert, hor) */
-static VALUE
-window_box(obj, vert, hor)
- VALUE obj;
- VALUE vert;
- VALUE hor;
-{
- struct windata *winp;
-
- GetWINDOW(obj, winp);
- box(winp->window, NUM2CHR(vert), NUM2CHR(hor));
-
- 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 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 CHR2FIX(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);
- wgetstr(winp->window, rtn);
- 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;
-{
-#ifdef HAVE_WDELETELN
- struct windata *winp;
-
- GetWINDOW(obj, winp);
- wdeleteln(winp->window);
-#endif
- return Qnil;
-}
-
-/*------------------------- Initialization -------------------------*/
-void
-Init_curses()
-{
- mCurses = rb_define_module("Curses");
- 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, "lines", curses_lines, 0);
- rb_define_module_function(mCurses, "cols", curses_cols, 0);
-
- 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, "box", window_box, 2);
- 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_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 e1bf24c435..0000000000
--- a/ext/curses/extconf.rb
+++ /dev/null
@@ -1,23 +0,0 @@
-require 'mkmf'
-
-make=false
-have_library("mytinfo", "tgetent") if /bow/ =~ 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_library("curses", "initscr")
- make=true
- end
-end
-
-if make
- for f in %w(isendwin ungetch beep doupdate flash deleteln wdeleteln)
- 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 a1915ce60d..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/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/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 2aeede2672..0000000000
--- a/ext/dbm/dbm.c
+++ /dev/null
@@ -1,584 +0,0 @@
-/************************************************
-
- dbm.c -
-
- $Author$
- $Date$
- created at: Mon Jan 24 15:59:52 JST 1994
-
- Copyright (C) 1995-1998 Yukihiro Matsumoto
-
-************************************************/
-
-#include "ruby.h"
-
-#ifdef HAVE_CDEFS_H
-# include <cdefs.h>
-#endif
-#include <ndbm.h>
-#include <fcntl.h>
-#include <errno.h>
-#ifdef USE_CWGUSI
-# include <sys/errno.h>
-#endif
-
-VALUE cDBM;
-
-struct dbmdata {
- int di_size;
- DBM *di_dbm;
-};
-
-static void
-closed_dbm()
-{
- rb_raise(rb_eRuntimeError, "closed DBM file");
-}
-
-#define GetDBM(obj, dbmp) {\
- Data_Get_Struct(obj, struct dbmdata, dbmp);\
- if (dbmp->di_dbm == 0) closed_dbm();\
-}
-
-static void
-free_dbm(dbmp)
- struct dbmdata *dbmp;
-{
- if (dbmp->di_dbm) dbm_close(dbmp->di_dbm);
- free(dbmp);
-}
-
-static VALUE
-fdbm_s_open(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- VALUE file, vmode;
- DBM *dbm;
- struct dbmdata *dbmp;
- int mode;
- VALUE obj;
-
- 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);
- }
- Check_SafeStr(file);
-
- dbm = 0;
- if (mode >= 0) {
- dbm = dbm_open(RSTRING(file)->ptr, O_RDWR|O_CREAT, mode);
- }
- if (!dbm) {
- mode = 0666;
- dbm = dbm_open(RSTRING(file)->ptr, O_RDWR, mode);
- }
- if (!dbm) {
- dbm = dbm_open(RSTRING(file)->ptr, O_RDONLY, mode);
- }
-
- if (!dbm) {
- if (mode == -1) return Qnil;
- rb_sys_fail(RSTRING(file)->ptr);
- }
-
- obj = Data_Make_Struct(klass,struct dbmdata,0,free_dbm,dbmp);
- dbmp->di_dbm = dbm;
- dbmp->di_size = -1;
- rb_obj_call_init(obj, argc, argv);
-
- return obj;
-}
-
-static VALUE
-fdbm_close(obj)
- VALUE obj;
-{
- struct dbmdata *dbmp;
-
- Data_Get_Struct(obj, struct dbmdata, dbmp);
- if (dbmp->di_dbm == 0) closed_dbm();
- dbm_close(dbmp->di_dbm);
- dbmp->di_dbm = 0;
-
- return Qnil;
-}
-
-static VALUE
-fdbm_fetch(obj, keystr)
- VALUE obj, keystr;
-{
- datum key, value;
- struct dbmdata *dbmp;
- DBM *dbm;
-
- Check_Type(keystr, T_STRING);
- 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) {
- return Qnil;
- }
- return rb_tainted_str_new(value.dptr, value.dsize);
-}
-
-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_delete(obj, keystr)
- VALUE obj, keystr;
-{
- datum key, value;
- struct dbmdata *dbmp;
- DBM *dbm;
-
- rb_secure(4);
- Check_Type(keystr, T_STRING);
- 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_iterator_p()) rb_yield(keystr);
- return Qnil;
- }
-
- if (dbm_delete(dbm, key)) {
- dbmp->di_size = -1;
- rb_raise(rb_eRuntimeError, "dbm_delete failed");
- }
- else if (dbmp->di_size >= 0) {
- dbmp->di_size--;
- }
- return obj;
-}
-
-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;
-
- key = dbm_firstkey(dbm);
- if (!key.dptr) return Qnil;
- val = dbm_fetch(dbm, key);
- dbm_delete(dbm, key);
-
- keystr = rb_tainted_str_new(key.dptr, key.dsize);
- valstr = rb_tainted_str_new(val.dptr, val.dsize);
- 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;
-
- rb_secure(4);
- 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);
- if (RTEST(rb_yield(rb_assoc_new(keystr, valstr)))) {
- if (dbm_delete(dbm, key)) {
- rb_raise(rb_eRuntimeError, "dbm_delete failed");
- }
- }
- }
- 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;
- for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
- if (dbm_delete(dbm, key)) {
- rb_raise(rb_eRuntimeError, "dbm_delete failed");
- }
- }
- 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 obj;
-}
-
-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;
-
- Data_Get_Struct(obj, struct dbmdata, 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_eRuntimeError, "dbm_store failed");
- }
-
- return valstr;
-}
-
-static VALUE
-fdbm_length(obj)
- VALUE obj;
-{
- datum key;
- struct dbmdata *dbmp;
- DBM *dbm;
- int i = 0;
-
- Data_Get_Struct(obj, struct dbmdata, 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;
-
- Data_Get_Struct(obj, struct dbmdata, 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;
-
- Check_Type(keystr, T_STRING);
- 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;
-
- Check_Type(valstr, T_STRING);
- 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;
-}
-
-void
-Init_dbm()
-{
- cDBM = rb_define_class("DBM", rb_cObject);
- rb_include_module(cDBM, rb_mEnumerable);
-
- rb_define_singleton_method(cDBM, "open", fdbm_s_open, -1);
- rb_define_singleton_method(cDBM, "new", fdbm_s_open, -1);
- rb_define_method(cDBM, "close", fdbm_close, 0);
- rb_define_method(cDBM, "[]", fdbm_fetch, 1);
- rb_define_method(cDBM, "[]=", fdbm_store, 2);
- rb_define_method(cDBM, "indexes", fdbm_indexes, -1);
- rb_define_method(cDBM, "indices", fdbm_indexes, -1);
- rb_define_method(cDBM, "length", fdbm_length, 0);
- rb_define_alias(cDBM, "size", "length");
- rb_define_method(cDBM, "empty?", fdbm_empty_p, 0);
- rb_define_method(cDBM, "each", fdbm_each_pair, 0);
- rb_define_method(cDBM, "each_value", fdbm_each_value, 0);
- rb_define_method(cDBM, "each_key", fdbm_each_key, 0);
- rb_define_method(cDBM, "each_pair", fdbm_each_pair, 0);
- rb_define_method(cDBM, "keys", fdbm_keys, 0);
- rb_define_method(cDBM, "values", fdbm_values, 0);
- rb_define_method(cDBM, "shift", fdbm_shift, 1);
- rb_define_method(cDBM, "delete", fdbm_delete, 1);
- rb_define_method(cDBM, "delete_if", fdbm_delete_if, 0);
- rb_define_method(cDBM, "clear", fdbm_clear, 0);
- rb_define_method(cDBM,"invert", fdbm_invert, 0);
- rb_define_method(cDBM,"update", fdbm_update, 1);
- rb_define_method(cDBM,"replace", fdbm_replace, 1);
-
- rb_define_method(cDBM, "include?", fdbm_has_key, 1);
- rb_define_method(cDBM, "has_key?", fdbm_has_key, 1);
- rb_define_method(cDBM, "has_value?", fdbm_has_value, 1);
- rb_define_method(cDBM, "key?", fdbm_has_key, 1);
- rb_define_method(cDBM, "value?", fdbm_has_value, 1);
-
- rb_define_method(cDBM, "to_a", fdbm_to_a, 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 55dadc2601..0000000000
--- a/ext/dbm/extconf.rb
+++ /dev/null
@@ -1,12 +0,0 @@
-require 'mkmf'
-
-dir_config("dbm")
-if have_library("gdbm", "dbm_open")
- gdbm = true
-end
-gdbm or have_library("db", "dbm_open") or have_library("dbm", "dbm_open")
-have_header("cdefs.h")
-if have_header("ndbm.h") and have_func("dbm_open")
- have_func("dbm_clearerr") unless gdbm
- create_makefile("dbm")
-end
diff --git a/ext/etc/MANIFEST b/ext/etc/MANIFEST
deleted file mode 100644
index 79fb1ff34c..0000000000
--- a/ext/etc/MANIFEST
+++ /dev/null
@@ -1,6 +0,0 @@
-MANIFEST
-etc.c
-etc.txt
-etc.txt.jp
-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 e5f69f9285..0000000000
--- a/ext/etc/etc.c
+++ /dev/null
@@ -1,271 +0,0 @@
-/************************************************
-
- etc.c -
-
- $Author$
- $Date$
- created at: Tue Mar 22 18:39:19 JST 1994
-
-************************************************/
-
-#include "ruby.h"
-
-#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;
-
- Check_Type(nam, T_STRING);
- 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_iterator_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;
-
- Check_Type(nam, T_STRING);
- 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_iterator_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 9801dc0e02..0000000000
--- a/ext/etc/etc.txt
+++ /dev/null
@@ -1,72 +0,0 @@
-.\" etc.doc - -*- 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.jp b/ext/etc/etc.txt.jp
deleted file mode 100644
index 8191f4886b..0000000000
--- a/ext/etc/etc.txt.jp
+++ /dev/null
@@ -1,72 +0,0 @@
-.\" etc.doc - -*- 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 6fe8810464..0000000000
--- a/ext/etc/extconf.rb
+++ /dev/null
@@ -1,31 +0,0 @@
-require 'mkmf'
-
-def etc_grep_header(field)
- f = open("conftest.c", "w")
- f.print <<EOF
-#include <pwd.h>
-EOF
- f.close
- begin
- if xsystem("#{CPP} | egrep #{field}")
- $defs.push(format("-D%s", field.upcase))
- end
- ensure
- system "rm -f conftest.c"
- 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 3e3ec3992e..0000000000
--- a/ext/extmk.rb.in
+++ /dev/null
@@ -1,680 +0,0 @@
-#! /usr/local/bin/ruby
-
-$".push 'mkmf.rb'
-
-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 = true
- ARGV.shift
-end
-
-SRC_EXT = ["c", "cc", "m", "cxx", "cpp", "C"]
-$extlist = []
-
-$includedir = "@includedir@".gsub(/\$\{prefix\}|\$\(prefix\)/,'@prefix@')
-
-$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("..")
-
-$:.push $top_srcdir
-$:.push $top_srcdir+"/lib"
-
-require 'find'
-
-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
-
-if RUBY_PLATFORM == "m68k-human"
- CFLAGS = "@CFLAGS@".gsub(/-c..-stack=[0-9]+ */, '')
-else
- CFLAGS = "@CFLAGS@"
-end
-LINK = "@CC@ -o conftest -I#$topdir -I#$top_srcdir #{CFLAGS} -I#$includedir @LDFLAGS@ %s %s conftest.c %s %s @LIBS@"
-CPP = "@CPP@ @CPPFLAGS@ -I#$topdir -I#$top_srcdir #{CFLAGS} -I#$includedir %s %s conftest.c"
-
-if /cygwin|mswin32|djgpp|mingw32|m68k-human|i386-os2_emx/i =~ RUBY_PLATFORM
- $null = open("nul", "w")
-else
- $null = open("/dev/null", "w")
-end
-
-$orgerr = $stderr.dup
-$orgout = $stdout.dup
-def xsystem command
- if $DEBUG
- puts command
- return system(command)
- end
- $stderr.reopen($null)
- $stdout.reopen($null)
- 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
- xsystem(format(LINK, $CFLAGS, $LDFLAGS, opt, $LOCAL_LIBS))
-end
-
-def try_link(src, opt="")
- begin
- try_link0(src, opt)
- ensure
- system "rm -f conftest*"
- end
-end
-
-def try_cpp(src, opt="")
- cfile = open("conftest.c", "w")
- cfile.print src
- cfile.close
- begin
- xsystem(format(CPP, $CFLAGS, opt))
- ensure
- system "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}", $CFLAGS, opt))
- ensure
- system "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
- system "rm -f conftest*"
- end
-end
-
-def install_rb(mfile, srcdir = nil)
- libdir = "lib"
- libdir = srcdir + "/" + libdir if srcdir
- path = []
- dir = []
- Find.find(libdir) do |f|
- next unless /\.rb$/ =~ f
- f = f[libdir.length+1..-1]
- path.push f
- dir |= File.dirname(f)
- end
- for f in dir
- next if f == "."
- mfile.printf "\t@$(RUBY) -r ftools -e 'File::makedirs(*ARGV)' $(DESTDIR)$(pkglibdir)/%s\n", f
- 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)/%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/ =~ RUBY_PLATFORM
- 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)
- ldflags = $LDFLAGS
- libs = append_library($libs, lib)
- until try_link(<<"SRC", libs)
-int main() { return 0; }
-int t() { #{func}(); return 0; }
-SRC
- if paths.size == 0
- $LDFLAGS = ldflags
- return false
- end
- $LDFLAGS = ldflags + " -L"+paths.shift
- end
- $libs = libs
- return true
-end
-
-def have_func(func)
- libs = $libs
-
- if /mswin32/ =~ RUBY_PLATFORM
- 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
- $defs.push(format("-DHAVE_%s", func.upcase))
- return true
-end
-
-def have_header(header)
- unless try_cpp(<<"SRC")
-#include <#{header}>
-SRC
- return false
- end
- header.tr!("a-z./\055", "A-Z___")
- $defs.push(format("-DHAVE_%s", header))
- return true
-end
-
-def arg_config(config, default=nil)
- unless defined? $configure_args
- $configure_args = {}
- args = "@configure_args@"
- if /mswin32/ =~ RUBY_PLATFORM and ENV["CONFIGURE_ARGS"]
- args = args + " " + ENV["CONFIGURE_ARGS"]
- end
- for arg in args.split
- next unless /^--/ =~ arg
- if /=/ =~ arg
- $configure_args[$`] = $'
- else
- $configure_args[arg] = true
- end
- 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)
- dir = with_config("%s-dir"%target)
- if dir
- idir = " -I"+dir+"/include"
- ldir = " -L"+dir+"/lib"
- end
- unless idir
- dir = with_config("%s-include"%target)
- idir = " -I"+dir if dir
- end
- unless ldir
- dir = with_config("%s-lib"%target)
- ldir = " -L"+dir if dir
- end
-
- $CFLAGS += idir if idir
- $LDFLAGS += ldir if ldir
-end
-
-def create_makefile(target)
- $target = target
-
- system "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 RUBY_PLATFORM =~ /beos/
- $libs = $libs + " -lruby"
- $DLDFLAGS = $DLDFLAGS + " -L" + $topdir
- end
-
- defflag = ''
- if RUBY_PLATFORM =~ /cygwin/ and not $static
- if File.exist? target + ".def"
- defflag = "--def=" + target + ".def"
- end
- $libs = $libs + " @LIBRUBYARG@"
- $DLDFLAGS = $DLDFLAGS + " -L" + $topdir
- end
-
- $srcdir = $top_srcdir + "/ext/" + $mdir
- mfile = open("Makefile", "w")
- mfile.printf "\
-SHELL = /bin/sh
-
-#### Start of system configuration section. ####
-
-srcdir = #{$srcdir}
-VPATH = #{$srcdir}
-
-topdir = #{$topdir}
-hdrdir = #{$top_srcdir}
-DESTDIR =
-
-CC = @CC@
-
-CFLAGS = %s -I$(topdir) -I$(hdrdir) #{CFLAGS} #$CFLAGS -I@includedir@ %s
-DLDFLAGS = #$DLDFLAGS #$LDFLAGS
-LDSHARED = @LDSHARED@ #{defflag}
-", if $static then "" else "@CCDLFLAGS@" end, $defs.join(" ")
-
- mfile.printf "\
-
-RUBY_INSTALL_NAME = @RUBY_INSTALL_NAME@
-
-prefix = @prefix@
-exec_prefix = @exec_prefix@
-libdir = @libdir@
-#pkglibdir = $(libdir)/$(RUBY_INSTALL_NAME)/@MAJOR@.@MINOR@
-pkglibdir = $(libdir)/ruby/@MAJOR@.@MINOR@
-archdir = $(pkglibdir)/@arch@
-@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
- end
- mfile.printf $objs.join(" ")
- mfile.printf "\n"
-
- ruby_interpreter = "$(topdir)/miniruby@EXEEXT@"
- if /mswin32/ =~ RUBY_PLATFORM
- ruby_interpreter = $topdir + "/miniruby@EXEEXT@"
- ruby_interpreter.gsub!("/", "\\")
- end
-
- mfile.printf <<EOS
-TARGET = #{target}
-DLLIB = $(TARGET).#{$static ? $LIBEXT : "@DLEXT@"}
-
-RUBY = #{ruby_interpreter} -I$(topdir) -I$(hdrdir)/lib
-
-EXEEXT = @EXEEXT@
-
-all: $(DLLIB)
-
-clean:; @rm -f *.#{$OBJEXT} *.so *.sl *.#{$LIBEXT} $(DLLIB)
- @rm -f *.ilk *.exp *.pdb *.bak
- @rm -f Makefile extconf.h conftest.*
- @rm -f core ruby$(EXEEXT) *~
-
-realclean: clean
-EOS
-
- mfile.printf <<EOS
-
-install:
- @$(RUBY) -r ftools -e 'File::makedirs(*ARGV)' $(DESTDIR)$(libdir) $(DESTDIR)$(pkglibdir) $(DESTDIR)$(archdir)
-EOS
- unless $static
- mfile.printf "\
- @$(RUBY) -r ftools -e 'File::install(ARGV[0], ARGV[1], 0555, true)' $(DLLIB) $(DESTDIR)$(archdir)/$(DLLIB)
-"
- end
- install_rb(mfile, $srcdir)
- mfile.printf "\n"
-
- 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.printf "\
-$(DLLIB): $(OBJS)
- $(LDSHARED) $(DLDFLAGS) -o $(DLLIB) $(OBJS) $(LIBS) $(LOCAL_LIBS)
-"
- 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()
- mfile.printf "%s", line.gsub('\$\(hdrdir\)/config.h', '$(topdir)/config.h')
- end
- dfile.close
- end
- mfile.close
-
- if RUBY_PLATFORM =~ /beos/
- if RUBY_PLATFORM =~ /^powerpc/ then
- deffilename = "ruby.exp"
- else
- deffilename = "ruby.def"
- end
- print "creating #{deffilename}\n"
- open(deffilename, "w") do |file|
- file.print("EXPORTS\n") if RUBY_PLATFORM =~ /^i/
- file.print("Init_#{target}\n")
- end
- end
-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
- $local_flags = ""
- case RUBY_PLATFORM
- when /cygwin|beos|openstep|nextstep|rhapsody/
- $libs = ""
- when /mswin32/
- $LIBEXT = "lib"
- $libs = ""
- $local_flags = "$(topdir)/rubymw.lib -link /EXPORT:Init_$(TARGET)"
- else
- $libs = "-lc"
- end
- $LOCAL_LIBS = "" # to be assigned in extconf.rb
- dir = with_config("opt-dir")
- if dir
- idir = "-I"+dir+"/include"
- ldir = "-L"+dir+"/lib"
- end
- unless idir
- dir = with_config("opt-include")
- idir = "-I"+dir if dir
- end
- unless ldir
- dir = with_config("opt-lib")
- ldir = "-L"+dir if dir
- end
-
- $CFLAGS = idir || ""
- $LDFLAGS = ldir || ""
-
- begin
- system "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", "../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,$target]
- end
- if $install
- system "#{$make} install DESTDIR=#{$destdir}"
- elsif $clean
- system "#{$make} clean"
- else
- system "#{$make} all" or exit
- end
- end
- if $static
- $extlibs ||= ""
- $extlibs += " " + $LDFLAGS unless $LDFLAGS == ""
- $extlibs += " " + $libs unless $libs == ""
- $extlibs += " " + $LOCAL_LIBS unless $LOCAL_LIBS == ""
- end
- ensure
- system "rm -f conftest*"
- Dir.chdir ".."
- 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 f.gets()
- $_.chomp!
- sub!(/#.*$/, '')
- next if /^\s*$/
- if /^option +nodynamic/
- $nodynamic = true
- next
- end
- target = $_.split[0]
- target = target.downcase if /mswin32/ =~ RUBY_PLATFORM
- $static_ext[target] = true
- end
- f.close
- break
- end
-end
-
-for d in Dir["#{$top_srcdir}/ext/*"]
- File.directory?(d) || next
- File.file?(d + "/MANIFEST") || next
-
- d = File.basename(d)
- 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.so\");\n\
-", t, t)
- $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)
- system("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)
- system("rm -f #{ruby}")
- system("#{$make} #{ruby}")
- end
-end
-
-#Local variables:
-# mode: ruby
-#end:
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 80e0112e4c..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-1998 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/MANIFEST b/ext/gdbm/MANIFEST
deleted file mode 100644
index f4a8796d18..0000000000
--- a/ext/gdbm/MANIFEST
+++ /dev/null
@@ -1,5 +0,0 @@
-MANIFEST
-README
-depend
-extconf.rb
-gdbm.c
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 116b19d18e..0000000000
--- a/ext/gdbm/gdbm.c
+++ /dev/null
@@ -1,594 +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>
-#ifdef USE_CWGUSI
-# include <sys/errno.h>
-#endif
-
-VALUE cGDBM;
-
-#define MY_BLOCK_SIZE (2048)
-#define MY_FATAL_FUNC (0)
-
-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->di_dbm == 0) closed_dbm();\
-}
-
-static void
-free_dbm(dbmp)
- struct dbmdata *dbmp;
-{
- if (dbmp->di_dbm) gdbm_close(dbmp->di_dbm);
- free(dbmp);
-}
-
-static VALUE
-fgdbm_s_open(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- VALUE file, vmode;
- GDBM_FILE dbm;
- struct dbmdata *dbmp;
- int mode;
- VALUE obj;
-
- 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);
- }
- Check_SafeStr(file);
-
- dbm = 0;
- if (mode >= 0)
- dbm = gdbm_open(RSTRING(file)->ptr, MY_BLOCK_SIZE,
- O_RDWR|O_CREAT, mode, MY_FATAL_FUNC);
- if (!dbm)
- dbm = gdbm_open(RSTRING(file)->ptr, MY_BLOCK_SIZE,
- O_RDWR, mode, MY_FATAL_FUNC);
- if (!dbm)
- dbm = gdbm_open(RSTRING(file)->ptr, MY_BLOCK_SIZE,
- O_RDONLY, mode, MY_FATAL_FUNC);
-
- if (!dbm) {
- if (mode == -1) return Qnil;
- rb_sys_fail(RSTRING(file)->ptr);
- }
-
- obj = Data_Make_Struct(klass,struct dbmdata,0,free_dbm,dbmp);
- dbmp->di_dbm = dbm;
- dbmp->di_size = -1;
- rb_obj_call_init(obj, argc, argv);
-
- return obj;
-}
-
-static VALUE
-fgdbm_close(obj)
- VALUE obj;
-{
- struct dbmdata *dbmp;
-
- Data_Get_Struct(obj, struct dbmdata, dbmp);
- if (dbmp->di_dbm == 0) closed_dbm();
- gdbm_close(dbmp->di_dbm);
- dbmp->di_dbm = 0;
-
- return Qnil;
-}
-
-static VALUE
-fgdbm_fetch(obj, keystr)
- VALUE obj, keystr;
-{
- datum key, value;
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
-
- Check_Type(keystr, T_STRING);
- key.dptr = RSTRING(keystr)->ptr;
- key.dsize = RSTRING(keystr)->len;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- value = gdbm_fetch(dbm, key);
- if (value.dptr == 0) {
- return Qnil;
- }
- return rb_tainted_str_new(value.dptr, value.dsize);
-}
-
-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, fgdbm_fetch(obj, argv[i]));
- }
-
- return new;
-}
-
-static VALUE
-fgdbm_delete(obj, keystr)
- VALUE obj, keystr;
-{
- datum key, value;
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
-
- rb_secure(4);
- Check_Type(keystr, T_STRING);
- key.dptr = RSTRING(keystr)->ptr;
- key.dsize = RSTRING(keystr)->len;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- value = gdbm_fetch(dbm, key);
- if (value.dptr == 0) {
- if (rb_iterator_p()) rb_yield(keystr);
- return Qnil;
- }
-
- if (gdbm_delete(dbm, key)) {
- dbmp->di_size = -1;
- rb_raise(rb_eRuntimeError, "gdbm_delete failed");
- }
- else if (dbmp->di_size >= 0) {
- dbmp->di_size--;
- }
- return obj;
-}
-
-static VALUE
-fgdbm_shift(obj)
- VALUE obj;
-{
- datum key, val;
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
- VALUE keystr, valstr;
-
- rb_secure(4);
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- key = gdbm_firstkey(dbm);
- if (!key.dptr) return Qnil;
- val = gdbm_fetch(dbm, key);
- gdbm_delete(dbm, key);
-
- keystr = rb_tainted_str_new(key.dptr, key.dsize);
- valstr = rb_tainted_str_new(val.dptr, val.dsize);
- return rb_assoc_new(keystr, valstr);
-}
-
-static VALUE
-fgdbm_delete_if(obj)
- VALUE obj;
-{
- datum key, val;
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
- VALUE keystr, valstr;
-
- rb_secure(4);
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- for (key = gdbm_firstkey(dbm); key.dptr; key = gdbm_nextkey(dbm, key)) {
- val = gdbm_fetch(dbm, key);
- keystr = rb_tainted_str_new(key.dptr, key.dsize);
- valstr = rb_tainted_str_new(val.dptr, val.dsize);
- if (RTEST(rb_yield(rb_assoc_new(keystr, valstr)))) {
- if (gdbm_delete(dbm, key)) {
- rb_raise(rb_eRuntimeError, "gdbm_delete failed");
- }
- }
- }
- 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;
- for (key = gdbm_firstkey(dbm); key.dptr; key = nextkey) {
- nextkey = gdbm_nextkey(dbm, key);
- if (gdbm_delete(dbm, key)) {
- rb_raise(rb_eRuntimeError, "gdbm_delete failed");
- }
- }
- return obj;
-}
-
-static VALUE
-fgdbm_invert(obj)
- VALUE obj;
-{
- datum key, val;
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
- VALUE keystr, valstr;
- VALUE hash = rb_hash_new();
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- for (key = gdbm_firstkey(dbm); key.dptr; key = gdbm_nextkey(dbm, key)) {
- val = gdbm_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 obj;
-}
-
-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);
- 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;
-
- Data_Get_Struct(obj, struct dbmdata, 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_eRuntimeError, "gdbm_store failed");
- }
-
- return valstr;
-}
-
-static VALUE
-fgdbm_length(obj)
- VALUE obj;
-{
- datum key;
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
- int i = 0;
-
- Data_Get_Struct(obj, struct dbmdata, dbmp);
- if (dbmp->di_size > 0) return INT2FIX(dbmp->di_size);
- dbm = dbmp->di_dbm;
-
- for (key = gdbm_firstkey(dbm); key.dptr; key = gdbm_nextkey(dbm, key)) {
- i++;
- }
- dbmp->di_size = i;
-
- return INT2FIX(i);
-}
-
-static VALUE
-fgdbm_empty_p(obj)
- VALUE obj;
-{
- datum key;
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
- int i = 0;
-
- Data_Get_Struct(obj, struct dbmdata, dbmp);
- if (dbmp->di_size < 0) {
- dbm = dbmp->di_dbm;
-
- for (key = gdbm_firstkey(dbm); key.dptr; key = gdbm_nextkey(dbm, key)) {
- i++;
- }
- }
- else {
- i = dbmp->di_size;
- }
- if (i == 0) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-fgdbm_each_value(obj)
- VALUE obj;
-{
- datum key, val;
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- for (key = gdbm_firstkey(dbm); key.dptr; key = gdbm_nextkey(dbm, key)) {
- val = gdbm_fetch(dbm, key);
- rb_yield(rb_tainted_str_new(val.dptr, val.dsize));
- }
- return obj;
-}
-
-static VALUE
-fgdbm_each_key(obj)
- VALUE obj;
-{
- datum key;
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- for (key = gdbm_firstkey(dbm); key.dptr; key = gdbm_nextkey(dbm, key)) {
- rb_yield(rb_tainted_str_new(key.dptr, key.dsize));
- }
- return obj;
-}
-
-static VALUE
-fgdbm_each_pair(obj)
- VALUE obj;
-{
- datum key, val;
- GDBM_FILE dbm;
- struct dbmdata *dbmp;
- VALUE keystr, valstr;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- for (key = gdbm_firstkey(dbm); key.dptr; key = gdbm_nextkey(dbm, key)) {
- val = gdbm_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
-fgdbm_keys(obj)
- VALUE obj;
-{
- datum key;
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
- VALUE ary;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- ary = rb_ary_new();
- for (key = gdbm_firstkey(dbm); key.dptr; key = gdbm_nextkey(dbm, key)) {
- rb_ary_push(ary, rb_tainted_str_new(key.dptr, key.dsize));
- }
-
- return ary;
-}
-
-static VALUE
-fgdbm_values(obj)
- VALUE obj;
-{
- datum key, val;
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
- VALUE ary;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- ary = rb_ary_new();
- for (key = gdbm_firstkey(dbm); key.dptr; key = gdbm_nextkey(dbm, key)) {
- val = gdbm_fetch(dbm, key);
- rb_ary_push(ary, rb_tainted_str_new(val.dptr, val.dsize));
- }
-
- return ary;
-}
-
-static VALUE
-fgdbm_has_key(obj, keystr)
- VALUE obj, keystr;
-{
- datum key, val;
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
-
- Check_Type(keystr, T_STRING);
- key.dptr = RSTRING(keystr)->ptr;
- key.dsize = RSTRING(keystr)->len;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- val = gdbm_fetch(dbm, key);
- if (val.dptr) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-fgdbm_has_value(obj, valstr)
- VALUE obj, valstr;
-{
- datum key, val;
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
-
- Check_Type(valstr, T_STRING);
- val.dptr = RSTRING(valstr)->ptr;
- val.dsize = RSTRING(valstr)->len;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
- for (key = gdbm_firstkey(dbm); key.dptr; key = gdbm_nextkey(dbm, key)) {
- val = gdbm_fetch(dbm, key);
- if (val.dsize == RSTRING(valstr)->len &&
- memcmp(val.dptr, RSTRING(valstr)->ptr, val.dsize) == 0)
- return Qtrue;
- }
- return Qfalse;
-}
-
-static VALUE
-fgdbm_to_a(obj)
- VALUE obj;
-{
- datum key, val;
- struct dbmdata *dbmp;
- GDBM_FILE dbm;
- VALUE ary;
-
- GetDBM(obj, dbmp);
- dbm = dbmp->di_dbm;
-
- ary = rb_ary_new();
- for (key = gdbm_firstkey(dbm); key.dptr; key = gdbm_nextkey(dbm, key)) {
- val = gdbm_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
-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;
-}
-
-void
-Init_gdbm()
-{
- cGDBM = rb_define_class("GDBM", rb_cObject);
- rb_include_module(cGDBM, rb_mEnumerable);
-
- rb_define_singleton_method(cGDBM, "open", fgdbm_s_open, -1);
- rb_define_singleton_method(cGDBM, "new", fgdbm_s_open, -1);
- rb_define_method(cGDBM, "close", fgdbm_close, 0);
- rb_define_method(cGDBM, "[]", fgdbm_fetch, 1);
- rb_define_method(cGDBM, "[]=", fgdbm_store, 2);
- rb_define_method(cGDBM, "indexes", fgdbm_indexes, -1);
- rb_define_method(cGDBM, "indices", fgdbm_indexes, -1);
- rb_define_method(cGDBM, "length", fgdbm_length, 0);
- rb_define_alias(cGDBM, "size", "length");
- rb_define_method(cGDBM, "empty?", fgdbm_empty_p, 0);
- rb_define_method(cGDBM, "each", fgdbm_each_pair, 0);
- rb_define_method(cGDBM, "each_value", fgdbm_each_value, 0);
- rb_define_method(cGDBM, "each_key", fgdbm_each_key, 0);
- rb_define_method(cGDBM, "each_pair", fgdbm_each_pair, 0);
- rb_define_method(cGDBM, "keys", fgdbm_keys, 0);
- rb_define_method(cGDBM, "values", fgdbm_values, 0);
- rb_define_method(cGDBM, "shift", fgdbm_shift, 1);
- rb_define_method(cGDBM, "delete", fgdbm_delete, 1);
- rb_define_method(cGDBM, "delete_if", fgdbm_delete_if, 0);
- rb_define_method(cGDBM, "clear", fgdbm_clear, 0);
- rb_define_method(cGDBM,"invert", fgdbm_invert, 0);
- rb_define_method(cGDBM,"update", fgdbm_update, 1);
- rb_define_method(cGDBM,"replace", fgdbm_replace, 1);
- rb_define_method(cGDBM,"reorganize", fgdbm_reorganize, 0);
-
- rb_define_method(cGDBM, "include?", fgdbm_has_key, 1);
- rb_define_method(cGDBM, "has_key?", fgdbm_has_key, 1);
- rb_define_method(cGDBM, "has_value?", fgdbm_has_value, 1);
- rb_define_method(cGDBM, "key?", fgdbm_has_key, 1);
- rb_define_method(cGDBM, "value?", fgdbm_has_value, 1);
-
- rb_define_method(cGDBM, "to_a", fgdbm_to_a, 0);
-}
diff --git a/ext/md5/MANIFEST b/ext/md5/MANIFEST
deleted file mode 100644
index 8057ebb06c..0000000000
--- a/ext/md5/MANIFEST
+++ /dev/null
@@ -1,7 +0,0 @@
-MANIFEST
-depend
-md5.txt
-md5.txt.jp
-md5.h
-md5c.c
-md5init.c
diff --git a/ext/md5/depend b/ext/md5/depend
deleted file mode 100644
index c99f78ee90..0000000000
--- a/ext/md5/depend
+++ /dev/null
@@ -1,2 +0,0 @@
-md5c.o: md5c.c md5.h
-md5init.o: md5init.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h md5.h
diff --git a/ext/md5/md5.h b/ext/md5/md5.h
deleted file mode 100644
index 81a6d7ff36..0000000000
--- a/ext/md5/md5.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/* MD5.H - header file for MD5C.C
- */
-
-/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
-rights reserved.
-
-License to copy and use this software is granted provided that it
-is identified as the "RSA Data Security, Inc. MD5 Message-Digest
-Algorithm" in all material mentioning or referencing this software
-or this function.
-
-License is also granted to make and use derivative works provided
-that such works are identified as "derived from the RSA Data
-Security, Inc. MD5 Message-Digest Algorithm" in all material
-mentioning or referencing the derived work.
-
-RSA Data Security, Inc. makes no representations concerning either
-the merchantability of this software or the suitability of this
-software for any particular purpose. It is provided "as is"
-without express or implied warranty of any kind.
-
-These notices must be retained in any copies of any part of this
-documentation and/or software.
- */
-
-/* ========== include global.h ========== */
-/* GLOBAL.H - RSAREF types and constants
- */
-
-/* PROTOTYPES should be set to one if and only if the compiler supports
- function argument prototyping.
-The following makes PROTOTYPES default to 0 if it has not already
- been defined with C compiler flags.
- */
-#ifdef HAVE_PROTOTYPES
-#define PROTOTYPES 1
-#endif
-#ifndef PROTOTYPES
-#define PROTOTYPES 0
-#endif
-
-/* POINTER defines a generic pointer type */
-typedef unsigned char *POINTER;
-
-/* UINT2 defines a two byte word */
-typedef unsigned short int UINT2;
-
-#ifdef HAVE_LIMITS_H
-#include <limits.h>
-#else
-/* Wild guess */
-#define LONG_MAX 2147483647L
-#endif
-
-/* UINT4 defines a four byte word */
-#if defined(INT_MAX) && INT_MAX == 2147483647
-typedef unsigned int UINT4;
-#else
-#if defined(LONG_MAX) && LONG_MAX == 2147483647L
-typedef unsigned long int UINT4;
-#endif
-/* Too bad if neither is */
-#endif
-
-/* PROTO_LIST is defined depending on how PROTOTYPES is defined above.
-If using PROTOTYPES, then PROTO_LIST returns the list, otherwise it
- returns an empty list.
- */
-#if PROTOTYPES
-#define PROTO_LIST(list) list
-#else
-#define PROTO_LIST(list) ()
-#endif
-/* ========== End global.h; continue md5.h ========== */
-
-/* MD5 context. */
-typedef struct {
- UINT4 state[4]; /* state (ABCD) */
- UINT4 count[2]; /* number of bits, modulo 2^64 (lsb first) */
- unsigned char buffer[64]; /* input buffer */
-} MD5_CTX;
-
-void MD5Init PROTO_LIST ((MD5_CTX *));
-void MD5Update PROTO_LIST
- ((MD5_CTX *, unsigned char *, unsigned int));
-void MD5Final PROTO_LIST ((unsigned char [16], MD5_CTX *));
diff --git a/ext/md5/md5.txt b/ext/md5/md5.txt
deleted file mode 100644
index 0eca7c9025..0000000000
--- a/ext/md5/md5.txt
+++ /dev/null
@@ -1,38 +0,0 @@
-.\" md5.doc - -*- Indented-Text -*- created at: Fri Aug 2 12:01:27 JST 1996
-
-** MD5(Class)
-
-A class to implement MD5 Message-Digest Algorithm by RSA Data
-Security, Inc., described in RFC1321.
-
-SuperClass: Object
-
-Class Methods:
-
- new([str])
- md5([str])
-
- creates a new MD5 object. If a string argument is given, it
- is added to the object. (see update.)
-
-Methods:
-
- clone
-
- copies the MD5 object.
-
- digest
-
- returns have value of the added strings as a 16 bytes string.
-
- update(str)
-
- Update the MD5 object with the string. 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).
-
--------------------------------------------------------
-Local variables:
-fill-column: 70
-end:
diff --git a/ext/md5/md5.txt.jp b/ext/md5/md5.txt.jp
deleted file mode 100644
index a1451f1175..0000000000
--- a/ext/md5/md5.txt.jp
+++ /dev/null
@@ -1,37 +0,0 @@
-.\" md5.doc - -*- Indented-Text -*- created at: Fri Aug 2 12:01:27 JST 1996
-
-** MD5(クラス)
-
-RFC1321に記述されているRSA Data Security, Inc. の MD5 Message-Digest
-Algorithmを実装するクラス.
-
-SuperClass: Object
-
-Class Methods:
-
- new([str])
- md5([str])
-
- 新しいMD5オブジェクトを生成する.文字列引数が与えられるとそれ
- を追加する(see update).
-
-Methods:
-
- clone
-
- MD5オブジェクトの複製を作る
-
- digest
-
- 今までに追加した文字列に対するハッシュ値を16バイト長の文字列で
- 返す.
-
- update(str)
-
- MD5オブジェクトに文字列を追加する。複数回updateを呼ぶことは文
- 字列を連結してupdateを呼ぶことと等しい.
-
--------------------------------------------------------
-Local variables:
-fill-column: 70
-end:
diff --git a/ext/md5/md5c.c b/ext/md5/md5c.c
deleted file mode 100644
index d7c7e4fb27..0000000000
--- a/ext/md5/md5c.c
+++ /dev/null
@@ -1,337 +0,0 @@
-/* MD5C.C - RSA Data Security, Inc., MD5 message-digest algorithm
- */
-
-/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
-rights reserved.
-
-License to copy and use this software is granted provided that it
-is identified as the "RSA Data Security, Inc. MD5 Message-Digest
-Algorithm" in all material mentioning or referencing this software
-or this function.
-
-License is also granted to make and use derivative works provided
-that such works are identified as "derived from the RSA Data
-Security, Inc. MD5 Message-Digest Algorithm" in all material
-mentioning or referencing the derived work.
-
-RSA Data Security, Inc. makes no representations concerning either
-the merchantability of this software or the suitability of this
-software for any particular purpose. It is provided "as is"
-without express or implied warranty of any kind.
-
-These notices must be retained in any copies of any part of this
-documentation and/or software.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#include "md5.h"
-
-/* Constants for MD5Transform routine.
- */
-
-#define S11 7
-#define S12 12
-#define S13 17
-#define S14 22
-#define S21 5
-#define S22 9
-#define S23 14
-#define S24 20
-#define S31 4
-#define S32 11
-#define S33 16
-#define S34 23
-#define S41 6
-#define S42 10
-#define S43 15
-#define S44 21
-
-static void MD5Transform PROTO_LIST ((UINT4 [4], unsigned char [64]));
-static void Encode PROTO_LIST
- ((unsigned char *, UINT4 *, unsigned int));
-static void Decode PROTO_LIST
- ((UINT4 *, unsigned char *, unsigned int));
-static void MD5_memcpy PROTO_LIST ((POINTER, POINTER, unsigned int));
-static void MD5_memset PROTO_LIST ((POINTER, int, unsigned int));
-
-static unsigned char PADDING[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
-};
-
-/* F, G, H and I are basic MD5 functions.
- */
-#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))
-#define G(x, y, z) (((x) & (z)) | ((y) & (~z)))
-#define H(x, y, z) ((x) ^ (y) ^ (z))
-#define I(x, y, z) ((y) ^ ((x) | (~z)))
-
-/* ROTATE_LEFT rotates x left n bits.
- */
-#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))
-
-/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.
-Rotation is separate from addition to prevent recomputation.
- */
-#define FF(a, b, c, d, x, s, ac) { \
- (a) += F ((b), (c), (d)) + (x) + (UINT4)(ac); \
- (a) = ROTATE_LEFT ((a), (s)); \
- (a) += (b); \
- }
-#define GG(a, b, c, d, x, s, ac) { \
- (a) += G ((b), (c), (d)) + (x) + (UINT4)(ac); \
- (a) = ROTATE_LEFT ((a), (s)); \
- (a) += (b); \
- }
-#define HH(a, b, c, d, x, s, ac) { \
- (a) += H ((b), (c), (d)) + (x) + (UINT4)(ac); \
- (a) = ROTATE_LEFT ((a), (s)); \
- (a) += (b); \
- }
-#define II(a, b, c, d, x, s, ac) { \
- (a) += I ((b), (c), (d)) + (x) + (UINT4)(ac); \
- (a) = ROTATE_LEFT ((a), (s)); \
- (a) += (b); \
- }
-
-/* MD5 initialization. Begins an MD5 operation, writing a new context.
- */
-void MD5Init (context)
-MD5_CTX *context; /* context */
-{
- context->count[0] = context->count[1] = 0;
- /* Load magic initialization constants.
-*/
- context->state[0] = 0x67452301;
- context->state[1] = 0xefcdab89;
- context->state[2] = 0x98badcfe;
- context->state[3] = 0x10325476;
-}
-
-/* MD5 block update operation. Continues an MD5 message-digest
- operation, processing another message block, and updating the
- context.
- */
-void MD5Update (context, input, inputLen)
-MD5_CTX *context; /* context */
-unsigned char *input; /* input block */
-unsigned int inputLen; /* length of input block */
-{
- unsigned int i, index, partLen;
-
- /* Compute number of bytes mod 64 */
- index = (unsigned int)((context->count[0] >> 3) & 0x3F);
-
- /* Update number of bits */
- if ((context->count[0] += ((UINT4)inputLen << 3))
- < ((UINT4)inputLen << 3))
- context->count[1]++;
- context->count[1] += ((UINT4)inputLen >> 29);
-
- partLen = 64 - index;
-
- /* Transform as many times as possible.
-*/
- if (inputLen >= partLen) {
- MD5_memcpy
- ((POINTER)&context->buffer[index], (POINTER)input, partLen);
- MD5Transform (context->state, context->buffer);
-
- for (i = partLen; i + 63 < inputLen; i += 64)
- MD5Transform (context->state, &input[i]);
-
- index = 0;
- }
- else
- i = 0;
-
- /* Buffer remaining input */
- MD5_memcpy
- ((POINTER)&context->buffer[index], (POINTER)&input[i],
- inputLen-i);
-}
-
-/* MD5 finalization. Ends an MD5 message-digest operation, writing the
- the message digest and zeroizing the context.
- */
-void MD5Final (digest, context)
-unsigned char digest[16]; /* message digest */
-MD5_CTX *context; /* context */
-{
- unsigned char bits[8];
- unsigned int index, padLen;
-
- /* Save number of bits */
- Encode (bits, context->count, 8);
-
- /* Pad out to 56 mod 64.
-*/
- index = (unsigned int)((context->count[0] >> 3) & 0x3f);
- padLen = (index < 56) ? (56 - index) : (120 - index);
- MD5Update (context, PADDING, padLen);
-
- /* Append length (before padding) */
- MD5Update (context, bits, 8);
-
- /* Store state in digest */
- Encode (digest, context->state, 16);
-
- /* Zeroize sensitive information.
-*/
- MD5_memset ((POINTER)context, 0, sizeof (*context));
-}
-
-/* MD5 basic transformation. Transforms state based on block.
- */
-static void MD5Transform (state, block)
-UINT4 state[4];
-unsigned char block[64];
-{
- UINT4 a = state[0], b = state[1], c = state[2], d = state[3], x[16];
-
- Decode (x, block, 64);
-
- /* Round 1 */
- FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
- FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
- FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
- FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
- FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
- FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
- FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
- FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
- FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
- FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
- FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
- FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
- FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
- FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
- FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
- FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
-
- /* Round 2 */
- GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
- GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
- GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
- GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
- GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
- GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */
- GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
- GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
- GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
- GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
- GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
- GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
- GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
- GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
- GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
- GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
-
- /* Round 3 */
- HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
- HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
- HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
- HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
- HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
- HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
- HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
- HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
- HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
- HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
- HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
- HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */
- HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
- HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
- HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
- HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
-
- /* Round 4 */
- II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
- II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
- II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
- II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
- II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
- II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
- II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
- II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
- II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
- II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
- II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
- II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
- II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
- II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
- II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
- II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
-
- state[0] += a;
- state[1] += b;
- state[2] += c;
- state[3] += d;
-
- /* Zeroize sensitive information.
-*/
- MD5_memset ((POINTER)x, 0, sizeof (x));
-}
-
-/* Encodes input (UINT4) into output (unsigned char). Assumes len is
- a multiple of 4.
- */
-static void Encode (output, input, len)
-unsigned char *output;
-UINT4 *input;
-unsigned int len;
-{
- unsigned int i, j;
-
- for (i = 0, j = 0; j < len; i++, j += 4) {
- output[j] = (unsigned char)(input[i] & 0xff);
- output[j+1] = (unsigned char)((input[i] >> 8) & 0xff);
- output[j+2] = (unsigned char)((input[i] >> 16) & 0xff);
- output[j+3] = (unsigned char)((input[i] >> 24) & 0xff);
- }
-}
-
-/* Decodes input (unsigned char) into output (UINT4). Assumes len is
- a multiple of 4.
- */
-static void Decode (output, input, len)
-UINT4 *output;
-unsigned char *input;
-unsigned int len;
-{
- unsigned int i, j;
-
- for (i = 0, j = 0; j < len; i++, j += 4)
- output[i] = ((UINT4)input[j]) | (((UINT4)input[j+1]) << 8) |
- (((UINT4)input[j+2]) << 16) | (((UINT4)input[j+3]) << 24);
-}
-
-/* Note: Replace "for loop" with standard memcpy if possible.
- */
-
-static void MD5_memcpy (output, input, len)
-POINTER output;
-POINTER input;
-unsigned int len;
-{
- unsigned int i;
-
- for (i = 0; i < len; i++)
- output[i] = input[i];
-}
-
-/* Note: Replace "for loop" with standard memset if possible.
- */
-static void MD5_memset (output, value, len)
-POINTER output;
-int value;
-unsigned int len;
-{
- unsigned int i;
-
- for (i = 0; i < len; i++)
- ((char *)output)[i] = (char)value;
-}
diff --git a/ext/md5/md5init.c b/ext/md5/md5init.c
deleted file mode 100644
index 552a407c6d..0000000000
--- a/ext/md5/md5init.c
+++ /dev/null
@@ -1,114 +0,0 @@
-/************************************************
-
- md5init.c -
-
- $Author$
- created at: Fri Aug 2 09:24:12 JST 1996
-
- Copyright (C) 1995-1998 Yukihiro Matsumoto
-
-************************************************/
-/* This module provides an interface to the RSA Data Security,
- Inc. MD5 Message-Digest Algorithm, described in RFC 1321.
- It requires the files md5c.c and md5.h (which are slightly changed
- from the versions in the RFC to avoid the "global.h" file.) */
-
-#include "ruby.h"
-#include "md5.h"
-
-static VALUE cMD5;
-
-static VALUE
-md5_update(obj, str)
- VALUE obj;
- struct RString *str;
-{
- MD5_CTX *md5;
-
- Check_Type(str, T_STRING);
- Data_Get_Struct(obj, MD5_CTX, md5);
- MD5Update(md5, str->ptr, str->len);
-
- return obj;
-}
-
-static VALUE
-md5_digest(obj)
- VALUE obj;
-{
- MD5_CTX *md5, ctx;
- unsigned char digest[16];
-
- Data_Get_Struct(obj, MD5_CTX, md5);
- ctx = *md5;
- MD5Final(digest, &ctx);
-
- return rb_str_new(digest, 16);
-}
-
-static VALUE
-md5_hexdigest(obj)
- VALUE obj;
-{
- MD5_CTX *md5, ctx;
- unsigned char digest[16];
- char buf[33];
- int i;
-
- Data_Get_Struct(obj, MD5_CTX, md5);
- ctx = *md5;
- MD5Final(digest, &ctx);
-
- for (i=0; i<16; i++) {
- sprintf(buf+i*2, "%02x", digest[i]);
- }
- return rb_str_new(buf, 32);
-}
-
-static VALUE
-md5_clone(obj)
- VALUE obj;
-{
- MD5_CTX *md5, *md5_new;
-
- Data_Get_Struct(obj, MD5_CTX, md5);
- obj = Data_Make_Struct(CLASS_OF(obj), MD5_CTX, 0, free, md5_new);
- *md5_new = *md5;
-
- return obj;
-}
-
-static VALUE
-md5_new(argc, argv, class)
- int argc;
- VALUE* argv;
- VALUE class;
-{
- VALUE arg, obj;
- MD5_CTX *md5;
-
- rb_scan_args(argc, argv, "01", &arg);
- if (!NIL_P(arg)) Check_Type(arg, T_STRING);
-
- obj = Data_Make_Struct(class, MD5_CTX, 0, free, md5);
- MD5Init(md5);
- if (!NIL_P(arg)) {
- md5_update(obj, arg);
- }
- rb_obj_call_init(obj, argc, argv);
-
- return obj;
-}
-
-void
-Init_md5()
-{
- cMD5 = rb_define_class("MD5", rb_cObject);
-
- rb_define_singleton_method(cMD5, "new", md5_new, -1);
-
- rb_define_method(cMD5, "update", md5_update, 1);
- rb_define_method(cMD5, "digest", md5_digest, 0);
- rb_define_method(cMD5, "hexdigest", md5_hexdigest, 0);
- rb_define_method(cMD5, "clone", md5_clone, 0);
-}
diff --git a/ext/mswin32_extmk.rb b/ext/mswin32_extmk.rb
deleted file mode 100644
index c79284dd8c..0000000000
--- a/ext/mswin32_extmk.rb
+++ /dev/null
@@ -1,41 +0,0 @@
-#!./miniruby
-
-def create_gsub_rb()
- f = open("mswin32_gsub.rb", "w")
- has_version = false
- f.print 'f = open("extmk.rb", "w")', "\n"
- f.print 'File.foreach "extmk.rb.in" do |$_|', "\n"
- File.foreach "../config.status" do |$_|
- next if /^#/
- if /^s%@(\w+)@%(.*)%g/
- name = $1
- val = $2 || ""
- next if name =~ /^(INSTALL|DEFS|configure_input|srcdir)$/
- val = ".." if name == "top_srcdir"
- val.gsub!(/\$\{([^{}]+)\}/) { "$(#{$1})" }
- f.print " gsub!(\"@#{name}@\", \"#{val}\")\n"
- has_version = true if name == "MAJOR"
- end
- end
-
- if not has_version
- VERSION.scan(/(\d+)\.(\d+)\.(\d+)/) {
- f.print " gsub!(\"@MAJOR@\", \"#{$1}\")\n"
- f.print " gsub!(\"@MINOR@\", \"#{$2}\")\n"
- f.print " gsub!(\"@TEENY@\", \"#{$3}\")\n"
- }
- end
- f.print ' f.print $_', "\n"
- f.print 'end', "\n"
- f.print 'f.close', "\n"
- f.close
-end
-
-begin
- create_gsub_rb()
- load "mswin32_gsub.rb"
-ensure
- File.unlink "mswin32_gsub.rb"
-end
-
-# vi:set sw=2:
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 b59688cb03..0000000000
--- a/ext/nkf/nkf.c
+++ /dev/null
@@ -1,196 +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;
-{
- int i;
- char *opt_ptr, *opt_end;
- volatile VALUE v;
-
- reinit();
- opt_ptr = str2cstr(opt, &i);
- opt_end = opt_ptr + i;
- for (; opt_ptr < opt_end; opt_ptr++) {
- if (*opt_ptr != '-') {
- continue;
- }
- arguments(opt_ptr);
- }
-
- incsize = INCSIZE;
-
- input_ctr = 0;
- input = str2cstr(src, &i_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;
-
- 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 plen;
- int sequence_counter = 0;
-
- Check_Type(src, T_STRING);
-
- p = str2cstr(src, &plen);
- pend = p + plen;
-
-#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/MANIFEST b/ext/pty/MANIFEST
deleted file mode 100644
index f46d611e5b..0000000000
--- a/ext/pty/MANIFEST
+++ /dev/null
@@ -1,12 +0,0 @@
-MANIFEST
-README
-README.expect
-README.expect.jp
-README.jp
-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.jp b/ext/pty/README.expect.jp
deleted file mode 100644
index db84695ee5..0000000000
--- a/ext/pty/README.expect.jp
+++ /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.jp b/ext/pty/README.jp
deleted file mode 100644
index 5ae4fb06a0..0000000000
--- a/ext/pty/README.jp
+++ /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 63383f7faf..0000000000
--- a/ext/pty/extconf.rb
+++ /dev/null
@@ -1,10 +0,0 @@
-require 'mkmf'
-
-have_header("sys/stropts.h")
-have_func("setresuid")
-$CFLAGS << "-DHAVE_DEV_PTMX" if /cygwin/ === PLATFORM
-if have_func("openpty") or
- have_func("_getpty") or
- have_func("ioctl")
- create_makefile('pty')
-end
diff --git a/ext/pty/lib/expect.rb b/ext/pty/lib/expect.rb
deleted file mode 100644
index 54c69edadb..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 iterator? 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 98be9044b7..0000000000
--- a/ext/pty/pty.c
+++ /dev/null
@@ -1,497 +0,0 @@
-#include "config.h"
-#include <stdio.h>
-#include <sys/types.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_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
-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 */
-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
-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",
- 0,
- };
-#endif /* _IBMESA */
-#endif /* HPUX */
-#endif /* !defined(HAVE_OPENPTY) */
-
-char SlaveName[DEVICELEN];
-
-extern int errno;
-
-#define MAX_PTY 16
-static int n_pty,last_pty;
-static int chld_pid[MAX_PTY];
-
-#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 */
-
-struct pty_info {
- int fd;
- pid_t child_pid;
-};
-
-static void
-set_signal_action(action)
- RETSIGTYPE (*action)();
-{
-#ifdef __hpux
- struct sigvec sv;
- /*
- * signal SIGCHLD should be delivered on stop of the child
- */
- sv.sv_handler = action;
- sv.sv_mask = sigmask(SIGCHLD);
- sv.sv_flags = SV_BSDSIG;
- sigvector(SIGCHLD, &sv, (struct sigvec *) 0);
-#else /* not HPUX */
-#if defined(SA_NOCLDSTOP)
- struct sigaction sa;
- /*
- * signal SIGCHLD should be delivered on stop of the child
- * (for SVR4)
- */
- sa.sa_handler = action;
- sigemptyset(&sa.sa_mask);
- sigaddset(&sa.sa_mask, SIGCHLD);
- sa.sa_flags = 0; /* SA_NOCLDSTOP flag is removed */
- sigaction(SIGCHLD, &sa, (struct sigaction *) 0);
-#else
- signal(SIGCHLD,action);
-#endif
-#endif /* not HPUX */
-
-}
-
-static void
-reset_signal_action()
-{
- set_signal_action(SIG_DFL);
-}
-
-static RETSIGTYPE
-chld_changed()
-{
- int cpid;
- int i,n = -1;
- int statusp;
-
- for (;;) {
-#ifdef HAVE_WAITPID
- cpid = waitpid(-1, &statusp, WUNTRACED|WNOHANG);
-#else
- cpid = wait3(&statusp, WUNTRACED|WNOHANG, 0);
-#endif
- if (cpid == 0 || cpid == -1)
- return;
- for (i = 0; i < last_pty; i++) {
- if (chld_pid[i] == cpid) {
- n = i;
- goto catched;
- }
- }
- rb_raise(rb_eRuntimeError, "fork: %d", cpid);
- }
- catched:
-
-#ifdef IF_STOPPED
- if (IF_STOPPED(statusp)) { /* suspend */
- rb_raise(rb_eRuntimeError, "Stopped: %d",cpid);
- }
-#else
-#ifdef WIFSTOPPED
- if (WIFSTOPPED(statusp)) { /* suspend */
- rb_raise(rb_eRuntimeError, "Stopped: %d",cpid);
- }
-#else
----->> Either IF_STOPPED or WIFSTOPPED is needed <<----
-#endif /* WIFSTOPPED */
-#endif /* IF_STOPPED */
- if (n >= 0) {
- chld_pid[n] = 0;
- n_pty--;
- if (n_pty == 0)
- reset_signal_action();
- }
- rb_raise(rb_eRuntimeError, "Child_changed: %d",cpid);
-}
-
-static void getDevice _((int*, int*));
-
-static void
-establishShell(shellname, info)
- char *shellname;
- struct pty_info *info;
-{
- static int i,j,master,slave,currentPid;
- char *p,*getenv();
- struct passwd *pwent;
- RETSIGTYPE chld_changed();
-
- if (shellname[0] == '\0') {
- if ((p = getenv("SHELL")) != NULL) {
- shellname = p;
- }
- else {
- pwent = getpwuid(getuid());
- if (pwent && pwent->pw_shell)
- shellname = pwent->pw_shell;
- else
- shellname = "/bin/sh";
- }
- }
- getDevice(&master,&slave);
-
- currentPid = getpid();
- set_signal_action(chld_changed);
- if((i = vfork()) < 0) {
- rb_sys_fail("fork failed");
- }
-
- if(i == 0) { /* child */
- int argc;
- char *argv[1024];
- 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);
-
- seteuid(getuid());
-
- argc = 0;
- for (i = 0; shellname[i];) {
- while (isspace(shellname[i])) i++;
- for (j = i; shellname[j] && !isspace(shellname[j]); j++);
- argv[argc] = (char*)xmalloc(j-i+1);
- strncpy(argv[argc],&shellname[i],j-i);
- argv[argc][j-i] = 0;
- i = j;
- argc++;
- }
- argv[argc] = NULL;
- execvp(argv[0],argv);
- sleep(1);
- _exit(1);
- }
-
- close(slave);
-
- if (n_pty == last_pty) {
- chld_pid[n_pty] = i;
- n_pty++;
- last_pty++;
- }
- else {
- for (j = 0; j < last_pty; j++) {
- if (chld_pid[j] == 0) {
- chld_pid[j] = i;
- n_pty++;
- }
- }
- }
- info->child_pid = i;
- info->fd = master;
-}
-
-#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_DEV_PTMX
- 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
- 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
- }
- }
-#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\n", SlaveDevice);
-#endif
-}
-#endif /* HAVE__GETPTY */
-#endif /* HAVE_OPENPTY */
-
-static void
-freeDevice()
-{
- chmod(SlaveName, 0666);
- chown(SlaveName, 0, 0);
-}
-
-/* ruby function: getpty */
-static VALUE
-pty_getpty(self, shell)
- VALUE self, shell;
-{
- VALUE res;
- struct pty_info info;
- OpenFile *wfptr,*rfptr;
- NEWOBJ(rport, struct RFile);
- NEWOBJ(wport, struct RFile);
-
- if (n_pty == MAX_PTY+1) {
- rb_raise(rb_eRuntimeError, "Too many ptys are open");
- }
-
- OBJSETUP(rport, rb_cFile, T_FILE);
- MakeOpenFile(rport, rfptr);
-
- OBJSETUP(wport, rb_cFile, T_FILE);
- MakeOpenFile(wport, wfptr);
-
- establishShell(RSTRING(shell)->ptr,&info);
-
- rfptr->mode = rb_io_mode_flags("r");
- rfptr->f = fdopen(info.fd, "r");
- rfptr->path = strdup(RSTRING(shell)->ptr);
-
- wfptr->mode = rb_io_mode_flags("w");
- wfptr->f = fdopen(dup(info.fd), "w");
- wfptr->path = strdup(RSTRING(shell)->ptr);
-
- res = rb_ary_new2(2);
- rb_ary_store(res,0,(VALUE)rport);
- rb_ary_store(res,1,(VALUE)wport);
- rb_ary_store(res,2,INT2FIX(info.child_pid));
-
- if (rb_iterator_p()) {
- rb_yield((VALUE)res);
- reset_signal_action();
- return Qnil;
- }
- else {
- return (VALUE)res;
- }
-}
-
-/* ruby function: protect_signal */
-static VALUE
-pty_protect(self)
- VALUE self;
-{
- reset_signal_action();
- rb_yield(Qnil);
- set_signal_action(chld_changed);
- return self;
-}
-
-static VALUE
-pty_reset_signal(self)
- VALUE self;
-{
- reset_signal_action();
- 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);
-}
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 0c04a2735c..0000000000
--- a/ext/pty/shl.rb
+++ /dev/null
@@ -1,96 +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
- PTY.protect_signal do
- system "stty -echo raw"
- end
- 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
- PTY.protect_signal do
- system "stty echo -raw"
- end
- 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/MANIFEST b/ext/readline/MANIFEST
deleted file mode 100644
index f8bfd1ea2c..0000000000
--- a/ext/readline/MANIFEST
+++ /dev/null
@@ -1,5 +0,0 @@
-MANIFEST
-README
-depend
-extconf.rb
-readline.c
diff --git a/ext/readline/README b/ext/readline/README
deleted file mode 100644
index 8a5fe9120f..0000000000
--- a/ext/readline/README
+++ /dev/null
@@ -1,55 +0,0 @@
-GNU Readline Libraryを利用するための拡張モジュールです。
-
-require "readline"
-include Readline
-
-line = readline("Prompt> ", TRUE)
-
-のように使用してください。
-
-[Readline]
-
-<モジュール関数>
-
-readline(prompt, add=nil)
-
- 一行入力を読み込みます。
- addがTRUEの場合、ヒストリに読み込んだ文字列を追加します。
-
-<クラスメソッド>
-
-completion_proc = proc
-
- 補完時の動作を決定するProcオブジェクトを指定します。
- procは引数に入力文字列を取り、候補文字列の配列を返すように
- してください。
-
-completion_proc
-
- 補完時の動作を決定するProcオブジェクトを返します。
-
-completion_case_fold = case_fold
-
- 補完時に大文字小文字を区別しない場合、TRUEを指定します。
-
-completion_case_fold
-
- 補完時に大文字小文字を区別しない場合、TRUEを返します。
-
-vi_editing_mode
-
- VIモードになります。
-
-emacs_editing_mode
-
- Emacsモードになります。
-
-<クラス定数>
-
-HISTORY
-
-ヒストリに対する操作はこの定数を通して行ってください。
-配列と同じように扱えるようになっています。
-
-
- \ No newline at end of file
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 3dd9c0fc1e..0000000000
--- a/ext/readline/extconf.rb
+++ /dev/null
@@ -1,11 +0,0 @@
-require "mkmf"
-
-dir_config("readline")
-have_library("user32", nil) if /cygwin/ === PLATFORM
-have_library("termcap", "tgetnum")
-have_library("curses", "tgetnum")
-if have_header("readline/readline.h") and
- have_header("readline/history.h") and
- have_library("readline", "readline")
- create_makefile("readline")
-end
diff --git a/ext/readline/readline.c b/ext/readline/readline.c
deleted file mode 100644
index 02b29796af..0000000000
--- a/ext/readline/readline.c
+++ /dev/null
@@ -1,421 +0,0 @@
-/* readline.c -- GNU Readline module
- Copyright (C) 1997-1998 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"
-
-static int
-readline_event()
-{
- CHECK_INTS;
- rb_thread_schedule();
-}
-
-static VALUE
-readline_readline(argc, argv, self)
- int argc;
- VALUE *argv;
- VALUE self;
-{
- VALUE tmp, add_hist, result;
- char *prompt = NULL;
- char *buff;
-
- if (rb_scan_args(argc, argv, "02", &tmp, &add_hist) > 0) {
- prompt = STR2CSTR(tmp);
- }
- buff = readline(prompt);
- if (RTEST(add_hist) && buff) {
- add_history(buff);
- }
- if (buff)
- result = rb_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_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
-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 - 1) {
- rb_raise(rb_eIndexError, "Invalid index");
- }
- return rb_str_new2(state->entries[i]->line);
-}
-
-static VALUE
-hist_set(self, index, str)
- VALUE self;
- VALUE index;
- VALUE str;
-{
- HISTORY_STATE *state;
- int i;
-
- state = history_get_history_state();
- i = NUM2INT(index);
- if (i < 0 || i > state->length - 1) {
- rb_raise(rb_eIndexError, "Invalid index");
- }
- replace_history_entry(i, STR2CSTR(str), NULL);
- return str;
-}
-
-static VALUE
-hist_push(self, str)
- VALUE self;
- VALUE str;
-{
- add_history(STR2CSTR(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(STR2CSTR(str));
- }
- return self;
-}
-
-static VALUE
-hist_pop(self)
- VALUE self;
-{
- HISTORY_STATE *state;
- HIST_ENTRY *entry;
-
- state = history_get_history_state();
- if (state->length > 0) {
- entry = remove_history(state->length - 1);
- return rb_str_new2(entry->line);
- } else {
- return Qnil;
- }
-}
-
-static VALUE
-hist_shift(self)
- VALUE self;
-{
- HISTORY_STATE *state;
- HIST_ENTRY *entry;
-
- state = history_get_history_state();
- if (state->length > 0) {
- entry = remove_history(0);
- return rb_str_new2(entry->line);
- } 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_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;
- HIST_ENTRY *entry;
- int i;
-
- state = history_get_history_state();
- i = NUM2INT(index);
- if (i < 0 || i > state->length - 1) {
- rb_raise(rb_eIndexError, "Invalid index");
- }
- entry = remove_history(NUM2INT(index));
- return rb_str_new2(entry->line);
-}
-
-static VALUE
-filename_completion_proc_call(self, str)
- VALUE self;
- VALUE str;
-{
- VALUE result;
- char **matches;
- int i;
-
- matches = completion_matches(STR2CSTR(str),
- filename_completion_function);
- if (matches) {
- result = rb_ary_new();
- for (i = 0; matches[i]; i++) {
- rb_ary_push(result, rb_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 = completion_matches(STR2CSTR(str),
- username_completion_function);
- if (matches) {
- result = rb_ary_new();
- for (i = 0; matches[i]; i++) {
- rb_ary_push(result, rb_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;
-
- 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);
-
- 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,"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);
-
- rl_attempted_completion_function
- = (CPPFunction *) readline_attempted_completion_function;
- rl_event_hook = readline_event;
- rl_clear_signals();
-}
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 a07cc55f6b..0000000000
--- a/ext/sdbm/_sdbm.c
+++ /dev/null
@@ -1,977 +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
- */
-#ifndef sun
-#ifndef MSDOS
-extern int errno;
-#endif
-#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.
- */
-#ifdef MSDOS
- flags |= O_BINARY;
-#endif
- 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];
-#ifdef MSDOS
- 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.
- */
-
-#ifdef MSDOS
- /*
- * 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 5ebffcb9fd..0000000000
--- a/ext/sdbm/init.c
+++ /dev/null
@@ -1,584 +0,0 @@
-/************************************************
-
- sdbminit.c -
-
- $Author$
- $Date$
- created at: Fri May 7 08:34:24 JST 1999
-
- Copyright (C) 1995-1998 Yukihiro Matsumoto
-
-************************************************/
-
-#include "ruby.h"
-
-#include "sdbm.h"
-#include <fcntl.h>
-#include <errno.h>
-#ifdef USE_CWGUSI
-# include <sys/errno.h>
-#endif
-
-VALUE cSDBM;
-
-struct dbmdata {
- int di_size;
- DBM *di_dbm;
-};
-
-static void
-closed_sdbm()
-{
- rb_raise(rb_eRuntimeError, "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_s_open(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- VALUE file, vmode;
- DBM *dbm;
- struct dbmdata *dbmp;
- int mode;
- VALUE obj;
-
- 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);
- }
- Check_SafeStr(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, mode);
- if (!dbm)
- dbm = sdbm_open(RSTRING(file)->ptr, O_RDONLY, mode);
-
- if (!dbm) {
- if (mode == -1) return Qnil;
- rb_sys_fail(RSTRING(file)->ptr);
- }
-
- obj = Data_Make_Struct(klass,struct dbmdata,0,free_sdbm,dbmp);
- dbmp->di_dbm = dbm;
- dbmp->di_size = -1;
-
- return obj;
-}
-
-static VALUE
-fsdbm_close(obj)
- VALUE obj;
-{
- struct dbmdata *dbmp;
-
- Data_Get_Struct(obj, struct dbmdata, dbmp);
- if (dbmp->di_dbm == 0) closed_sdbm();
- sdbm_close(dbmp->di_dbm);
- dbmp->di_dbm = 0;
-
- return Qnil;
-}
-
-static VALUE
-fsdbm_fetch(obj, keystr)
- VALUE obj, keystr;
-{
- datum key, value;
- struct dbmdata *dbmp;
- DBM *dbm;
-
- Check_Type(keystr, T_STRING);
- 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) {
- return Qnil;
- }
- return rb_tainted_str_new(value.dptr, value.dsize);
-}
-
-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_delete(obj, keystr)
- VALUE obj, keystr;
-{
- datum key, value;
- struct dbmdata *dbmp;
- DBM *dbm;
-
- rb_secure(4);
- Check_Type(keystr, T_STRING);
- 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 (rb_iterator_p()) rb_yield(keystr);
- return Qnil;
- }
-
- if (sdbm_delete(dbm, key)) {
- dbmp->di_size = -1;
- rb_raise(rb_eRuntimeError, "dbm_delete failed");
- }
- else if (dbmp->di_size >= 0) {
- dbmp->di_size--;
- }
- return obj;
-}
-
-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);
- sdbm_delete(dbm, key);
-
- keystr = rb_tainted_str_new(key.dptr, key.dsize);
- valstr = rb_tainted_str_new(val.dptr, val.dsize);
- 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;
-
- rb_secure(4);
- 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);
- if (RTEST(rb_yield(rb_assoc_new(keystr, valstr)))) {
- if (sdbm_delete(dbm, key)) {
- rb_raise(rb_eRuntimeError, "sdbm_delete failed");
- }
- }
- }
- 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;
- for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) {
- if (sdbm_delete(dbm, key)) {
- rb_raise(rb_eRuntimeError, "sdbm_delete failed");
- }
- }
- 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 obj;
-}
-
-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;
-
- Data_Get_Struct(obj, struct dbmdata, 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_eRuntimeError, "sdbm_store failed");
- }
-
- return valstr;
-}
-
-static VALUE
-fsdbm_length(obj)
- VALUE obj;
-{
- datum key;
- struct dbmdata *dbmp;
- DBM *dbm;
- int i = 0;
-
- Data_Get_Struct(obj, struct dbmdata, 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;
-
- Data_Get_Struct(obj, struct dbmdata, 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;
-
- Check_Type(keystr, T_STRING);
- 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;
-
- Check_Type(valstr, T_STRING);
- 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;
-}
-
-void
-Init_sdbm()
-{
- cSDBM = rb_define_class("SDBM", rb_cObject);
- rb_include_module(cSDBM, rb_mEnumerable);
-
- rb_define_singleton_method(cSDBM, "open", fsdbm_s_open, -1);
- rb_define_singleton_method(cSDBM, "new", fsdbm_s_open, -1);
- rb_define_method(cSDBM, "close", fsdbm_close, 0);
- rb_define_method(cSDBM, "[]", fsdbm_fetch, 1);
- rb_define_method(cSDBM, "[]=", fsdbm_store, 2);
- rb_define_method(cSDBM, "indexes", fsdbm_indexes, -1);
- rb_define_method(cSDBM, "indices", fsdbm_indexes, -1);
- rb_define_method(cSDBM, "length", fsdbm_length, 0);
- rb_define_alias(cSDBM, "size", "length");
- rb_define_method(cSDBM, "empty?", fsdbm_empty_p, 0);
- rb_define_method(cSDBM, "each", fsdbm_each_pair, 0);
- rb_define_method(cSDBM, "each_value", fsdbm_each_value, 0);
- rb_define_method(cSDBM, "each_key", fsdbm_each_key, 0);
- rb_define_method(cSDBM, "each_pair", fsdbm_each_pair, 0);
- rb_define_method(cSDBM, "keys", fsdbm_keys, 0);
- rb_define_method(cSDBM, "values", fsdbm_values, 0);
- rb_define_method(cSDBM, "shift", fsdbm_shift, 1);
- rb_define_method(cSDBM, "delete", fsdbm_delete, 1);
- rb_define_method(cSDBM, "delete_if", fsdbm_delete_if, 0);
- rb_define_method(cSDBM, "clear", fsdbm_clear, 0);
- rb_define_method(cSDBM,"invert", fsdbm_invert, 0);
- rb_define_method(cSDBM,"update", fsdbm_update, 1);
- rb_define_method(cSDBM,"replace", fsdbm_replace, 1);
-
- rb_define_method(cSDBM, "include?", fsdbm_has_key, 1);
- rb_define_method(cSDBM, "has_key?", fsdbm_has_key, 1);
- rb_define_method(cSDBM, "has_value?", fsdbm_has_value, 1);
- rb_define_method(cSDBM, "key?", fsdbm_has_key, 1);
- rb_define_method(cSDBM, "value?", fsdbm_has_value, 1);
-
- rb_define_method(cSDBM, "to_a", fsdbm_to_a, 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/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 74fae207b9..0000000000
--- a/ext/socket/addrinfo.h
+++ /dev/null
@@ -1,172 +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
-
-#ifdef NT
-#define IN_EXPERIMENTAL(x) 0
-#define IN_LOOPBACKNET 0
-#endif
-
-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 *));
-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 6975994ef8..0000000000
--- a/ext/socket/extconf.rb
+++ /dev/null
@@ -1,287 +0,0 @@
-require 'mkmf'
-$LDFLAGS += " -L/usr/local/lib" if File.directory?("/usr/local/lib")
-$CFLAGS += " -Dss_family=__ss_family -Dss_len=__ss_len"
-
-case PLATFORM
-when /mswin32/
- test_func = "WSACleanup"
- have_library("wsock32", "WSACleanup")
-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")
-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
-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"
- $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
- end
-
- if $ipv6lib
- if File.directory? $ipv6libdir and File.exist? "#{$ipv6libdir}/lib#{$ipv6lib}.a"
- $LOCAL_LIBS = " -L#$ipv6libdir -l#$ipv6lib"
- else
- 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>
-#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")
-have_header("netinet/udp.h")
-
-$getaddr_info_ok = false
-if 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 (inet6 != 2 || inet4 != 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
-
-
-$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_header("arpa/nameser.h")
- have_header("resolv.h")
-end
-
-have_header("sys/un.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 ebb03fe959..0000000000
--- a/ext/socket/getaddrinfo.c
+++ /dev/null
@@ -1,675 +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 <sys/types.h>
-#ifndef NT
-#include <sys/param.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-#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 "config.h"
-#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; }
-
-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:
- pai->ai_socktype = SOCK_RAW;
- break;
- }
- break;
- case SOCK_RAW:
- break;
- 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;
- close(s);
-
- 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;
-#ifndef INET6
-#ifndef NT
- extern int h_errno;
-#endif
-#endif
-
- 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 cb65e4c070..0000000000
--- a/ext/socket/getnameinfo.c
+++ /dev/null
@@ -1,254 +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 <sys/types.h>
-#ifndef NT
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-#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 "config.h"
-#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];
-#ifndef NT
- extern int h_errno;
-#endif
-
- 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) > servlen)
- return ENI_MEMORY;
- strcpy(serv, numserv);
- } else {
- sp = getservbyport(port, (flags & NI_DGRAM) ? "udp" : "tcp");
- if (sp) {
- if (strlen(sp->s_name) > servlen)
- return ENI_MEMORY;
- strcpy(serv, sp->s_name);
- } else
- return ENI_NOSERVNAME;
- }
-
- switch (sa->sa_family) {
- case AF_INET:
- v4a = ((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 || v4a == IN_LOOPBACKNET)
- 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) > 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 94597055aa..0000000000
--- a/ext/socket/socket.c
+++ /dev/null
@@ -1,2214 +0,0 @@
-/************************************************
-
- socket.c -
-
- $Author$
- $Date$
- created at: Thu Mar 31 12:21:29 JST 1994
-
-************************************************/
-
-#include "ruby.h"
-#include "rubyio.h"
-#include "rubysig.h"
-#include <stdio.h>
-#include <sys/types.h>
-#ifndef NT
-#include <sys/socket.h>
-#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
-
-#ifdef USE_CWGUSI
-extern int fileno(FILE *stream); /* <unix.mac.h> */
-extern int rb_thread_select(int, fd_set*, fd_set*, fd_set*, struct timeval*); /* thread.c */
-# include <sys/errno.h>
-# include <GUSI.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 INET6
-# undef ss_family
-# define sockaddr_storage sockaddr
-# define ss_family sa_family
-#endif
-
-#ifdef NT
-static void
-sock_finalize(fptr)
- OpenFile *fptr;
-{
- SOCKET s;
- extern int errno;
-
- if (!fptr->f) return;
-
- myfdclose(fptr->f);
- if(fptr->f2) myfdclose(fptr->f);
-/*
- s = get_osfhandle(fileno(fptr->f));
- closesocket(s);
-*/
-}
-#endif
-
-static VALUE
-sock_new(class, fd)
- VALUE class;
- int fd;
-{
- OpenFile *fp;
- NEWOBJ(sock, struct RFile);
- OBJSETUP(sock, class, T_FILE);
-
- MakeOpenFile(sock, fp);
- fp->f = rb_fdopen(fd, "r");
-#ifdef NT
- fp->finalize = sock_finalize;
-#else
- fd = dup(fd);
-#endif
- fp->f2 = rb_fdopen(fd, "w");
- fp->mode = FMODE_READWRITE;
- rb_io_synchronized(fp);
-
- return (VALUE)sock;
-}
-
-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->f2 == 0) {
- return rb_io_close(sock);
- }
- rb_thread_fd_close(fileno(fptr->f));
- fptr->mode &= ~FMODE_READABLE;
-#ifdef NT
- free(fptr->f);
-#else
- fclose(fptr->f);
-#endif
- fptr->f = fptr->f2;
- fptr->f2 = 0;
-
- 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->f2 == 0) {
- return rb_io_close(sock);
- }
- shutdown(fileno(fptr->f2), 1);
- fptr->mode &= ~FMODE_WRITABLE;
-#ifdef NT
- free(fptr->f2);
-#else
- fclose(fptr->f2);
-#endif
- fptr->f2 = 0;
-
- 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;
-
- 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:
- v = rb_str2cstr(val, &vlen);
- }
-
- 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, 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_str_new(buf, len);
-#else
- rb_notimplement();
-#endif
-}
-
-static VALUE
-bsock_getsockname(sock)
- VALUE sock;
-{
- char buf[1024];
- int 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_str_new(buf, len);
-}
-
-static VALUE
-bsock_getpeername(sock)
- VALUE sock;
-{
- char buf[1024];
- int 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_str_new(buf, len);
-}
-
-static VALUE
-bsock_send(argc, argv, sock)
- int argc;
- VALUE *argv;
- VALUE sock;
-{
- VALUE msg, to;
- VALUE flags;
- OpenFile *fptr;
- FILE *f;
- int fd, n;
- char *m, *t;
- int mlen, tlen;
-
- rb_secure(4);
- rb_scan_args(argc, argv, "21", &msg, &flags, &to);
-
- GetOpenFile(sock, fptr);
- f = GetWriteFile(fptr);
- fd = fileno(f);
- retry:
- rb_thread_fd_writable(fd);
- m = rb_str2cstr(msg, &mlen);
- if (RTEST(to)) {
- t = rb_str2cstr(to, &tlen);
- n = sendto(fd, m, mlen, NUM2INT(flags),
- (struct sockaddr*)t, tlen);
- }
- else {
- n = send(fd, m, mlen, NUM2INT(flags));
- }
- if (n < 0) {
- switch (errno) {
- case EINTR:
- rb_thread_schedule();
- goto retry;
- case EWOULDBLOCK:
-#if EAGAIN != EWOULDBLOCK
- case EAGAIN:
-#endif
- rb_thread_fd_writable(fd);
- 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_TCP, /* TCPSocket#recvfrom */
- RECV_UDP, /* UDPSocket#recvfrom */
- RECV_UNIX, /* UNIXSocket#recvfrom */
- RECV_SOCKET, /* Socket#recvfrom */
-};
-
-static VALUE
-s_recv(sock, argc, argv, from)
- VALUE sock;
- int argc;
- VALUE *argv;
- enum sock_recv_type from;
-{
- OpenFile *fptr;
- VALUE str;
- char buf[1024];
- int fd, alen = sizeof buf;
- VALUE len, flg;
- int flags;
-
- rb_scan_args(argc, argv, "11", &len, &flg);
-
- if (flg == Qnil) flags = 0;
- else flags = NUM2INT(flg);
-
- str = rb_str_new(0, NUM2INT(len));
-
- GetOpenFile(sock, fptr);
- fd = fileno(fptr->f);
- rb_thread_wait_fd(fd);
- TRAP_BEG;
- retry:
- 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;
-
- case EWOULDBLOCK:
-#if EAGAIN != EWOULDBLOCK
- case EAGAIN:
-#endif
- rb_thread_wait_fd(fd);
- goto retry;
- }
- rb_sys_fail("recvfrom(2)");
- }
- rb_obj_taint(str);
- switch (from) {
- case RECV_RECV:
- return (VALUE)str;
- case RECV_TCP:
- case RECV_UDP:
-#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_str_new(buf, alen));
- }
-}
-
-static VALUE
-bsock_recv(argc, argv, sock)
- int argc;
- VALUE *argv;
- VALUE sock;
-{
- return s_recv(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, "%s", gai_strerror(error));
- }
-}
-
-static VALUE
-mkipaddr(addr)
- struct sockaddr *addr;
-{
- char buf[1024];
-
- mkipaddr0(addr, buf, sizeof(buf));
- return rb_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));
- }
- else {
- char *name = STR2CSTR(host);
-
- if (*name == 0) {
- mkinetaddr(INADDR_ANY, hbuf, sizeof(hbuf));
- }
- else if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
- mkinetaddr(INADDR_BROADCAST, hbuf, sizeof(hbuf));
- }
- else {
- strcpy(hbuf, name);
- }
- }
- hostp = hbuf;
- if (NIL_P(port)) {
- portp = 0;
- }
- else if (FIXNUM_P(port)) {
- snprintf(pbuf, sizeof(pbuf), "%d", FIX2INT(port));
- portp = pbuf;
- }
- else {
- portp = STR2CSTR(port);
- }
-
- MEMZERO(&hints, struct addrinfo, 1);
- hints.ai_family = PF_UNSPEC;
- hints.ai_socktype = SOCK_DGRAM;
- error = getaddrinfo(hostp, portp, &hints, &res);
- if (error) {
- rb_raise(rb_eSocket, "%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_INET:
- family = rb_str_new2("AF_INET");
- break;
-#ifdef INET6
- case AF_INET6:
- family = rb_str_new2("AF_INET6");
- break;
-#endif
- default:
- family = 0;
- break;
- }
- if (!do_not_reverse_lookup) {
- error = getnameinfo(sockaddr, SA_LEN(sockaddr), hbuf, sizeof(hbuf),
- NULL, 0, 0);
- if (error) {
- rb_raise(rb_eSocket, "%s", gai_strerror(error));
- }
- addr1 = rb_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, "%s", gai_strerror(error));
- }
- addr2 = rb_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 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_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 int
-ruby_connect(fd, sockaddr, len, socks)
- int fd;
- struct sockaddr *sockaddr;
- int len;
- int socks;
-{
- int status;
- int mode;
-
-#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:
-#endif
- thread_write_select(fd);
- continue;
-
-#ifdef EISCONN
- case EISCONN:
- status = 0;
- errno = 0;
- break;
-#endif
- }
- }
-#ifdef HAVE_FCNTL
- mode &= ~NONBLOCKING;
- fcntl(fd, F_SETFL, mode);
-#endif
- return status;
- }
-}
-
-static VALUE
-open_inet(class, h, serv, type)
- VALUE class, h, serv;
- int type;
-{
- struct addrinfo hints, *res, *res0;
- int fd, status;
- char *syscall;
- char pbuf[1024], *portp;
- char *host;
- int error;
-
- if (h) {
- Check_SafeStr(h);
- host = RSTRING(h)->ptr;
- }
- else {
- host = NULL;
- }
- if (FIXNUM_P(serv)) {
- snprintf(pbuf, sizeof(pbuf), "%d", FIX2UINT(serv));
- portp = pbuf;
- }
- else {
- strcpy(pbuf, STR2CSTR(serv));
- 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, &res0);
- if (error) {
- rb_raise(rb_eSocket, "%s", gai_strerror(error));
- }
-
- fd = -1;
- for (res = res0; 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) {
- status = 1;
- setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
- (char*)&status, sizeof(status));
- status = bind(fd, res->ai_addr, res->ai_addrlen);
- syscall = "bind(2)";
- }
- else {
- status = ruby_connect(fd, res->ai_addr, res->ai_addrlen,
- (type == INET_SOCKS));
- syscall = "connect(2)";
- }
-
- if (status < 0) {
- close(fd);
- fd = -1;
- continue;
- } else
- break;
- }
- if (status < 0) {
- if (fd >= 0)
- close(fd);
- freeaddrinfo(res0);
- rb_sys_fail(syscall);
- }
-
- if (type == INET_SERVER)
- listen(fd, 5);
-
- /* create new instance */
- freeaddrinfo(res0);
- return sock_new(class, fd);
-}
-
-static VALUE
-tcp_s_open(class, host, serv)
- VALUE class, host, serv;
-{
- Check_SafeStr(host);
- return open_inet(class, host, serv, INET_CLIENT);
-}
-
-#ifdef SOCKS
-static VALUE
-socks_s_open(class, host, serv)
- VALUE class, host, serv;
-{
- static init = 0;
-
- if (init == 0) {
- SOCKSinit("ruby");
- init = 1;
- }
-
- Check_SafeStr(host);
- return open_inet(class, host, serv, 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;
-
- 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_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_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_s_open(argc, argv, class)
- int argc;
- VALUE *argv;
- VALUE class;
-{
- VALUE arg1, arg2;
-
- if (rb_scan_args(argc, argv, "11", &arg1, &arg2) == 2)
- return open_inet(class, arg1, arg2, INET_SERVER);
- else
- return open_inet(class, 0, arg1, INET_SERVER);
-}
-
-static VALUE
-s_accept(class, fd, sockaddr, len)
- VALUE class;
- int fd;
- struct sockaddr *sockaddr;
- int *len;
-{
- int fd2;
-
- retry:
- rb_thread_wait_fd(fd);
- TRAP_BEG;
- fd2 = accept(fd, sockaddr, len);
- TRAP_END;
- if (fd2 < 0) {
- switch (errno) {
- case EINTR:
- rb_thread_schedule();
- goto retry;
-
- case EWOULDBLOCK:
-#if EAGAIN != EWOULDBLOCK
- case EAGAIN:
-#endif
- rb_thread_wait_fd(fd);
- goto retry;
- }
- rb_sys_fail(0);
- }
- return sock_new(class, fd2);
-}
-
-static VALUE
-tcp_accept(sock)
- VALUE sock;
-{
- OpenFile *fptr;
- struct sockaddr_storage from;
- int fromlen;
-
- GetOpenFile(sock, fptr);
- fromlen = sizeof(from);
- return s_accept(rb_cTCPSocket, fileno(fptr->f),
- (struct sockaddr*)&from, &fromlen);
-}
-
-static VALUE
-tcp_recvfrom(argc, argv, sock)
- int argc;
- VALUE *argv;
- VALUE sock;
-{
- return s_recv(sock, argc, argv, RECV_TCP);
-}
-
-#ifdef HAVE_SYS_UN_H
-static VALUE
-open_unix(class, path, server)
- VALUE class;
- struct RString *path;
- int server;
-{
- struct sockaddr_un sockaddr;
- int fd, status;
- VALUE sock;
- OpenFile *fptr;
-
- Check_SafeStr(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, 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) {
- close(fd);
- rb_sys_fail(sockaddr.sun_path);
- }
-
- if (server) listen(fd, 5);
-
- sock = sock_new(class, fd);
- GetOpenFile(sock, fptr);
- fptr->path = strdup(path->ptr);
-
- return sock;
-}
-#endif
-
-static VALUE
-ip_addr(sock)
- VALUE sock;
-{
- OpenFile *fptr;
- struct sockaddr_storage addr;
- int 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;
- int 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_s_getaddress(obj, host)
- VALUE obj, host;
-{
- struct sockaddr_storage addr;
-
- setipaddr(host, &addr);
- return mkipaddr((struct sockaddr *)&addr);
-}
-
-static VALUE
-udp_s_open(argc, argv, class)
- int argc;
- VALUE *argv;
- VALUE class;
-{
- VALUE arg;
- int socktype = AF_INET;
- int fd;
-
- 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 sock_new(class, fd);
-}
-
-static VALUE
-udp_connect(sock, host, port)
- VALUE sock, host, port;
-{
- OpenFile *fptr;
- int fd;
- struct addrinfo *res0, *res;
-
- 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;
-
- 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;
- char *m;
- int mlen;
- struct addrinfo *res0, *res;
-
- if (argc == 2) {
- return bsock_send(argc, argv, sock);
- }
- rb_scan_args(argc, argv, "4", &mesg, &flags, &host, &port);
-
- GetOpenFile(sock, fptr);
- res0 = ip_addrsetup(host, port);
- f = GetWriteFile(fptr);
- m = rb_str2cstr(mesg, &mlen);
- for (res = res0; res; res = res->ai_next) {
- retry:
- n = sendto(fileno(f), m, mlen, 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;
-
- case EWOULDBLOCK:
-#if EAGAIN != EWOULDBLOCK
- case EAGAIN:
-#endif
- thread_write_select(fileno(f));
- goto retry;
- }
- }
- freeaddrinfo(res0);
- rb_sys_fail("sendto(2)");
- return INT2FIX(n);
-}
-
-static VALUE
-udp_recvfrom(argc, argv, sock)
- int argc;
- VALUE *argv;
- VALUE sock;
-{
- return s_recv(sock, argc, argv, RECV_UDP);
-}
-
-#ifdef HAVE_SYS_UN_H
-static VALUE
-unix_s_sock_open(sock, path)
- VALUE sock, path;
-{
- return open_unix(sock, path, 0);
-}
-
-static VALUE
-unix_path(sock)
- VALUE sock;
-{
- OpenFile *fptr;
-
- GetOpenFile(sock, fptr);
- if (fptr->path == 0) {
- struct sockaddr_un addr;
- int 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_str_new2(fptr->path);
-}
-
-static VALUE
-unix_svr_s_open(sock, path)
- VALUE sock, path;
-{
- return open_unix(sock, path, 1);
-}
-
-static VALUE
-unix_recvfrom(argc, argv, sock)
- int argc;
- VALUE *argv;
- VALUE sock;
-{
- return s_recv(sock, argc, argv, RECV_UNIX);
-}
-
-static VALUE
-unix_accept(sock)
- VALUE sock;
-{
- OpenFile *fptr;
- struct sockaddr_un from;
- int 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_str_new2(sockaddr->sun_path));
-}
-
-static VALUE
-unix_addr(sock)
- VALUE sock;
-{
- OpenFile *fptr;
- struct sockaddr_un addr;
- int len = sizeof addr;
-
- GetOpenFile(sock, fptr);
-
- if (getsockname(fileno(fptr->f), (struct sockaddr*)&addr, &len) < 0)
- rb_sys_fail("getsockname(2)");
- return unixaddr(&addr);
-}
-
-static VALUE
-unix_peeraddr(sock)
- VALUE sock;
-{
- OpenFile *fptr;
- struct sockaddr_un addr;
- int len = sizeof addr;
-
- GetOpenFile(sock, fptr);
-
- if (getpeername(fileno(fptr->f), (struct sockaddr*)&addr, &len) < 0)
- rb_sys_fail("getsockname(2)");
- 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) {
- 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) {
- 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_s_open(class, domain, type, protocol)
- VALUE class, domain, type, protocol;
-{
- int fd;
- int d, t;
-
- setup_domain_and_type(domain, &d, type, &t);
- fd = ruby_socket(d, t, NUM2INT(protocol));
- if (fd < 0) rb_sys_fail("socket(2)");
-
- return sock_new(class, fd);
-}
-
-static VALUE
-sock_s_for_fd(class, fd)
- VALUE class, fd;
-{
- return sock_new(class, NUM2INT(fd));
-}
-
-static VALUE
-sock_s_socketpair(class, domain, type, protocol)
- VALUE class, domain, type, protocol;
-{
-#if !defined(NT) && !defined(__BEOS__) && !defined(__EMX__)
- 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(sock_new(class, sp[0]), sock_new(class, sp[1]));
-#else
- rb_notimplement();
-#endif
-}
-
-static VALUE
-sock_connect(sock, addr)
- VALUE sock, addr;
-{
- OpenFile *fptr;
- int fd;
-
- Check_Type(addr, T_STRING);
- 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;
-
- Check_Type(addr, T_STRING);
- 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;
-
- 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_recv(sock, argc, argv, RECV_SOCKET);
-}
-
-static VALUE
-sock_accept(sock)
- VALUE sock;
-{
- OpenFile *fptr;
- VALUE sock2;
- char buf[1024];
- int len = sizeof buf;
-
- GetOpenFile(sock, fptr);
- sock2 = s_accept(rb_cSocket,fileno(fptr->f),(struct sockaddr*)buf,&len);
-
- return rb_assoc_new(sock2, rb_str_new(buf, len));
-}
-
-#ifdef HAVE_GETHOSTNAME
-static VALUE
-sock_gethostname(obj)
- VALUE obj;
-{
- char buf[1024];
-
- if (gethostname(buf, (int)sizeof buf - 1) < 0)
- rb_sys_fail("gethostname");
-
- buf[sizeof buf - 1] = '\0';
- return rb_str_new2(buf);
-}
-#else
-#ifdef HAVE_UNAME
-
-#include <sys/utsname.h>
-
-static VALUE
-sock_gethostname(obj)
- VALUE obj;
-{
- struct utsname un;
-
- uname(&un);
- return rb_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_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_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_str_new(*pch, h->h_length));
- }
-#else
- rb_ary_push(ary, rb_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 vaddr, vtype;
- int type;
- int alen;
- char *addr;
- struct hostent *h;
-
- rb_scan_args(argc, argv, "11", &vaddr, &vtype);
- addr = rb_str2cstr(vaddr, &alen);
- if (!NIL_P(vtype)) {
- type = NUM2INT(vtype);
- }
- else {
- type = AF_INET;
- }
-
- h = gethostbyaddr(addr, alen, type);
-
- 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 = STR2CSTR(protocol);
-
- sp = getservbyname(STR2CSTR(service), proto);
- if (sp) {
- port = ntohs(sp->s_port);
- }
- else {
- char *s = STR2CSTR(service);
- char *end;
-
- port = strtoul(s, &end, 0);
- if (*end != '\0') {
- rb_raise(rb_eSocket, "no such servce %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, STR2CSTR(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), "%d", FIX2INT(port));
- pptr = pbuf;
- }
- else {
- strncpy(pbuf, STR2CSTR(port), sizeof(pbuf));
- pbuf[sizeof(pbuf) - 1] = '\0';
- pptr = pbuf;
- }
-
- MEMZERO(&hints, struct addrinfo, 1);
- if (!NIL_P(family)) {
- hints.ai_family = NUM2INT(family);
- }
- else {
- hints.ai_family = PF_UNSPEC;
- }
- 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, "%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, host, port, flags;
- static char hbuf[1024], pbuf[1024];
- char *hptr, *pptr;
- int fl;
- struct addrinfo hints, *res = NULL;
- int error;
- struct sockaddr_storage ss;
- struct sockaddr *sap;
-
- sa = flags = Qnil;
- rb_scan_args(argc, argv, "11", &sa, &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) {
- 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];
- }
- }
- if (NIL_P(host)) {
- hptr = NULL;
- }
- else {
- strncpy(hbuf, STR2CSTR(host), sizeof(hbuf));
- hbuf[sizeof(hbuf) - 1] = '\0';
- hptr = hbuf;
- }
- if (NIL_P(port)) {
- strcpy(pbuf, "0");
- pptr = NULL;
- }
- else if (!NIL_P(port)) {
- snprintf(pbuf, sizeof(pbuf), "%d", NUM2INT(port));
- pptr = pbuf;
- }
- else {
- strncpy(pbuf, STR2CSTR(port), sizeof(pbuf));
- pbuf[sizeof(pbuf) - 1] = '\0';
- pptr = pbuf;
- }
- MEMZERO(&hints, struct addrinfo, 1);
- if (strcmp(STR2CSTR(af), "AF_INET") == 0) {
- hints.ai_family = PF_INET;
- }
-#ifdef INET6
- else if (strcmp(STR2CSTR(af), "AF_INET6") == 0) {
- hints.ai_family = PF_INET6;
- }
-#endif
- else {
- hints.ai_family = PF_UNSPEC;
- }
- error = getaddrinfo(hptr, pptr, &hints, &res);
- if (error) {
- rb_raise(rb_eSocket, "%s", gai_strerror(error));
- }
- sap = res->ai_addr;
- }
- else {
- rb_raise(rb_eTypeError, "expecting String or Array");
- }
-
- fl = 0;
- if (!NIL_P(flags)) {
- fl = NUM2INT(flags);
- }
-
- gotsap:
- error = getnameinfo(sap, SA_LEN(sap), hbuf, sizeof(hbuf),
- pbuf, sizeof(pbuf), fl);
- if (error) {
- rb_raise(rb_eSocket, "%s", gai_strerror(error));
- }
- if (res)
- freeaddrinfo(res);
-
- return rb_ary_new3(2, rb_str_new2(hbuf), rb_str_new2(pbuf));
-}
-
-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(CLASS_OF(rb_cBasicSocket), "new");
- rb_undef_method(CLASS_OF(rb_cBasicSocket), "open");
-
- 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_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_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, "open", tcp_s_open, 2);
- rb_define_singleton_method(rb_cTCPSocket, "new", tcp_s_open, 2);
- rb_define_singleton_method(rb_cTCPSocket, "gethostbyname", tcp_s_gethostbyname, 1);
- rb_define_method(rb_cTCPSocket, "recvfrom", tcp_recvfrom, -1);
-
-#ifdef SOCKS
- rb_cSOCKSSocket = rb_define_class("SOCKSSocket", rb_cTCPSocket);
- rb_define_global_const("SOCKSsocket", rb_cSOCKSSocket);
- rb_define_singleton_method(rb_cSOCKSSocket, "open", socks_s_open, 2);
- rb_define_singleton_method(rb_cSOCKSSocket, "new", socks_s_open, 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_singleton_method(rb_cTCPServer, "open", tcp_svr_s_open, -1);
- rb_define_singleton_method(rb_cTCPServer, "new", tcp_svr_s_open, -1);
- rb_define_method(rb_cTCPServer, "accept", tcp_accept, 0);
-
- rb_cUDPSocket = rb_define_class("UDPSocket", rb_cIPSocket);
- rb_define_global_const("UDPsocket", rb_cUDPSocket);
- rb_define_singleton_method(rb_cUDPSocket, "open", udp_s_open, -1);
- rb_define_singleton_method(rb_cUDPSocket, "new", udp_s_open, -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);
- rb_define_method(rb_cUDPSocket, "recvfrom", udp_recvfrom, -1);
-
-#ifdef HAVE_SYS_UN_H
- rb_cUNIXSocket = rb_define_class("UNIXSocket", rb_cBasicSocket);
- rb_define_global_const("UNIXsocket", rb_cUNIXSocket);
- rb_define_singleton_method(rb_cUNIXSocket, "open", unix_s_sock_open, 1);
- rb_define_singleton_method(rb_cUNIXSocket, "new", unix_s_sock_open, 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_cUNIXServer = rb_define_class("UNIXServer", rb_cUNIXSocket);
- rb_define_global_const("UNIXserver", rb_cUNIXServer);
- rb_define_singleton_method(rb_cUNIXServer, "open", unix_svr_s_open, 1);
- rb_define_singleton_method(rb_cUNIXServer, "new", unix_svr_s_open, 1);
- rb_define_method(rb_cUNIXServer, "accept", unix_accept, 0);
-#endif
-
- rb_cSocket = rb_define_class("Socket", rb_cBasicSocket);
- rb_define_singleton_method(rb_cSocket, "open", sock_s_open, 3);
- rb_define_singleton_method(rb_cSocket, "new", sock_s_open, 3);
- rb_define_singleton_method(rb_cSocket, "for_fd", sock_s_for_fd, 1);
-
- 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);
-
- /* 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 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 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 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_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 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 99bec91a1a..0000000000
--- a/ext/socket/sockport.h
+++ /dev/null
@@ -1,43 +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) (len)
-#endif
-
-#endif
diff --git a/ext/tcltklib/MANIFEST b/ext/tcltklib/MANIFEST
deleted file mode 100644
index b5e88278e0..0000000000
--- a/ext/tcltklib/MANIFEST
+++ /dev/null
@@ -1,15 +0,0 @@
-MANIFEST
-README.euc
-MANUAL.euc
-tcltklib.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 e91f9dacbf..0000000000
--- a/ext/tcltklib/depend
+++ /dev/null
@@ -1 +0,0 @@
-tcltklib.o: tcltklib.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 713cc811e5..0000000000
--- a/ext/tcltklib/extconf.rb
+++ /dev/null
@@ -1,49 +0,0 @@
-# extconf.rb for tcltklib
-
-require 'mkmf'
-
-have_library("nsl", "t_open")
-have_library("socket", "socket")
-have_library("dl", "dlopen")
-have_library("m", "log")
-
-dir_config("tk")
-dir_config("tcl")
-dir_config("X11")
-
-tklib = with_config("tklib")
-tcllib = with_config("tcllib")
-
-def find_tcl(tcllib)
- paths = ["/usr/local/lib", "/usr/pkg"]
- func = "Tcl_FindExecutable"
- if tcllib
- find_library(tcllib, func, *paths)
- else
- find_library("tcl", 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)
- paths = ["/usr/local/lib", "/usr/pkg"]
- func = "Tk_Init"
- if tklib
- find_library(tklib, func, *paths)
- else
- find_library("tk", 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/ =~ RUBY_PLATFORM || find_library("X11", "XOpenDisplay",
- "/usr/X11/lib", "/usr/X11R6/lib", "/usr/openwin/lib")) &&
- find_tcl(tcllib) &&
- find_tk(tklib)
- 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/tcltklib.c b/ext/tcltklib/tcltklib.c
deleted file mode 100644
index 314246869e..0000000000
--- a/ext/tcltklib/tcltklib.c
+++ /dev/null
@@ -1,521 +0,0 @@
-/*
- * tcltklib.c
- * Aug. 27, 1997 Y. Shigehiro
- * Oct. 24, 1997 Y. Matsumoto
- */
-
-#include <stdio.h>
-#include <string.h>
-#include <tcl.h>
-#include <tk.h>
-#include "ruby.h"
-#include "rubysig.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 */
-
-/*
- * 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;
-
-/*---- 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;
-}
-
-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_rescue(rb_eval_string, (VALUE)arg, ip_eval_rescue, (VALUE)&failed);
- rb_trap_immediate = old_trapflg;
-
- Tcl_ResetResult(interp);
- if (failed) {
- VALUE eclass = CLASS_OF(failed);
- Tcl_AppendResult(interp, STR2CSTR(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", STR2CSTR(res));
- DUMP1("Tcl_AppendResult");
- Tcl_AppendResult(interp, STR2CSTR(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 = STR2CSTR(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;
-
- encoding = Tcl_GetEncoding(interp,STR2CSTR(encodename));
- buf = ALLOCA_N(char,strlen(STR2CSTR(str))+1);
- strcpy(buf,STR2CSTR(str));
-
- 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;
-
- encoding = Tcl_GetEncoding(interp,STR2CSTR(encodename));
- buf = ALLOCA_N(char,strlen(STR2CSTR(str))+1);
- strcpy(buf,STR2CSTR(str));
-
- 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;
-{
- struct tcltkip *ptr; /* tcltkip data struct */
- int i;
- Tcl_CmdInfo info;
- char *cmd;
- 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 */
- cmd = STR2CSTR(argv[0]);
-
- /* 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) {
- char *s = STR2CSTR(argv[i]);
- ov[i] = Tcl_NewStringObj(s, strlen(s));
- 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) {
- char *s = STR2CSTR(argv[i]);
-
- 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()
-{
- extern VALUE rb_argv0; /* the argv[0] */
-
- VALUE lib = rb_define_module("TclTkLib");
- VALUE ip = rb_define_class("TclTkIp", rb_cObject);
-
- 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);
-
- 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/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/tk.rb b/ext/tk/lib/tk.rb
deleted file mode 100644
index 9f1bae1d40..0000000000
--- a/ext/tk/lib/tk.rb
+++ /dev/null
@@ -1,2470 +0,0 @@
-#
-# tk.rb - Tk interface modue using tcltklib
-# $Date$
-# by Yukihiro Matsumoto <matz@netlab.co.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('{')
- 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('{')
- 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?(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
-
- 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+)/
- 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,b,f,h,k,s,t,w,x,y,aa,ee,kk,nn,ww,tt,xx,yy)
- @serial = seq
- @num = b
- @focus = (f == 1)
- @height = h
- @keycode = k
- @state = s
- @time = t
- @width = w
- @x = x
- @y = y
- @char = aa
- @send_event = (ee == 1)
- @keysym = kk
- @keysym_num = nn
- @type = tt
- @widget = ww
- @x_root = xx
- @y_root = yy
- end
- attr :serial
- attr :num
- attr :focus
- attr :height
- attr :keycode
- attr :state
- attr :time
- attr :width
- attr :x
- attr :y
- attr :char
- attr :send_event
- attr :keysym
- attr :keysym_num
- 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 + ' %# %b %f %h %k %s %t %w %x %y %A %E %K %N %W %T %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 context.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
- private :install_bind, :tk_event_sequence, :_bind_core, :_bind, :_bind_append
-
- 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(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_list(tk_call(*what)).collect{|seq|
- seq[1..-2].gsub(/></,',')
- }
- end
- end
-
- def bindinfo(tagOrClass, context=nil)
- _bindinfo(['bind', tagOrClass], 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", "if {[set st [catch {ruby [format \"TkCore.callback %%Q!%s!\" $args]} ret]] != 0} {return -code $st $ret} {return $ret}")
-
- def callback_break
- raise TkCallbackBreak, "Tk callback returns 'break' status"
- end
-
- def callback_continue
- raise 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 TkCore.callback(arg)
- arg = Array(tk_split_list(arg))
- _get_eval_string(TkUtil.eval_cmd(Tk_CMDTBL[arg.shift], *arg))
- 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.filter{|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.filter{|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 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)
- tk_call 'tk_getOpenFile', *hash_kv(keys)
- end
-
- def getSaveFile(keys)
- tk_call 'tk_getSaveFile', *hash_kv(keys)
- end
-
- def chooseColor(keys)
- tk_call 'tk_chooseColor', *hash_kv(keys)
- end
-
- def tk_call(*args)
- print args.join(" "), "\n" if $DEBUG
- args.filter {|x|_get_eval_string(x)}
- args.compact!
- args.flatten!
- begin
- res = INTERP._invoke(*args)
- rescue NameError
- err = $!
- begin
- args.unshift "unknown"
- res = INTERP._invoke(*args)
- rescue
- raise unless /^invalid command/ =~ $!
- raise err
- end
- end
- if INTERP._return_value() != 0
- fail RuntimeError, res, error_at
- end
- print "==> ", res, "\n" if $DEBUG
- return res
- end
-end
-
-module Tk
- include TkCore
- extend Tk
-
- TCL_VERSION = INTERP._invoke("info", "tclversion")
- TK_VERSION = INTERP._invoke("set", "tk_version")
- 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 toUTF8(str,encoding)
- INTERP._toUTF8(str,encoding)
- end
-
- def 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
- end
-
- module Wm
- include TkComm
- def aspect(*args)
- w = window(tk_call('wm', 'grid', path, *args))
- w.split.collect{|s|s.to_i} 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)
- list(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)
- tk_call 'wm', 'group', path, *args
- 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 not 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)
- list(tk_call('wm', 'sizefrom', path, *args))
- end
- def state
- tk_call 'wm', 'state', path
- end
- def title(*args)
- tk_call 'wm', 'title', path, *args
- end
- def transient(*args)
- tk_call 'wm', 'transient', path, *args
- end
- def withdraw
- tk_call 'wm', 'withdraw', path
- end
- 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"
- raise
- 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"
- raise
- 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
- raise
- 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
- Integer(number(value))
- end
-
- def to_f
- Float(number(value))
- end
-
- def to_s
- String(string(value))
- 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{|i,e|
- 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{|i,e|
- 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 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)
- id = install_cmd(func)
- tk_call 'selection', 'handle', win.path, id, type, format
- end
- def handle(func, type=None, format=None)
- TkSelection.handle self, func, type, format
- end
- def TkSelection.own(win, func=None)
- id = install_cmd(func)
- tk_call 'selection', 'own', win.path, id
- 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 TkWinfo
- include Tk
- extend Tk
- def TkWinfo.atom(name)
- tk_call 'winfo', name
- end
- def winfo_atom(name)
- TkWinfo.atom name
- end
- def TkWinfo.atomname(id)
- tk_call 'winfo', id
- end
- def winfo_atomname(id)
- TkWinfo.atomname id
- end
- def TkWinfo.cells(window)
- number(tk_call('winfo', 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.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)
- list(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)
- number(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', '-displayof', window.path,
- 'interps'))
- 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.appname(window)
- bool(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.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.vrootheigh(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 propagate(master, bool=None)
- bool(tk_call('pack', 'propagate', master.epath, bool))
- end
- module_function :configure, :forget, :propagate
-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 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)
- bool(tk_call('grid', 'propagate', master.epath, bool))
- end
-
- def remove(*args)
- tk_call 'grid', 'remove', *args
- end
-
- def size(master)
- tk_call 'grid', 'size', master
- end
-
- def slaves(args)
- list(tk_call('grid', 'slaves', *hash_kv(args)))
- end
-
- module_function :bbox, :forget, :propagate, :info
- module_function :remove, :size, :slaves, :location
- module_function :configure, :columnconfigure, :rowconfigure
-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['font'])
- slot['font'] = nil
- 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['latinfont'])
- slot['latinfont'] = nil
- latinfont_configure(ltn) if ltn
- end
- if (ltn = slot['asciifont'])
- slot['asciifont'] = nil
- latinfont_configure(ltn) if ltn
- end
- if (knj = slot['kanjifont'])
- slot['kanjifont'] = nil
- 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
-
-class TkObject<TkKernel
- include Tk
- include TkTreatFont
-
- 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)
- tk_tcl2ruby tk_call path, 'cget', "-#{slot}"
- 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
- conf = tk_split_list(tk_send('configure', "-#{slot}") )
- conf[0] = conf[0][1..-1]
- conf
- else
- ret = tk_split_list(tk_send('configure') ).collect{|conf|
- conf[0] = conf[0][1..-1]
- conf
- }
- if ret.assoc('font')
- ret.delete_if{|item| item[0] == 'font' || item[0] == 'kanjifont'}
- ret.push(['font', fontobj])
- else
- ret
- end
- end
- end
- end
-
- def bind(context, cmd=Proc.new, args=nil)
- _bind(["bind", to_eval], context, cmd, args)
- end
-
- def bind_append(context, cmd=Proc.new, args=nil)
- _bind_append(["bind", to_eval], context, cmd, args)
- end
-
- def bindinfo(context=nil)
- _bindinfo(['bind', to_eval], context)
- 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 TkClassBind
-
- def initialize(parent=nil, keys=nil)
- install_win(if parent then parent.path end)
- create_self
- if keys
- # tk_call @path, 'configure', *hash_kv(keys)
- configure(keys)
- end
- end
-
- def create_self
- end
- private :create_self
-
- def pack(keys = nil)
- tk_call 'pack', epath, *hash_kv(keys)
- self
- end
-
- def unpack(keys = nil)
- tk_call 'pack', 'forget', epath
- self
- end
-
- def grid(keys = nil)
- tk_call 'grid', epath, *hash_kv(keys)
- self
- end
-
- def ungrid(keys = nil)
- tk_call 'grid', 'forget', epath
- self
- end
-
- def place(keys = nil)
- tk_call 'place', epath, *hash_kv(keys)
- self
- end
-
- def unplace(keys = nil)
- tk_call 'place', 'forget', epath, *hash_kv(keys)
- self
- end
- alias place_forget unplace
-
- def place_config(keys)
- tk_call "place", 'configure', epath, *hash_kv(keys)
- 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 pack_slaves()
- list(tk_call('pack', 'slaves', epath))
- 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 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'
- tk_call 'grab', 'set', '-global', 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', path, below
- self
- end
- def raise(above=None)
- tk_call 'raise', path, 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', path
- 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', path
- end
-
- def bindtags(taglist=nil)
- if taglist
- fail unless taglist.kind_of? Array
- tk_call('bindtags', path, taglist)
- else
- tk_split_list(tk_call('bindtags', path)).collect{|tag|
- if tag == nil
- '.'
- elsif tag.kind_of?(String) && (cls = WidgetClassNames[tag])
- cls
- 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
-
- 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
- if keys['classname']
- @classname = keys['classname']
- keys['classname'] = nil
- end
- if keys['colormap']
- @colormap = keys['colormap']
- keys['colormap'] = nil
- end
- if keys['container']
- @classname = keys['container']
- keys['classname'] = nil
- end
- if keys['screen']
- @screen = keys['screen']
- keys['screen'] = nil
- end
- if keys['use']
- @use = keys['use']
- keys['use'] = nil
- end
- if keys['visual']
- @screen = keys['visual']
- keys['visual'] = nil
- end
- end
- super(parent, keys)
- end
-
- def create_self
- s = []
- s.push << "-class" << @classname if @classname
- s.push << "-colormap" << @colormap if @colormap
- s.push << "-container" << @container if @container
- s.push << "-screen" << @screen if @screen
- s.push << "-use" << @use if @use
- s.push << "-visual" << @visual if @visual
- tk_call 'toplevel', @path, *s
- end
-
- def specific_class
- @classname
- end
-end
-
-class TkFrame<TkWindow
- WidgetClassName = 'Frame'.freeze
- WidgetClassNames[WidgetClassName] = self
- def self.to_eval
- WidgetClassName
- end
-
- def initialize(parent=nil, keys=nil)
- if keys.kind_of? Hash
- keys = keys.dup
- if keys['classname']
- @classname = keys['classname']
- keys['classname'] = nil
- end
- if keys['colormap']
- @colormap = keys['colormap']
- keys['colormap'] = nil
- end
- if keys['container']
- @classname = keys['container']
- keys['classname'] = nil
- end
- if keys['visual']
- @screen = keys['visual']
- keys['visual'] = nil
- end
- end
- super(parent, keys)
- end
-
- def create_self
- s = []
- s.push << "-class" << @classname if @classname
- s.push << "-colormap" << @colormap if @colormap
- s.push << "-container" << @container if @container
- s.push << "-visual" << @visual if @visual
- tk_call 'frame', @path, *s
- end
-end
-
-class TkLabel<TkWindow
- WidgetClassName = 'Label'.freeze
- WidgetClassNames[WidgetClassName] = self
- def self.to_eval
- WidgetClassName
- end
- def create_self
- tk_call 'label', @path
- 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
- tk_call 'button', @path
- 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
- tk_call 'radiobutton', @path
- end
- def deselect
- tk_send 'deselect'
- end
- def select
- tk_send 'select'
- end
- def variable(v)
- configure 'variable', tk_trace_variable(v)
- end
-end
-
-class TkCheckButton<TkRadioButton
- WidgetClassNames['Checkbutton'] = self
- def TkCheckButton.to_eval
- 'Checkbutton'
- end
- def create_self
- tk_call 'checkbutton', @path
- end
- def toggle
- tk_send 'toggle'
- end
-end
-
-class TkMessage<TkLabel
- WidgetClassNames['Message'] = self
- def TkMessage.to_eval
- 'Message'
- end
- def create_self
- tk_call 'message', @path
- end
-end
-
-class TkScale<TkWindow
- WidgetClassName = 'Scale'.freeze
- WidgetClassNames[WidgetClassName] = self
- def self.to_eval
- WidgetClassName
- end
-
- def create_self
- tk_call 'scale', path
- end
-
- def get
- number(tk_send('get'))
- 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
- tk_call 'scrollbar', path
- 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=None, y=None)
- tk_send('fraction', 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
-end
-
-class TkTextWin<TkWindow
- def create_self
- raise 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
-
-class TkListbox<TkTextWin
- include Scrollable
-
- WidgetClassNames['Listbox'] = self
- def TkListbox.to_eval
- 'Listbox'
- end
- def create_self
- tk_call 'listbox', path
- end
-
- def activate(y)
- tk_send 'activate', y
- end
- def curselection
- list(tk_send('curselection'))
- 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 xview(cmd, *more)
- v = tk_send('xview', cmd, *more)
- v.to_i if more.size == 0
- end
- def yview(cmd, *more)
- v = tk_send('yview', cmd, *more)
- v.to_i if more.size == 0
- end
-end
-
-module TkTreatMenuEntryFont
- def tagfont_configinfo(index)
- pathname = self.path + ';' + index
- ret = TkFont.used_on(pathname)
- if ret == nil
- ret = TkFont.init_widget_font(pathname,
- self.path, 'entryconfigure', index)
- end
- ret
- end
- alias tagfontobj tagfont_configinfo
-
- def tagfont_configure(index, slot)
- pathname = self.path + ';' + index
- if (fnt = slot['font'])
- slot['font'] = nil
- if fnt.kind_of? TkFont
- return fnt.call_font_configure(pathname,
- self.path,'entryconfigure',index,slot)
- else
- latintagfont_configure(index, fnt) if fnt
- end
- end
- if (ltn = slot['latinfont'])
- slot['latinfont'] = nil
- latintagfont_configure(index, ltn) if ltn
- end
- if (ltn = slot['asciifont'])
- slot['asciifont'] = nil
- latintagfont_configure(index, ltn) if ltn
- end
- if (knj = slot['kanjifont'])
- slot['kanjifont'] = nil
- kanjitagfont_configure(index, knj) if knj
- end
-
- tk_call(self.path, 'entryconfigure', index, *hash_kv(slot)) if slot != {}
- self
- end
-
- def latintagfont_configure(index, ltn, keys=nil)
- fobj = tagfontobj(index)
- 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(index, knj, keys=nil)
- fobj = tagfontobj(index)
- 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(index, window, wintag=nil)
- if wintag
- window.tagfontobj(wintag).configinfo.each{|key,value|
- tagfontobj(index).configure(key,value)
- }
- tagfontobj(index).replace(window.tagfontobj(wintag).latin_font,
- window.tagfontobj(wintag).kanji_font)
- else
- window.tagfont(wintag).configinfo.each{|key,value|
- tagfontobj(index).configure(key,value)
- }
- tagfontobj(index).replace(window.fontobj.latin_font,
- window.fontobj.kanji_font)
- end
- end
-
- def latintagfont_copy(index, window, wintag=nil)
- if wintag
- tagfontobj(index).latin_replace(window.tagfontobj(wintag).latin_font)
- else
- tagfontobj(index).latin_replace(window.fontobj.latin_font)
- end
- end
- alias asciitagfont_copy latintagfont_copy
-
- def kanjitagfont_copy(index, window, wintag=nil)
- if wintag
- tagfontobj(index).kanji_replace(window.tagfontobj(wintag).kanji_font)
- else
- tagfontobj(index).kanji_replace(window.fontobj.kanji_font)
- end
- end
-end
-
-class TkMenu<TkWindow
- include TkTreatMenuEntryFont
-
- WidgetClassName = 'Menu'.freeze
- WidgetClassNames[WidgetClassName] = self
- def self.to_eval
- WidgetClassName
- end
- def create_self
- tk_call 'menu', path
- 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 'add', index, type, *hash_kv(keys)
- end
- def delete(index, last=None)
- tk_send 'delete', index, last
- 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 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)
- tk_tcl2ruby tk_send 'entrycget', index, "-#{key}"
- 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
- conf = tk_split_list(tk_send('entryconfigure',index,"-#{key}"))
- conf[0] = conf[0][1..-1]
- conf
- else
- tk_split_list(tk_send('entryconfigure', index)).collect{|conf|
- conf[0] = conf[0][1..-1]
- conf
- }
- end
- end
-end
-
-class TkMenubutton<TkLabel
- WidgetClassNames['Menubutton'] = self
- def TkMenubutton.to_eval
- 'Menubutton'
- end
- def create_self
- tk_call 'menubutton', path
- 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 :TkText, 'tktext'
-autoload :TkDialog, 'tkdialog'
-autoload :TkMenubar, 'tkmenubar'
-autoload :TkAfter, 'tkafter'
-autoload :TkPalette, 'tkpalette'
-autoload :TkFont, 'tkfont'
-autoload :TkVirtualEvent, 'tkvirtevent'
diff --git a/ext/tk/lib/tkafter.rb b/ext/tk/lib/tkafter.rb
deleted file mode 100644
index be2e50ff3a..0000000000
--- a/ext/tk/lib/tkafter.rb
+++ /dev/null
@@ -1,296 +0,0 @@
-#
-# tkafter.rb : methods for Tcl/Tk after command
-# 1998/07/02 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(' ').filter{|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
- ret = @current_proc.call(*args)
- 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
-
- 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]
- 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 c67bc456ed..0000000000
--- a/ext/tk/lib/tkcanvas.rb
+++ /dev/null
@@ -1,814 +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
- def tagfont_configinfo(tagOrId)
- if tagOrId.kind_of?(TkcItem) || tagOrId.kind_of?(TkcTag)
- pathname = self.path + ';' + tagOrId.id.to_s
- else
- pathname = self.path + ';' + tagOrId.to_s
- end
- ret = TkFont.used_on(pathname)
- if ret == nil
- ret = TkFont.init_widget_font(pathname,
- self.path, 'itemconfigure', tagOrId)
- end
- ret
- end
- alias tagfontobj tagfont_configinfo
-
- def tagfont_configure(tagOrId, slot)
- if tagOrId.kind_of?(TkcItem) || tagOrId.kind_of?(TkcTag)
- pathname = self.path + ';' + tagOrId.id.to_s
- else
- pathname = self.path + ';' + tagOrId.to_s
- end
- if (fnt = slot['font'])
- slot['font'] = nil
- if fnt.kind_of? TkFont
- return fnt.call_font_configure(pathname,
- self.path,'itemconfigure',tagOrId,slot)
- else
- latintagfont_configure(tagOrId, fnt) if fnt
- end
- end
- if (ltn = slot['latinfont'])
- slot['latinfont'] = nil
- latintagfont_configure(tagOrId, ltn) if ltn
- end
- if (ltn = slot['asciifont'])
- slot['asciifont'] = nil
- latintagfont_configure(tagOrId, ltn) if ltn
- end
- if (knj = slot['kanjifont'])
- slot['kanjifont'] = nil
- kanjitagfont_configure(tagOrId, knj) if knj
- end
-
- tk_call(self.path, 'itemconfigure', 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(tagOrId).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 TkCanvas<TkWindow
- include TkTreatCItemFont
- include Scrollable
-
- WidgetClassName = 'Canvas'.freeze
- WidgetClassNames[WidgetClassName] = self
- def self.to_eval
- WidgetClassName
- end
-
- def create_self
- tk_call 'canvas', path
- 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))
- 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
- 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).filter{|id|
- TkcItem.id2obj(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(ret)
- end
- end
- end
-
- def gettags(tagOrId)
- list(tk_send('gettags', tagid(tagOrId))).collect{|tag|
- TkcTag.id2obj(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)
- tk_tcl2ruby tk_send 'itemcget', tagid(tagOrId), "-#{option}"
- 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
- conf = tk_split_list(tk_send 'itemconfigure', tagid(tagOrId), "-#{key}")
- conf[0] = conf[0][1..-1]
- conf
- else
- tk_split_list(tk_send 'itemconfigure', tagid(tagOrId)).collect{|conf|
- conf[0] = conf[0][1..-1]
- conf
- }
- end
- end
-
- def lower(tag, below=None)
- tk_send 'lower', tagid(tag), 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), 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
-
- def xview(*index)
- tk_send 'xview', *index
- end
- def yview(*index)
- tk_send 'yview', *index
- 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
-end
-
-class TkcTag<TkObject
- include TkcTagAccess
-
- CTagID_TBL = {}
-
- def TkcTag.id2obj(id)
- CTagID_TBL[id]? CTagID_TBL[id]: id
- end
-
- $tk_canvas_tag = '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
- @path = @id = $tk_canvas_tag
- CTagID_TBL[@id] = self
- $tk_canvas_tag = $tk_canvas_tag.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[@id] = nil
- 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_enclosest(@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 TkcTagAll<TkcTag
- def initialize(parent)
- if not parent.kind_of?(TkCanvas)
- fail format("%s need to be TkCanvas", parent.inspect)
- end
- @c = parent
- @path = @id = 'all'
- CTagID_TBL[@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
- @path = @id = 'current'
- CTagID_TBL[@id] = self
- end
-end
-
-class TkcGroup<TkcTag
- $tk_group_id = 'tkg00000'
- def create_self(parent, *args)
- if not parent.kind_of?(TkCanvas)
- fail format("%s need to be TkCanvas", parent.inspect)
- end
- @c = parent
- @path = @id = $tk_group_id
- CTagID_TBL[@id] = self
- $tk_group_id = $tk_group_id.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(id)
- CItemID_TBL[id]? CItemID_TBL[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
- if args[-1].kind_of? Hash
- keys = args.pop
- end
- @id = create_self(*args).to_i ;# 'canvas item id' is integer number
- CItemID_TBL[@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[@id] = nil
- 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
- $tk_image_id = $tk_image_id.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 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.filter{|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)
- tk_tcl2ruby tk_send 'cget', option
- 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 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 90d5fe3b43..0000000000
--- a/ext/tk/lib/tkentry.rb
+++ /dev/null
@@ -1,73 +0,0 @@
-#
-# tkentry.rb - Tk entry classes
-# $Date$
-# by Yukihiro Matsumoto <matz@caelum.co.jp>
-
-require 'tk.rb'
-
-class TkEntry<TkLabel
- WidgetClassName = 'Entry'.freeze
- WidgetClassNames[WidgetClassName] = self
- def self.to_eval
- WidgetClassName
- end
-
- def create_self
- tk_call 'entry', @path
- end
- def xscrollcommand(cmd=Proc.new)
- configure_cmd 'xscrollcommand', cmd
- end
-
- def delete(s, e=None)
- tk_send 'delete', s, e
- 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()
- tk_send('selection', 'present') == 1
- end
- def selection_range(s, e)
- tk_send 'selection', 'range', s, e
- end
- def selection_to(index)
- tk_send 'selection', 'to', index
- end
- def xview(*index)
- tk_send 'xview', *index
- end
-
- def value
- tk_send 'get'
- end
- def value= (val)
- tk_send 'delete', 0, 'end'
- tk_send 'insert', 0, val
- end
-end
diff --git a/ext/tk/lib/tkfont.rb b/ext/tk/lib/tkfont.rb
deleted file mode 100644
index 2683260d69..0000000000
--- a/ext/tk/lib/tkfont.rb
+++ /dev/null
@@ -1,966 +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 = {}
-
- DEFAULT_LATIN_FONT_NAME = 'a14'.freeze
- DEFAULT_KANJI_FONT_NAME = 'k14'.freeze
-
- ###################################
- # 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)
- keys = {}
- font.configure.each{|key,value| keys[key] = value }
- new_font = 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[*list(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
-
- ###################################
- private
- ###################################
- def initialize(ltn=nil, knj=nil, keys=nil)
- @id = format("@font%.4d", Tk_FontID[0])
- Tk_FontID[0] += 1
- Tk_FontNameTBL[@id] = self
-
- ltn = DEFAULT_LATIN_FONT_NAME unless ltn
- create_latinfont(ltn)
-
- knj = DEFAULT_KANJI_FONT_NAME unless knj
- create_kanjifont(knj)
-
- create_compoundfont(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
- @latinfont = font
-
- 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
- @kanjifont = font
- end
- end
-
- def create_compoundfont_tk4x(keys)
- 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
- tk_call('font', 'create', @latinfont, *hash_kv(font))
- elsif font.kind_of? Array
- tk_call('font', 'create', @latinfont, '-copy', array2tk_list(font))
- elsif font.kind_of? TkFont
- tk_call('font', 'create', @latinfont, '-copy', font.latin_font)
- else
- tk_call('font', 'create', @latinfont, '-copy', font)
- 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}
- else
- actual_core(font).each{|key,val| keys[key] = val}
- end
- tk_call('font', 'create', @latinfont, *hash_kv(keys))
- end
- end
- end
-
- def create_kanjifont_tk80(font)
- unless JAPANIZED_TK
- @kanjifont = ""
- return
- end
-
- @kanjifont = @id + 'k'
-
- 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)
- else
- tk_call('font', 'create', @kanjifont, '-copy', font,
- '-charset', 'jisx0208.1983')
- end
- end
-
- def create_kanjifont_tk81(font)
- @kanjifont = @id + 'k'
-
- 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}
- else
- actual_core(font).each{|key,val| keys[key] = val}
- end
- tk_call('font', 'create', @kanjifont, *hash_kv(keys))
- end
-
- keys = {}
- actual_core(@kanjifont).each{|key,val| keys[key] = val}
- begin
- tk_call('font', 'configure', @compoundfont, *hash_kv(keys))
- rescue
- end
- end
-
- def create_compoundfont_tk80(keys)
- @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
- @fontslot = {'font'=>@compoundfont}
- tk_call('font', 'configure', @compoundfont, *hash_kv(keys))
- end
- end
-
- def create_compoundfont_tk81(keys)
- @compoundfont = @id + 'c'
- 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
-
- 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
-
- @fontslot = {'font'=>@compoundfont}
- tk_call('font', 'configure', @compoundfont, *hash_kv(keys))
- 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, "-#{option}")
- else
- tk_call('font', 'actual', font, "-displayof", window, "-#{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_tk80(knj)
- return self unless JAPANIZED_TK
-
- begin
- tk_call('font', 'delete', @kanjifont)
- rescue
- end
- create_kanjifont(knj)
- self
- end
-
- def kanji_replace_core_tk81(knj)
- if font.kind_of? Hash
- tk_call('font', 'configure', @compoundfont, *hash_kv(knj))
- else
- keys = {}
- if knj.kind_of? Array
- actual_core(array2tk_list(knj)).each{|key,val| keys[key] = val}
- elsif knj.kind_of? TkFont
- actual_core(knj.latin_font).each{|key,val| keys[key] = val}
- else
- actual_core(knj).each{|key,val| keys[key] = val}
- end
- tk_call('font', 'configure', @compoundfont, *hash_kv(keys))
- end
- 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, "-#{option}"))
- else
- number(tk_call('font', 'metrics', font,
- "-displayof", window, "-#{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\.0/
- alias create_latinfont create_latinfont_tk8x
- alias create_kanjifont create_kanjifont_tk80
- alias create_compoundfont create_compoundfont_tk80
- 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_tk80
- alias measure_core measure_core_tk8x
- alias metrics_core metrics_core_tk8x
-
- when /^8\.[12]/
- alias create_latinfont create_latinfont_tk8x
- alias create_kanjifont create_kanjifont_tk81
- alias create_compoundfont create_compoundfont_tk81
- 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_tk81
- 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_tk81
- alias create_compoundfont create_compoundfont_tk81
- 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_tk81
- alias measure_core measure_core_tk8x
- alias metrics_core metrics_core_tk8x
-
- end
-
- ###################################
- public
- ###################################
- 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(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
- configure(slot, value)
- 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 83999cb3e2..0000000000
--- a/ext/tk/lib/tktext.rb
+++ /dev/null
@@ -1,903 +0,0 @@
-#
-# tktext.rb - Tk text classes
-# $Date$
-# by Yukihiro Matsumoto <matz@caelum.co.jp>
-
-require 'tk.rb'
-require 'tkfont'
-
-module TkTreatTextTagFont
- def tagfont_configinfo(tag)
- if tag.kind_of? TkTextTag
- pathname = self.path + ';' + tag.id
- else
- pathname = self.path + ';' + tag
- end
- ret = TkFont.used_on(pathname)
- if ret == nil
- ret = TkFont.init_widget_font(pathname,
- self.path, 'tag', 'configure', tag)
- end
- ret
- end
- alias tagfontobj tagfont_configinfo
-
- def tagfont_configure(tag, slot)
- if tag.kind_of? TkTextTag
- pathname = self.path + ';' + tag.id
- else
- pathname = self.path + ';' + tag
- end
- if (fnt = slot['font'])
- slot['font'] = nil
- if fnt.kind_of? TkFont
- return fnt.call_font_configure(pathname,
- self.path,'tag','configure',tag,slot)
- else
- latintagfont_configure(tag, fnt) if fnt
- end
- end
- if (ltn = slot['latinfont'])
- slot['latinfont'] = nil
- latintagfont_configure(tag, ltn) if ltn
- end
- if (ltn = slot['asciifont'])
- slot['asciifont'] = nil
- latintagfont_configure(tag, ltn) if ltn
- end
- if (knj = slot['kanjifont'])
- slot['kanjifont'] = nil
- kanjitagfont_configure(tag, knj) if knj
- end
-
- tk_call(self.path, 'tag', 'configure', tag, *hash_kv(slot)) if slot != {}
- self
- end
-
- def latintagfont_configure(tag, ltn, keys=nil)
- fobj = tagfontobj(tag)
- 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(tag, knj, keys=nil)
- fobj = tagfontobj(tag)
- 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(tag, window, wintag=nil)
- if wintag
- window.tagfontobj(wintag).configinfo.each{|key,value|
- tagfontobj(tag).configure(key,value)
- }
- tagfontobj(tag).replace(window.tagfontobj(wintag).latin_font,
- window.tagfontobj(wintag).kanji_font)
- else
- window.tagfont(wintag).configinfo.each{|key,value|
- tagfontobj(tag).configure(key,value)
- }
- tagfontobj(tag).replace(window.fontobj.latin_font,
- window.fontobj.kanji_font)
- end
- end
-
- def latintagfont_copy(tag, window, wintag=nil)
- if wintag
- tagfontobj(tag).latin_replace(window.tagfontobj(wintag).latin_font)
- else
- tagfontobj(tag).latin_replace(window.fontobj.latin_font)
- end
- end
- alias asciitagfont_copy latintagfont_copy
-
- def kanjitagfont_copy(tag, window, wintag=nil)
- if wintag
- tagfontobj(tag).kanji_replace(window.tagfontobj(wintag).kanji_font)
- else
- tagfontobj(tag).kanji_replace(window.fontobj.kanji_font)
- end
- end
-end
-
-class TkText<TkTextWin
- include TkTreatTextTagFont
-
- WidgetClassName = 'Text'.freeze
- WidgetClassNames[WidgetClassName] = self
- def self.to_eval
- WidgetClassName
- end
- include Scrollable
- def create_self
- tk_call 'text', @path
- @tags = {}
- 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 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.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(*what)
- tk_send 'yview', *what
- end
- def yview_pickplace(*what)
- tk_send 'yview', '-pickplace', *what
- end
-
- def xview(*what)
- tk_send 'xview', *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)
- tk_tcl2ruby tk_call @path, 'tag', 'cget', tag, "-#{key}"
- 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({key=>val})
- else
- tk_send 'tag', 'configure', tag, "-#{key}", val
- end
- end
- end
-
- def tag_configinfo(tag, key=nil)
- if key
- conf = tk_split_list(tk_send('tag','configure',tag,"-#{key}"))
- conf[0] = conf[0][1..-1]
- conf
- else
- tk_split_list(tk_send('tag', 'configure', tag)).collect{|conf|
- conf[0] = conf[0][1..-1]
- 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 search_with_length(pat,start,stop=None)
- pat = pat.char if pat.kind_of? Integer
- if stop != None
- return ["", 0] if compare(start,'>=',stop)
- txt = get(start,stop)
- if (pos = txt.index(pat))
- pos = txt[0..(pos-1)].split('').length if pos > 0
- if pat.kind_of? String
- return [index(start + " + #{pos} chars"), pat.split('').length]
- else
- return [index(start + " + #{pos} chars"), $&.split('').length]
- end
- else
- return ["", 0]
- end
- else
- txt = get(start,'end - 1 char')
- if (pos = txt.index(pat))
- pos = txt[0..(pos-1)].split('').length if pos > 0
- if pat.kind_of? String
- return [index(start + " + #{pos} chars"), pat.split('').length]
- else
- return [index(start + " + #{pos} chars"), $&.split('').length]
- end
- else
- txt = get('1.0','end - 1 char')
- if (pos = txt.index(pat))
- pos = txt[0..(pos-1)].split('').length if pos > 0
- if pat.kind_of? String
- return [index("1.0 + #{pos} chars"), pat.split('').length]
- else
- return [index("1.0 + #{pos} chars"), $&.split('').length]
- 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.char if pat.kind_of? Integer
- if stop != None
- return ["", 0] if compare(start,'<=',stop)
- txt = get(stop,start)
- if (pos = txt.rindex(pat))
- pos = txt[0..(pos-1)].split('').length if pos > 0
- if pat.kind_of? String
- return [index(stop + " + #{pos} chars"), pat.split('').length]
- else
- return [index(stop + " + #{pos} chars"), $&.split('').length]
- end
- else
- return ["", 0]
- end
- else
- txt = get('1.0',start)
- if (pos = txt.rindex(pat))
- pos = txt[0..(pos-1)].split('').length if pos > 0
- if pat.kind_of? String
- return [index("1.0 + #{pos} chars"), pat.split('').length]
- else
- return [index("1.0 + #{pos} chars"), $&.split('').length]
- end
- else
- txt = get('1.0','end - 1 char')
- if (pos = txt.rindex(pat))
- pos = txt[0..(pos-1)].split('').length if pos > 0
- if pat.kind_of? String
- return [index("1.0 + #{pos} chars"), pat.split('').length]
- else
- return [index("1.0 + #{pos} chars"), $&.split('').length]
- end
- else
- return ["", 0]
- end
- end
- end
- end
-
- def rsearch(pat,start,stop=None)
- rsearch_with_length(pat,start,stop)[0]
- end
-end
-
-class TkTextTag<TkObject
- include TkTreatTagFont
-
- $tk_text_tag = '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_text_tag
- $tk_text_tag = $tk_text_tag.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)
- tk_tcl2ruby tk_call @t.path, 'tag', 'cget', @id, "-#{key}"
- 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_text_mark = '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_text_mark
- $tk_text_mark = $tk_text_mark.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
-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)
- tk_tcl2ruby tk_call @t.path, 'window', 'cget', @index, "-#{slot}"
- 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
- conf = tk_split_list(tk_call @t.path, 'window', 'configure',
- @index, "-#{slot}")
- conf[0] = conf[0][1..-1]
- conf
- else
- tk_split_list(tk_call @t.path, 'window', 'configure',
- @index).collect{|conf|
- conf[0] = conf[0][1..-1]
- conf
- }
- end
- end
-
- def _dump(type, *index)
- str = tk_send('dump', type, *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_tcl2rb(val)
- end
- when 'tagon'
- if val == 'sel'
- if sel
- result.push sel
- else
- result.push TkTextTagSel.new(self)
- end
- else
- result.push tk_tcl2rb val
- end
- when 'tagoff'
- result.push tk_tcl2rb sel
- when 'window'
- result.push tk_tcl2rb 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
- private :_dump
-
- 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)
- _dump('-all', *index)
- end
- def dump_mark(*index)
- _dump('-mark', *index)
- end
- def dump_tag(*index)
- _dump('-tag', *index)
- end
- def dump_text(*index)
- _dump('-text', *index)
- end
- def dump_window(*index)
- _dump('-window', *index)
- 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)
- tk_tcl2ruby tk_call @t.path, 'image', 'cget', @index, "-#{slot}"
- 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
- conf = tk_split_list(tk_call @t.path, 'image', 'configure',
- @index, "-#{slot}")
- conf[0] = conf[0][1..-1]
- conf
- else
- tk_split_list(tk_call @t.path, 'image', 'configure',
- @index).collect{|conf|
- conf[0] = conf[0][1..-1]
- conf
- }
- end
- end
-end
diff --git a/ext/tk/lib/tkvirtevent.rb b/ext/tk/lib/tkvirtevent.rb
deleted file mode 100644
index 0d100c2186..0000000000
--- a/ext/tk/lib/tkvirtevent.rb
+++ /dev/null
@@ -1,66 +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
-
- TkVirturlEventID = [0]
- TkVirturlEventTBL = {}
-
- def TkVirtualEvent.getobj(event)
- obj = TkVirturlEventTBL[event]
- obj ? obj : event
- end
-
- def TkVirtualEvent.info
- tk_call('event', 'info').split(/\s+/).filter{|seq|
- TkVirtualEvent.getobj(seq[1..-2])
- }
- end
-
- def initialize(*sequences)
- @path = @id = format("<VirtEvent%.4d>", TkVirturlEventID[0])
- TkVirturlEventID[0] += 1
- add(*sequences)
- end
-
- def add(*sequences)
- if sequences != []
- tk_call('event', 'add', "<#{@id}>",
- *(sequences.collect{|seq| "<#{tk_event_sequence(seq)}>"}) )
- TkVirturlEventTBL[@id] = self
- end
- self
- end
-
- def delete(*sequences)
- if sequences == []
- tk_call('event', 'delete', "<#{@id}>")
- TkVirturlEventTBL[@id] = nil
- else
- tk_call('event', 'delete', "<#{@id}>",
- *(sequences.collect{|seq| "<#{tk_event_sequence(seq)}>"}) )
- TkVirturlEventTBL[@id] = nil if info == []
- end
- self
- end
-
- def info
- tk_call('event', 'info', "<#{@id}>").split(/\s+/).filter{|seq|
- l = seq.scan(/<*[^<>]+>*/).filter{|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 d2d7bf7beb..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 f.gets()
- $_.chop!
- next if /^From / # skip From-line
- break if /^$/ # end of header
- if /^(\S+):\s*(.*)/
- @header[attr = $1.capitalize] = $2
- elsif attr
- sub(/^\s*/, '')
- @header[attr] += "\n" + $_
- end
- end
-
- return if ! $_
-
- while f.gets()
- break if /^From /
- @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 ba0e547799..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 f.gets()
- $_.chop!
- next if /^From / # skip From-line
- break if /^$/ # end of header
- if /^(\S+):\s*(.*)/
- @header[attr = $1.capitalize] = $2
- elsif attr
- sub(/^\s*/, '')
- @header[attr] += "\n" + $_
- end
- end
-
- return if ! $_
-
- while f.gets()
- break if /^From /
- @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 9d4ca0a9d0..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);
-}
-
-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_iterator_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 deaa40d9b4..0000000000
--- a/file.c
+++ /dev/null
@@ -1,2095 +0,0 @@
-/************************************************
-
- file.c -
-
- $Author$
- $Date$
- created at: Mon Nov 15 12:24:34 JST 1993
-
- Copyright (C) 1993-1999 Yukihiro Matsumoto
-
-************************************************/
-
-#ifdef NT
-#include "missing/file.h"
-#endif
-
-#include "ruby.h"
-#include "rubyio.h"
-#include "rubysig.h"
-
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#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 USE_CWGUSI
- #include "macruby_missing.h"
- extern int fileno(FILE *stream);
- extern int utimes();
- char* strdup(char*);
-#endif
-
-#ifdef __EMX__
-#define lstat stat
-#endif
-
-VALUE rb_cFile;
-VALUE rb_mFileTest;
-static VALUE rb_cStat;
-
-static int
-apply2files(func, vargs, arg)
- int (*func)();
- VALUE vargs;
- void *arg;
-{
- int i;
- VALUE path;
- struct RArray *args = RARRAY(vargs);
-
- for (i=0; i<args->len; i++) {
- Check_SafeStr(args->ptr[i]);
- }
-
- for (i=0; i<args->len; i++) {
- path = args->ptr[i];
- if ((*func)(RSTRING(path)->ptr, arg) < 0)
- rb_sys_fail(RSTRING(path)->ptr);
- }
-
- 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);
-}
-
-#ifndef NT
-# ifndef USE_CWGUSI
-# include <sys/file.h>
-# endif
-#else
-#include "missing/file.h"
-#endif
-
-static VALUE
-stat_new(st)
- struct stat *st;
-{
- struct stat *nst;
- if (!st) rb_bug("stat_new() called with bad value");
-
- nst = ALLOC(struct stat);
- *nst = *st;
- return Data_Wrap_Struct(rb_cStat, NULL, free, nst);
-}
-
-static struct stat*
-get_stat(self)
- VALUE self;
-{
- struct stat* st;
- Data_Get_Struct(self, struct stat, st);
- if (!st) rb_bug("collapsed File::Stat");
- return st;
-}
-
-static VALUE
-rb_stat_cmp(self, other)
- VALUE self, other;
-{
- 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);
-}
-
-static VALUE
-rb_stat_dev(self)
- VALUE self;
-{
- return INT2FIX((int)get_stat(self)->st_dev);
-}
-
-static VALUE
-rb_stat_ino(self)
- VALUE self;
-{
- return INT2FIX((int)get_stat(self)->st_ino);
-}
-
-static VALUE
-rb_stat_mode(self)
- VALUE self;
-{
- return INT2FIX((int)get_stat(self)->st_mode);
-}
-
-static VALUE
-rb_stat_nlink(self)
- VALUE self;
-{
- return INT2FIX((int)get_stat(self)->st_nlink);
-}
-
-static VALUE
-rb_stat_uid(self)
- VALUE self;
-{
- return INT2FIX((int)get_stat(self)->st_uid);
-}
-
-static VALUE
-rb_stat_gid(self)
- VALUE self;
-{
- return INT2FIX((int)get_stat(self)->st_gid);
-}
-
-static VALUE
-rb_stat_rdev(self)
- VALUE self;
-{
-#ifdef HAVE_ST_RDEV
- return INT2FIX((int)get_stat(self)->st_rdev);
-#else
- return INT2FIX(0);
-#endif
-}
-
-static VALUE
-rb_stat_size(self)
- VALUE self;
-{
- return INT2FIX((int)get_stat(self)->st_size);
-}
-
-static VALUE
-rb_stat_blksize(self)
- VALUE self;
-{
-#ifdef HAVE_ST_BLKSIZE
- return INT2FIX((int)get_stat(self)->st_blksize);
-#else
- return INT2FIX(0);
-#endif
-}
-
-static VALUE
-rb_stat_blocks(self)
- VALUE self;
-{
-#ifdef HAVE_ST_BLOCKS
- return INT2FIX((int)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 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);
- }
- Check_SafeStr(file);
-#if defined DJGPP
- if (RSTRING(file)->len == 0) return -1;
-#endif
- return stat(RSTRING(file)->ptr, st);
-}
-
-static VALUE
-rb_file_s_stat(obj, fname)
- VALUE obj, fname;
-{
- struct stat st;
-
- Check_SafeStr(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(obj, fname)
- VALUE obj, fname;
-{
-#if !defined(MSDOS) && !defined(NT) && !defined(__EMX__)
- struct stat st;
-
- Check_SafeStr(fname);
- if (lstat(RSTRING(fname)->ptr, &st) == -1) {
- rb_sys_fail(RSTRING(fname)->ptr);
- }
- return stat_new(&st);
-#else
- rb_notimplement();
- return Qnil; /* not reached */
-#endif
-}
-
-static VALUE
-rb_file_lstat(obj)
- VALUE obj;
-{
-#if !defined(MSDOS) && !defined(NT)
- 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
- rb_notimplement();
- return Qnil; /* not reached */
-#endif
-}
-
-static int
-group_member(gid)
- GETGROUPS_T gid;
-{
-#if !defined(NT) && !defined(USE_CWGUSI)
- if (getgid() == gid || getegid() == gid)
- return Qtrue;
-
-# ifdef HAVE_GETGROUPS
-# ifndef NGROUPS
-# define NGROUPS 32
-# 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;
-{
-#ifndef NT
- struct stat st;
- static int euid = -1;
-
- if (stat(path, &st) < 0) return (-1);
-
- if (euid == -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;
- }
-
- if (st.st_uid == euid) /* owner */
- mode <<= 6;
- else if (group_member (st.st_gid))
- mode <<= 3;
-
- if (st.st_mode & mode) return 0;
-
- return -1;
-#else /* !NT*/
- return 0;
-#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;
-
- Check_SafeStr(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_ISBLK(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;
-{
- Check_SafeStr(fname);
- if (eaccess(RSTRING(fname)->ptr, R_OK) < 0) return Qfalse;
- return Qtrue;
-}
-
-static VALUE
-test_R(obj, fname)
- VALUE obj, fname;
-{
- Check_SafeStr(fname);
- if (access(RSTRING(fname)->ptr, R_OK) < 0) return Qfalse;
- return Qtrue;
-}
-
-static VALUE
-test_w(obj, fname)
- VALUE obj, fname;
-{
- Check_SafeStr(fname);
- if (eaccess(RSTRING(fname)->ptr, W_OK) < 0) return Qfalse;
- return Qtrue;
-}
-
-static VALUE
-test_W(obj, fname)
- VALUE obj, fname;
-{
- Check_SafeStr(fname);
- if (access(RSTRING(fname)->ptr, W_OK) < 0) return Qfalse;
- return Qtrue;
-}
-
-static VALUE
-test_x(obj, fname)
- VALUE obj, fname;
-{
- Check_SafeStr(fname);
- if (eaccess(RSTRING(fname)->ptr, X_OK) < 0) return Qfalse;
- return Qtrue;
-}
-
-static VALUE
-test_X(obj, fname)
- VALUE obj, fname;
-{
- Check_SafeStr(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 rb_int2inum(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(file, mode)
- const char *file;
- int mode;
-{
- struct stat st;
-
- if (stat(file, &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
- Check_SafeStr(fname);
- return check3rdbyte(RSTRING(fname)->ptr, S_ISUID);
-#else
- return Qfalse;
-#endif
-}
-
-static VALUE
-test_sgid(obj, fname)
- VALUE obj, fname;
-{
-#ifndef NT
- Check_SafeStr(fname);
- return check3rdbyte(RSTRING(fname)->ptr, S_ISGID);
-#else
- return Qfalse;
-#endif
-}
-
-static VALUE
-test_sticky(obj, fname)
- VALUE obj, fname;
-{
-#ifdef S_ISVTX
- return check3rdbyte(STR2CSTR(fname), S_ISVTX);
-#else
- return Qnil;
-#endif
-}
-
-static VALUE
-rb_file_s_size(obj, fname)
- VALUE obj, 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(obj, fname)
- VALUE obj, fname;
-{
- struct stat st;
-
-#if defined(MSDOS) || defined(NT)
- if (rb_stat(fname, &st) < 0)
- rb_sys_fail(RSTRING(fname)->ptr);
-#else
- Check_SafeStr(fname);
- if (lstat(RSTRING(fname)->ptr, &st) == -1) {
- rb_sys_fail(RSTRING(fname)->ptr);
- }
-#endif
-
- return rb_file_ftype(&st);
-}
-
-static VALUE
-rb_file_s_atime(obj, fname)
- VALUE obj, 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(obj, fname)
- VALUE obj, 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(obj, fname)
- VALUE obj, 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) == -1)
- rb_sys_fail(path);
-}
-
-static VALUE
-rb_file_s_chmod(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE vmode;
- VALUE rest;
- int mode, n;
-
- 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);
-#if defined(DJGPP) || defined(NT) || defined(USE_CWGUSI) || defined(__BEOS__) || defined(__EMX__)
- if (!fptr->path) return Qnil;
- if (chmod(fptr->path, mode) == -1)
- rb_sys_fail(fptr->path);
-#else
- if (fchmod(fileno(fptr->f), mode) == -1)
- rb_sys_fail(fptr->path);
-#endif
-
- return INT2FIX(0);
-}
-
-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_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(USE_CWGUSI) || 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);
-}
-
-struct timeval rb_time_timeval();
-
-#ifdef HAVE_UTIMES
-
-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)
-# 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(obj, from, to)
- VALUE obj, from, to;
-{
-#if defined(USE_CWGUSI)
- rb_notimplement();
-#else
- Check_SafeStr(from);
- Check_SafeStr(to);
-
- if (link(RSTRING(from)->ptr, RSTRING(to)->ptr) < 0)
- rb_sys_fail(RSTRING(from)->ptr);
- return INT2FIX(0);
-#endif /* USE_CWGUSI */
-}
-
-static VALUE
-rb_file_s_symlink(obj, from, to)
- VALUE obj, from, to;
-{
-#if !defined(MSDOS) && !defined(NT) && !defined(__EMX__)
- Check_SafeStr(from);
- Check_SafeStr(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(obj, path)
- VALUE obj, path;
-{
-#if !defined(MSDOS) && !defined(NT) && !defined(__EMX__)
- char buf[MAXPATHLEN];
- int cc;
-
- Check_SafeStr(path);
-
- if ((cc = readlink(RSTRING(path)->ptr, buf, MAXPATHLEN)) < 0)
- rb_sys_fail(RSTRING(path)->ptr);
-
- return rb_tainted_str_new(buf, cc);
-#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(obj, args)
- VALUE obj, args;
-{
- int n;
-
- n = apply2files(unlink_internal, args, 0);
- return INT2FIX(n);
-}
-
-static VALUE
-rb_file_s_rename(obj, from, to)
- VALUE obj, from, to;
-{
- Check_SafeStr(from);
- Check_SafeStr(to);
-
- if (rename(RSTRING(from)->ptr, RSTRING(to)->ptr) < 0)
- rb_sys_fail(RSTRING(from)->ptr);
-
- return INT2FIX(0);
-}
-
-static VALUE
-rb_file_s_umask(argc, argv)
- int argc;
- VALUE *argv;
-{
-#ifdef USE_CWGUSI
- rb_notimplement();
-#else
- 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 # of argument");
- }
- return INT2FIX(omask);
-#endif /* USE_CWGUSI */
-}
-
-#if defined DOSISH
-#define isdirsep(x) ((x) == '/' || (x) == '\\')
-#else
-#define isdirsep(x) ((x) == '/')
-#endif
-
-VALUE
-rb_file_s_expand_path(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE fname, dname;
- char *s, *p;
- char buf[MAXPATHLEN+2];
- int tainted = 0;
-
- rb_scan_args(argc, argv, "11", &fname, &dname);
-
- s = STR2CSTR(fname);
- p = buf;
- 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);
- }
- strcpy(buf, dir);
- p = &buf[strlen(buf)];
- s++;
- tainted = 1;
- }
- else {
-#ifdef HAVE_PWD_H
- struct passwd *pwPtr;
- s++;
-#endif
- while (*s && !isdirsep(*s)) {
- *p++ = *s++;
- }
- *p = '\0';
-#ifdef HAVE_PWD_H
- pwPtr = getpwnam(buf);
- if (!pwPtr) {
- endpwent();
- rb_raise(rb_eArgError, "user %s doesn't exist", buf);
- }
- strcpy(buf, pwPtr->pw_dir);
- p = &buf[strlen(buf)];
- endpwent();
-#endif
- }
- }
-#if defined DOSISH
- /* skip drive letter */
- else if (isalpha(s[0]) && s[1] == ':' && isdirsep(s[2])) {
- while (*s && !isdirsep(*s)) {
- *p++ = *s++;
- }
- }
-#endif
- else if (!isdirsep(*s)) {
- if (argc == 2) {
- dname = rb_file_s_expand_path(1, &dname);
- if (OBJ_TAINTED(dname)) tainted = 1;
- strcpy(buf, RSTRING(dname)->ptr);
- }
- else {
- tainted = 1;
-#ifdef HAVE_GETCWD
- getcwd(buf, MAXPATHLEN);
-#else
- getwd(buf);
-#endif
- }
- p = &buf[strlen(buf)];
- while (p > buf && *(p - 1) == '/') p--;
- }
- else if (isdirsep(*s)) {
- while (*s && isdirsep(*s)) {
- *p++ = '/';
- s++;
- }
- if (p > buf && *s) p--;
- }
- *p = '/';
-
- for ( ; *s; s++) {
- switch (*s) {
- case '.':
- if (*(s+1)) {
- switch (*++s) {
- case '.':
- if (*(s+1) == '\0' || isdirsep(*(s+1))) {
- /* We must go back to the parent */
- if (isdirsep(*p) && p > buf) p--;
- while (p > buf && !isdirsep(*p)) p--;
- }
- else {
- *++p = '.';
- *++p = '.';
- }
- break;
- case '/':
-#if defined DOSISH
- case '\\':
-#endif
- if (!isdirsep(*p)) *++p = '/';
- break;
- default:
- *++p = '.'; *++p = *s; break;
- }
- }
- break;
- case '/':
-#if defined DOSISH
- case '\\':
-#endif
- if (!isdirsep(*p)) *++p = '/'; break;
- default:
- *++p = *s;
- }
- }
-
- /* Place a \0 at end. If path ends with a "/", delete it */
- if (p == buf || !isdirsep(*p)) p++;
- *p = '\0';
-
- fname = rb_str_new2(buf);
- if (tainted) OBJ_TAINT(fname);
- return fname;
-}
-
-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 = STR2CSTR(fext);
- }
- name = STR2CSTR(fname);
- p = strrchr(name, '/');
- if (!p) {
- if (!NIL_P(fext)) {
- f = rmext(name, ext);
- if (f) return rb_str_new(name, f);
- }
- return fname;
- }
- p++; /* skip last `/' */
- if (!NIL_P(fext)) {
- f = rmext(p, ext);
- if (f) return rb_str_new(p, f);
- }
- basename = rb_str_new2(p);
- if (OBJ_TAINTED(fname)) OBJ_TAINT(basename);
- return basename;
-}
-
-static VALUE
-rb_file_s_dirname(obj, fname)
- VALUE obj, fname;
-{
- char *name, *p;
- VALUE dirname;
-
- name = STR2CSTR(fname);
- p = strrchr(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(obj, path)
- VALUE obj, 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(obj, args)
- VALUE obj, args;
-{
- return rb_ary_join(args, separator);
-}
-
-static VALUE
-rb_file_s_truncate(obj, path, len)
- VALUE obj, path, len;
-{
- Check_SafeStr(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 defined(EWOULDBLOCK)
-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 EINTR: /* can be happen? */
- case EWOULDBLOCK:
- rb_thread_schedule(); /* busy wait */
- rb_io_check_closed(fptr);
- break;
- 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;
-{
-#ifdef USE_CWGUSI
- rb_notimplement();
-#else
- OpenFile *fptr;
-
- rb_secure(2);
- GetOpenFile(obj, fptr);
-
- if (flock(fileno(fptr->f), NUM2INT(operation)) < 0) {
-#ifdef EWOULDBLOCK
- if (errno == EWOULDBLOCK) {
- return Qfalse;
- }
-#endif
- rb_sys_fail(fptr->path);
- }
- return INT2FIX(0);
-#endif /* USE_CWGUSI */
-}
-#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 # of arguments(%d for %d)", argc, n);
- for (i=1; i<n; i++) {
- switch (TYPE(argv[i])) {
- case T_STRING:
- Check_SafeStr(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 # of arguments");
- 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_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_ISBLK(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;
-{
-#ifndef NT
- 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 Qnil;
-}
-
-static VALUE rb_mConst;
-
-void
-rb_file_const(name, value)
- const char *name;
- VALUE value;
-{
- rb_define_const(rb_cFile, name, value);
- rb_define_const(rb_mConst, name, value);
-}
-
-void
-Init_File()
-{
- rb_mFileTest = rb_define_module("FileTest");
-
- rb_define_module_function(rb_mFileTest, "directory?", test_d, 1);
- rb_define_module_function(rb_mFileTest, "exist?", test_e, 1);
- rb_define_module_function(rb_mFileTest, "exists?", test_e, 1); /* temporary */
- rb_define_module_function(rb_mFileTest, "readable?", test_r, 1);
- rb_define_module_function(rb_mFileTest, "readable_real?", test_R, 1);
- rb_define_module_function(rb_mFileTest, "writable?", test_w, 1);
- rb_define_module_function(rb_mFileTest, "writable_real?", test_W, 1);
- rb_define_module_function(rb_mFileTest, "executable?", test_x, 1);
- rb_define_module_function(rb_mFileTest, "executable_real?", test_X, 1);
- rb_define_module_function(rb_mFileTest, "file?", test_f, 1);
- rb_define_module_function(rb_mFileTest, "zero?", test_z, 1);
- rb_define_module_function(rb_mFileTest, "size?", test_s, 1);
- rb_define_module_function(rb_mFileTest, "size", test_s, 1);
- rb_define_module_function(rb_mFileTest, "owned?", test_owned, 1);
- rb_define_module_function(rb_mFileTest, "grpowned?", test_grpowned, 1);
-
- rb_define_module_function(rb_mFileTest, "pipe?", test_p, 1);
- rb_define_module_function(rb_mFileTest, "symlink?", test_l, 1);
- rb_define_module_function(rb_mFileTest, "socket?", test_S, 1);
-
- rb_define_module_function(rb_mFileTest, "blockdev?", test_b, 1);
- rb_define_module_function(rb_mFileTest, "chardev?", test_c, 1);
-
- rb_define_module_function(rb_mFileTest, "setuid?", test_suid, 1);
- rb_define_module_function(rb_mFileTest, "setgid?", test_sgid, 1);
- rb_define_module_function(rb_mFileTest, "sticky?", test_sticky, 1);
-
- rb_cFile = rb_define_class("File", rb_cIO);
- rb_extend_object(rb_cFile, CLASS_OF(rb_mFileTest));
-
- 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, "size", rb_file_s_size, 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, "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_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);
-
-#ifdef DOSISH
- rb_define_const(rb_cFile, "ALT_SEPARATOR", rb_str_new2("\\"));
-#else
- rb_define_const(rb_cFile, "ALT_SEPARATOR", Qnil);
-#endif
- rb_define_const(rb_cFile, "PATH_SEPARATOR", 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_mConst = rb_define_module_under(rb_cFile, "Constants");
- 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_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, "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, "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 ad0e2d2ebf..0000000000
--- a/gc.c
+++ /dev/null
@@ -1,1220 +0,0 @@
-/************************************************
-
- gc.c -
-
- $Author$
- $Date$
- created at: Tue Oct 5 09:44:46 JST 1993
-
- Copyright (C) 1993-1999 Yukihiro Matsumoto
-
-************************************************/
-
-#include "ruby.h"
-#include "rubysig.h"
-#include "st.h"
-#include "node.h"
-#include "env.h"
-#include "re.h"
-#include <stdio.h>
-#include <setjmp.h>
-
-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
-
-#ifdef C_ALLOCA
-#ifndef alloca
-void *alloca();
-#endif
-#endif
-
-static void run_final();
-
-#ifndef GC_MALLOC_LIMIT
-#if defined(MSDOS) || defined(__human68k__)
-#define GC_MALLOC_LIMIT 100000
-#else
-#define GC_MALLOC_LIMIT 400000
-#endif
-#endif
-#define GC_NEWOBJ_LIMIT 10000
-
-static unsigned long malloc_memories = 0;
-static unsigned long alloc_objects = 0;
-
-static int malloc_called = 0;
-static int free_called = 0;
-static int second_mem_error = 0;
-
-static void
-mem_error(mesg)
- char *mesg;
-{
- if (rb_safe_level() >= 4) {
- rb_raise(rb_eNoMemError, mesg);
- }
- rb_fatal(mesg);
-}
-
-#ifndef xmalloc
-void *
-xmalloc(size)
- size_t size;
-{
- void *mem;
-
- if (size < 0) {
- rb_raise(rb_eArgError, "negative allocation size (or too big)");
- }
- if (size == 0) size = 1;
- malloc_memories += size;
- if (malloc_memories > GC_MALLOC_LIMIT && alloc_objects > GC_NEWOBJ_LIMIT) {
- rb_gc();
- }
- malloc_called++;
- mem = malloc(size);
- if (!mem) {
- rb_gc();
- mem = malloc(size);
- if (!mem) {
- if (size >= 10 * 1024 * 1024) {
- rb_raise(rb_eNoMemError, "try to allocate too big memory");
- }
- mem_error("failed to allocate memory");
- }
- }
-
- return mem;
-}
-
-void *
-xcalloc(n, size)
- size_t n, size;
-{
- void *mem;
-
- mem = xmalloc(n * size);
- memset(mem, 0, n * size);
-
- return mem;
-}
-
-void *
-xrealloc(ptr, size)
- void *ptr;
- size_t 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;
- mem = realloc(ptr, size);
- if (!mem) {
- rb_gc();
- mem = realloc(ptr, size);
- if (!mem)
- if (size >= 10 * 1024 * 1024) {
- rb_raise(rb_eNoMemError, "try to re-allocate too big memory");
- }
- mem_error("failed to allocate memory(realloc)");
- }
-
- return mem;
-}
-
-static void
-xfree(x)
- void *x;
-{
- free_called++;
- free(x);
-}
-#endif
-
-/* The way of garbage collecting which allows use of the cstack is due to */
-/* Scheme In One Defun, but in C this time.
-
- * COPYRIGHT (c) 1989 BY *
- * PARADIGM ASSOCIATES INCORPORATED, CAMBRIDGE, MASSACHUSETTS. *
- * ALL RIGHTS RESERVED *
-
-Permission to use, copy, modify, distribute and sell this software
-and its documentation for any purpose and without fee is hereby
-granted, provided that the above copyright notice appear in all copies
-and that both that copyright notice and this permission notice appear
-in supporting documentation, and that the name of Paradigm Associates
-Inc not be used in advertising or publicity pertaining to distribution
-of the software without specific, written prior permission.
-
-PARADIGM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
-ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
-PARADIGM BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
-ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
-WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
-ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
-SOFTWARE.
-
-gjc@paradigm.com
-
-Paradigm Associates Inc Phone: 617-492-6079
-29 Putnam Ave, Suite 6
-Cambridge, MA 02138
-*/
-
-extern int ruby_in_compile;
-static int dont_gc;
-static int during_gc;
-static int need_call_final = 0;
-
-static VALUE
-gc_enable()
-{
- int old = dont_gc;
-
- dont_gc = Qfalse;
- return old;
-}
-
-static VALUE
-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_global_variable(var)
- VALUE *var;
-{
- struct gc_list *tmp;
-
- tmp = ALLOC(struct gc_list);
- tmp->next = Global_List;
- tmp->varptr = var;
- Global_List = tmp;
-}
-
-typedef struct RVALUE {
- union {
- struct {
- unsigned long flag; /* 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;
-
-#define HEAPS_INCREMENT 10
-static RVALUE **heaps;
-static int heaps_length = 0;
-static int heaps_used = 0;
-
-#define HEAP_SLOTS 10000
-#define FREE_MIN 512
-
-static RVALUE *himem, *lomem;
-
-static void
-add_heap()
-{
- RVALUE *p, *pend;
-
- if (heaps_used == heaps_length) {
- /* Realloc heaps */
- heaps_length += HEAPS_INCREMENT;
- 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");
- }
-
- p = heaps[heaps_used++] = (RVALUE*)malloc(sizeof(RVALUE)*HEAP_SLOTS);
- if (p == 0) mem_error("add_heap: can't alloc memory");
- pend = p + HEAP_SLOTS;
- if (lomem == 0 || lomem > p) lomem = p;
- if (himem < pend) himem = pend;
-
- while (p < pend) {
- p->as.free.flag = 0;
- p->as.free.next = freelist;
- freelist = p;
- p++;
- }
-}
-#define RANY(o) ((RVALUE*)(o))
-
-VALUE
-rb_newobj()
-{
- VALUE obj;
-
- if (freelist) {
- retry:
- obj = (VALUE)freelist;
- freelist = freelist->as.free.next;
- alloc_objects++;
- return obj;
- }
- if (dont_gc || during_gc || rb_prohibit_interrupt) add_heap();
- else rb_gc();
-
- goto retry;
-}
-
-VALUE
-rb_data_object_alloc(klass, datap, dmark, dfree)
- VALUE klass;
- void *datap;
- void (*dfree)();
- void (*dmark)();
-{
- 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;
-
-#if defined(__GNUC__) && __GNUC__ >= 2
-__inline__
-#endif
-static int
-looks_pointerp(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 + HEAP_SLOTS
- && ((((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 (looks_pointerp(*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)
- void *obj;
-{
- if (looks_pointerp(obj)) {
- rb_gc_mark(obj);
- }
-}
-
-void
-rb_gc_mark(ptr)
- void *ptr;
-{
- register RVALUE *obj = RANY(ptr);
-
- Top:
- if (FIXNUM_P(obj)) return; /* fixnum not marked */
- if (rb_special_const_p((VALUE)obj)) 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;
-
- 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:
- 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(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(obj->as.node.u1.node);
- /* fall through */
- case NODE_SUPER: /* 3 */
- case NODE_FCALL:
- case NODE_DEFN:
- case NODE_NEWLINE:
- obj = RANY(obj->as.node.u3.node);
- goto Top;
-
- 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(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_PUSH:
- case NODE_IASGN:
- case NODE_CASGN:
- case NODE_MODULE:
- case NODE_COLON3:
- case NODE_OPT_N:
- obj = RANY(obj->as.node.u2.node);
- goto Top;
-
- case NODE_HASH: /* 1 */
- case NODE_LIT:
- case NODE_STR:
- case NODE_XSTR:
- case NODE_DEFINED:
- case NODE_MATCH:
- case NODE_RETURN:
- case NODE_YIELD:
- case NODE_COLON2:
- case NODE_ARGS:
- obj = RANY(obj->as.node.u1.node);
- goto Top;
-
- case NODE_SCOPE: /* 2,3 */
- case NODE_CLASS:
- case NODE_BLOCK_PASS:
- rb_gc_mark(obj->as.node.u3.node);
- obj = RANY(obj->as.node.u2.node);
- goto Top;
-
- 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_BREAK:
- case NODE_NEXT:
- 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);
- obj = RANY(obj->as.node.u2.node);
- goto Top;
-#endif
-
- default:
- if (looks_pointerp(obj->as.node.u1.node)) {
- rb_gc_mark(obj->as.node.u1.node);
- }
- if (looks_pointerp(obj->as.node.u2.node)) {
- rb_gc_mark(obj->as.node.u2.node);
- }
- if (looks_pointerp(obj->as.node.u3.node)) {
- obj = RANY(obj->as.node.u3.node);
- goto Top;
- }
- }
- 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++);
- }
- break;
-
- case T_HASH:
- rb_mark_hash(obj->as.hash.tbl);
- rb_gc_mark(obj->as.hash.ifnone);
- break;
-
- case T_STRING:
- if (obj->as.string.orig) {
- obj = RANY(obj->as.string.orig);
- goto Top;
- }
- 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:
- break;
-
- case T_MATCH:
- if (obj->as.match.str) {
- obj = RANY(obj->as.match.str);
- goto Top;
- }
- break;
-
- case T_VARMAP:
- rb_gc_mark(obj->as.varmap.val);
- obj = RANY(obj->as.varmap.next);
- goto Top;
- break;
-
- case T_SCOPE:
- if (obj->as.scope.local_vars &&
- obj->as.scope.flag != SCOPE_ALLOCA) {
- 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,
- looks_pointerp(obj)?"corrupted object":"non object");
- }
-}
-
-#define MIN_FREE_OBJ 512
-
-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) {
- /* sould not reclaim nodes during compilation */
- for (i = 0; i < used; i++) {
- p = heaps[i]; pend = p + HEAP_SLOTS;
- while (p < pend) {
- if (!(p->as.basic.flags&FL_MARK) && BUILTIN_TYPE(p) == T_NODE)
- rb_gc_mark(p);
- p++;
- }
- }
- }
-
- freelist = 0;
- final_list = 0;
- for (i = 0; i < used; i++) {
- int n = 0;
-
- p = heaps[i]; pend = p + HEAP_SLOTS;
- 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.flag = FL_MARK; /* remain marked */
- p->as.free.next = final_list;
- final_list = p;
- }
- else {
- p->as.free.flag = 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 (need_call_final) {
- RVALUE *tmp;
-
- for (p = final_list; p; p = tmp) {
- tmp = p->as.free.next;
- run_final((VALUE)p);
- p->as.free.flag = 0;
- p->as.free.next = freelist;
- freelist = p;
- }
- }
-}
-
-void
-rb_gc_force_recycle(p)
- VALUE p;
-{
- RANY(p)->as.free.flag = 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:
- rb_clear_cache();
- 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:
-#define STR_NO_ORIG FL_USER3 /* copied from string.c */
- if (!RANY(obj)->as.string.orig || FL_TEST(obj, STR_NO_ORIG))
- free(RANY(obj)->as.string.ptr);
- break;
- case T_ARRAY:
- if (RANY(obj)->as.array.ptr) 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) free(RANY(obj)->as.regexp.str);
- break;
- case T_DATA:
- if (DATA_PTR(obj)) {
- if ((long)RANY(obj)->as.data.dfree == -1) {
- 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);
- 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);
- free(RANY(obj)->as.file.fptr);
- }
- break;
- case T_ICLASS:
- /* iClass shares table with the module */
- break;
-
- case T_FLOAT:
- case T_VARMAP:
- break;
-
- case T_BIGNUM:
- if (RANY(obj)->as.bignum.digits) free(RANY(obj)->as.bignum.digits);
- break;
- case T_NODE:
- switch (nd_type(obj)) {
- case NODE_SCOPE:
- if (RANY(obj)->as.node.u1.tbl) {
- free(RANY(obj)->as.node.u1.tbl);
- }
- break;
-#ifdef C_ALLOCA
- case NODE_ALLOCA:
- free(RANY(obj)->as.node.u1.value);
- break;
-#endif
- }
- return; /* no need to free iv_tbl */
-
- case T_SCOPE:
- if (RANY(obj)->as.scope.local_vars &&
- RANY(obj)->as.scope.flag != SCOPE_ALLOCA) {
- VALUE *vars = RANY(obj)->as.scope.local_vars-1;
- if (vars[0] == 0)
- free(RANY(obj)->as.scope.local_tbl);
- if (RANY(obj)->as.scope.flag&SCOPE_MALLOC)
- free(vars);
- }
- break;
-
- case T_STRUCT:
- if (RANY(obj)->as.rstruct.ptr)
- free(RANY(obj)->as.rstruct.ptr);
- break;
-
- default:
- rb_bug("gc_sweep(): unknown data type %d",
- 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
-_rb_setjmp:
- move.l 4(sp),a0
- movem.l d3-d7/a3-a5,(a0)
- moveq.l #0,d0
- rts");
-#else
-#if defined(DJGPP)
-typedef unsigned long rb_jmp_buf[6];
-__asm__ (".align 4
-_rb_setjmp:
- pushl %ebp
- movl %esp,%ebp
- movl 8(%ebp),%ebp
- movl %eax,(%ebp)
- movl %ebx,4(%ebp)
- movl %ecx,8(%ebp)
- movl %edx,12(%ebp)
- movl %esi,16(%ebp)
- movl %edi,20(%ebp)
- popl %ebp
- xorl %eax,%eax
- 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
- VALUE *stack_end = alloca(1);
-# define STACK_END (stack_end)
-#endif
-
- alloc_objects = 0;
- malloc_memories = 0;
-
- if (during_gc) return;
- during_gc++;
-
- /* 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(ruby_class);
- rb_gc_mark(ruby_scope);
- rb_gc_mark(ruby_dyna_vars);
-
- 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(THINK_C) || defined(__human68k__)
-#ifndef __human68k__
- mark_locations_array((VALUE*)((char*)save_regs_gc_mark+2),
- sizeof(save_regs_gc_mark) / sizeof(VALUE *));
-#endif
- 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_sweep();
-}
-
-static VALUE
-gc_start()
-{
- rb_gc();
- return Qnil;
-}
-
-void
-Init_stack(addr)
- VALUE *addr;
-{
-#ifdef __human68k__
- extern void *_SEND;
- rb_gc_stack_start = _SEND;
-#else
- VALUE start;
-
- if (!addr) addr = &start;
- rb_gc_stack_start = addr;
-#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 + HEAP_SLOTS;
- 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:
- 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 + HEAP_SLOTS;
- 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 (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;
-{
- 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_ary_delete(finalizers, proc);
- return proc;
-}
-
-static VALUE
-finals()
-{
- return finalizers;
-}
-
-static VALUE
-call_final(os, obj)
- VALUE os, obj;
-{
- need_call_final = 1;
- FL_SET(obj, FL_FINALIZE);
- return obj;
-}
-
-static VALUE
-run_single_final(args)
- VALUE *args;
-{
- rb_eval_cmd(args[0], args[1]);
- return Qnil;
-}
-
-static void
-run_final(obj)
- VALUE obj;
-{
- int i, status;
- VALUE args[2];
-
- obj = rb_obj_id(obj); /* make obj into id */
- args[1] = rb_ary_new3(1, obj);
- for (i=0; i<RARRAY(finalizers)->len; i++) {
- args[0] = RARRAY(finalizers)->ptr[i];
- rb_protect(run_single_final, (VALUE)args, &status);
- }
-}
-
-void
-rb_gc_call_finalizer_at_exit()
-{
- RVALUE *p, *pend;
- int i;
-
- /* run finalizers */
- for (i = 0; i < heaps_used; i++) {
- p = heaps[i]; pend = p + HEAP_SLOTS;
- while (p < pend) {
- if (FL_TEST(p, FL_FINALIZE))
- run_final((VALUE)p);
- p++;
- }
- }
- /* run data object's finaliers */
- for (i = 0; i < heaps_used; i++) {
- p = heaps[i]; pend = p + HEAP_SLOTS;
- while (p < pend) {
- if (BUILTIN_TYPE(p) == T_DATA &&
- DATA_PTR(p) && RANY(p)->as.data.dfree) {
- (*RANY(p)->as.data.dfree)(DATA_PTR(p));
- }
- else if (BUILTIN_TYPE(p) == T_FILE) {
- rb_io_fptr_finalize(RANY(p)->as.file.fptr);
- }
- p++;
- }
- }
-}
-
-static VALUE
-id2ref(obj, id)
- VALUE obj, id;
-{
- unsigned long ptr;
-
- rb_secure(4);
- ptr = NUM2UINT(id);
- if (FIXNUM_P(ptr)) return (VALUE)ptr;
- if (ptr == Qtrue) return Qtrue;
- if (ptr == Qfalse) return Qfalse;
- if (ptr == Qnil) return Qnil;
-
- ptr = id ^ FIXNUM_FLAG;
- if (!looks_pointerp(ptr)) {
- rb_raise(rb_eIndexError, "0x%x is not id value", ptr);
- }
- if (BUILTIN_TYPE(ptr) == 0) {
- rb_raise(rb_eIndexError, "0x%x is recycled object", ptr);
- }
- return (VALUE)ptr;
-}
-
-void
-Init_GC()
-{
- VALUE rb_mObSpace;
-
- rb_mGC = rb_define_module("GC");
- rb_define_singleton_method(rb_mGC, "start", gc_start, 0);
- rb_define_singleton_method(rb_mGC, "enable", gc_enable, 0);
- rb_define_singleton_method(rb_mGC, "disable", gc_disable, 0);
- rb_define_method(rb_mGC, "garbage_collect", 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", 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, "_id2ref", id2ref, 1);
-
- rb_global_variable(&finalizers);
- finalizers = rb_ary_new();
-}
diff --git a/hash.c b/hash.c
deleted file mode 100644
index bfead82e8a..0000000000
--- a/hash.c
+++ /dev/null
@@ -1,1527 +0,0 @@
-/************************************************
-
- hash.c -
-
- $Author$
- $Date$
- created at: Mon Nov 22 18:51:18 JST 1993
-
- Copyright (C) 1993-1999 Yukihiro Matsumoto
-
-************************************************/
-
-#include "ruby.h"
-#include "st.h"
-#include "util.h"
-#include "rubysig.h"
-
-#include <sys/types.h>
-#include <sys/stat.h>
-
-#ifndef HAVE_STRING_H
-char *strchr _((char*,char));
-#endif
-
-#ifdef USE_CWGUSI
-char* strdup(const char*);
-#endif
-
-#define HASH_FREEZE FL_USER1
-#define HASH_DELETED FL_USER2
-
-static void
-rb_hash_modify(hash)
- VALUE hash;
-{
- if (FL_TEST(hash, HASH_FREEZE))
- rb_raise(rb_eTypeError, "can't modify 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;
-{
- if (rb_safe_level() >= 4 && !OBJ_TAINTED(hash))
- rb_raise(rb_eSecurityError, "Insecure: can't freeze hash");
-
- FL_SET(hash, HASH_FREEZE);
- return hash;
-}
-
-static VALUE
-rb_hash_frozen_p(hash)
- VALUE hash;
-{
- if (FL_TEST(hash, HASH_FREEZE))
- return Qtrue;
- return Qfalse;
-}
-
-VALUE rb_cHash;
-
-static VALUE envtbl;
-static ID hash;
-
-VALUE
-rb_hash(obj)
- VALUE obj;
-{
- return rb_funcall(obj, 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)) {
- if (FIXNUM_P(b)) return a != b;
- }
- else if (TYPE(a) == T_STRING) {
- if (TYPE(b) == T_STRING) return rb_str_cmp(a, b);
- }
-
- args[0] = a;
- args[1] = b;
- return !rb_with_disable_interrupt(eql, (VALUE)args);
-}
-
-static int
-rb_any_hash(a)
- VALUE a;
-{
- unsigned int hval;
-
- switch (TYPE(a)) {
- case T_FIXNUM:
- hval = a;
- break;
-
- case T_STRING:
- hval = rb_str_hash(a);
- break;
-
- default:
- DEFER_INTS;
- hval = rb_funcall(a, hash, 0);
- if (!FIXNUM_P(hval)) {
- hval = rb_funcall(hval, '%', 1, INT2FIX(65439));
- }
- ENABLE_INTS;
- hval = FIX2LONG(hval);
- }
- return 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 == Qnil) 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, Qnil);
- 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_new(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- VALUE ifnone;
-
- NEWOBJ(hash, struct RHash);
- OBJSETUP(hash, klass, T_HASH);
-
- hash->iter_lev = 0;
- hash->ifnone = Qnil;
- hash->tbl = 0; /* avoid GC crashing */
-
- rb_scan_args(argc, argv, "01", &ifnone);
-
- hash->ifnone = ifnone;
- hash->tbl = st_init_table(&objhash);
-
- return (VALUE)hash;
-}
-
-static VALUE
-rb_hash_new2(klass)
- VALUE klass;
-{
- NEWOBJ(hash, struct RHash);
- OBJSETUP(hash, klass, T_HASH);
-
- hash->iter_lev = 0;
- hash->ifnone = Qnil;
- hash->tbl = 0; /* avoid GC crashing */
- hash->tbl = st_init_table(&objhash);
-
- return (VALUE)hash;
-}
-
-VALUE
-rb_hash_new()
-{
- return rb_hash_new2(rb_cHash);
-}
-
-static VALUE
-rb_hash_s_create(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- VALUE hash;
- int i;
-
- if (argc == 1) {
- if (TYPE(argv[0]) == T_HASH) {
- NEWOBJ(hash, struct RHash);
- OBJSETUP(hash, klass, T_HASH);
-
- hash->iter_lev = 0;
- hash->ifnone = Qnil;
- hash->tbl = 0; /* avoid GC crashing */
- hash->tbl = st_copy(RHASH(argv[0])->tbl);
-
- return (VALUE)hash;
- }
- else {
- VALUE a = rb_Array(argv[0]);
- return rb_hash_s_create(RARRAY(a)->len, RARRAY(a)->ptr, klass);
- }
- }
-
- if (argc % 2 != 0) {
- rb_raise(rb_eArgError, "odd number args for Hash");
- }
- hash = rb_hash_new2(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;
-{
- NEWOBJ(hash2, struct RHash);
- CLONESETUP(hash2, hash);
-
- hash2->iter_lev = 0;
- hash2->ifnone = RHASH(hash)->ifnone;
- hash2->tbl = 0; /* avoid GC crashing */
- hash2->tbl = (st_table*)st_copy(RHASH(hash)->tbl);
-
- return (VALUE)hash2;
-}
-
-static VALUE
-rb_hash_dup(hash)
- VALUE hash;
-{
- NEWOBJ(hash2, struct RHash);
- OBJSETUP(hash2, CLASS_OF(hash), T_HASH);
-
- hash2->iter_lev = 0;
- hash2->ifnone = RHASH(hash)->ifnone;
- hash2->tbl = 0; /* avoid GC crashing */
- hash2->tbl = (st_table*)st_copy(RHASH(hash)->tbl);
-
- return (VALUE)hash2;
-}
-
-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 != Qnil) {
- 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 RHASH(hash)->ifnone;
- }
- 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_iterator_p()) {
- if (argc > 1) {
- rb_raise(rb_eArgError, "wrong # of arguments", argc);
- }
- return rb_yield(argv[0]);
- }
- if (argc == 1) {
- rb_raise(rb_eIndexError, "key not found");
- }
- return if_none;
- }
- return val;
-}
-
-static VALUE
-rb_hash_default(hash)
- VALUE hash;
-{
- return RHASH(hash)->ifnone;
-}
-
-static VALUE
-rb_hash_set_default(hash, ifnone)
- VALUE hash, ifnone;
-{
- RHASH(hash)->ifnone = ifnone;
- return hash;
-}
-
-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;
-
- indexes = rb_ary_new2(argc);
- for (i=0; i<argc; i++) {
- RARRAY(indexes)->ptr[i] = rb_hash_aref(hash, argv[i]);
- }
- RARRAY(indexes)->len = i;
- return indexes;
-}
-
-static VALUE
-rb_hash_delete(hash, key)
- VALUE hash, key;
-{
- VALUE val;
-
- rb_hash_modify(hash);
- if (RHASH(hash)->iter_lev > 0 &&
- st_delete_safe(RHASH(hash)->tbl, &key, &val, Qnil)) {
- FL_SET(hash, HASH_DELETED);
- return val;
- }
- else if (st_delete(RHASH(hash)->tbl, &key, &val))
- return val;
- if (rb_iterator_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 == Qnil) 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 Qnil;
- return rb_assoc_new(var.key, var.val);
-}
-
-static int
-delete_if_i(key, value)
- VALUE key, value;
-{
- if (key == Qnil) return ST_CONTINUE;
- if (RTEST(rb_yield(rb_assoc_new(key, value))))
- return ST_DELETE;
- return ST_CONTINUE;
-}
-
-static VALUE
-rb_hash_delete_if(hash)
- VALUE hash;
-{
- rb_hash_modify(hash);
- rb_hash_foreach(hash, delete_if_i, 0);
-
- return hash;
-}
-
-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;
-{
- 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 == Qnil) 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 == Qnil) 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 == Qnil) 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 == Qnil) 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);
-
- return ary;
-}
-
-static VALUE
-rb_hash_sort(hash)
- VALUE hash;
-{
- return rb_ary_sort_bang(rb_hash_to_a(hash));
-}
-
-static int
-inspect_i(key, value, str)
- VALUE key, value, str;
-{
- VALUE str2;
-
- if (key == Qnil) return ST_CONTINUE;
- if (RSTRING(str)->len > 1) {
- rb_str_cat(str, ", ", 2);
- }
- str2 = rb_inspect(key);
- rb_str_cat(str, RSTRING(str2)->ptr, RSTRING(str2)->len);
- rb_str_cat(str, "=>", 2);
- str2 = rb_inspect(value);
- rb_str_cat(str, RSTRING(str2)->ptr, RSTRING(str2)->len);
-
- return ST_CONTINUE;
-}
-
-static VALUE
-inspect_hash(hash)
- VALUE hash;
-{
- VALUE str;
-
- str = rb_str_new2("{");
- st_foreach(RHASH(hash)->tbl, inspect_i, str);
- rb_str_cat(str, "}", 1);
-
- return str;
-}
-
-static VALUE
-rb_hash_inspect(hash)
- VALUE hash;
-{
- if (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
-hash_to_s(hash)
- VALUE hash;
-{
- VALUE str;
-
- if (rb_inspecting_p(hash)) return rb_str_new2("{...}");
- str = rb_ary_to_s(rb_hash_to_a(hash));
- if (OBJ_TAINTED(hash)) OBJ_TAINT(str);
- return hash;
-}
-
-static VALUE
-rb_hash_to_s(hash)
- VALUE hash;
-{
- if (rb_inspecting_p(hash)) return rb_str_new2("{...}");
- return rb_protect_inspect(hash_to_s, 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 == Qnil) 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 == Qnil) 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 == Qnil) 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 == Qnil) 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 (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 == Qnil) 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 == Qnil) return ST_CONTINUE;
- rb_hash_aset(hash, key, value);
- return ST_CONTINUE;
-}
-
-static VALUE
-rb_hash_update(hash1, hash2)
- VALUE hash1, hash2;
-{
- hash2 = to_hash(hash2);
- st_foreach(RHASH(hash2)->tbl, rb_hash_update_i, hash1);
- return hash1;
-}
-
-static int path_tainted = -1;
-
-#ifndef NT
-extern char **environ;
-#endif
-static char **origenviron;
-
-static VALUE
-env_delete(obj, name)
- VALUE obj, name;
-{
- int len;
- char *nam, *val;
-
- rb_secure(4);
- nam = str2cstr(name, &len);
- if (strlen(nam) != len) {
- rb_raise(rb_eArgError, "bad environment variable name");
- }
- val = getenv(nam);
- if (val) {
- ruby_setenv(nam, 0);
- if (strcmp(nam, "PATH") == 0 && !OBJ_TAINTED(name)) {
- path_tainted = 0;
- }
- return rb_tainted_str_new2(val);
- }
- return Qnil;
-}
-
-static VALUE
-env_delete_method(obj, name)
- VALUE obj, name;
-{
- VALUE val = env_delete(obj, name);
- if (rb_iterator_p()) rb_yield(name);
- return val;
-}
-
-static VALUE
-rb_f_getenv(obj, name)
- VALUE obj, name;
-{
- char *nam, *env;
- int len;
-
- nam = str2cstr(name, &len);
- if (strlen(nam) != 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 int
-path_check_1(path)
- char *path;
-{
- struct stat st;
- char *p = 0;
- char *s;
-
- for (;;) {
- if (stat(path, &st) == 0 && (st.st_mode & 002)) {
- return 0;
- }
- s = strrchr(path, '/');
- if (p) *p = '/';
- if (!s || s == path) return 1;
- p = s;
- *p = '\0';
- }
-}
-
-int
-rb_path_check(path)
- char *path;
-{
- char *p, *pend;
- const char sep = PATH_SEP_CHAR;
-
- if (!path) return 1;
-
- p = path;
- pend = strchr(path, sep);
-
- for (;;) {
- int safe;
-
- if (pend) *pend = '\0';
- safe = path_check_1(p);
- if (!pend) break;
- *pend = sep;
- if (!safe) {
- return 0;
- }
- p = pend + 1;
- pend = strchr(p, sep);
- }
- return 1;
-}
-
-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);
-
- for (i = 0; environ[i]; i++) {
- if (
-#ifdef WIN32
- strnicmp(environ[i],nam,len) == 0
-#else
- memcmp(environ[i],nam,len) == 0
-#endif
- && environ[i][len] == '=')
- break; /* memcmp must come first to avoid */
- } /* potential SEGV's */
- return i;
-}
-
-void
-ruby_setenv(name, value)
- const char *name;
- const char *value;
-{
-#if defined(WIN32) && !defined(__CYGWIN32__)
-#ifdef USE_WIN32_RTL_ENV
- register char *envstr;
- STRLEN namlen = strlen(name);
- STRLEN vallen;
- char *oldstr = environ[envix(name)];
-
- /* putenv() has totally broken semantics in both the Borland
- * and Microsoft CRTLs. They either store the passed pointer in
- * the environment without making a copy, or make a copy and don't
- * free it. And on top of that, they dont free() old entries that
- * are being replaced/deleted. This means the caller must
- * free any old entries somehow, or we end up with a memory
- * leak every time setenv() is called. One might think
- * one could directly manipulate environ[], like the UNIX code
- * above, but direct changes to environ are not allowed when
- * calling putenv(), since the RTLs maintain an internal
- * *copy* of environ[]. Bad, bad, *bad* stink.
- * GSAR 97-06-07
- */
-
- if (!value) {
- if (!oldstr)
- return;
- value = "";
- vallen = 0;
- }
- else
- vallen = strlen(val);
- envstr = ALLOC_N(char, namelen + vallen + 3);
- sprintf(envstr,"%s=%s",name,value);
- putenv(envstr);
- if (oldstr) free(oldstr);
-#ifdef _MSC_VER
- free(envstr); /* MSVCRT leaks without this */
-#endif
-
-#else /* !USE_WIN32_RTL_ENV */
-
- /* 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
- */
- SetEnvironmentVariable(name,value);
-#endif
-
-#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) {
- 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 {
- 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
-rb_f_setenv(obj, nm, val)
- VALUE obj, nm, val;
-{
- char *name, *value;
- int nlen, vlen;
-
- if (rb_safe_level() >= 4) {
- rb_raise(rb_eSecurityError, "cannot change environment variable");
- }
-
- if (NIL_P(val)) {
- env_delete(obj, nm);
- return Qnil;
- }
-
- name = str2cstr(nm, &nlen);
- value = str2cstr(val, &vlen);
- if (strlen(name) != nlen)
- rb_raise(rb_eArgError, "bad environment variable name");
- if (strlen(value) != vlen)
- 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 Qtrue;
- }
- else {
- path_tainted_p(value);
- }
- }
- return Qtrue;
-}
-
-static VALUE
-env_keys()
-{
- char **env;
- VALUE ary = rb_ary_new();
-
- env = environ;
- while (*env) {
- char *s = strchr(*env, '=');
- if (s) {
- rb_ary_push(ary, rb_tainted_str_new(*env, s-*env));
- }
- env++;
- }
- return ary;
-}
-
-static VALUE
-env_each_key(hash)
- VALUE hash;
-{
- char **env;
-
- env = environ;
- while (*env) {
- char *s = strchr(*env, '=');
- if (s) {
- rb_yield(rb_tainted_str_new(*env, s-*env));
- }
- env++;
- }
- return Qnil;
-}
-
-static VALUE
-env_values()
-{
- char **env;
- VALUE ary = rb_ary_new();
-
- env = environ;
- while (*env) {
- char *s = strchr(*env, '=');
- if (s) {
- rb_ary_push(ary, rb_tainted_str_new2(s+1));
- }
- env++;
- }
- return ary;
-}
-
-static VALUE
-env_each_value(hash)
- VALUE hash;
-{
- char **env;
-
- env = environ;
- while (*env) {
- char *s = strchr(*env, '=');
- if (s) {
- rb_yield(rb_tainted_str_new2(s+1));
- }
- env++;
- }
- return Qnil;
-}
-
-static VALUE
-env_each(hash)
- VALUE hash;
-{
- char **env;
-
- env = 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++;
- }
- return Qnil;
-}
-
-static VALUE
-env_delete_if()
-{
- volatile VALUE keys;
- VALUE *ptr;
- int len;
-
- 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);
- }
- }
- ptr++;
- }
- return envtbl;
-}
-
-static VALUE
-env_to_s()
-{
- return rb_str_new2("ENV");
-}
-
-static VALUE
-env_to_a()
-{
- char **env;
- VALUE ary = rb_ary_new();
-
- env = 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++;
- }
- return ary;
-}
-
-static VALUE
-env_none()
-{
- return Qnil;
-}
-
-static VALUE
-env_size()
-{
- int i;
-
- for(i=0; environ[i]; i++)
- ;
- return INT2FIX(i);
-}
-
-static VALUE
-env_empty_p()
-{
- if (environ[0] == 0) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-env_has_key(env, key)
- VALUE env, key;
-{
- if (TYPE(key) != T_STRING) return Qfalse;
- if (getenv(STR2CSTR(key))) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-env_has_value(dmy, value)
- VALUE dmy, value;
-{
- char **env;
-
- if (TYPE(value) != T_STRING) return Qfalse;
- env = environ;
- while (*env) {
- char *s = strchr(*env, '=')+1;
- if (s) {
- if (strncmp(s, RSTRING(value)->ptr, strlen(s)) == 0)
- return Qtrue;
- }
- env++;
- }
- return Qfalse;
-}
-
-static VALUE
-env_index(dmy, value)
- VALUE dmy, value;
-{
- char **env;
-
- if (TYPE(value) != T_STRING) return Qnil;
- env = environ;
- while (*env) {
- char *s = strchr(*env, '=')+1;
- if (s) {
- if (strncmp(s, RSTRING(value)->ptr, strlen(s)) == 0) {
- return rb_tainted_str_new(*env, s-*env);
- }
- }
- env++;
- }
- return Qnil;
-}
-
-static VALUE
-env_indexes(argc, argv)
- int argc;
- VALUE *argv;
-{
- int i;
- VALUE indexes = rb_ary_new2(argc);
-
- 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(obj)
- VALUE obj;
-{
- char **env;
- VALUE hash = rb_hash_new();
-
- env = 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++;
- }
- return hash;
-}
-
-void
-Init_Hash()
-{
- hash = rb_intern("hash");
-
- rb_cHash = rb_define_class("Hash", rb_cObject);
-
- rb_include_module(rb_cHash, rb_mEnumerable);
-
- rb_define_singleton_method(rb_cHash, "new", rb_hash_s_new, -1);
- rb_define_singleton_method(rb_cHash, "[]", rb_hash_s_create, -1);
-
- rb_define_method(rb_cHash,"clone", rb_hash_clone, 0);
- rb_define_method(rb_cHash,"dup", rb_hash_dup, 0);
- rb_define_method(rb_cHash,"rehash", rb_hash_rehash, 0);
-
- rb_define_method(rb_cHash,"freeze", rb_hash_freeze, 0);
- rb_define_method(rb_cHash,"frozen?",rb_hash_frozen_p, 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, 0);
- 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,"reject!", rb_hash_delete_if, 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,"[]=", rb_f_setenv, 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_method, 1);
- rb_define_singleton_method(envtbl,"delete_if", env_delete_if, 0);
- rb_define_singleton_method(envtbl,"reject!", env_delete_if, 0);
- rb_define_singleton_method(envtbl,"to_s", env_to_s, 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 fdc49f0f4b..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-1999 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 52c7c2397f..0000000000
--- a/instruby.rb
+++ /dev/null
@@ -1,91 +0,0 @@
-#!./miniruby -I.
-
-require "rbconfig.rb"
-include Config
-
-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"]
-bindir = destdir+CONFIG["bindir"]
-libdir = destdir+CONFIG["libdir"]
-#pkglibdir = libdir + "/" + ruby_install_name+"/"+CONFIG["MAJOR"]+"."+CONFIG["MINOR"]
-pkglibdir = libdir + "/ruby/"+CONFIG["MAJOR"]+"."+CONFIG["MINOR"]
-archdir = pkglibdir + "/" + CONFIG["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
-for dll in Dir['*.dll']
- File.install dll, "#{bindir}/#{dll}", 0755, true
-end
-File.makedirs libdir, true
-for lib in ["libruby.so.LIB", CONFIG["LIBRUBY_SO"]]
- if File.exist? lib
- File.install lib, libdir, 0555, true
- 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 pkglibdir, true
-File.makedirs archdir, true
-File.makedirs pkglibdir+"/site_ruby", true
-File.makedirs pkglibdir+"/site_ruby/"+CONFIG["arch"], true
-
-if RUBY_PLATFORM =~ /cygwin/ and File.exist? "import.h"
- File.install "import.h", archdir, 0644, true
-end
-
-if RUBY_PLATFORM =~ /-aix/
- File.install "ruby.imp", archdir, 0644, true
-end
-
-Dir.chdir "ext"
-system "../miniruby#{exeext} extmk.rb install #{destdir}"
-Dir.chdir CONFIG["srcdir"]
-
-Find.find("lib") do |f|
- next unless /\.rb$/ =~ f
- dir = pkglibdir+"/"+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, archdir, 0644, true
-end
-if RUBY_PLATFORM =~ /mswin32/
- File.makedirs archdir + "/win32", true
- File.install "win32/win32.h", archdir + "/win32", 0644, true
- if File.exist? wdir+'/rubymw.lib'
- File.install wdir+'/rubymw.lib', archdir, 0644, true
- end
-end
-File.install wdir+'/'+CONFIG['LIBRUBY_A'], archdir, 0644, true
-
-File.makedirs mandir, true
-File.install "ruby.1", mandir, 0644, true
-Dir.chdir wdir
-File.install "config.h", archdir, 0644, true
-File.install "rbconfig.rb", archdir, 0644, true
-# vi:set sw=2:
diff --git a/intern.h b/intern.h
deleted file mode 100644
index bcf3921aa9..0000000000
--- a/intern.h
+++ /dev/null
@@ -1,340 +0,0 @@
-/* Functions and variables that are used by more than one source file of
- * the kernel. Not available to extensions and applications.
- */
-
-/* array.c */
-void rb_mem_clear _((register VALUE*, register size_t));
-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_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));
-VALUE rb_ary_sort_bang _((VALUE));
-VALUE rb_ary_delete _((VALUE, VALUE));
-VALUE rb_ary_delete_at _((VALUE, 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_protect_inspect _((VALUE(*)(),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_str2inum _((const char*, 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)
-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_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_new _((VALUE));
-VALUE rb_singleton_class_new _((VALUE));
-VALUE rb_singleton_class_clone _((VALUE));
-void rb_singleton_class_attached _((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_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 _((VALUE));
-void rb_define_method_id _((VALUE, ID, VALUE (*)(), int));
-void rb_undef_method _((VALUE, const char*));
-void rb_define_protected_method _((VALUE, const char*, VALUE (*)(), int));
-void rb_define_private_method _((VALUE, const char*, VALUE (*)(), int));
-void rb_define_singleton_method _((VALUE,const char*,VALUE(*)(),int));
-void rb_define_private_method _((VALUE,const char*,VALUE(*)(),int));
-VALUE rb_singleton_class _((VALUE));
-/* enum.c */
-VALUE rb_enum_length _((VALUE));
-/* 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));
-void rb_loaderror __((const char*, ...)) NORETURN;
-void rb_compile_error __((const char*, ...));
-void rb_compile_error_append __((const char*, ...));
-/* eval.c */
-void rb_exc_raise _((VALUE)) NORETURN;
-void rb_exc_fatal _((VALUE)) NORETURN;
-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_ref _((ID));
-void rb_dvar_asgn _((ID, VALUE));
-void rb_dvar_push _((ID, VALUE));
-VALUE rb_eval_cmd _((VALUE, VALUE));
-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));
-void rb_load _((VALUE, int));
-void rb_load_protect _((VALUE, int, int*));
-void rb_jump_tag _((int)) NORETURN;
-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, int*));
-void rb_set_end_proc _((void (*)(), VALUE));
-void rb_exec_end_proc _((void));
-void rb_mark_end_proc _((void));
-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_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 (*)(), void*));
-int rb_thread_scope_shared_p _((void));
-void rb_thread_interrupt _((void));
-void rb_thread_trap_eval _((VALUE, int));
-void rb_thread_signal_raise _((char*));
-int rb_thread_select();
-void rb_thread_wait_for();
-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));
-/* file.c */
-int eaccess _((const char*, int));
-VALUE rb_file_s_expand_path _((int, VALUE *));
-void rb_file_const _((const char*, VALUE));
-/* gc.c */
-void rb_global_variable _((VALUE*));
-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();
-void rb_gc_mark();
-void rb_gc_force_recycle _((VALUE));
-void rb_gc _((void));
-void rb_gc_call_finalizer_at_exit _((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));
-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_file_open _((const char*, const char*));
-VALUE rb_gets _((void));
-void rb_str_setter _((VALUE, ID, 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_taint _((VALUE));
-VALUE rb_obj_tainted _((VALUE));
-VALUE rb_obj_untaint _((VALUE));
-VALUE rb_obj_id _((VALUE));
-VALUE rb_convert_type _((VALUE,int,const char*,const char*));
-VALUE rb_Integer _((VALUE));
-VALUE rb_Float _((VALUE));
-VALUE rb_String _((VALUE));
-VALUE rb_Array _((VALUE));
-/* parse.y */
-extern int ruby_sourceline;
-extern char *ruby_sourcefile;
-#define yyparse rb_yyparse
-#define yylex rb_yylex
-#define yyerror rb_yyerror
-#define yylval rb_yylval
-#define yychar rb_yychar
-#define yydebug rb_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));
-VALUE rb_backref_get _((void));
-void rb_backref_set _((VALUE));
-VALUE rb_lastline_get _((void));
-void rb_lastline_set _((VALUE));
-/* process.c */
-int rb_proc_exec _((const char*));
-void rb_syswait _((int));
-/* 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 */
-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));
-const char* rb_get_kcode _((void));
-void rb_set_kcode _((const char*));
-int rb_ignorecase_p _((void));
-void rb_match_busy _((VALUE, int));
-/* 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));
-/* 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, void (*)()));
-#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_tainted_str_new _((const char*, long));
-VALUE rb_tainted_str_new2 _((const char*));
-VALUE rb_obj_as_string _((VALUE));
-VALUE rb_str_to_str _((VALUE));
-VALUE rb_str_dup _((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_concat _((VALUE, VALUE));
-int rb_str_hash _((VALUE));
-int rb_str_cmp _((VALUE, VALUE));
-VALUE rb_str_upto _((VALUE, VALUE, int));
-VALUE rb_str_inspect _((VALUE));
-VALUE rb_str_split _((VALUE, const char*));
-/* 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));
-/* time.c */
-VALUE rb_time_new();
-/* 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));
-void rb_clone_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_obj_instance_variables _((VALUE));
-VALUE rb_obj_remove_instance_variable _((VALUE, VALUE));
-VALUE rb_mod_const_at _((VALUE, VALUE));
-VALUE rb_mod_constants _((VALUE));
-VALUE rb_mod_const_of _((VALUE, 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));
-VALUE rb_mod_constants _((VALUE));
-void rb_autoload_load _((ID));
-/* 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 1db0cef426..0000000000
--- a/io.c
+++ /dev/null
@@ -1,3379 +0,0 @@
-/************************************************
-
- io.c -
-
- $Author$
- $Date$
- created at: Fri Oct 15 18:08:59 JST 1993
-
- Copyright (C) 1993-1999 Yukihiro Matsumoto
-
-************************************************/
-
-#include "ruby.h"
-#include "rubyio.h"
-#include "rubysig.h"
-#include "env.h"
-#include <ctype.h>
-#include <errno.h>
-
-#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
-
-#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
-#ifdef HAVE_VFORK_H
-#include <vfork.h>
-#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
-
-#ifdef USE_CWGUSI
- #include <sys/errno.h>
- #include <unix.mac.h>
- #include <compat.h>
-#endif
-
-#ifndef strdup
-char *strdup();
-#endif
-
-extern void Init_File _((void));
-
-#ifdef __BEOS__
-# ifdef _X86_
-# 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;
-
-VALUE rb_fs;
-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;
-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)
-# else
-# define READ_DATA_PENDING(fp) ((fp)->_gptr < (fp)->_egptr)
-# endif
-#elif defined(FILE_COUNT)
-# define READ_DATA_PENDING(fp) ((fp)->FILE_COUNT > 0)
-#elif defined(__BEOS__)
-# define ReadDataPending(fp) (fp->_state._eof == 0)
-#elif defined(USE_CWGUSI)
-# define READ_DATA_PENDING(fp) (fp->state.eof == 0)
-#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");
-}
-
-void
-rb_io_check_closed(fptr)
- OpenFile *fptr;
-{
- if (!fptr) {
- rb_raise(rb_eIOError, "uninitialized stream");
- }
- if (fptr->f == NULL && fptr->f2 == NULL)
- 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");
- }
-}
-
-void
-rb_read_check(fp)
- FILE *fp;
-{
- if (!READ_DATA_PENDING(fp)) {
- rb_thread_wait_fd(fileno(fp));
- }
-}
-
-/* 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)
- rb_sys_fail(fptr->path);
- n = ptr - RSTRING(str)->ptr;
- }
- if (ferror(f))
- rb_sys_fail(fptr->path);
-#else
- n = fwrite(RSTRING(str)->ptr, 1, RSTRING(str)->len, f);
- if (ferror(f)) {
- rb_sys_fail(fptr->path);
- }
-#endif
- if (fptr->mode & FMODE_SYNC) {
- fflush(f);
- }
-
- return INT2FIX(n);
-}
-
-VALUE
-rb_io_write(io, str)
- VALUE io, str;
-{
- return rb_funcall(io, id_write, 1, str);
-}
-
-static 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);
-
- if (fflush(f) == EOF) rb_sys_fail(0);
-
- return io;
-}
-
-static VALUE
-rb_io_tell(io)
- VALUE io;
-{
- OpenFile *fptr;
- long pos;
-
- GetOpenFile(io, fptr);
- pos = ftell(fptr->f);
- if (ferror(fptr->f)) rb_sys_fail(fptr->path);
-
- return rb_int2inum(pos);
-}
-
-static VALUE
-rb_io_seek(io, offset, ptrname)
- VALUE io, offset, ptrname;
-{
- OpenFile *fptr;
- long pos;
-
- GetOpenFile(io, fptr);
- pos = fseek(fptr->f, NUM2INT(offset), NUM2INT(ptrname));
- if (pos != 0) rb_sys_fail(fptr->path);
- clearerr(fptr->f);
-
- return INT2FIX(0);
-}
-
-#ifndef SEEK_CUR
-# define SEEK_SET 0
-# define SEEK_CUR 1
-# define SEEK_END 2
-#endif
-
-static VALUE
-rb_io_set_pos(io, offset)
- VALUE io, offset;
-{
- OpenFile *fptr;
- long pos;
-
- GetOpenFile(io, fptr);
- pos = fseek(fptr->f, NUM2INT(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 (fseek(fptr->f, 0L, 0) != 0) rb_sys_fail(fptr->path);
- clearerr(fptr->f);
-
- 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_fileno(io)
- VALUE io;
-{
- OpenFile *fptr;
- int fd;
-
- GetOpenFile(io, fptr);
- fd = fileno(fptr->f);
- return INT2FIX(fd);
-}
-
-static VALUE
-rb_io_to_io(io)
- VALUE io;
-{
- return io;
-}
-
-/* reading functions */
-
-#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;
- long 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 {
- long pos = ftell(fptr->f);
- if (st.st_size > pos && pos >= 0) {
- siz = st.st_size - pos + 1;
- }
- }
- }
- str = rb_str_new(0, siz);
- for (;;) {
- READ_CHECK(fptr->f);
- TRAP_BEG;
- n = fread(RSTRING(str)->ptr+bytes, 1, siz-bytes, fptr->f);
- TRAP_END;
- 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);
- OBJ_TAINT(str);
-
- return str;
-}
-
-static size_t
-io_fread(ptr, len, f)
- char *ptr;
- size_t len;
- FILE *f;
-{
- size_t n = len;
- int c;
-
- while (n--) {
- if (!READ_DATA_PENDING(f)) {
- rb_thread_wait_fd(fileno(f));
- }
- c = getc(f);
- if (c == EOF) {
- *ptr = '\0';
- break;
- }
- *ptr++ = c;
- }
-
- return len - n - 1;
-}
-
-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_gets_internal(argc, argv, io)
- int argc;
- VALUE *argv;
- VALUE io;
-{
- OpenFile *fptr;
- FILE *f;
- VALUE str = Qnil;
- int c, newline;
- char *rsptr;
- int rslen, rspara = 0;
- VALUE rs;
-
- if (argc == 0) {
- rs = rb_rs;
- }
- else {
- rb_scan_args(argc, argv, "1", &rs);
- if (!NIL_P(rs)) Check_Type(rs, T_STRING);
- }
-
- if (NIL_P(rs)) {
- rsptr = 0;
- rslen = 0;
- }
- else {
- 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_gets(io);
- }
- else {
- rsptr = RSTRING(rs)->ptr;
- }
- }
-
- GetOpenFile(io, fptr);
- rb_io_check_readable(fptr);
- 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) && errno == EINTR) continue;
- 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;
- FILE *f;
- VALUE str = Qnil;
- int c;
- char buf[8192];
- char *bp, *bpe = buf + sizeof buf - 3;
- int cnt;
- int append = 0;
-
- GetOpenFile(io, fptr);
- rb_io_check_readable(fptr);
- f = fptr->f;
-
- again:
- bp = buf;
- for (;;) {
- READ_CHECK(f);
- TRAP_BEG;
- c = getc(f);
- TRAP_END;
- if (c == EOF) {
- if (ferror(f) && errno == EINTR) continue;
- 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_gets_method(argc, argv, io)
- int argc;
- VALUE *argv;
- VALUE io;
-{
- VALUE str = rb_io_gets_internal(argc, argv, io);
-
- 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);
- return fptr->lineno = NUM2INT(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_method(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;
-
- ary = rb_ary_new();
- while (!NIL_P(line = rb_io_gets_internal(argc, argv, io))) {
- rb_ary_push(ary, line);
- }
- return ary;
-}
-
-static VALUE
-rb_io_each_line(argc, argv, io)
- int argc;
- VALUE *argv;
- VALUE io;
-{
- VALUE str;
-
- while (!NIL_P(str = rb_io_gets_internal(argc, argv, io))) {
- 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) break;
- rb_yield(INT2FIX(c & 0xff));
- }
- if (ferror(f)) rb_sys_fail(fptr->path);
- return Qnil;
-}
-
-VALUE
-rb_io_getc(io)
- VALUE io;
-{
- OpenFile *fptr;
- FILE *f;
- int c;
-
- GetOpenFile(io, fptr);
- rb_io_check_readable(fptr);
- f = fptr->f;
-
- READ_CHECK(f);
- TRAP_BEG;
- c = getc(f);
- TRAP_END;
-
- if (c == EOF) {
- if (ferror(f)) 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;
-
- Check_Type(c, T_FIXNUM);
- GetOpenFile(io, fptr);
- rb_io_check_readable(fptr);
-
- if (ungetc(FIX2INT(c), fptr->f) == 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)
- OpenFile *fptr;
-{
- if (fptr->f != NULL) {
- fclose(fptr->f);
- }
- if (fptr->f2 != NULL) {
- fclose(fptr->f2);
- }
-}
-
-static void
-rb_io_fptr_close(fptr)
- OpenFile *fptr;
-{
- int fd;
-
- if (fptr->f == NULL && fptr->f2 == NULL) return;
-
- fd = fileno(fptr->f);
- if (fptr->finalize) {
- (*fptr->finalize)(fptr);
- }
- else {
- fptr_finalize(fptr);
- }
- fptr->f = fptr->f2 = NULL;
- rb_thread_fd_close(fd);
-}
-
-void
-rb_io_fptr_finalize(fptr)
- OpenFile *fptr;
-{
- rb_io_fptr_close(fptr);
- if (fptr->path) {
- free(fptr->path);
- fptr->path = NULL;
- }
-}
-
-VALUE
-rb_io_close(io)
- VALUE io;
-{
- OpenFile *fptr;
-
- GetOpenFile(io, fptr);
- rb_io_fptr_close(fptr);
- if (fptr->pid) {
- rb_syswait(fptr->pid);
- fptr->pid = 0;
- }
-
- return Qnil;
-}
-
-static VALUE
-rb_io_close_method(io)
- VALUE io;
-{
- if (rb_safe_level() >= 4 && !OBJ_TAINTED(io)) {
- rb_raise(rb_eSecurityError, "Insecure: can't close");
- }
- 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;
-}
-
-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 (!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);
-
- str = rb_str_new(0, ilen);
-
- 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(USE_CWGUSI) || defined(__EMX__)
- OpenFile *fptr;
-
- GetOpenFile(io, fptr);
-#ifdef __human68k__
- if (fptr->f)
- fmode(fptr->f, _IOBIN);
- if (fptr->f2)
- fmode(fptr->f2, _IOBIN);
-#else
-# ifndef USE_CWGUSI
- 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);
-# else /* USE_CWGUSI */
- if (fptr->f)
- fptr->f->mode.binary_io = 1;
- if (fptr->f2)
- fptr->f2->mode.binary_io = 1;
-# endif /* USE_CWGUSI */
-#endif
-
- fptr->mode |= FMODE_BINMODE;
-#endif
- return io;
-}
-
-int
-rb_io_mode_flags(mode)
- const char *mode;
-{
- int flags = 0;
-
- switch (mode[0]) {
- 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 (mode[1] == 'b') {
- flags |= FMODE_BINMODE;
- mode++;
- }
-
- if (mode[1] == '+') {
- flags |= FMODE_READWRITE;
- if (mode[2] != 0) goto error;
- }
- else if (mode[1] != 0) goto error;
-
- return flags;
-}
-
-static int
-rb_io_mode_flags2(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 char*
-rb_io_flags_mode(flags)
- int flags;
-{
- static char mode[4];
- 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_open(fname, flag, mode)
- char *fname;
- int flag;
- unsigned int mode;
-{
- int fd;
-
- fd = open(fname, flag, mode);
- if (fd < 0) {
- if (errno == EMFILE || errno == ENFILE) {
- rb_gc();
- fd = open(fname, flag, 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 == NULL) {
- if (errno == EMFILE || errno == ENFILE) {
- rb_gc();
- file = fopen(fname, mode);
- }
- if (file == NULL) {
- rb_sys_fail(fname);
- }
- }
- return file;
-}
-
-FILE *
-rb_fdopen(fd, mode)
- int fd;
- const char *mode;
-{
- FILE *file;
-
- file = fdopen(fd, mode);
- if (file == NULL) {
- if (errno == EMFILE || errno == ENFILE) {
- rb_gc();
- file = fdopen(fd, mode);
- }
- if (file == NULL) {
- rb_sys_fail(0);
- }
- }
- return file;
-}
-
-static VALUE
-rb_file_open_internal(klass, fname, mode)
- VALUE klass;
- const char *fname, *mode;
-{
- OpenFile *fptr;
- NEWOBJ(port, struct RFile);
- OBJSETUP(port, klass, T_FILE);
- MakeOpenFile(port, fptr);
-
- fptr->mode = rb_io_mode_flags(mode);
- fptr->f = rb_fopen(fname, mode);
- fptr->path = strdup(fname);
-
- return (VALUE)port;
-}
-
-VALUE
-rb_file_open(fname, mode)
- const char *fname, *mode;
-{
- return rb_file_open_internal(rb_cFile, fname, mode);
-}
-
-VALUE
-rb_file_sysopen_internal(klass, fname, flags, mode)
- VALUE klass;
- char *fname;
- int flags, mode;
-{
-#ifdef USE_CWGUSI
- if (mode != 0666) {
- rb_warn("can't specify file mode on this platform");
- }
- return rb_file_open_internal(klass, fname, rb_io_flags_mode(flags));
-#else
- OpenFile *fptr;
- int fd;
- char *m;
- NEWOBJ(port, struct RFile);
- OBJSETUP(port, klass, T_FILE);
- MakeOpenFile(port, fptr);
-
- fd = rb_open(fname, flags, mode);
- m = rb_io_flags_mode(flags);
- fptr->mode = rb_io_mode_flags2(flags);
- fptr->f = rb_fdopen(fd, m);
- fptr->path = strdup(fname);
-
- return (VALUE)port;
-#endif
-}
-
-VALUE
-rb_file_sysopen(fname, flags, mode)
- const char *fname;
- int flags, mode;
-{
- return rb_file_sysopen_internal(rb_cFile, 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;
- }
-}
-
-static void
-pipe_atexit()
-{
- struct pipe_list *list = pipe_list;
- struct pipe_list *tmp;
-
- while (list) {
- tmp = list->next;
- rb_io_fptr_finalize(list->fptr);
- list = tmp;
- }
-}
-
-static void
-pipe_finalize(fptr)
- OpenFile *fptr;
-{
-#if !defined (__CYGWIN__)
- if (fptr->f != NULL) {
- pclose(fptr->f);
- }
- if (fptr->f2 != NULL) {
- pclose(fptr->f2);
- }
- fptr->f = fptr->f2 = NULL;
-#else
- fptr_finalize(fptr);
-#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;
-{
-#ifndef USE_CWGUSI
- int modef = rb_io_mode_flags(mode);
- OpenFile *fptr;
-
-#if defined(NT) || defined(DJGPP) || defined(__human68k__)
- FILE *f = popen(pname, mode);
-
- if (f == NULL) rb_sys_fail(pname);
- else {
- NEWOBJ(port, struct RFile);
- OBJSETUP(port, rb_cIO, T_FILE);
- 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) {
- fptr->f2 = f;
- rb_io_synchronized(fptr);
- }
- return (VALUE)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 = (doexec?vfork():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);
- }
- 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 {
- NEWOBJ(port, struct RFile);
- OBJSETUP(port, rb_cIO, T_FILE);
- 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 (VALUE)port;
- }
- }
-#endif
-#else /* USE_CWGUSI */
- rb_notimplement();
- return Qnil; /* not reached */
-#endif
-}
-
-static VALUE
-rb_io_s_popen(argc, argv, self)
- int argc;
- VALUE *argv;
- VALUE self;
-{
- char *mode;
- VALUE pname, pmode, port;
-
- if (rb_scan_args(argc, argv, "11", &pname, &pmode) == 1) {
- mode = "r";
- }
- else {
- int len;
-
- mode = STR2CSTR(pmode);
- len = strlen(mode);
- if (len == 0 || len > 3)
- rb_raise(rb_eArgError, "illegal access mode");
- }
- Check_SafeStr(pname);
- port = pipe_open(RSTRING(pname)->ptr, mode);
- if (NIL_P(port)) return Qnil;
- return port;
-}
-
-static VALUE
-rb_file_s_open(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- VALUE fname, vmode, file, perm;
- char *path, *mode;
-
- rb_scan_args(argc, argv, "12", &fname, &vmode, &perm);
- Check_SafeStr(fname);
- path = RSTRING(fname)->ptr;
-
- if (FIXNUM_P(vmode)) {
- int flags = FIX2INT(vmode);
- int fmode = NIL_P(perm) ? 0666 : FIX2INT(perm);
-
- file = rb_file_sysopen_internal(klass, path, flags, fmode);
- }
- else {
- if (!NIL_P(vmode)) {
- mode = STR2CSTR(vmode);
- }
- else {
- mode = "r";
- }
- file = rb_file_open_internal(klass, RSTRING(fname)->ptr, mode);
- }
-
- if (rb_iterator_p()) {
- return rb_ensure(rb_yield, file, rb_io_close, file);
- }
-
- return file;
-}
-
-static VALUE
-rb_f_open(argc, argv)
- int argc;
- VALUE *argv;
-{
- char *mode;
- VALUE pname, pmode, perm;
- VALUE port;
-
- rb_scan_args(argc, argv, "12", &pname, &pmode, &perm);
- Check_SafeStr(pname);
- if (RSTRING(pname)->ptr[0] != '|') /* open file */
- return rb_file_s_open(argc, argv, rb_cFile);
-
- /* open pipe */
- if (NIL_P(pmode)) {
- mode = "r";
- }
- else if (FIXNUM_P(pmode)) {
- mode = rb_io_flags_mode(FIX2INT(pmode));
- }
- else {
- int len;
-
- mode = STR2CSTR(pmode);
- len = strlen(mode);
- if (len == 0 || len > 3)
- rb_raise(rb_eArgError, "illegal access mode %s", mode);
- }
-
- port = pipe_open(RSTRING(pname)->ptr+1, mode);
- if (NIL_P(port)) return Qnil;
- if (rb_iterator_p()) {
- return rb_ensure(rb_yield, port, rb_io_close, port);
- }
-
- return port;
-}
-
-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
-rb_io_reopen(io, nfile)
- VALUE io, nfile;
-{
- OpenFile *fptr, *orig;
- char *mode;
- int fd;
-
- 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->f2) {
- fflush(orig->f2);
- }
- else if (orig->mode & FMODE_WRITABLE) {
- fflush(orig->f);
- }
- 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) {
- /* need to keep stdio */
- 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 (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_file_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_FILE) { /* fname must be IO */
- return rb_io_reopen(file, fname);
- }
- }
-
- Check_SafeStr(fname);
- if (!NIL_P(nmode)) {
- mode = STR2CSTR(nmode);
- }
- else {
- mode = "r";
- }
-
- GetOpenFile(file, fptr);
- if (fptr->path) free(fptr->path);
- 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 = NULL;
- }
- return file;
- }
-
- if (freopen(RSTRING(fname)->ptr, mode, fptr->f) == NULL) {
- rb_sys_fail(fptr->path);
- }
- if (fptr->f2) {
- if (freopen(RSTRING(fname)->ptr, "w", fptr->f2) == NULL) {
- rb_sys_fail(fptr->path);
- }
- }
-
- return file;
-}
-
-static VALUE
-rb_io_clone(io)
- VALUE io;
-{
- OpenFile *fptr, *orig;
- int fd;
- char *mode;
-
- NEWOBJ(obj, struct RFile);
- CLONESETUP(obj, io);
-
- GetOpenFile(io, orig);
- MakeOpenFile(obj, fptr);
-
- if (orig->f2) {
- fflush(orig->f2);
- }
- else if (orig->mode & FMODE_WRITABLE) {
- fflush(orig->f);
- }
-
- /* 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 = dup(fileno(orig->f));
- fptr->f = rb_fdopen(fd, mode);
- if (fptr->f2) {
- fd = dup(fileno(orig->f2));
- fptr->f = rb_fdopen(fd, "w");
- }
- if (fptr->mode & FMODE_BINMODE) {
- rb_io_binmode((VALUE)obj);
- }
-
- return (VALUE)obj;
-}
-
-static VALUE
-rb_io_printf(argc, argv, out)
- int argc;
- VALUE argv[];
- VALUE out;
-{
- 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--;
- }
- io_write(out, rb_f_sprintf(argc, argv));
-
- return Qnil;
-}
-
-static 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);
- if (fptr->mode & FMODE_SYNC)
- fflush(f);
-
- return ch;
-}
-
-static VALUE
-rb_f_putc(recv, ch)
- VALUE recv, ch;
-{
- return rb_io_putc(rb_defout, ch);
-}
-
-static VALUE rb_io_puts _((int, VALUE*, VALUE));
-
-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;
-}
-
-static 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++) {
- switch (TYPE(argv[i])) {
- case T_NIL:
- line = rb_str_new2("nil");
- break;
- case T_ARRAY:
- rb_protect_inspect(io_puts_ary, argv[i], out);
- continue;
- default:
- line = argv[i];
- break;
- }
- line = rb_obj_as_string(line);
- 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;
-{
- obj = rb_obj_as_string(rb_inspect(obj));
- fwrite(RSTRING(obj)->ptr, 1, RSTRING(obj)->len, stdout);
- obj = rb_default_rs;
- fwrite(RSTRING(obj)->ptr, 1, RSTRING(obj)->len, stdout);
-}
-
-static VALUE
-rb_f_p(argc, argv)
- int argc;
- VALUE *argv;
-{
- int i;
-
- for (i=0; i<argc; i++) {
- rb_p(argv[i]);
- }
- 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 int
-rb_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
-set_stdin(val, id, var)
- VALUE val;
- ID id;
- VALUE *var;
-{
- OpenFile *fptr;
- int fd;
- char *mode;
-
- 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);
-
- GetOpenFile(*var, fptr);
- mode = rb_io_mode_string(fptr);
- fd = rb_dup(fileno(fptr->f));
- if (fileno(fptr->f) > 2) {
- fclose(fptr->f);
- }
- fptr->f = rb_fdopen(fd, mode);
-
- GetOpenFile(val, fptr);
- dup2(fileno(fptr->f), 0);
- fclose(fptr->f);
- fptr->f = stdin;
-
- *var = val;
-}
-
-static void
-set_outfile(val, var, orig, stdf)
- VALUE val;
- VALUE *var;
- VALUE orig;
- FILE *stdf;
-{
- OpenFile *fptr;
- FILE *f;
- int fd;
- char *mode;
-
- if (val == *var) return;
-
- if (TYPE(*var) == T_FILE) {
- 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);
-
- GetOpenFile(*var, fptr);
- mode = rb_io_mode_string(fptr);
- f = GetWriteFile(fptr);
- fd = rb_dup(fileno(f));
- if (fileno(f) > 2) {
- fclose(fptr->f);
- }
- f = rb_fdopen(fd, mode);
- if (fptr->f2) fptr->f2 = f;
- else fptr->f = f;
-
- GetOpenFile(val, fptr);
- f = GetWriteFile(fptr);
- dup2(fileno(f), fileno(stdf));
- fclose(f);
- if (fptr->f2) fptr->f2 = stdf;
- else fptr->f = stdf;
-
- *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;
- NEWOBJ(io, struct RFile);
- OBJSETUP(io, klass, T_FILE);
-
- MakeOpenFile(io, fp);
- fp->f = f;
- fp->mode = mode;
-
- return (VALUE)io;
-}
-
-static VALUE
-rb_io_s_new(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- VALUE fnum, mode;
- char *m = "r";
-
- if (rb_scan_args(argc, argv, "11", &fnum, &mode) == 2) {
- Check_SafeStr(mode);
- m = RSTRING(mode)->ptr;
- }
- return prep_stdio(rb_fdopen(NUM2INT(fnum), m), rb_io_mode_flags(m), 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;
- }
- init_p = 1;
- gets_lineno = 0;
- }
-
- retry:
- if (next_p == 1) {
- next_p = 0;
- if (RARRAY(rb_argv)->len > 0) {
- filename = rb_ary_shift(rb_argv);
- fn = STR2CSTR(filename);
- if (strlen(fn) == 1 && fn[0] == '-') {
- current_file = rb_stdin;
- if (ruby_inplace_mode) {
- 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);
-#if defined(MSDOS) || defined(__CYGWIN__) || defined(NT)
- ruby_add_suffix(str, ruby_inplace_mode);
-#else
- rb_str_cat(str, ruby_inplace_mode,
- strlen(ruby_inplace_mode));
-#endif
-#if defined(MSDOS) || defined(__BOW__) || defined(__CYGWIN__) || defined(NT) || defined(__human68k__) || defined(__EMX__)
- (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 {
-#if !defined(MSDOS) && !defined(__BOW__) && !defined(__CYGWIN__) && !defined(NT) && !defined(__human68k__)
- if (unlink(fn) < 0) {
- rb_warn("Can't remove %s: %s, skipping file",
- fn, strerror(errno));
- fclose(fr);
- goto retry;
- }
-#else
- rb_fatal("Can't do inplace edit without backup");
-#endif
- }
- fw = rb_fopen(fn, "w");
-#if !defined(MSDOS) && !defined(__CYGWIN__) && !(NT) && !defined(__human68k__) && !defined(USE_CWGUSI) && !defined(__BEOS__) && !defined(__EMX__)
- fstat(fileno(fw), &st2);
- fchmod(fileno(fw), st.st_mode);
- 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);
- }
- current_file = prep_stdio(fr, FMODE_READABLE, rb_cFile);
- }
- 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
-rb_f_gets_internal(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);
- }
- if (argc == 0 && rb_rs == rb_default_rs) {
- line = rb_io_gets(current_file);
- }
- else {
- line = rb_io_gets_internal(argc, argv, current_file);
- }
- 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 = rb_f_gets_internal(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 = rb_f_gets_internal(argc, argv))) {
- rb_ary_push(ary, line);
- }
-
- return ary;
-}
-
-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;
-}
-
-static VALUE
-rb_f_backquote(obj, str)
- VALUE obj, str;
-{
- VALUE port, result;
-
- Check_SafeStr(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 = NULL;
- }
- 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 = NULL;
-
- 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 = NULL;
-
- 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 = NULL;
-
- 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 */
-}
-
-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;
- int fd;
- 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 {
- Check_Type(arg, T_STRING);
-
-#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;
- }
- fd = fileno(fptr->f);
-#ifdef HAVE_FCNTL
- TRAP_BEG;
-# if defined(USE_CWGUSI) || 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
- 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");
- }
- 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;
-{
-#ifdef HAVE_SYSCALL
-#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); argv++;
- }
- else {
- Check_Type(*argv, T_STRING);
- rb_str_modify(*argv);
- arg[i] = (unsigned long)RSTRING(*argv)->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, ary;
-
-#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, rb_cIO);
-
- ary = rb_ary_new2(2);
- rb_ary_push(ary, r);
- rb_ary_push(ary, w);
-
- return ary;
-#else
- rb_notimplement();
- return Qnil; /* not reached */
-#endif
-}
-
-struct foreach_arg {
- int argc;
- VALUE sep;
- VALUE io;
-};
-
-static VALUE
-rb_io_foreach_line(arg)
- struct foreach_arg *arg;
-{
- VALUE str;
-
- while (!NIL_P(str = rb_io_gets_internal(arg->argc, &arg->sep, arg->io))) {
- rb_yield(str);
- }
- return Qnil;
-}
-
-static VALUE
-rb_io_s_foreach(argc, argv, io)
- int argc;
- VALUE *argv;
- VALUE io;
-{
- VALUE fname;
- struct foreach_arg arg;
-
- rb_scan_args(argc, argv, "11", &fname, &arg.sep);
- Check_SafeStr(fname);
-
- arg.argc = argc - 1;
- arg.io = rb_io_open(RSTRING(fname)->ptr, "r");
- if (NIL_P(arg.io)) return Qnil;
- return rb_ensure(rb_io_foreach_line, (VALUE)&arg, rb_io_close, arg.io);
-}
-
-static VALUE
-rb_io_readline_line(arg)
- struct foreach_arg *arg;
-{
- VALUE line, ary;
-
- ary = rb_ary_new();
- while (!NIL_P(line = rb_io_gets_internal(arg->argc, &arg->sep, arg->io))) {
- rb_ary_push(ary, line);
- }
-
- return ary;
-}
-
-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);
- Check_SafeStr(fname);
-
- arg.argc = argc - 1;
- arg.io = rb_io_open(RSTRING(fname)->ptr, "r");
- if (NIL_P(arg.io)) return Qnil;
- return rb_ensure(rb_io_readline_line, (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(self, offset, ptrname)
- VALUE self, offset, ptrname;
-{
- if (!next_argv()) {
- rb_raise(rb_eArgError, "no stream to seek");
- }
-
- if (TYPE(current_file) != T_FILE) {
- return argf_forward();
- }
- return rb_io_seek(current_file, offset, ptrname);
-}
-
-static VALUE
-argf_set_pos(self, offset)
- VALUE self, offset;
-{
- if (!next_argv()) {
- rb_raise(rb_eArgError, "no stream to pos");
- }
-
- 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();
- STR2CSTR(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_cat(str, RSTRING(tmp)->ptr, RSTRING(tmp)->len);
- 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()
-{
- if (init_p == 0 && !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 = rb_f_gets_internal(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)) {
- ruby_inplace_mode = 0;
- return;
- }
- ruby_inplace_mode = STR2CSTR(val);
-}
-
-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, "new", rb_io_s_new, -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, "select", rb_f_select, -1);
- rb_define_singleton_method(rb_cIO, "pipe", rb_io_s_pipe, 0);
-
- rb_fs = rb_output_fs = Qnil;
- rb_define_hooked_variable("$;", &rb_fs, 0, rb_str_setter);
- rb_define_hooked_variable("$-F", &rb_fs, 0, rb_str_setter);
- 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);
- rb_str_freeze(rb_default_rs); /* avoid modifying RS_default */
- rb_define_hooked_variable("$/", &rb_rs, 0, rb_str_setter);
- rb_define_hooked_variable("$-0", &rb_rs, 0, rb_str_setter);
- rb_define_hooked_variable("$\\", &rb_output_rs, 0, rb_str_setter);
-
- 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, "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_method, -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, 2);
- 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_method, 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_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, 2);
- 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, "reopen", rb_file_reopen, -1);
-
- rb_define_singleton_method(rb_cFile, "new", rb_file_s_open, -1);
- rb_define_singleton_method(rb_cFile, "open", rb_file_s_open, -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
-}
diff --git a/keywords b/keywords
deleted file mode 100644
index f5380382d3..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_END
-case, kCASE, kCASE, EXPR_BEG
-class, kCLASS, kCLASS, EXPR_CLASS
-def, kDEF, kDEF, EXPR_FNAME
-defined?, kDEFINED, kDEFINED, EXPR_END
-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_END
-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_END
-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_END
diff --git a/lex.c b/lex.c
deleted file mode 100644
index 292760c359..0000000000
--- a/lex.c
+++ /dev/null
@@ -1,132 +0,0 @@
-/* C code produced by gperf version 2.7.1 (19981006 egcs) */
-/* Command-line: gperf -p -j1 -i 1 -g -o -t -N rb_reserved_word -k1,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
-#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]];
-}
-
-#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_END},
- {"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_END},
- {"super", kSUPER, kSUPER, EXPR_END},
- {"undef", kUNDEF, kUNDEF, EXPR_FNAME},
- {"break", kBREAK, kBREAK, EXPR_END},
- {"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_END},
- {"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 c7e13bebe6..0000000000
--- a/lib/English.rb
+++ /dev/null
@@ -1,28 +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 $OUPUT_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 b3ee3bae8a..0000000000
--- a/lib/Env.rb
+++ /dev/null
@@ -1,31 +0,0 @@
-# Env.rb -- imports environment variables as global variables
-#
-# Usage:
-#
-# require 'Env'
-# 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} = %q!#{v}!
- trace_var "$#{k}", proc{|v|
- ENV[%q!#{k}!] = v;
- $#{k} = %q!#{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/README b/lib/README
deleted file mode 100644
index 765c380f7d..0000000000
--- a/lib/README
+++ /dev/null
@@ -1,48 +0,0 @@
-English.rb access global variables by english names
-Env.rb access environment variables as globals
-README this file
-base64.rb encode/decode base64 (obsolete)
-cgi-lib.rb decode CGI data
-complex.rb complex number suppor
-date.rb date object (compatible)
-date2.rb yet another (better) date object
-debug.rb ruby debugger
-delegate.rb delegate messages to other object
-e2mmap.rb exception utilities
-eregex.rb extended regular expression (just a proof of concept)
-final.rb add finalizer to the object (simple)
-finalize.rb add finalizer to the object
-find.rb traverse directory tree
-ftools.rb file tools
-ftplib.rb ftp access library
-getoptlong.rb GNU getoptlong compatible
-getopts.rb parse command line options
-importenv.rb access environment variables as globals
-jcode.rb japanese text handling (replace String methods)
-mailread.rb read 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
-observer.rb observer desing pattern library (provides Observable)
-open3.rb open subprocess connection stdin/stdout/stderr
-ostruct.rb python style object
-parsearg.rb argument parser using getopts
-parsedate.rb parse date string
-ping.rb check whether host is up, using TCP echo.
-profile.rb ruby profiler
-pstore.rb persistent object strage using marshal
-rational.rb rational number support
-readbytes.rb define IO#readbytes
-shell.rb shell like operation under Ruby (imcomplete)
-shellwords.rb split into words like shell
-singleton.rb singleton design pattern library
-sync.rb 2 phase lock
-telnet.rb telnet library
-tempfile.rb temporary file that automatically removed
-thread.rb thread support
-thwait.rb thread syncronization class
-timeout.rb provids timeout
-tracer.rb execution tracer
-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/cgi-lib.rb b/lib/cgi-lib.rb
deleted file mode 100644
index bf04601238..0000000000
--- a/lib/cgi-lib.rb
+++ /dev/null
@@ -1,272 +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 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 escape(str)
- str.gsub(/[^a-zA-Z0-9_\-.]/n){ sprintf("%%%02X", $&.unpack("C")[0]) }
- end
-
- # unescape url encoded
- def unescape(str)
- str.gsub(/\+/, ' ').gsub(/%([0-9a-fA-F]{2})/){ [$1.hex].pack("c") }
- end
-
- # escape HTML
- def escapeHTML(str)
- str.gsub(/&/, "&amp;").gsub(/\"/, "&quot;").gsub(/>/, "&gt;").gsub(/</, "&lt;")
- end
-
- module_function :escape, :unescape, :escapeHTML, :rfc1123_date
-
- # 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|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 = unescape(key)
- val = val.split(/&/).collect{|x|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 4a17c8b191..0000000000
--- a/lib/cgi.rb
+++ /dev/null
@@ -1,1984 +0,0 @@
-=begin
-$Date$
-
-== CGI SUPPORT LIBRARY
-
-CGI.rb
-
-Version 1.10
-
-Copyright (C) 1999 Network Applied Communication Laboratory, Inc.
-
-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 }){}
-
- cgi.cookies # { "name1" => cookie1, "name2" => cookie2, ... }
-
- require "cgi"
- cgi = CGI.new
- cgi.cookies['name'].expires = Time.now + 30
- cgi.out({ "cookie" => cgi.cookies['name'] }){}
-
-and see MAKE COOKIE OBJECT.
-
-
-=== GET ENVIRONMENT VALUE
-
- require "CGI"
- cgi = CGI.new
- value = cgi.auth_type
- # ENV["AUTH_TYPE"]
-
-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 $>
-
- require "cgi"
- cgi = CGI.new("html3") # add HTML generation methods
- cgi.out{
- cgi.html{
- cgi.head{ cgi.title{"TITLE"} } +
- cgi.body{
- cgi.form{
- cgi.textarea("get_text") +
- cgi.br +
- cgi.submit
- } +
- cgi.pre{
- CGI::escapeHTML(
- "params: " + cgi.params.inspect + "\n" +
- "cookies: " + cgi.cookies.inspect + "\n" +
- ENV.collect{|key, value|
- key + " --> " + value + "\n"
- }.to_s
- )
- }
- }
- }
- }
-
- # 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
-
-
-class CGI
-
- CR = "\015"
- LF = "\012"
- EOL = CR + LF
-v = $-v
-$-v = false
- VERSION = "1.10"
- RELEASE_DATE = "$Date$"
-$-v = v
-
- NEEDS_BINMODE = true if /WIN/ni === 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
- $>
- end
-
- private :env_table, :stdinput, :stdoutput
-
-=begin
-== METHODS
-=end
-
-=begin
-=== ESCAPE URL ENCODE
- url_encoded_string = CGI::escape("string")
-=end
- def CGI::escape(string)
- str = string.dup
- str.gsub!(/[^a-zA-Z0-9_.-]/n){ sprintf("%%%02X", $&.unpack("C")[0]) }
- str
- end
-
-
-=begin
-=== UNESCAPE URL ENCODED
- string = CGI::unescape("url encoded string")
-=end
- def CGI::unescape(string)
- str = string.dup
- str.gsub!(/\+/n, ' ')
- str.gsub!(/%([0-9a-fA-F]{2})/n){ [$1.hex].pack("c") }
- str
- end
-
-
-=begin
-=== ESCAPE HTML &"<>
- CGI::escapeHTML("string")
-=end
- def CGI::escapeHTML(string)
- str = string.dup
- str.gsub!(/&/n, '&amp;')
- str.gsub!(/\"/n, '&quot;')
- str.gsub!(/>/n, '&gt;')
- str.gsub!(/</n, '&lt;')
- str
- end
-
-
-=begin
-=== UNESCAPE HTML
- CGI::unescapeHTML("HTML escaped string")
-=end
- def CGI::unescapeHTML(string)
- str = string.dup
- str.gsub!(/&(.*?);/n){
- 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#(\d+)\z/n then Integer($1).chr
- when /\A#x([0-9a-f]+)\z/ni then $1.hex.chr
- end
- }
- str
- 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, *element)
- str = string.dup
- str.gsub!(/<\/?(?:#{element.join("|")})(?!\w)(?:.|\n)*?>/ni){
- CGI::escapeHTML($&)
- }
- str
- 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, *element)
- str = string.dup
- str.gsub!(/&lt;\/?(?:#{element.join("|")})(?!\w)(?:.|\n)*?&gt;/ni){
- CGI::unescapeHTML($&)
- }
- str
- end
-
-
-=begin
-=== MAKE RFC1123 DATE STRING
- CGI::rfc1123_date(Time.now)
- # Sut, 1 Jan 2000 00:00:00 GMT
-=end
- 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
-
-
-=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 = ""
-
- if options.kind_of?(String)
- options = { "type" => options }
- end
-
- unless options.has_key?("type")
- options["type"] = "text/html"
- end
-
- if options.has_key?("charset")
- options["type"].concat( "; charset=" )
- options["type"].concat( options.delete("charset") )
- end
-
- if options.delete("nph") or (/IIS/n === env_table['SERVER_SOFTWARE'])
- buf.concat( (env_table["SERVER_PROTOCOL"] or "HTTP/1.0") + " " )
- buf.concat( (HTTP_STATUS[options["status"]] or
- options["status"] or
- "200 OK"
- ) + EOL
- )
- buf.concat(
- "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
-
- end
- options.delete("status")
-
- if options.has_key?("server")
- buf.concat("Server: " + options.delete("server") + EOL)
- end
-
- if options.has_key?("connection")
- buf.concat("Connection: " + options.delete("connection") + EOL)
- end
-
- buf.concat("Content-Type: " + options.delete("type") + EOL)
-
- if options.has_key?("length")
- buf.concat("Content-Length: " + options.delete("length").to_s + EOL)
- end
-
- if options.has_key?("language")
- buf.concat("Content-Language: " + options.delete("language") + EOL)
- end
-
- if options.has_key?("expires")
- buf.concat("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.concat("Set-Cookie: " + options.delete("cookie").to_s + EOL)
- elsif options["cookie"].kind_of?(Array)
- options.delete("cookie").each{|cookie|
- buf.concat("Set-Cookie: " + cookie.to_s + EOL)
- }
- elsif options["cookie"].kind_of?(Hash)
- options.delete("cookie").each_value{|cookie|
- buf.concat("Set-Cookie: " + cookie.to_s + EOL)
- }
- end
- end
- if @output_cookies
- for cookie in @output_cookies
- buf.concat("Set-Cookie: " + cookie.to_s + EOL)
- end
- end
-
- options.each{|key, value|
- buf.concat(key + ": " + value + EOL)
- }
-
- if defined?(MOD_RUBY)
- buf.scan(/([^:]+): (.+)#{EOL}/n){
- Apache::request[$1] = $2
- }
- Apache::request.send_http_header
- ''
- else
- buf + EOL
- end
-
- end # header()
-
-
-=begin
-=== PRINT HTTP HEADER AND STRING TO $>
- 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 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
- end
-
-
-=begin
-=== PRINT
- cgi = CGI.new
- cgi.print # default: cgi.print == $>.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"])
- @path = options["path"]
- @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.concat(@name + '=')
-
- if @value.kind_of?(String)
- buf.concat CGI::escape(@value)
- else
- buf.concat(@value.filter{|v| CGI::escape(v) }.join("&"))
- end
-
- if @domain
- buf.concat('; domain=' + @domain)
- end
-
- if @path
- buf.concat('; path=' + @path)
- end
-
- if @expires
- buf.concat('; expires=' + CGI::rfc1123_date(@expires))
- end
-
- if @secure == true
- buf.concat('; 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([])
-
- raw_cookie.split('; ').each do |pairs|
- name, values = pairs.split('=',2)
- name = CGI::unescape(name)
- values = values.split('&').filter{|v| CGI::unescape(v) }
- if cookies.has_key?(name)
- cookies[name].value.push(*values)
- else
- 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).filter{|v| CGI::unescape(v) }
- if params.has_key?(key)
- params[key].push(value)
- else
- params[key] = [value]
- end
- end
-
- params
- end
-
-
- module QueryExtension
-
- %w[ CONTENT_LENGTH SERVER_PORT ].
- each{|env|
- eval( <<-END )
- def #{env.sub(/^HTTP_/n, '').downcase}
- env_table["#{env}"] && Integer(env_table["#{env}"])
- end
- END
- }
-
- %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 ].
- each{|env|
- eval( <<-END )
- def #{env.sub(/^HTTP_/n, '').downcase}
- env_table["#{env}"]
- 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 read_multipart(boundary, content_length)
- params = Hash.new([])
- boundary = "--" + boundary
- buf = ""
- bufsize = 10 * 1024
-
- # start multipart/form-data
- stdinput.binmode
- content_length -= stdinput.read((boundary + EOL).size).size
-
- require "tempfile.rb"
-
- until -1 == content_length
- head = nil
- body = Tempfile.new("CGI")
- body.binmode
-
- until head and (/#{boundary}(?:#{EOL}|--)/n === buf)
-
- if (not head) and (/#{EOL}#{EOL}/n === buf)
- buf.sub!(/\A((?:.|\n)*?#{EOL})#{EOL}/n){
- head = $1.dup
- ""
- }
- 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.concat c
- content_length -= c.size
-
- end
-
- buf.sub!(/\A((?:.|\n)*?)(?:#{EOL})?#{boundary}(#{EOL}|--)/n){
- body.print $1
- if "--" == $2
- content_length = -1
- end
- ""
- }
-
- body.rewind
-
- eval <<-END
- def body.local_path
- #{body.path.dump}
- end
- END
-
- /Content-Disposition:.* filename="?([^\";]*)"?/ni === head
- eval <<-END
- def body.original_filename
- #{
- filename = ($1 or "").dup
- if (/Mac/ni === env_table['HTTP_USER_AGENT']) and
- (/Mozilla/ni === env_table['HTTP_USER_AGENT']) and
- (not /MSIE/ni === env_table['HTTP_USER_AGENT'])
- CGI::unescape(filename)
- else
- filename
- end.dump
- }
- end
- END
-
- /Content-Type: (.*)/ni === head
- eval <<-END
- def body.content_type
- #{($1 or "").dump}
- end
- END
-
- /Content-Disposition:.* name="?([^\";]*)"?/ni === 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.rb"
-
- unless ARGV.empty?
- str = ARGV.join(' ')
- else
- if STDIN.tty?
- STDERR.print(
- %|(offline mode: enter name=value pairs on standard input)\n|
- )
- end
- str = readlines.join(' ')
- str.gsub!(/\n/n, '')
- end
-
- str.gsub!(/\\=/n, '%3D')
- str.gsub!(/\\&/n, '%26')
-
- words = Shellwords.shellwords(str)
-
- if words.find{|x| /=/n === 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 ===
- 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'] or ""))
-
- 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_shift(string, shift = " ")
- shift = " " if true == shift
- str = string.dup
- str.gsub!(/\n(?!\z)/n, "\n" + shift)
- str
- end
- def CGI::pretty_nest(string, shift = " ")
- str = string.dup
- str.gsub!(/(<(\w+).*?>)((?:.|\n)*?)(<\/\2>)/n){
- $1 + CGI::pretty_shift(CGI::pretty_nest($3, shift), shift) + $4
- }
- str
- end
- def CGI::pretty(string, shift = " ")
- str = string.dup
- str.gsub!(/<(?:.|\n)*?>/n, "\n\\0")
- str.gsub!(/<(?:.|\n)*?>(?!\n)/n, "\\0\n")
- CGI::pretty_nest(str, shift)
- end
-
-
-=begin
-== HTML ELEMENTS
-
- cgi = CGI.new("html3") # add HTML generation methods
- cgi.element
- cgi.element{ "string" }
- cgi.element({ "ATTRILUTE1" => "value1", "ATTRIBUTE2" => "value2" })
- cgi.element({ "ATTRILUTE1" => "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 if value == nil
- " " + CGI::escapeHTML(name) +
- if true == value
- ""
- else
- '="' + CGI::escapeHTML(value) + '"'
- end
- }.to_s + ">" +
- if iterator?
- 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 if value == nil
- " " + 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 if value == nil
- " " + CGI::escapeHTML(name) +
- if true == value
- ""
- else
- '="' + CGI::escapeHTML(value) + '"'
- end
- }.to_s + ">" +
- if iterator?
- yield.to_s + "</element.upcase>"
- else
- ""
- end
- END
- end
-
- end # TagMaker
-
-
- module HtmlExtension
- extend TagMaker
-
-
-=begin
-=== A ELEMENT
- a("url")
- # = a({ "HREF" => "url" })
-=end
- def a(href = "")
- attributes = if href.kind_of?(String)
- { "HREF" => href }
- else
- href
- end
- if iterator?
- 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 iterator?
- 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 iterator?
- 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 iterator?
- 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>
-=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"] = method
- end
- unless method.has_key?("ENCTYPE")
- method["ENCTYPE"] = enctype
- end
- method
- end
- if iterator?
- body = yield
- else
- body = ""
- end
- if @output_hidden
- hidden = @output_hidden.collect{|k,v|
- "<INPUT TYPE=HIDDEN NAME=\"#{k}\" VALUE=\"#{v}\">"
- }.to_s
- body.concat 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")
- buf = ""
-
- if attributes.has_key?("DOCTYPE")
- if attributes["DOCTYPE"]
- buf.concat( attributes.delete("DOCTYPE") )
- else
- attributes.delete("DOCTYPE")
- end
- else
- buf.concat( doctype )
- end
-
- if iterator?
- buf.concat( super(attributes){ yield } )
- else
- buf.concat( 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
- name["TYPE"] = "image"
- name
- 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 iterator?
- 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 iterator?
- super(attributes){ yield }
- else
- super(attributes)
- end
- end
-
- end # HtmlExtension
-
-
- module Html3
- extend TagMaker
-
- def doctype
- %|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">|
- end
-
- # - -
- %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 ].
- each{|element|
- eval( <<-BEGIN + nn_element_def(element) + <<-END )
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- }
-
- # - O EMPTY
- %w[ IMG BASE BASEFONT BR AREA LINK PARAM HR INPUT ISINDEX META ].
- each{|element|
- eval( <<-BEGIN + nOE_element_def(element) + <<-END )
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- }
-
- # O O or - O
- %w[ HTML HEAD BODY P PLAINTEXT DT DD LI OPTION tr th td ].
- each{|element|
- eval( <<-BEGIN + nO_element_def(element) + <<-END )
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- }
-
- end # Html3
-
-
- module Html4
- extend TagMaker
-
- def doctype
- %|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">|
- end
-
- # - -
- %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 ].
- each{|element|
- eval( <<-BEGIN + nn_element_def(element) + <<-END )
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- }
-
- # - O EMPTY
- %w[ IMG BASE BR AREA LINK PARAM HR INPUT COL META ].
- each{|element|
- eval( <<-BEGIN + nOE_element_def(element) + <<-END )
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- }
-
- # O O or - O
- %w[ HTML BODY P DT DD LI OPTION THEAD TFOOT TBODY COLGROUP TR TH TD HEAD].
- each{|element|
- eval( <<-BEGIN + nO_element_def(element) + <<-END )
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- }
-
- end # Html4
-
-
- module Html4Tr
- extend TagMaker
-
- def doctype
- %|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">|
- end
-
- # - -
- %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 ].
- each{|element|
- eval( <<-BEGIN + nn_element_def(element) + <<-END )
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- }
-
- # - O EMPTY
- %w[ IMG BASE BASEFONT BR AREA LINK PARAM HR INPUT COL ISINDEX META ].
- each{|element|
- eval( <<-BEGIN + nOE_element_def(element) + <<-END )
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- }
-
- # O O or - O
- %w[ HTML BODY P DT DD LI OPTION THEAD TFOOT TBODY COLGROUP TR TH TD HEAD ].
- each{|element|
- eval( <<-BEGIN + nO_element_def(element) + <<-END )
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- }
-
- end # Html4Tr
-
-
- module Html4Fr
- include Html4Tr
- extend TagMaker
-
- def doctype
- %|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN" "http://www.w3.org/TR/REC-html40/frameset.dtd">|
- end
-
- # - -
- %w[ FRAMESET ].
- each{|element|
- eval( <<-BEGIN + nn_element_def(element) + <<-END )
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- }
-
- # - O EMPTY
- %w[ FRAME ].
- each{|element|
- eval( <<-BEGIN + nOE_element_def(element) + <<-END )
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- 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
- extend HtmlExtension
- when "html4"
- extend Html4
- extend HtmlExtension
- when "html4Tr"
- extend Html4Tr
- extend HtmlExtension
- when "html4Fr"
- extend Html4Fr
- 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
-
-== HISTRY
-
-=== Version 1.10 - wakou
-
-1999/12/06 20:16:34
-
-- can make many CGI objects.
-- if use mod_ruby, then require ruby1.4.3 or later.
-
-=== Version 1.01 - wakou
-
-1999/11/29 21:35:58
-
-- support for ruby 1.5.0 (1999-11-20)
-
-=== Version 1.00 - wakou
-
-1999/09/13 23:00:58
-
-- COUTION! name change. CGI.rb --> cgi.rb
-
-- CGI#auth_type, CGI#content_length, CGI#content_type, ...
-if not ENV included it, then return nil.
-
-- CGI#content_length and CGI#server_port return Integer.
-
-- if not CGI#params.include?('name'), then CGI#params['name'] return [].
-
-- if not CGI#cookies.include?('name'), then CGI#cookies['name'] return [].
-
-=== Version 0.41 - wakou
-
-1999/08/05 18:04:59
-
-- typo. thanks to MJ Ray <markj@altern.org>
- HTTP_STATUS["NOT_INPLEMENTED"] --> HTTP_STATUS["NOT_IMPLEMENTED"]
-
-=== Version 0.40 - wakou
-
-1999/07/20 20:44:31
-
-- COUTION! incompatible change.
- sorry, but probably this change is last big incompatible change.
-
-- CGI::print --> CGI#out
-
- cgi = CGI.new
- cgi.out{"string"} # old: CGI::print{"string"}
-
-- CGI::cookie --> CGI::Cookie::new
-
- cookie1 = CGI::Cookie::new # old: CGI::cookie
-
-- CGI::header --> CGI#header
-
-=== Version 0.30 - wakou
-
-1999/06/29 06:50:21
-
-- COUTION! incompatible change.
- query = CGI.new
- cookies = query.cookies # old: query.cookie
- values = query.cookies[name] # old: query.cookie[name]
-
-=== Version 0.24 - wakou
-
-1999/06/21 21:05:57
-
-- CGI::Cookie::parse() return { name => CGI::Cookie object } pairs.
-
-=== Version 0.23 - wakou
-
-1999/06/20 23:29:12
-
-- modified a bit to clear module separation.
-
-=== Version 0.22 - matz
-
-Mon Jun 14 17:49:32 JST 1999
-
-- Cookies are now CGI::Cookie objects.
-- Cookie modeled after CGI::Cookie.pm.
-
-=== Version 0.21 - matz
-
-Fri Jun 11 11:19:11 JST 1999
-
-- modified a bit to clear module separation.
-
-=== Version 0.20 - wakou
-
-1999/06/03 06:48:15
-
-- support for multipart form.
-
-=== Version 0.10 - wakou
-
-1999/05/24 07:05:41
-
-- first release.
-
-=end
diff --git a/lib/cgi/session.rb b/lib/cgi/session.rb
deleted file mode 100644
index edbae8c850..0000000000
--- a/lib/cgi/session.rb
+++ /dev/null
@@ -1,157 +0,0 @@
-
-require 'cgi'
-require 'final'
-
-class CGI
- class Session
-
- attr_reader :session_id
-
- def Session::callback(dbman)
- lambda{
- dbman.close
- }
- end
-
- def create_new_id
- require 'md5'
- md5 = MD5::new
- md5.update(String(Time::now))
- md5.update(String(rand(0)))
- md5.update(String($$))
- md5.update('foobar')
- @session_id = md5.hexdigest[0,16]
- end
- private :create_new_id
-
- def initialize(request, option={})
- session_key = option['session_key'] || '_session_id'
- id, = option['session_id']
- unless id
- if option['new_session']
- id = 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 = 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(session_key,id)]
- end
- ObjectSpace::define_finalizer(self, Session::callback(@dbman))
- 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] = String(val)
- end
-
- def update
- @dbman.update
- end
-
- def delete
- @dbman.delete
- end
-
- class FileStore
- def initialize(session, option={})
- dir = option['tmpdir'] || ENV['TMP'] || '/tmp'
- prefix = option['prefix'] || ''
- path = dir+"/"+prefix+session.session_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(v)
- end
- @f.truncate @f.tell
- end
-
- def close
- 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={})
- @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[@session_id] = nil
- end
- end
- end
-end
diff --git a/lib/complex.rb b/lib/complex.rb
deleted file mode 100644
index 0af8c20b89..0000000000
--- a/lib/complex.rb
+++ /dev/null
@@ -1,498 +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
-# Complex::abs
-# Complex::abs2
-# Complex::arg
-# Complex::polar
-# Complex::conjugate
-# Complex::<=>
-# Complex::==
-# Complex::to_i
-# 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 == 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, rdiv)
- 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 to_i
- Complex(@real.to_i, @image.to_i)
- end
-
- def to_f
- Complex(@real.to_f, @image.to_f)
- end
-
- def to_r
- Complex(@real.to_r, @image.to_r)
- 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 ^ @image
- 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 9de49bcbc7..0000000000
--- a/lib/date.rb
+++ /dev/null
@@ -1,258 +0,0 @@
-#
-# Date.rb -
-# $Release Version: $
-# $Revision: 1.1.1.1.4.5 $
-# $Date: 1998/03/03 02:39:34 $
-# by Yasuo OHBA(SHL Japan Inc. Technology Dept.)
-#
-# --
-#
-# September 1752
-# S M Tu W Th F S
-# 1 2 14 15 16
-# 17 18 19 20 21 22 23
-# 24 25 26 27 28 29 30
-#
-
-class Date
- include Comparable
-
- Weektag = [
- "Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"
- ]
-
- Monthtag = [
- "January","February","March","April", "May", "June","July",
- "August", "September", "October", "November", "December"
- ]
-
- Monthtab = {
- "jan"=>1, "feb"=>2, "mar"=>3, "apr"=>4, "may"=>5, "jun"=>6,
- "jul"=>7, "aug"=>8, "sep"=>9, "oct"=>10, "nov"=>11, "dec"=>12
- }
-
- def initialize(y = 1, m = 1, d = 1)
- if y.kind_of?(String)
- case y
- when /(\d\d\d\d)-?(?:(\d\d)-?(\d\d)?)?/
- @year = $1.to_i
- @month = if $2 then $2.to_i else 1 end
- @day = if $3 then $3.to_i else 1 end
- else
- require 'parsedate'
- @year, @month, @day = ParseDate.parsedate(y)
- end
- else
- if m.kind_of?(String)
- m = Monthtab[m.downcase]
- if m.nil?
- raise ArgumentError, "Wrong argument. (month)"
- end
- end
- @year = y.to_i
- @month = m.to_i
- @day = d.to_i
- end
- _check_date
- return self
- end
-
- def year
- return @year
- end
-
- def month
- return @month
- end
-
- def day
- return @day
- end
-
- def period
- return Date.period!(@year, @month, @day)
- end
-
- def jd
- return period + 1721423
- end
-
- def mjd
- return jd - 2400000.5
- end
-
- def to_s
- format("%.3s, %.3s %2d %4d", name_of_week, name_of_month, @day, @year)
- end
-
- def inspect
- to_s
- end
-
- def day_of_week
- return (period + 5) % 7
- end
-
- def name_of_week
- return Weektag[self.day_of_week]
- end
-
- def name_of_month
- return Monthtag[@month-1]
- end
-
- def +(o)
- if o.kind_of?(Numeric)
- d = Integer(self.period + o)
- elsif o.kind_of?(Date)
- d = self.period + o.period
- else
- raise TypeError, "Illegal type. (Integer or Date)"
- end
- if d <= 0
- raise ArgumentError, "argument out of range. (self > other)"
- end
- return Date.at(d)
- end
-
- def -(o)
- if o.kind_of?(Numeric)
- d = Integer(self.period - o)
- elsif o.kind_of?(Date)
- return Integer(self.period - o.period)
- else
- raise TypeError, "Illegal type. (Integer or Date)"
- end
- if d <= 0
- raise ArgumentError, "argument out of range. (self > other)"
- end
- return Date.at(d)
- end
-
- def <=>(o)
- if o.kind_of?(Integer)
- d = o
- elsif o.kind_of?(Date)
- d = o.period
- else
- raise TypeError, "Illegal type. (Integer or Date)"
- end
- return self.period <=> d
- end
-
- def eql?(o)
- self == o
- end
-
- def hash
- return @year ^ @month ^ @day
- end
-
- def leapyear?
- Date.leapyear(@year) != 1
- end
-
- def _check_date
- if @year == nil or @month == nil or @day == nil
- raise ArgumentError, "argument contains nil"
- end
- m = Date.daylist(@year)
- if @month < 1 || @month > 12
- raise ArgumentError, "argument(month) out of range."
- return nil
- end
- if @year == 1752 && @month == 9
- if @day >= 3 && @day <= 13
- raise ArgumentError, "argument(1752/09/3-13) out of range."
- return nil
- end
- d = 30
- else
- d = m[@month]
- end
- if @day < 1 || @day > d
- raise ArgumentError, "argument(day) out of range."
- return nil
- end
- return self
- end
-
- private :_check_date
-end
-
-def Date.at(d)
- if d.kind_of? Time
- return Date.new(d.year, d.mon, d.mday)
- end
- if d.kind_of? Date
- return Date.at(d.period)
- end
- mm = 1
- yy = (d / 366.0).to_i
- if yy != 0
- dd = d - (Date.period!(yy, 1, 1) - 1)
- else
- dd = d
- yy = 1
- end
- dl = Date.daylist(yy)
- while dd > dl[mm]
- if dd > dl[0]
- dd -= dl[0]
- yy += 1
- dl = Date.daylist(yy)
- else
- dd -= dl[mm]
- mm += 1
- end
- end
- if yy == 1752 && mm == 9 && dd >= 3 && dd <= 19
- dd += (14 - 3) # 1752/09/03-19 -> 1752/09/14-30
- end
-
- return Date.new(yy, mm, dd)
-end
-
-def Date.period!(y, m, d)
- p = d
- dl = Date.daylist(y)
- for mm in 1..(m - 1)
- p += dl[mm]
- end
- p += (y - 1) * 365 + ((y - 1) / 4.0).to_i
- if y > 1752
- p -= ((y - 1) / 100.0).to_i
- p += ((y - 1) / 400.0).to_i
- p += 2
- elsif y == 1752 && m == 9 && d >= 14 && d <= 30
- p -= (14 - 3)
- end
- return p
-end
-
-def Date.leapyear(yy)
- return ((Date.jan1!(yy + 1) + 7 - Date.jan1!(yy)) % 7)
-end
-
-def Date.daylist(yy)
- case (Date.leapyear(yy))
- when 1 # non-leapyear
- return [365, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
- when 2 # leapyear
- return [366, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
- else # 1752
- return [355, 31, 29, 31, 30, 31, 30, 31, 31, 19, 31, 30, 31]
- end
-end
-
-def Date.jan1!(y)
- d = 4 + y + (y + 3) / 4
- if y > 1800
- d -= (y - 1701) / 100
- d += (y - 1601) / 400
- end
- if y > 1752
- d += 3
- end
- return (d % 7)
-end
diff --git a/lib/date2.rb b/lib/date2.rb
deleted file mode 100644
index 38d477b78d..0000000000
--- a/lib/date2.rb
+++ /dev/null
@@ -1,346 +0,0 @@
-# date2.rb: Written by Tadayoshi Funaba 1998, 1999
-# $Id: date2.rb,v 1.17 1999/09/15 05:34:07 tadf Exp $
-
-class Date
-
- include Comparable
-
- IDENT = 2
-
- MONTHNAMES = [ nil, 'January', 'February', 'March',
- 'April', 'May', 'June', 'July', 'August',
- 'September', 'October', 'November', 'December' ]
-
- DAYNAMES = [ '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 = (x / y).to_i
- z = (q * y)
- q -= 1 if (y > 0 and x < z) or (y < 0 and x > z)
- r = x - q * y
- 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 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?
-
- def new1(jd=0, sg=ITALY) new(jd, sg) end
-
- def exist3? (y, m, d, sg=ITALY)
- if m < 0
- m += 13
- end
- if d < 0
- ny, nm = Date.clfloor(y * 12 + m, 12)
- nm, = Date.clfloor(m + 1, 1)
- la = nil
- 31.downto 1 do |z|
- break if la = exist3?(y, m, z, sg)
- end
- ns = ns?(la, sg)
- d = jd_to_civil(civil_to_jd(ny, nm, 1, ns) + d, ns)[-1]
- end
- jd = civil_to_jd(y, m, d, sg)
- return unless [y, m, d] == jd_to_civil(jd, sg)
- jd
- end
-
- alias_method :exist?, :exist3?
-
- def new3(y=-4712, m=1, d=1, sg=ITALY)
- unless jd = exist3?(y, m, d, sg)
- fail ArgumentError, 'invalid date'
- end
- new(jd, sg)
- end
-
- def exist2? (y, d, sg=ITALY)
- if d < 0
- ny = y + 1
- la = nil
- 366.downto 1 do |z|
- break if la = exist2?(y, z, sg)
- end
- ns = ns?(la, sg)
- d = jd_to_ordinal(ordinal_to_jd(ny, 1, ns) + d, ns)[-1]
- end
- jd = ordinal_to_jd(y, d, sg)
- return unless [y, d] == jd_to_ordinal(jd, sg)
- jd
- end
-
- def new2(y=-4712, d=1, sg=ITALY)
- unless jd = exist2?(y, d, sg)
- fail ArgumentError, 'invalid date'
- end
- new(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)
- fail ArgumentError, 'invalid date'
- end
- new(jd, sg)
- end
-
- def today(sg=ITALY)
- new(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}__, #{id}
- def #{id.id2name}(*args, &block)
- def self.#{id.id2name}(*args, &block); @__#{id}__ end
- @__#{id}__ = __#{id}__(*args, &block)
- end
- end;
- end
- end
-
- private :once
-
- end
-
- def initialize(rjd=0, sg=ITALY) @rjd, @sg = rjd, sg end
-
- def rjd() @rjd end
- def rmjd() Date.jd_to_mjd(@rjd) end
- def rtjd() Date.jd_to_tjd(@rjd) end
-
- once :rmjd, :rtjd
-
- def jd() Date.rjd_to_jd(@rjd)[0] end
- def fr1() Date.rjd_to_jd(@rjd)[1] end
- def mjd() Date.jd_to_mjd(jd) end
- def tjd() Date.jd_to_tjd(jd) end
-
- once :jd, :fr1, :mjd, :tjd
-
- def civil() Date.jd_to_civil(jd, @sg) end
- def ordinal() Date.jd_to_ordinal(jd, @sg) end
- def commercial() Date.jd_to_commercial(jd, @sg) end
-
- once :civil, :ordinal, :commercial
-
- def year() civil[0] end
- def yday() ordinal[1] end
- def mon() civil[1] end
-
- alias_method :month, :mon
- once :year, :yday, :mon, :month
-
- def mday() civil[2] end
-
- alias_method :day, :mday
- once :mday, :day
-
- def cwyear() commercial[0] end
- def cweek() commercial[1] end
- def cwday() commercial[2] end
-
- once :cwyear, :cweek, :cwday
-
- def wday() (jd + 1) % 7 end
-
- once :wday
-
- def os? () Date.os?(jd, @sg) end
- def ns? () Date.ns?(jd, @sg) end
-
- once :os?, :ns?
-
- def leap?
- Date.jd_to_civil(Date.civil_to_jd(year, 3, 1, ns?) - 1,
- ns?)[-1] == 29
- end
-
- once :leap?
-
- def sg() @sg end
- def newsg(sg=Date::ITALY) Date.new(@rjd, sg) end
-
- def italy() newsg(Date::ITALY) end
- def england() newsg(Date::ENGLAND) end
- def julian() newsg(Date::JULIAN) end
- def gregorian() newsg(Date::GREGORIAN) end
-
- def + (n)
- case n
- when Numeric; return Date.new(@rjd + n, @sg)
- end
- fail TypeError, 'expected numeric'
- end
-
- def - (x)
- case x
- when Numeric; return Date.new(@rjd - x, @sg)
- when Date; return @rjd - x.rjd
- end
- fail TypeError, 'expected numeric or date'
- end
-
- def <=> (other)
- case other
- when Numeric; return @rjd <=> other
- when Date; return @rjd <=> other.rjd
- end
- fail TypeError, 'expected numeric or date'
- end
-
- def === (other)
- case other
- when Numeric; return jd == other
- when Date; return jd == other.jd
- end
- fail TypeError, 'expected numeric or date'
- end
-
- def >> (n)
- y, m = Date.clfloor(year * 12 + (mon - 1) + n, 12)
- m, = Date.clfloor(m + 1, 1)
- d = mday
- d -= 1 until jd2 = Date.exist3?(y, m, d, ns?)
- self + (jd2 - jd)
- end
-
- def << (n) self >> -n end
-
- def step(limit, step)
- rjd = @rjd
- if (step > 0)
- while rjd <= limit.rjd
- yield Date.new(rjd, @sg)
- rjd += step
- end
- else
- while rjd >= limit.rjd
- yield Date.new(rjd, @sg)
- rjd += step
- end
- 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() Date.clfloor(@rjd)[0] end
- def inspect() format('#<Date: %s,%s>', @rjd, @sg) end
- def to_s() format('%.4d-%02d-%02d', year, mon, mday) end
-
- def _dump(limit) Marshal.dump([@rjd, @sg], -1) end
- def Date._load(str) Date.new(*Marshal.load(str)) end
-
-end
diff --git a/lib/debug.rb b/lib/debug.rb
deleted file mode 100644
index 244db021e2..0000000000
--- a/lib/debug.rb
+++ /dev/null
@@ -1,399 +0,0 @@
-LINES__ = {} unless defined? LINES__
-
-class DEBUGGER__
- 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
- line.chomp!
- line
- end
- USE_READLINE = false
- end
-
- trap("INT") { DEBUGGER__::CONTEXT.interrupt }
- $DEBUG = true
- def initialize
- @break_points = []
- @display = []
- @stop_next = 1
- @frames = [nil]
- @last_file = nil
- @last = [nil, nil]
- @no_step = nil
- @finish_pos = 0
- end
-
- DEBUG_LAST_CMD = []
-
- def interrupt
- @stop_next = 1
- end
-
- def debug_eval(str, binding)
- begin
- val = eval(str, binding)
- val
- rescue
- at = caller(0)
- STDOUT.printf "%s:%s\n", at.shift, $!
- for i in at
- break if i =~ /`debug_(eval|command)'$/ #`
- STDOUT.printf "\tfrom %s\n", i
- end
- end
- end
-
- def debug_command(file, line, id, binding)
- frame_pos = 0
- binding_file = file
- binding_line = line
- previus_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
- display_expressions(binding)
- while input = readline("(rdb:-) ", true)
- if input == ""
- input = DEBUG_LAST_CMD[0]
- else
- DEBUG_LAST_CMD[0] = input
- end
-
- case input
- when /^b(?:reak)?\s+((?:[^:\n]+:)?.+)$/
- pos = $1
- if pos.index(":")
- file, pos = pos.split(":")
- 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 /^wat(?:ch)?\s+(.+)$/
- exp = $1
- @break_points.push [true, 1, exp]
- STDOUT.printf "Set watchpoint %d\n", @break_points.size, exp
-
- when /^b(?:reak)?$/, /^info b(?:reak)?$/
- 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
- 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
- STDOUT.print "\n"
-
- when /^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 /^disp(?:lay)?\s+(.+)$/
- exp = $1
- @display.push.push [true, exp]
- STDOUT.printf " %d: %s = %s\n", @display.size, exp,
- debug_eval(exp, binding).to_s
-
- when /^disp(?:lay)?$/, /^info disp(?:lay)?$/
- display_expressions(binding)
-
- when /^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 /^c(?:ont)?$/
- return
-
- when /^s(?:tep)?(?:\s+(\d+))?$/
- if $1
- lev = $1.to_i
- else
- lev = 1
- end
- @stop_next = lev
- return
-
- when /^n(?:ext)?(?:\s+(\d+))?$/
- if $1
- lev = $1.to_i
- else
- lev = 1
- end
- @stop_next = lev
- @no_step = @frames.size - frame_pos
- return
-
- when /^w(?:here)?$/, /^f(?:rame)?$/
- at = caller(0)
- 0.upto(@frames.size - 1) do |n|
- if frame_pos == n
- STDOUT.printf "--> #%d %s\n", n, at[-(@frames.size - n)]
- else
- STDOUT.printf " #%d %s\n", n, at[-(@frames.size - n)]
- end
- end
-
- when /^l(?:ist)?(?:\s+(.+))?$/
- if not $1
- b = previus_line ? previus_line + 10 : binding_line - 5
- e = b + 9
- elsif $1 == '-'
- b = previus_line ? previus_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
- previus_line = b
- STDOUT.printf "[%d, %d] in %s\n", b, e, binding_file
- line_at(binding_file, binding_line)
- if lines = LINES__[binding_file] and lines != true
- n = 0
- b.upto(e) do |n|
- if n > 0 && lines[n-1]
- if n == binding_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", binding_file
- end
-
- when /^up(?:\s+(\d+))?$/
- previus_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 = @frames[frame_pos]
- info, binding_file, binding_line = frame_info(frame_pos)
- STDOUT.printf "#%d %s\n", frame_pos, info
-
- when /^down(?:\s+(\d+))?$/
- previus_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 = @frames[frame_pos]
- info, binding_file, binding_line = frame_info(frame_pos)
- STDOUT.printf "#%d %s\n", frame_pos, info
-
- when /^fi(?:nish)?$/
- if frame_pos == 0
- STDOUT.print "\"finish\" not meaningful in the outermost frame.\n"
- else
- @finish_pos = @frames.size - frame_pos
- frame_pos = 0
- return
- end
-
- when /^q(?:uit)?$/
- input = readline("really quit? (y/n) ", false)
- exit if input == "y"
-
- when /^p\s+/
- p debug_eval($', binding)
-
- else
- v = debug_eval(input, binding)
- p v unless (v == nil)
- end
- end
- end
-
- def display_expressions(binding)
- n = 1
- for d in @display
- if d[0]
- STDOUT.printf "%d: %s = %s\n", n, d[1], debug_eval(d[1], binding).to_s
- end
- n += 1
- end
- end
-
- def frame_info(pos = 0)
- info = caller(0)[-(@frames.size - pos)]
- info.sub(/:in `.*'$/, "") =~ /^(.*):(\d+)$/ #`
- [info, $1, $2.to_i]
- end
-
- def line_at(file, line)
- lines = 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 == 0
- "toplevel"
- else
- id.id2name
- end
- end
-
- def check_break_points(file, pos, binding, id)
- 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 and debug_eval(b[2], binding)
- STDOUT.printf "watchpoint %d, %s at %s:%s\n", n, debug_funcname(id),
- file, pos
- return true
- end
- end
- n += 1
- end
- return false
- end
-
- def excn_handle(file, line, id, binding)
- fs = @frames.size
- tb = caller(0)[-fs..-1]
-
- STDOUT.printf "%s\n", $!
- for i in tb
- STDOUT.printf "\tfrom %s\n", i
- end
- debug_command(file, line, id, binding)
- end
-
- def trace_func(event, file, line, id, binding)
- case event
- when '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
- if [file, line] == @last
- @stop_next = 1
- else
- @no_step = nil
- debug_command(file, line, id, binding)
- @last = [file, line]
- end
- end
- if check_break_points(file, line, binding, id)
- debug_command(file, line, id, binding)
- end
-
- when 'call'
- @frames.unshift binding
- if check_break_points(file, id.id2name, binding, id)
- debug_command(file, line, id, binding)
- end
-
- when 'class'
- @frames.unshift binding
-
- when 'return', 'end'
- @frames.shift
- if @frames.size == @finish_pos
- @stop_next = 1
- end
-
- when 'raise'
- excn_handle(file, line, id, binding)
-
- end
- @last_file = file
- end
-
- CONTEXT = new
-
-
- set_trace_func proc{|event, file, line, id, binding,*rest|
- DEBUGGER__::CONTEXT.trace_func event, file, line, id, binding
- }
-end
diff --git a/lib/delegate.rb b/lib/delegate.rb
deleted file mode 100644
index 29f2a5ded2..0000000000
--- a/lib/delegate.rb
+++ /dev/null
@@ -1,120 +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 # => true
-#
-# 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
- 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
- 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
- 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
- klass.module_eval <<-EOS
- def #{method}(*args, &block)
- begin
- @obj.__send__(:#{method}, *args, &block)
- rescue
- $@[0,2] = nil
- raise
- end
- end
- EOS
- 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 2b023601d2..0000000000
--- a/lib/e2mmap.rb
+++ /dev/null
@@ -1,196 +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 Exception2MassageMapper
-# def_e2message ExistingExceptionClass, "message..."
-# def_exception :NewExceptionClass, "message..."[, superclass]
-# ...
-# end
-#
-# U2)
-# module Error
-# extend Exception2MassageMapper
-# def_e2meggage ExistingExceptionClass, "message..."
-# def_exception :NewExceptionClass, "message..."[, superclass]
-# ...
-# end
-# class Foo
-# include Exp
-# ...
-# end
-#
-# foo = Foo.new
-# foo.Fail ....
-#
-# U3)
-# module Error
-# extend Exception2MassageMapper
-# 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
-
- # 以前との互換性のために残してある.
- 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.append_features(mod)
- super
- mod.extend Exception2MessageMapper
- end
- ]
- end
-
- # Fail(err, *rest)
- # err: 例外
- # rest: メッセージに渡すパラメータ
- #
- def Raise(err = nil, *rest)
- E2MM.Raise(self, err, *rest)
- end
- alias Fail Raise
-
- # 過去の互換性のため
- 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
- # 例外cのメッセージをmとする.
- #
- def def_e2message(c, m)
- E2MM.def_e2message(self, c, m)
- end
-
- # def_exception(c, m)
- # n: exception_name
- # m: message_form
- # s: 例外スーパークラス(デフォルト: StandardError)
- # 例外名``c''をもつ例外を定義し, そのメッセージを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: 例外を定義するクラス
- # e: exception
- # m: message_form
- # 例外cのメッセージをmとする.
- #
- def E2MM.def_e2message(k, c, m)
- E2MM.instance_eval{@MessageMap[[k, c]] = m}
- c
- end
-
- # E2MM.def_exception(k, c, m)
- # k: 例外を定義するクラス
- # n: exception_name
- # m: message_form
- # s: 例外スーパークラス(デフォルト: StandardError)
- # 例外名``c''をもつ例外を定義し, そのメッセージを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: 例外の定義されているクラス
- # err: 例外
- # rest: メッセージに渡すパラメータ
- #
- 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 384d531e0f..0000000000
--- a/lib/eregex.rb
+++ /dev/null
@@ -1,36 +0,0 @@
-
-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 cdffd941e7..0000000000
--- a/lib/final.rb
+++ /dev/null
@@ -1,41 +0,0 @@
-#
-# $Id$
-# Copyright (C) 1998 Yukihiro Matsumoto. All rights reserved.
-
-# The ObjectSpace extension:
-#
-# ObjectSpace.define_finalizer(obj, proc=lambda())
-#
-# Defines the finalizer for the specified object.
-#
-# ObjectSpace.undefine_finalizer(obj)
-#
-# Removes the finalizers for the object. If multiple finalizers are
-# defined for the object, all finalizers will be removed.
-#
-
-module ObjectSpace
- Finalizers = {}
- def define_finalizer(obj, proc=lambda())
- ObjectSpace.call_finalizer(obj)
- if assoc = Finalizers[obj.id]
- assoc.push(proc)
- else
- Finalizers[obj.id] = [proc]
- end
- end
- def undefine_finalizer(obj)
- Finalizers.delete(obj.id)
- end
- module_function :define_finalizer, :undefine_finalizer
-
- Generic_Finalizer = proc {|id|
- if Finalizers.key? id
- for proc in Finalizers[id]
- proc.call(id)
- end
- Finalizers.delete(id)
- end
- }
- add_finalizer Generic_Finalizer
-end
diff --git a/lib/finalize.rb b/lib/finalize.rb
deleted file mode 100644
index 3cf79ff92f..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).
-# fainalize_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 fainalize_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 :fainalize_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 3f1b82d2b3..0000000000
--- a/lib/find.rb
+++ /dev/null
@@ -1,39 +0,0 @@
-# Usage:
-# require "find"
-#
-# Find.find('/foo','/bar') {|f| ...}
-# or
-# include Find
-# find('/foo','/bar') {|f| ...}
-#
-
-module Find
- def find(*path)
- while file = path.shift
- catch(:prune) {
- yield file
- if File.directory? file then
- d = Dir.open(file)
- begin
- for f in d
- next if f =~ /^\.\.?$/
- if file == "/" then
- f = "/" + f
- else
- f = file + "/" + f
- end
- path.unshift f
- end
- ensure
- d.close
- end
- end
- }
- end
- end
-
- def prune
- throw :prune
- end
- module_function :find, :prune
-end
diff --git a/lib/ftools.rb b/lib/ftools.rb
deleted file mode 100644
index 39d6ca9462..0000000000
--- a/lib/ftools.rb
+++ /dev/null
@@ -1,182 +0,0 @@
-class << File
-
- TOO_BIG = 1024 * 1024 * 2 # 2MB
-
- def catname from, to
- if FileTest.directory? to
- to +
- if to =~ /\\/
- if to[-1,1] != '\\' then '\\' end + basename(from)
- else
- if to[-1,1] != '/' then '/' end + basename(from)
- end
- 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
-
- 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)
- 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, tpath)
- 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
- if fr = from.read(fsize)
- 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
-
- 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
-
- 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 657825424f..0000000000
--- a/lib/ftplib.rb
+++ /dev/null
@@ -1,629 +0,0 @@
-# ftplib.rb by Shugo Maeda <shugo@netlab.co.jp>
-
-require "socket"
-require "monitor"
-
-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"
-
- attr_accessor :passive, :return_code, :debug_mode
- 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
- 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 = TCPsocket.getaddress(@sock.addr[2])
- 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)
- if @passive
- host, port = makepasv
- conn = open_socket(host, port)
- resp = sendcmd(cmd)
- if resp[0] != ?1
- raise FTPReplyError, resp
- end
- else
- sock = makeport
- resp = sendcmd(cmd)
- if resp[0] != ?1
- raise FTPReplyError, resp
- end
- conn = sock.accept
- 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, callback = Proc.new)
- synchronize do
- voidcmd("TYPE I")
- conn = transfercmd(cmd)
- 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 iterator?
- 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, callback = nil)
- if iterator?
- callback = Proc.new
- end
- use_callback = callback.is_a?(Proc)
- synchronize do
- voidcmd("TYPE I")
- conn = transfercmd(cmd)
- 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 iterator?
- 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, callback = nil)
- if iterator?
- callback = Proc.new
- end
- use_callback = callback.is_a?(Proc)
- f = open(localfile, "w")
- begin
- f.binmode
- retrbinary("RETR " + remotefile, blocksize) do |data|
- f.write(data)
- callback.call(data) if use_callback
- end
- ensure
- f.close
- end
- end
-
- def gettextfile(remotefile, localfile, callback = nil)
- if iterator?
- 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, callback = nil)
- if iterator?
- callback = Proc.new
- end
- use_callback = callback.is_a?(Proc)
- f = open(localfile)
- begin
- f.binmode
- storbinary("STOR " + remotefile, f, blocksize) do |data|
- callback.call(data) if use_callback
- end
- ensure
- f.close
- end
- end
-
- def puttextfile(localfile, remotefile, callback = nil)
- if iterator?
- 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
- 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 :parse228
-
- 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
diff --git a/lib/getoptlong.rb b/lib/getoptlong.rb
deleted file mode 100644
index 82cccf43b9..0000000000
--- a/lib/getoptlong.rb
+++ /dev/null
@@ -1,473 +0,0 @@
-# -*- Ruby -*-
-# Copyright (C) 1998 Motoyuki Kasahara
-#
-# 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, 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.
-#
-
-#
-# 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..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 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
- name, argument = nil, ''
-
- #
- # Check status.
- #
- return 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
- $_ = '-' + @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
- $_ = ARGV.shift
- elsif @ordering == REQUIRE_ORDER
- if (ARGV[0] !~ /^-./)
- terminate
- return nil
- end
- $_ = ARGV.shift
- else
- $_ = ARGV.shift
- end
-
- #
- # Check the special argument `--'.
- # `--' indicates the end of the option list.
- #
- if $_ == '--' && @rest_singles.length == 0
- terminate
- return nil
- end
-
- #
- # Check for long and short options.
- #
- if /^(--[^=]+)/ && @rest_singles.length == 0
- #
- # This is a long style option, which start with `--'.
- #
- pattern = $1
- if @canonical_names.include?(pattern)
- name = pattern
- else
- #
- # The 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
- name = key
- match_count += 1
- end
- end
- if 2 <= match_count
- set_error(AmbigousOption, "option `#{$_}' is ambiguous")
- elsif match_count == 0
- set_error(InvalidOption, "unrecognized option `#{$_}'")
- end
- end
-
- #
- # Check an argument to the option.
- #
- if @argument_flags[name] == REQUIRED_ARGUMENT
- if /=(.*)$/
- argument = $1
- elsif 0 < ARGV.length
- argument = ARGV.shift
- else
- set_error(MissingArgument, "option `#{$_}' requires an argument")
- end
- elsif @argument_flags[name] == OPTIONAL_ARGUMENT
- if /=(.*)$/
- argument = $1
- elsif 0 < ARGV.length && ARGV[0] !~ /^-./
- argument = ARGV.shift
- else
- argument = ''
- end
- elsif /=(.*)$/
- set_error(NeedlessArgument,
- "option `#{name}' doesn't allow an argument")
- end
-
- elsif /^(-(.))(.*)/
- #
- # This is a short style option, which start with `-' (not `--').
- # Short options may be catinated (e.g. `-l -g' is equivalent to
- # `-lg').
- #
- name, ch, @rest_singles = $1, $2, $3
-
- if @canonical_names.include?(name)
- #
- # The option `name' is found in `@canonical_names'.
- # Check its argument.
- #
- if @argument_flags[name] == REQUIRED_ARGUMENT
- if 0 < @rest_singles.length
- argument = @rest_singles
- @rest_singles = ''
- elsif 0 < ARGV.length
- argument = ARGV.shift
- else
- # 1003.2 specifies the format of this message.
- set_error(MissingArgument, "option requires an argument -- #{ch}")
- end
- elsif @argument_flags[name] == OPTIONAL_ARGUMENT
- if 0 < @rest_singles.length
- argument = @rest_singles
- @rest_singles = ''
- elsif 0 < ARGV.length && ARGV[0] !~ /^-./
- argument = ARGV.shift
- else
- 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 '', $_
- end
-
- return @canonical_names[name], argument
- end
-
- #
- # `get_option' is an alias of `get'.
- #
- alias get_option get
-
- #
- # Iterator version of `get'.
- #
- def each
- loop do
- name, argument = get_option
- break if name == nil
- yield name, 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 5b9562d5b2..0000000000
--- a/lib/getopts.rb
+++ /dev/null
@@ -1,141 +0,0 @@
-#
-# getopts.rb -
-# $Release Version: $
-# $Revision$
-# $Date$
-# by Yasuo OHBA(SHL Japan Inc. Technology Dept.)
-#
-# --
-#
-#
-#
-
-$RCS_ID=%q$Header$
-
-def isSingle(lopt)
- if lopt.index(":")
- if lopt.split(":")[0].length == 1
- return true
- end
- end
- return nil
-end
-
-def getOptionName(lopt)
- return lopt.split(":")[0]
-end
-
-def getDefaultOption(lopt)
- od = lopt.split(":")[1]
- if od
- return od
- end
- return nil
-end
-
-def setOption(name, value)
- eval("$OPT_" + name + " = " + 'value')
-end
-
-def setDefaultOption(lopt)
- d = getDefaultOption(lopt)
- if d
- setOption(getOptionName(lopt), d)
- end
-end
-
-def setNewArgv(newargv)
- ARGV.clear
- for na in newargv
- ARGV << na
- end
-end
-
-
-def getopts(single_opts, *options)
- if options
- single_colon = ""
- long_opts = []
- sc = 0
- for o in options
- setDefaultOption(o)
- if isSingle(o)
- single_colon[sc, 0] = getOptionName(o)
- sc += 1
- else
- long_opts.push(o)
- end
- end
- end
-
- opts = {}
- count = 0
- newargv = []
- while ARGV.length != 0
- compare = nil
- case ARGV[0]
- when /^--?$/
- ARGV.shift
- newargv += ARGV
- break
- when /^--.*/
- compare = ARGV[0][2, (ARGV[0].length - 2)]
- if long_opts != ""
- for lo in long_opts
- if lo.index(":") && getOptionName(lo) == compare
- if ARGV.length <= 1
- return nil
- end
- setOption(compare, ARGV[1])
- opts[compare] = true
- ARGV.shift
- count += 1
- break
- elsif lo == compare
- setOption(compare, true)
- opts[compare] = true
- count += 1
- break
- end
- end
- end
- if compare.length <= 1
- return nil
- end
- when /^-.*/
- for idx in 1..(ARGV[0].length - 1)
- compare = ARGV[0][idx, 1]
- if single_opts && compare =~ "[" + single_opts + "]"
- setOption(compare, true)
- opts[compare] = true
- count += 1
- elsif single_colon != "" && compare =~ "[" + single_colon + "]"
- if ARGV[0][idx..-1].length > 1
- setOption(compare, ARGV[0][(idx + 1)..-1])
- opts[compare] = true
- count += 1
- elsif ARGV.length <= 1
- return nil
- else
- setOption(compare, ARGV[1])
- opts[compare] = true
- ARGV.shift
- count += 1
- end
- break
- end
- end
- else
- compare = ARGV[0]
- opts[compare] = true
- newargv << ARGV[0]
- end
-
- ARGV.shift
- if !opts.has_key?(compare)
- return nil
- end
- end
- setNewArgv(newargv)
- return count
-end
diff --git a/lib/importenv.rb b/lib/importenv.rb
deleted file mode 100644
index 10b289199c..0000000000
--- a/lib/importenv.rb
+++ /dev/null
@@ -1,32 +0,0 @@
-# importenv.rb -- imports environment variables as global variables
-#
-# 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} = %q!#{v}!
- trace_var "$#{k}", proc{|v|
- ENV[%q!#{k}!] = v;
- $#{k} = %q!#{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/jcode.rb b/lib/jcode.rb
deleted file mode 100644
index 7a4cddd693..0000000000
--- a/lib/jcode.rb
+++ /dev/null
@@ -1,206 +0,0 @@
-# jcode.rb - ruby code to handle japanese (EUC/SJIS) string
-
-$vsave, $VERBOSE = $VERBOSE, FALSE
-class String
- printf STDERR, "feel free for some warnings:\n" if $VERBOSE
-
- 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(/(.|\n)-(.|\n)|(.|\n)/) do |r|
- if $3
- a.push $3
- elsif $1.length != $2.length
- next
- elsif $1.length == 1
- $1[0].upto($2[0]) { |c| a.push c.chr }
- else
- $1.upto($2) { |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
-
- def bsquote(str)
- str.gsub(/\\/, '\\\\\\\\')
- end
-
- HashCache = {}
- TrPatternCache = {}
- DeletePatternCache = {}
- SqueezePatternCache = {}
-
- public
-
- def tr!(from, to)
- return self.delete!(from) if to.length == 0
-
- pattern = TrPatternCache[from] ||= /[#{bsquote(from)}]/
- if from[0] == ?^
- last = /.$/.match(to)[0]
- self.gsub!(pattern, last)
- else
- h = HashCache[from + "::" + 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] ||= /[#{bsquote(del)}]+/, '')
- end
-
- def delete(del)
- (str = self.dup).delete!(del) or str
- end
-
- def squeeze!(del=nil)
- pattern =
- if del
- SqueezePatternCache[del] ||= /([#{bsquote(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] ||= /([#{bsquote(from)}])\1+"/
- if from[0] == ?^
- last = /.$/.match(to)[0]
- self.gsub!(pattern, last)
- else
- h = HashCache[from + "::" + 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 iterator?
- scan(/./) do |x|
- yield x
- end
- else
- scan(/./)
- end
- end
-
-end
-$VERBOSE = $vsave
diff --git a/lib/mailread.rb b/lib/mailread.rb
deleted file mode 100644
index 2edcca002a..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 f.gets()
- $_.chop!
- next if /^From / # skip From-line
- break if /^$/ # end of header
-
- if /^(\S+):\s*(.*)/
- (attr = $1).capitalize!
- @header[attr] = $2
- elsif attr
- sub!(/^\s*/, '')
- @header[attr] += "\n" + $_
- end
- end
-
- return unless $_
-
- while f.gets()
- break if /^From /
- @body.push($_)
- 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 8d92272159..0000000000
--- a/lib/mathn.rb
+++ /dev/null
@@ -1,309 +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
-
- 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 f31da643ff..0000000000
--- a/lib/matrix.rb
+++ /dev/null
@@ -1,1022 +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]
-#
-# column: 列
-# row: 行
-#
-# 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
- }
- self
- 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 iterator?
- for e in @rows[i]
- yield e
-
- end
- else
- Vector.elements(@rows[i])
- end
- end
-
- def column(j)
- if iterator?
- 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) #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
- else
- a = to_a
- end
- rank = 0
- k = 0
- begin
- if (akk = a[k][k]) == 0
- i = k
- exists = true
- begin
- if (i += 1) > 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) > row_size - 1
- exists = false
- break
- end
- end while a[k][i] == 0
- if exists
- k.upto(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(row_size - 1) do
- |i|
- q = a[i][k] / akk
- (k + 1).upto(column_size - 1) do
- |j|
- a[i][j] -= a[k][j] * q
- end
- end
- rank += 1
- end while (k += 1) <= 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 .. column_size - 1).collect {
- |i|
- row(i)
- }
- rows
- end
-
- def column_vectors
- columns = (0 .. row_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) "is matrix or number"
- case x
- when Numeric
- els = @elements.collect{|e| e * x}
- Vector.elements(els, FALSE)
- when Matrix
- self.covector * 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 e77c45871e..0000000000
--- a/lib/mkmf.rb
+++ /dev/null
@@ -1,474 +0,0 @@
-# module to create Makefile for extension modules
-# invoke like: ruby -r mkmf extconf.rb
-
-require 'rbconfig'
-require 'find'
-
-CONFIG = Config::MAKEFILE_CONFIG
-
-SRC_EXT = ["c", "cc", "m", "cxx", "cpp", "C"]
-
-$config_cache = CONFIG["compile_dir"]+"/ext/config.cache"
-
-$srcdir = CONFIG["srcdir"]
-$libdir = CONFIG["libdir"]+"/ruby/"+CONFIG["MAJOR"]+"."+CONFIG["MINOR"]
-$archdir = $libdir+"/"+CONFIG["arch"]
-
-if File.exist? $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/
- CFLAGS.gsub!( /-arch\s\w*/, '' )
-end
-if /win32|djgpp|mingw32|m68k-human|i386-os2_emx/i =~ RUBY_PLATFORM
- $null = open("nul", "w")
-else
- $null = open("/dev/null", "w")
-end
-LINK = "#{CONFIG['CC']} -o conftest -I#{$hdrdir} #{CFLAGS} -I#{CONFIG['includedir']} %s #{CONFIG['LDFLAGS']} %s conftest.c %s %s #{CONFIG['LIBS']}"
-CPP = "#{CONFIG['CPP']} -E -I#{$hdrdir} #{CFLAGS} -I#{CONFIG['includedir']} %s %s conftest.c"
-
-$orgerr = $stderr.dup
-$orgout = $stdout.dup
-def xsystem command
- if $DEBUG
- print command, "\n"
- return system(command)
- end
- $stderr.reopen($null)
- $stdout.reopen($null)
- 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
- xsystem(format(LINK, $CFLAGS, $LDFLAGS, opt, $LOCAL_LIBS))
-end
-
-def try_link(src, opt="")
- begin
- try_link0(src, opt)
- ensure
- system "rm -f conftest*"
- end
-end
-
-def try_cpp(src, opt="")
- cfile = open("conftest.c", "w")
- cfile.print src
- cfile.close
- begin
- xsystem(format(CPP, $CFLAGS, opt))
- ensure
- system "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}", $CFLAGS, opt))
- ensure
- system "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
- system "rm -f conftest*"
- end
-end
-
-def install_rb(mfile, srcdir = nil)
- libdir = "lib"
- libdir = srcdir + "/" + libdir if srcdir
- path = []
- dir = []
- Find.find(libdir) do |f|
- next unless /\.rb$/ =~ f
- f = f[libdir.length+1..-1]
- path.push f
- dir |= File.dirname(f)
- end
- for f in dir
- next if f == "."
- mfile.printf "\t@$(RUBY) -r ftools -e 'File::makedirs(*ARGV)' $(libdir)/%s\n", f
- end
- for f in path
- mfile.printf "\t@$(RUBY) -r ftools -e 'File::install(ARGV[0], ARGV[1], 0644, true)' lib/%s $(libdir)/%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")
- printf "checking for %s() in -l%s... ", func, lib
- STDOUT.flush
-
- if func && func != ""
- libs = append_library($libs, lib)
- if /mswin32/ =~ RUBY_PLATFORM
- 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
-
- ldflags = $LDFLAGS
- libs = append_library($libs, lib)
- until try_link(<<"SRC", libs)
-int main() { return 0; }
-int t() { #{func}(); return 0; }
-SRC
- if paths.size == 0
- $LDFLAGS = ldflags
- print "no\n"
- return false
- end
- $LDFLAGS = ldflags + " -L"+paths.shift
- end
- $libs = libs
- print "yes\n"
- return true
-end
-
-def have_func(func)
- printf "checking for %s()... ", func
- STDOUT.flush
-
- libs = $libs
-
- if /mswin32/ =~ RUBY_PLATFORM
- 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
- $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
- header.tr!("a-z./\055", "A-Z___")
- $defs.push(format("-DHAVE_%s", header))
- 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
- if /=/ =~ arg
- $configure_args[$`] = $'
- else
- $configure_args[arg] = true
- end
- 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)
- dir = with_config("%s-dir"%target)
- if dir
- idir = " -I"+dir+"/include"
- ldir = " -L"+dir+"/lib"
- end
- unless idir
- dir = with_config("%s-include"%target)
- idir = " -I"+dir if dir
- end
- unless ldir
- dir = with_config("%s-lib"%target)
- ldir = " -L"+dir if dir
- end
-
- $CFLAGS += idir if idir
- $LDFLAGS += ldir if ldir
-end
-
-def create_makefile(target)
- print "creating Makefile\n"
- system "rm -f conftest*"
- STDOUT.flush
- 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"]
-
- if RUBY_PLATFORM =~ /beos/
- $libs = $libs + " -lruby"
- $DLDFLAGS = $DLDFLAGS + " -L" + CONFIG["prefix"] + "/lib"
- end
-
- defflag = ''
- if RUBY_PLATFORM =~ /cygwin/
- if File.exist? target + ".def"
- defflag = "--def=" + target + ".def"
- end
- $libs = $libs + " " + CONFIG["LIBRUBYARG"]
- $DLDFLAGS = $DLDFLAGS + " -L$(topdir)"
- end
-
- unless $objs then
- $objs = []
- for f in Dir["*.{#{SRC_EXT.join(%q{,})}}"]
- f = File.basename(f)
- f.sub!(/(#{SRC_EXT.join(%q{|})})$/, $OBJEXT)
- $objs.push f
- end
- end
- $objs = $objs.join(" ")
-
- mfile = open("Makefile", "w")
- mfile.print <<EOMF
-SHELL = /bin/sh
-
-#### Start of system configuration section. ####
-
-srcdir = #{$srcdir}
-topdir = #{$topdir}
-hdrdir = #{$hdrdir}
-
-CC = #{CONFIG["CC"]}
-
-CFLAGS = #{CONFIG["CCDLFLAGS"]} -I$(hdrdir) #{CFLAGS} #{$CFLAGS} -I#{CONFIG["includedir"]} #{$defs.join(" ")}
-CXXFLAGS = $(CFLAGS)
-DLDFLAGS = #{$DLDFLAGS} #{$LDFLAGS}
-LDSHARED = #{CONFIG["LDSHARED"]} #{defflag}
-
-prefix = #{CONFIG["prefix"]}
-exec_prefix = #{CONFIG["exec_prefix"]}
-libdir = #{$libdir}
-archdir = #{$archdir}
-
-#### 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"]}
-
-EXEEXT = #{CONFIG["EXEEXT"]}
-
-all: $(DLLIB)
-
-clean:; @rm -f *.#{$OBJEXT} *.so *.sl *.a $(DLLIB)
- @rm -f $(TARGET).lib $(TARGET).exp
- @rm -f Makefile extconf.h conftest.*
- @rm -f core ruby$(EXEEXT) *~
-
-realclean: clean
-
-install: $(archdir)/$(DLLIB)
-
-$(archdir)/$(DLLIB): $(DLLIB)
- @$(RUBY) -r ftools -e 'File::makedirs(*ARGV)' $(libdir) $(archdir)
- @$(RUBY) -r ftools -e 'File::install(ARGV[0], ARGV[1], 0555, true)' $(DLLIB) $(archdir)/$(DLLIB)
-EOMF
- install_rb(mfile)
- mfile.printf "\n"
-
- if CONFIG["DLEXT"] != $OBJEXT
- mfile.printf <<EOMF
-$(DLLIB): $(OBJS)
- $(LDSHARED) $(DLDFLAGS) -o $(DLLIB) $(OBJS) $(LIBS) $(LOCAL_LIBS)
-EOMF
- 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
-
- if File.exist?("depend")
- dfile = open("depend", "r")
- mfile.printf "###\n"
- while line = dfile.gets()
- mfile.printf "%s", line.gsub(/\.o/, ".#{$OBJEXT}")
- end
- dfile.close
- end
- mfile.close
-
- if RUBY_PLATFORM =~ /beos/
- if RUBY_PLATFORM =~ /^powerpc/ then
- deffilename = "ruby.exp"
- else
- deffilename = "ruby.def"
- end
- print "creating #{deffilename}\n"
- open(deffilename, "w") do |file|
- file.print("EXPORTS\n") if RUBY_PLATFORM =~ /^i/
- file.print("Init_#{target}\n")
- end
- end
-end
-
-$OBJEXT = CONFIG["OBJEXT"]
-$objs = nil
-$libs = "-lc"
-$local_flags = ""
-case RUBY_PLATFORM
-when /cygwin|beos|openstep|nextstep|rhapsody/
- $libs = ""
-when /mswin32/
- $libs = ""
- $local_flags = "rubymw.lib -link /LIBPATH:$(topdir) /EXPORT:Init_$(TARGET)"
-end
-$LOCAL_LIBS = ""
-$defs = []
-
-dir = with_config("opt-dir")
-if dir
- idir = "-I"+dir+"/include"
- ldir = "-L"+dir+"/lib"
-end
-unless idir
- dir = with_config("opt-include")
- idir = "-I"+dir if dir
-end
-unless ldir
- dir = with_config("opt-lib")
- ldir = "-L"+dir if dir
-end
-
-$CFLAGS = idir || ""
-$LDFLAGS = ldir || ""
diff --git a/lib/monitor.rb b/lib/monitor.rb
deleted file mode 100644
index 75d9c35821..0000000000
--- a/lib/monitor.rb
+++ /dev/null
@@ -1,229 +0,0 @@
-=begin
-
-monitor.rb
-Author: Shugo Maeda <shugo@netlab.co.jp>
-Version: 1.2.1
-
-USAGE:
-
- foo = Foo.new
- foo.extend(MonitorMixin)
- cond = foo.new_cond
-
- thread1:
- foo.synchronize {
- ...
- cond.wait_until { foo.done? }
- ...
- }
-
- thread2:
- foo.synchronize {
- foo.do_something
- 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
-
- 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)
-
- if timeout
- t = Thread.current
- timeout_thread = Thread.start {
- sleep(timeout)
- t.raise(Timeout.new)
- }
- end
- begin
- Thread.stop
- rescue Timeout
- @waiters.delete(Thread.current)
- ensure
- if timeout && timeout_thread.alive?
- Thread.kill(timeout_thread)
- end
- end
-
- Thread.critical = true
- 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
-
- 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 e0fcf0f209..0000000000
--- a/lib/mutex_m.rb
+++ /dev/null
@@ -1,111 +0,0 @@
-#
-# mutex_m.rb -
-# $Release Version: 2.0$
-# $Revision: 1.7 $
-# $Date: 1998/02/27 04:28:57 $
-# Original from mutex.rb
-# by Keiju ISHITSUKA(SHL Japan Inc.)
-#
-# --
-# Usage:
-# require "mutex_m.rb"
-# obj = Object.new
-# obj.extend Mutex_m
-# ...
-# extended object can be handled like Mutex
-#
-
-module Mutex_m
- def Mutex_m.append_features(cl)
- super
- unless cl.instance_of?(Module)
- 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
- return self
- 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)
- eval "class << self
- alias locked? mu_locked?
- alias lock mu_lock
- alias unlock mu_unlock
- alias try_lock mu_try_lock
- alias synchronize mu_synchronize
- end"
- end
- 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 initialize(*args)
- ret = super
- @mu_waiting = []
- @mu_locked = false;
- return ret
- end
-end
diff --git a/lib/observer.rb b/lib/observer.rb
deleted file mode 100644
index 0c74b49750..0000000000
--- a/lib/observer.rb
+++ /dev/null
@@ -1,42 +0,0 @@
-# Observable Mixin
-#
-# Observers must respond to update
-
-module Observable
- def add_observer(observer)
- @observer_peers = [] unless @observer_peers
- unless defined? observer.update
- raise NameError, "observer needs to respond to `update'"
- end
- @observer_peers.push observer
- end
- def delete_observer(observer)
- @observer_peers.delete observer if @observer_peers
- end
- def delete_observers
- @observer_peers.clear if @observer_peers
- end
- def count_observers
- if @observer_peers
- @observer_peers.size
- else
- 0
- end
- end
- def changed(state=true)
- @observer_state = state
- end
- def changed?
- @observer_state
- end
- def notify_observers(*arg)
- if @observer_state
- if @observer_peers
- for i in @observer_peers
- 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 9e34acffc9..0000000000
--- a/lib/open3.rb
+++ /dev/null
@@ -1,55 +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
- if pid == nil then # child
- 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
- else
- pw[0].close
- pr[1].close
- pe[1].close
- pi = [ pw[1], pr[0], pe[0] ]
- end
- end
- module_function :popen3
-end
-
-if $0 == __FILE__
- a = Open3.popen3("nroff -man")
- Thread.start do
- while gets
- a[0].print $_
- end
- a[0].close
- end
- while a[1].gets
- print ":", $_
- 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 29b3fa43b9..0000000000
--- a/lib/parsedate.rb
+++ /dev/null
@@ -1,93 +0,0 @@
-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, guess=false)
- # part of ISO 8601
- # yyyy-mm-dd | yyyy-mm | yyyy
- # date hh:mm:ss | date Thh:mm:ss
- if date =~ /^(\d\d\d\d)-?(?:(\d\d)-?(\d\d)?)? *T?(?:(\d\d):?(\d\d):?(\d\d)?)?$/
- return $1.to_i,
- if $2 then $2.to_i else 1 end,
- if $3 then $3.to_i else 1 end,
- if $4 then $4.to_i end,
- if $5 then $5.to_i end,
- if $6 then $6.to_i end,
- nil,
- nil
- end
- date = date.dup
- if date.sub!(/(#{DAYPAT})[a-z]*,?/i, ' ')
- wday = DAYS[$1.downcase]
- end
- if date.sub!(/(\d+):(\d+)(?::(\d+))?(?:\s*(am|pm))?(?:\s+([a-z]{1,4}(?:\s+[a-z]{1,4})?|[-+]\d{4}))?/i, ' ')
- hour = $1.to_i
- min = $2.to_i
- if $3
- sec = $3.to_i
- end
- if $4 == 'pm'
- hour += 12
- end
- if $5
- zone = $5
- end
- end
- if date.sub!(/(\d+)\S*\s+(#{MONTHPAT})\S*(?:\s+(\d+))?/i, ' ')
- mday = $1.to_i
- mon = MONTHS[$2.downcase]
- if $3
- year = $3.to_i
- end
- elsif date.sub!(/(#{MONTHPAT})\S*\s+(\d+)\S*,?(?:\s+(\d+))?/i, ' ')
- mon = MONTHS[$1.downcase]
- mday = $2.to_i
- if $3
- year = $3.to_i
- end
- elsif date.sub!(/(\d+)\/(\d+)(?:\/(\d+))/, ' ')
- mon = $1.to_i
- mday = $2.to_i
- if $3
- year = $3.to_i
- end
- elsif date.sub!(/(\d+)-(#{MONTHPAT})-(\d+)/i, ' ')
- mday = $1.to_i
- mon = MONTHS[$2.downcase]
- year = $3.to_i
- elsif date.sub!(/(\d+)-(#{MONTHPAT})-(\d+)/i, ' ')
- mday = $1.to_i
- mon = MONTHS[$2.downcase]
- year = $3.to_i
- end
- if date.sub!(/\d{4}/i, ' ')
- year = $&.to_i
- elsif date.sub!(/\d\d/i, ' ')
- year = $&.to_i
- end
- if guess 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
-
-if __FILE__ == $0
- p Time.now.asctime
- p ParseDate.parsedate(Time.now.asctime)
-end
diff --git a/lib/ping.rb b/lib/ping.rb
deleted file mode 100644
index 065b1d2303..0000000000
--- a/lib/ping.rb
+++ /dev/null
@@ -1,62 +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'
-
-module Ping
- require "socket"
- def pingecho(host, timeout=5, service="echo")
- begin
- timeout(timeout) do
- s = TCPsocket.new(host, service)
- s.close
- end
- 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/profile.rb b/lib/profile.rb
deleted file mode 100644
index e4b1b4b189..0000000000
--- a/lib/profile.rb
+++ /dev/null
@@ -1,55 +0,0 @@
-
-module Profiler__
- Start = Float(Time.times[0])
- top = "toplevel".intern
- Stack = [[0, 0, top]]
- MAP = {top => [1, 0, 0, "#toplevel"]}
-
- p = proc{|event, file, line, id, binding, klass|
- case event
- when "call", "c-call"
- now = Float(Time.times[0])
- Stack.push [now, 0.0, id]
- when "return", "c-return"
- now = Float(Time.times[0])
- tick = Stack.pop
- data = MAP[id]
- unless data
- name = klass.to_s
- if name.nil? then name = '' end
- if klass.kind_of? Class
- name += "#"
- else
- name += "."
- end
- data = [0.0, 0.0, 0.0, name+id.id2name]
- MAP[id] = 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(Time.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
- p total
- f.close
- }
- set_trace_func p
-end
diff --git a/lib/pstore.rb b/lib/pstore.rb
deleted file mode 100644
index 9ea9ab3660..0000000000
--- a/lib/pstore.rb
+++ /dev/null
@@ -1,138 +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 "marshal"
-require "ftools"
-
-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
- value = @table[name]
- if value == nil
- raise PStore::Error, format("undefined root name `%s'", name)
- end
- value
- end
- def []=(name, value)
- in_transaction
- @table[name] = value
- end
-
- def roots
- in_transaction
- @table.keys
- end
- def root?(name)
- in_transaction
- @table.key? name
- end
- def path
- @filename
- end
-
- def commit
- @abort = false
- throw :pstore_abort_transaction
- end
- def abort
- @abort = true
- throw :pstore_abort_transaction
- end
-
- def transaction
- raise PStore::Error, "nested transaction" if @transaction
- begin
- @transaction = true
- value = nil
- backup = @filename+"~"
- if File::exist?(@filename)
- file = File::open(@filename, "r+")
- orig = true
- else
- file = File::open(@filename, "w+")
- end
- file.flock(File::LOCK_EX)
- if orig
- File::copy @filename, backup
- @table = Marshal::load(file)
- else
- @table = {}
- end
- begin
- catch(:pstore_abort_transaction) do
- value = yield(self)
- end
- rescue Exception
- @abort = true
- raise
- ensure
- unless @abort
- begin
- file.rewind
- Marshal::dump(@table, file)
- rescue
- File::rename backup, @filename if File::exist?(backup)
- raise
- end
- end
- @abort = false
- end
- ensure
- @table = nil
- @transaction = false
- file.close
- 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
-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/shellwords.rb b/lib/shellwords.rb
deleted file mode 100644
index 60996be17c..0000000000
--- a/lib/shellwords.rb
+++ /dev/null
@@ -1,46 +0,0 @@
-# shellwords.rb
-# original is shellwords.pl
-#
-# Usage:
-# require 'shellwords.rb'
-# words = Shellwords.shellwords(line)
-#
-# or
-#
-# include Shellwords
-# words = shellwords(line)
-
-module Shellwords
- def shellwords(line)
- return '' unless line
- line.sub! /^\s+/, ''
- words = []
- while line != ''
- field = ''
- while true
- if line.sub! /^"(([^"\\]|\\.)*)"/, '' then #"
- snippet = $1
- snippet.gsub! /\\(.)/, '\1'
- elsif line =~ /^"/ then #"
- raise ArgError, "Unmatched double quote: #{line}"
- elsif line.sub! /^'(([^'\\]|\\.)*)'/, '' then #'
- snippet = $1
- snippet.gsub! /\\(.)/, '\1'
- elsif line =~ /^'/ then #'
- raise ArgError, "Unmatched single quote: #{line}"
- elsif line.sub! /^\\(.)/, '' then
- snippet = $1
- elsif line.sub! /^([^\s\\'"]+)/, '' then #'
- snippet = $1
- else
- line.sub! /^\s+/, ''
- break
- end
- field += snippet
- end
- words += field
- end
- words
- end
- module_function :shellwords
-end
diff --git a/lib/singleton.rb b/lib/singleton.rb
deleted file mode 100644
index 2785c77134..0000000000
--- a/lib/singleton.rb
+++ /dev/null
@@ -1,43 +0,0 @@
-# Singleton module that ensures only one object to be allocated.
-#
-# Usage:
-# class SomeSingletonClass
-# include Singleton
-# #....
-# end
-# a = SomeSingletonClass.instance
-# b = SomeSingletonClass.instance # a and b are same object
-# p [a,b]
-# a = SomeSingletonClass.new # error (`new' is private)
-
-module Singleton
- def Singleton.append_features(klass)
- klass.private_class_method(:new)
- klass.instance_eval %{
- @__instance__ = nil
- def instance
- unless @__instance__
- Thread.critical = true
- begin
- @__instance__ = new
- ensure
- Thread.critical = false
- end
- end
- return @__instance__
- end
- }
- end
-end
-
-if __FILE__ == $0
- class SomeSingletonClass
- include Singleton
- #....
- end
-
- a = SomeSingletonClass.instance
- b = SomeSingletonClass.instance # a and b are same object
- p [a,b]
- a = SomeSingletonClass.new # error (`new' is private)
-end
diff --git a/lib/sync.rb b/lib/sync.rb
deleted file mode 100644
index f1410af1a9..0000000000
--- a/lib/sync.rb
+++ /dev/null
@@ -1,313 +0,0 @@
-#
-# sync.rb - 2 phase lock with counter
-# $Release Version: 0.2$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA
-# modified by matz
-#
-# --
-# Sync_m, Synchronizer_m
-# Usage:
-# obj.extend(Sync_m)
-# or
-# class Foo
-# Sync_m.include_to self
-# :
-# 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.append_features(cl)
- super
- unless cl.instance_of?(Module)
- # do nothing for Modules
- # make aliases and include the proper module.
- 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
- return self
- 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)
- eval "class << self
- 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"
- end
- 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)
- sync_lock(mode)
- begin
- 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 initialize(*args)
- ret = super
- @sync_mode = UN
- @sync_waiting = []
- @sync_upgrade_waiting = []
- @sync_sh_locker = Hash.new
- @sync_ex_locker = nil
- @sync_ex_count = 0
- return ret
- 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
- include Sync_m
-
- private
-
- def initialize
- super
- end
-end
-Synchronizer = Sync
diff --git a/lib/telnet.rb b/lib/telnet.rb
deleted file mode 100644
index b6623513e0..0000000000
--- a/lib/telnet.rb
+++ /dev/null
@@ -1,696 +0,0 @@
-=begin
-$Date: 1999/10/04 22:51:26 $
-
-== SIMPLE TELNET CLIANT LIBRARY
-
-telnet.rb
-
-Version 1.00
-
-Wakou Aoyama <wakou@fsinet.or.jp>
-
-
-=== MAKE NEW TELNET OBJECT
-
- host = Telnet.new({"Binmode" => false, # default: false
- "Host" => "localhost", # default: "localhost"
- "Output_log" => "output_log", # default: not output
- "Dump_log" => "dump_log", # default: not 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 Telnet or TCPsocket 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 = 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",
- "Prompt" => /[$%#>] \z/n,
- "Timeout" => 10})
-
-
-==== REALTIME OUTPUT
-
- host.cmd("string"){|c| print c }
- host.cmd({"String" => "string",
- "Prompt" => /[$%#>] \z/n,
- "Timeout" => 10}){|c| print c }
-
-of cource, set sync=true or flush is necessary.
-
-
-=== SEND STRING
-
- host.print("string")
- # == host.write("string\n")
-
-
-=== TURN TELNET COMMAND INTERPRETATION
-
- host.telnetmode # turn on/off
- host.telnetmode(true) # on
- host.telnetmode(false) # off
-
-
-=== TOGGLE NEWLINE TRANSLATION
-
- host.binmode # turn true/false
- host.binmode(true) # no translate newline
- host.binmode(false) # translate newline
-
-
-=== LOGIN
-
- host.login("username", "password")
- host.login({"Name" => "username",
- "Password" => "password",
- "Prompt" => /[$%#>] \z/n,
- "Timeout" => 10})
-
-if no password prompt.
-
- host.login("username")
- host.login({"Name" => "username",
- "Prompt" => /[$%#>] \z/n,
- "Timeout" => 10})
-
-
-==== REALTIME OUTPUT
-
- host.login("username", "password"){|c| print c }
- host.login({"Name" => "username",
- "Password" => "password",
- "Prompt" => /[$%#>] \z/n,
- "Timeout" => 10}){|c| print c }
-
-of cource, set sync=true or flush is necessary.
-
-
-== EXAMPLE
-
-=== LOGIN AND SEND COMMAND
-
- localhost = 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 = 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}
-
-
-== HISTORY
-
-=== Version 1.00
-
-1999/10/04 22:51:26
-
-- bug fix: waitfor(preprocess) method
- thanks to Shin-ichiro Hara <sinara@blade.nagaokaut.ac.jp>
-- add simple support for AO, DM, IP, NOP, SB, SE
-- COUTION! TimeOut --> TimeoutError
-
-=== Version 0.50
-
-1999/09/21 21:24:07
-
-- add write method
-
-=== Version 0.40
-
-1999/09/17 17:41:41
-
-- bug fix: preprocess method
-
-=== Version 0.30
-
-1999/09/14 23:09:05
-
-- change prompt check order.
- not IO::select([@sock], nil, nil, waittime) and prompt === line
- --> prompt === line and not IO::select([@sock], nil, nil, waittime)
-
-=== Version 0.24
-
-1999/09/13 22:28:33
-
-- Telnet#login
-if ommit password, then not require password prompt.
-
-=== Version 0.232
-
-1999/08/10 05:20:21
-
-- STATUS OUTPUT sample code typo. thanks to Tadayoshi Funaba <tadf@kt.rim.or.jp>
- host = Telnet.new({"Hosh" => "localhost"){|c| print c }
- --> host = Telnet.new({"Host" => "localhost"){|c| print c }
-
-=== Version 0.231
-
-1999/07/16 13:39:42
-
-- TRUE --> true, FALSE --> false
-
-=== Version 0.23
-
-1999/07/15 22:32:09
-
-- waitfor: if end of file reached, then return nil.
-
-=== Version 0.22
-
-1999/06/29 09:08:51
-
-- new, waitfor, cmd: {"Timeout" => false} # ignore timeout
-
-=== Version 0.21
-
-1999/06/28 18:18:55
-
-- waitfor: not rescue (EOFError)
-
-=== Version 0.20
-
-1999/06/04 06:24:58
-
-- waitfor: support for divided telnet command
-
-=== Version 0.181
-
-1999/05/22
-
-- bug fix: print method
-
-=== Version 0.18
-
-1999/05/14
-
-- respond to "IAC WON'T SGA" with "IAC DON'T SGA"
-- DON'T SGA : end of line --> CR + LF
-- bug fix: preprocess method
-
-=== Version 0.17
-
-1999/04/30
-
-- bug fix: $! + "\n" --> $!.to_s + "\n"
-
-=== Version 0.163
-
-1999/04/11
-
-- STDOUT.write(message) --> yield(message) if iterator?
-
-=== Version 0.162
-
-1999/03/17
-
-- add "Proxy" option
-- required timeout.rb
-
-=== Version 0.161
-
-1999/02/03
-
-- select --> IO::select
-
-=== Version 0.16
-
-1998/10/09
-
-- preprocess method change for the better
-- add binmode method.
-- change default Binmode. TRUE --> FALSE
-
-=== Version 0.15
-
-1998/10/04
-
-- add telnetmode method.
-
-=== Version 0.141
-
-1998/09/22
-
-- change default prompt. /[$%#>] $/ --> /[$%#>] \Z/
-
-=== Version 0.14
-
-1998/09/01
-
-- IAC WILL SGA send EOL --> CR+NULL
-- IAC WILL SGA IAC DO BIN send EOL --> CR
-- NONE send EOL --> LF
-- add Dump_log option.
-
-=== Version 0.13
-
-1998/08/25
-
-- add print method.
-
-=== Version 0.122
-
-1998/08/05
-
-- support for HP-UX 10.20 thanks to WATANABE Tetsuya <tetsu@jpn.hp.com>
-- socket.<< --> socket.write
-
-=== Version 0.121
-
-1998/07/15
-
-- string.+= --> string.concat
-
-=== Version 0.12
-
-1998/06/01
-
-- add timeout, waittime.
-
-=== Version 0.11
-
-1998/04/21
-
-- add realtime output.
-
-=== Version 0.10
-
-1998/04/13
-
-- first release.
-
-=end
-
-require "socket"
-require "delegate"
-require "thread"
-require "timeout"
-
-class Telnet < SimpleDelegator
-
- IAC = 255.chr # "\377" # interpret as command:
- DONT = 254.chr # "\376" # you are not to use option
- DO = 253.chr # "\375" # please, you use option
- WONT = 252.chr # "\374" # I won't use option
- WILL = 251.chr # "\373" # I will use option
- SB = 250.chr # "\372" # interpret as subnegotiation
- GA = 249.chr # "\371" # you may reverse the line
- EL = 248.chr # "\370" # erase the current line
- EC = 247.chr # "\367" # erase the current character
- AYT = 246.chr # "\366" # are you there
- AO = 245.chr # "\365" # abort output--but let prog finish
- IP = 244.chr # "\364" # interrupt process--permanently
- BREAK = 243.chr # "\363" # break
- DM = 242.chr # "\362" # data mark--for connect. cleaning
- NOP = 241.chr # "\361" # nop
- SE = 240.chr # "\360" # end sub negotiation
- EOR = 239.chr # "\357" # end of record (transparent mode)
- ABORT = 238.chr # "\356" # Abort process
- SUSP = 237.chr # "\355" # Suspend process
- EOF = 236.chr # "\354" # End of file
- SYNCH = 242.chr # "\362" # for telfunc calls
-
- OPT_BINARY = 0.chr # "\000" # Binary Transmission
- OPT_ECHO = 1.chr # "\001" # Echo
- OPT_RCP = 2.chr # "\002" # Reconnection
- OPT_SGA = 3.chr # "\003" # Suppress Go Ahead
- OPT_NAMS = 4.chr # "\004" # Approx Message Size Negotiation
- OPT_STATUS = 5.chr # "\005" # Status
- OPT_TM = 6.chr # "\006" # Timing Mark
- OPT_RCTE = 7.chr # "\a" # Remote Controlled Trans and Echo
- OPT_NAOL = 8.chr # "\010" # Output Line Width
- OPT_NAOP = 9.chr # "\t" # Output Page Size
- OPT_NAOCRD = 10.chr # "\n" # Output Carriage-Return Disposition
- OPT_NAOHTS = 11.chr # "\v" # Output Horizontal Tab Stops
- OPT_NAOHTD = 12.chr # "\f" # Output Horizontal Tab Disposition
- OPT_NAOFFD = 13.chr # "\r" # Output Formfeed Disposition
- OPT_NAOVTS = 14.chr # "\016" # Output Vertical Tabstops
- OPT_NAOVTD = 15.chr # "\017" # Output Vertical Tab Disposition
- OPT_NAOLFD = 16.chr # "\020" # Output Linefeed Disposition
- OPT_XASCII = 17.chr # "\021" # Extended ASCII
- OPT_LOGOUT = 18.chr # "\022" # Logout
- OPT_BM = 19.chr # "\023" # Byte Macro
- OPT_DET = 20.chr # "\024" # Data Entry Terminal
- OPT_SUPDUP = 21.chr # "\025" # SUPDUP
- OPT_SUPDUPOUTPUT = 22.chr # "\026" # SUPDUP Output
- OPT_SNDLOC = 23.chr # "\027" # Send Location
- OPT_TTYPE = 24.chr # "\030" # Terminal Type
- OPT_EOR = 25.chr # "\031" # End of Record
- OPT_TUID = 26.chr # "\032" # TACACS User Identification
- OPT_OUTMRK = 27.chr # "\e" # Output Marking
- OPT_TTYLOC = 28.chr # "\034" # Terminal Location Number
- OPT_3270REGIME = 29.chr # "\035" # Telnet 3270 Regime
- OPT_X3PAD = 30.chr # "\036" # X.3 PAD
- OPT_NAWS = 31.chr # "\037" # Negotiate About Window Size
- OPT_TSPEED = 32.chr # " " # Terminal Speed
- OPT_LFLOW = 33.chr # "!" # Remote Flow Control
- OPT_LINEMODE = 34.chr # "\"" # Linemode
- OPT_XDISPLOC = 35.chr # "#" # X Display Location
- OPT_OLD_ENVIRON = 36.chr # "$" # Environment Option
- OPT_AUTHENTICATION = 37.chr # "%" # Authentication Option
- OPT_ENCRYPT = 38.chr # "&" # Encryption Option
- OPT_NEW_ENVIRON = 39.chr # "'" # New Environment Option
- OPT_EXOPL = 255.chr # "\377" # Extended-Options-List
-
- NULL = "\000"
- CR = "\015"
- LF = "\012"
- EOL = CR + LF
-v = $-v
-$-v = false
- VERSION = "1.00"
- RELEASE_DATE = "$Date: 1999/10/04 22:51:26 $"
-$-v = v
-
- def initialize(options)
- @options = options
- @options["Binmode"] = false unless @options.key?("Binmode")
- @options["Host"] = "localhost" unless @options.key?("Host")
- @options["Port"] = 23 unless @options.key?("Port")
- @options["Prompt"] = /[$%#>] \z/n unless @options.key?("Prompt")
- @options["Telnetmode"] = true unless @options.key?("Telnetmode")
- @options["Timeout"] = 10 unless @options.key?("Timeout")
- @options["Waittime"] = 0 unless @options.key?("Waittime")
-
- @telnet_option = { "SGA" => false, "BINARY" => false }
-
- if @options.key?("Output_log")
- @log = File.open(@options["Output_log"], 'a+')
- @log.sync = true
- @log.binmode
- end
-
- if @options.key?("Dump_log")
- @dumplog = File.open(@options["Dump_log"], 'a+')
- @dumplog.sync = true
- @dumplog.binmode
- end
-
- if @options.key?("Proxy")
- if @options["Proxy"].kind_of?(Telnet)
- @sock = @options["Proxy"].sock
- elsif @options["Proxy"].kind_of?(TCPsocket)
- @sock = @options["Proxy"]
- else
- raise "Error; Proxy is Telnet or TCPSocket object."
- end
- else
- message = "Trying " + @options["Host"] + "...\n"
- yield(message) if iterator?
- @log.write(message) if @options.key?("Output_log")
- @dumplog.write(message) if @options.key?("Dump_log")
-
- begin
- if @options["Timeout"] == false
- @sock = TCPsocket.open(@options["Host"], @options["Port"])
- else
- timeout(@options["Timeout"]){
- @sock = TCPsocket.open(@options["Host"], @options["Port"])
- }
- end
- rescue TimeoutError
- raise TimeoutError, "timed-out; opening of the host"
- rescue
- @log.write($!.to_s + "\n") if @options.key?("Output_log")
- @dumplog.write($!.to_s + "\n") if @options.key?("Dump_log")
- raise
- end
- @sock.sync = true
- @sock.binmode
-
- message = "Connected to " + @options["Host"] + ".\n"
- yield(message) if iterator?
- @log.write(message) if @options.key?("Output_log")
- @dumplog.write(message) if @options.key?("Dump_log")
- end
-
- super(@sock)
- end # initialize
-
- attr :sock
-
- def telnetmode(mode = 'turn')
- if 'turn' == mode
- @options["Telnetmode"] = @options["Telnetmode"] ? false : true
- else
- @options["Telnetmode"] = mode ? true : false
- end
- end
-
- def binmode(mode = 'turn')
- if 'turn' == mode
- @options["Binmode"] = @options["Binmode"] ? false : true
- else
- @options["Binmode"] = mode ? true : false
- end
- end
-
- def preprocess(string)
- str = string.dup
-
- # combine CR+NULL into CR
- str.gsub!(/#{CR}#{NULL}/no, CR) if @options["Telnetmode"]
-
- # combine EOL into "\n"
- str.gsub!(/#{EOL}/no, "\n") unless @options["Binmode"]
-
- str.gsub!(/#{IAC}(
- [#{IAC}#{AO}#{AYT}#{DM}#{IP}#{NOP}]|
- [#{DO}#{DONT}#{WILL}#{WONT}]
- [#{OPT_BINARY}-#{OPT_NEW_ENVIRON}#{OPT_EXOPL}]|
- #{SB}[^#{IAC}]*#{IAC}#{SE}
- )/xno){
- 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_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)
- 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)
- end
- ''
- else
- ''
- end
- }
-
- str
- end # preprocess
-
- def waitfor(options)
- time_out = @options["Timeout"]
- waittime = @options["Waittime"]
-
- if options.kind_of?(Hash)
- prompt = if options.key?("Match")
- options["Match"]
- elsif options.key?("Prompt")
- options["Prompt"]
- elsif options.key?("String")
- Regexp.new( Regexp.quote(options["String"]) )
- end
- time_out = options["Timeout"] if options.key?("Timeout")
- waittime = options["Waittime"] if options.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.print(c) if @options.key?("Dump_log")
- if @options["Telnetmode"]
- if Integer(c.rindex(/#{IAC}#{SE}/no)) <
- Integer(c.rindex(/#{IAC}#{SB}/no))
- buf = preprocess(rest + 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(rest + c[0 ... pt])
- rest = c[pt .. -1]
- else
- buf = preprocess(c)
- rest = ''
- end
- end
- @log.print(buf) if @options.key?("Output_log")
- line.concat(buf)
- yield buf if iterator?
- rescue EOFError # End of file reached
- if line == ''
- line = nil
- yield nil if iterator?
- end
- break
- end
- end
- line
- end
-
- def write(string)
- length = string.length
- while 0 < length
- IO::select(nil, [@sock])
- length -= @sock.syswrite(string)
- end
- end
-
- def print(string)
- str = string.dup + "\n"
-
- str.gsub!(/#{IAC}/no, IAC + IAC) if @options["Telnetmode"]
-
- unless @options["Binmode"]
- if @telnet_option["BINARY"] and @telnet_option["SGA"]
- # IAC WILL SGA IAC DO BIN send EOL --> CR
- str.gsub!(/\n/n, CR)
- elsif @telnet_option["SGA"]
- # IAC WILL SGA send EOL --> CR+NULL
- str.gsub!(/\n/n, CR + NULL)
- else
- # NONE send EOL --> CR+LF
- str.gsub!(/\n/n, EOL)
- end
- end
-
- self.write(str)
- end
-
- def cmd(options)
- match = @options["Prompt"]
- time_out = @options["Timeout"]
-
- if options.kind_of?(Hash)
- string = options["String"]
- match = options["Match"] if options.key?("Match")
- time_out = options["Timeout"] if options.key?("Timeout")
- else
- string = options
- end
-
- self.print(string)
- if iterator?
- 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 iterator?
- line = waitfor(/login[: ]*\z/n){|c| yield c }
- if password
- line.concat( cmd({"String" => username,
- "Match" => /Password[: ]*\z/n}){|c| yield c } )
- line.concat( cmd(password){|c| yield c } )
- else
- line.concat( cmd(username){|c| yield c } )
- end
- else
- line = waitfor(/login[: ]*\z/n)
- if password
- line.concat( cmd({"String" => username,
- "Match" => /Password[: ]*\z/n}) )
- line.concat( cmd(password) )
- else
- line.concat( cmd(username) )
- end
- end
- line
- end
-
-end
diff --git a/lib/tempfile.rb b/lib/tempfile.rb
deleted file mode 100644
index 11a8fba979..0000000000
--- a/lib/tempfile.rb
+++ /dev/null
@@ -1,94 +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 tmpfile.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'
-require 'final'
-
-class Tempfile < SimpleDelegator
- Max_try = 10
-
- def Tempfile.callback(path)
- lambda{
- print "removing ", path, "..." if $DEBUG
- if File.exist?(path)
- File.unlink(path)
- end
- if File.exist?(path + '.lock')
- Dir.rmdir(path + '.lock')
- end
- print "done\n" if $DEBUG
- }
- end
-
- def initialize(basename, tmpdir=ENV['TMPDIR']||ENV['TMP']||ENV['TEMP']||'/tmp')
- umask = File.umask(0177)
- begin
- 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 tmpfile `%s'" % tmpname if n >= Max_try
- #sleep(1)
- end
- n += 1
- end
-
- @clean_files = Tempfile.callback(tmpname)
- ObjectSpace.define_finalizer(self, @clean_files)
-
- @tmpfile = File.open(tmpname, 'w+')
- @tmpname = tmpname
- super(@tmpfile)
- Dir.rmdir(lock)
- ensure
- File.umask(umask)
- end
- end
-
- def Tempfile.open(*args)
- Tempfile.new(*args)
- end
-
- def open
- @tmpfile.close if @tmpfile
- @tmpfile = File.open(@tmpname, 'r+')
- __setobj__(@tmpfile)
- end
-
- def close(real=false)
- @tmpfile.close if @tmpfile
- @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 22610f2992..0000000000
--- a/lib/thread.rb
+++ /dev/null
@@ -1,233 +0,0 @@
-#
-# thread.rb - thread support classes
-# $Date$
-# by Yukihiro Matsumoto <matz@caelum.co.jp>
-#
-
-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
- begin
- Thread.critical = true
- r = yield
- ensure
- Thread.critical = false
- end
- r
-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
- t = @waiting.shift
- @locked = false
- Thread.critical = false
- t.run if t
- self
- end
-
- def synchronize
- lock
- begin
- yield
- ensure
- unlock
- end
- end
-
- def exclusive_unlock
- return unless @locked
- Thread.exclusive do
- t = @waiting.shift
- @locked = false
- t.wakeup if t
- 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
- t = @waiters.shift
- t.run if t
- end
-
- def broadcast
- waiters0 = nil
- Thread.exclusive do
- waiters0 = @waiters.dup
- @waiters.clear
- end
- for t in waiters0
- t.run
- 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
- t = @waiting.shift
- Thread.critical = false
- t.run if t
- end
- alias enq push
-
- def pop non_block=false
- Thread.critical = true
- begin
- loop do
- if @que.length == 0
- 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.length == 0
- end
-
- def clear
- @que.replace([])
- end
-
- def length
- @que.length
- end
- alias size length
-
-
- 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
- t = @queue_wait.shift
- t.run if t
- 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
-
- def pop(*args)
- Thread.critical = true
- if @que.length < @max
- t = @queue_wait.shift
- t.run if t
- end
- super
- 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 958163edef..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("ErrNoFinshedThread", "No finished threads.")
-
- def ThreadsWait.all_waits(*threads)
- tw = ThreadsWait.new(*threads)
- if iterator?
- 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.concat threads
- for th in threads
- Thread.start do
- th = th.join
- @wait_queue.push th
- 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 ErrNoFinshedThread
- 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 iterator?
- end
- end
-end
-
-ThWait = ThreadsWait
diff --git a/lib/timeout.rb b/lib/timeout.rb
deleted file mode 100644
index d4ea758acd..0000000000
--- a/lib/timeout.rb
+++ /dev/null
@@ -1,42 +0,0 @@
-#
-# timeout.rb -- execution timeout
-#
-#= 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<StandardError
-end
-
-Thread.abort_on_exception = true
-
-def timeout(sec)
- begin
- x = Thread.current
- y = Thread.start {
- sleep sec
- x.raise TimeoutError, "execution expired" if x.status
- }
- yield sec
- return true
- ensure
- Thread.kill y if y.status
- end
-end
diff --git a/lib/tracer.rb b/lib/tracer.rb
deleted file mode 100644
index 095173e53b..0000000000
--- a/lib/tracer.rb
+++ /dev/null
@@ -1,163 +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 $-'
-
- class << self
- attr :verbose, TRUE
- alias verbose? verbose
- end
- verbose = TRUE
-
- MY_FILE_NAME = caller(0)[0].scan(/^(.*):[0-9]+$/)[0][0]
-
- EVENT_SYMBOL = {
- "line" => "-",
- "call" => ">",
- "return" => "<",
- "class" => "C",
- "end" => "E"}
-
- 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 on
- if iterator?
- on
- begin
- yield
- ensure
- off
- end
- else
- set_trace_func proc{|event, file, line, id, binding, klass|
- trace_func event, file, line, id, binding
- }
- print "Trace on\n" if Tracer.verbose?
- end
- end
-
- def off
- set_trace_func nil
- 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 = LINES__[file]
-# print file if $DEBUG
- begin
- f = open(file)
- begin
- LINES__[file] = list = f.readlines
- ensure
- f.close
- end
- rescue
- 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)
- return if file == MY_FILE_NAME
- #printf "Th: %s\n", Thread.current.inspect
-
- for p in @filters
- return unless p.call event, file, line, id, binding
- end
-
- Thread.critical = TRUE
- printf("#%d:%s:%d:%s: %s",
- get_thread_no,
- file,
- line,
- EVENT_SYMBOL[event],
- get_line(file, line))
- Thread.critical = FALSE
- end
-
- Single = new
- def Tracer.on
- if iterator?
- 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
-
-LINES__ = {} unless defined? 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/weakref.rb b/lib/weakref.rb
deleted file mode 100644
index c6fe8cd21b..0000000000
--- a/lib/weakref.rb
+++ /dev/null
@@ -1,75 +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
- ObjectSpace.add_finalizer(lambda{|id|
- 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
- })
-
- def initialize(orig)
- super
- @__id = orig.__id__
- ObjectSpace.call_finalizer orig
- ObjectSpace.call_finalizer self
- ID_MAP[@__id] = [] unless ID_MAP[@__id]
- ID_MAP[@__id].concat self.__id__
- ID_REV_MAP[self.id] = @__id
- end
-
- def __getobj__
- unless ID_MAP[@__id]
- raise RefError, "Illegal Reference - probably recycled", caller(2)
- end
- ObjectSpace._id2ref(@__id)
- end
-
- def weakref_alive?
- if ID_MAP[@__id]
- true
- else
- false
- end
- end
-
- def []
- __getobj__
- 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 dccf0a8953..0000000000
--- a/main.c
+++ /dev/null
@@ -1,41 +0,0 @@
-/************************************************
-
- main.c -
-
- $Author$
- $Date$
- created at: Fri Aug 19 13:19:58 JST 1994
-
-************************************************/
-
-#include "ruby.h"
-
-#ifdef DJGPP
-unsigned int _stklen = 0x180000;
-#endif
-
-#ifdef __human68k__
-int _stacksize = 131072;
-#endif
-
-#if defined(__MACOS__) && defined(__MWERKS__)
-#include <console.h>
-#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 fe29385b42..0000000000
--- a/marshal.c
+++ /dev/null
@@ -1,929 +0,0 @@
-/************************************************
-
- marshal.c -
-
- $Author$
- $Date$
- created at: Thu Apr 27 16:30:01 JST 1995
-
-************************************************/
-
-#include "ruby.h"
-#include "rubyio.h"
-#include "st.h"
-
-#ifndef atof
-double strtod();
-#endif
-
-#define MARSHAL_MAJOR 4
-#define MARSHAL_MINOR 2
-
-#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_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_LINK '@'
-
-static ID s_dump, s_load;
-
-struct dump_arg {
- VALUE obj;
- FILE *fp;
- VALUE str;
- st_table *symbol;
- st_table *data;
-};
-
-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_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;
-{
- int i;
-
- for (i=0; i<sizeof(short); i++) {
- w_byte((x >> (i*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 (x == 0) {
- w_byte(0, 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];
-
- sprintf(buf, "%.12g", d);
- w_bytes(buf, strlen(buf), arg);
-}
-
-static void
-w_symbol(id, arg)
- ID id;
- struct dump_arg *arg;
-{
- char *sym = rb_id2name(id);
- int 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;
-{
- 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 (CLASS_OF(obj) != klass) {
- w_byte(TYPE_UCLASS, arg);
- w_unique(rb_class2name(CLASS_OF(obj)), arg);
- }
-}
-
-static void
-w_object(obj, arg, limit)
- VALUE obj;
- struct dump_arg *arg;
- int limit;
-{
- struct dump_call_arg c_arg;
-
- if (limit == 0) {
- rb_raise(rb_eRuntimeError, "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, 32) == 0 || RSHIFT((long)obj, 32) == -1) {
- w_byte(TYPE_FIXNUM, arg);
- w_long(FIX2LONG(obj), arg);
- }
- else {
- w_object(rb_int2big(FIX2LONG(obj)), arg, limit);
- return;
- }
-#endif
- }
- else {
- int 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;
- }
-
- 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;
- }
-
- switch (BUILTIN_TYPE(obj)) {
- case T_CLASS:
- w_byte(TYPE_CLASS, arg);
- {
- VALUE path = rb_class_path(obj);
- w_bytes(RSTRING(path)->ptr, RSTRING(path)->len, arg);
- }
- return;
-
- case T_MODULE:
- w_byte(TYPE_MODULE, arg);
- {
- VALUE path = rb_class_path(obj);
- w_bytes(RSTRING(path)->ptr, RSTRING(path)->len, arg);
- }
- return;
-
- case T_FLOAT:
- w_byte(TYPE_FLOAT, arg);
- w_float(RFLOAT(obj)->value, arg);
- return;
-
- case T_BIGNUM:
- w_byte(TYPE_BIGNUM, arg);
- {
- char sign = RBIGNUM(obj)->sign?'+':'-';
- int len = RBIGNUM(obj)->len;
- unsigned short *d = RBIGNUM(obj)->digits;
-
- w_byte(sign, arg);
- w_long(len, arg);
- while (len--) {
- w_short(*d, arg);
- d++;
- }
- }
- return;
-
- case T_STRING:
- w_uclass(obj, rb_cString, arg);
- w_byte(TYPE_STRING, arg);
- w_bytes(RSTRING(obj)->ptr, RSTRING(obj)->len, arg);
- return;
-
- 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);
- return;
-
- case T_ARRAY:
- w_uclass(obj, rb_cArray, arg);
- w_byte(TYPE_ARRAY, arg);
- {
- int 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);
- {
- int len = RSTRUCT(obj)->len;
- char *path = rb_class2name(CLASS_OF(obj));
- VALUE mem;
- int i;
-
- w_unique(path, arg);
- w_long(len, arg);
- mem = rb_ivar_get(CLASS_OF(obj), rb_intern("__member__"));
- if (mem == Qnil) {
- rb_raise(rb_eTypeError, "non-initialized struct");
- }
- for (i=0; i<len; i++) {
- w_symbol(FIX2LONG(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;
-
- if (FL_TEST(klass, FL_SINGLETON)) {
- rb_raise(rb_eTypeError, "singleton can't be dumped");
- }
- path = rb_class2name(klass);
- w_unique(path, arg);
- if (ROBJECT(obj)->iv_tbl) {
- w_long(ROBJECT(obj)->iv_tbl->num_entries, arg);
- st_foreach(ROBJECT(obj)->iv_tbl, obj_each, &c_arg);
- }
- else {
- w_long(0, arg);
- }
- }
- break;
-
- default:
- rb_raise(rb_eTypeError, "can't dump %s",
- rb_class2name(CLASS_OF(obj)));
- break;
- }
- }
-}
-
-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);
- 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) {
- 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_new(0, 0);
- arg.str = port;
- }
-
- arg.symbol = st_init_numtable();
- arg.data = st_init_numtable();
- 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;
-};
-
-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;
- int i;
-
- x = 0;
- for (i=0; i<sizeof(short); i++) {
- x |= r_byte(arg)<<(i*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);
-}
-
-static long
-r_long(arg)
- struct load_arg *arg;
-{
- register long x;
- int c = (char)r_byte(arg);
- int i;
-
- if (c == 0) return 0;
- if (c > 0) {
- if (c > sizeof(long)) long_toobig((int)c);
- x = 0;
- for (i=0;i<c;i++) {
- x |= (long)r_byte(arg) << (8*i);
- }
- }
- else {
- c = -c;
- if (c > sizeof(long)) long_toobig((int)c);
- x = -1;
- for (i=0;i<c;i++) {
- x &= ~(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 { \
- int r_bytes_len; \
- r_bytes2((s), r_bytes_len, (arg)); \
-} while (0)
-
-static void
-r_bytes0(s, len, arg)
- char *s;
- int 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_symbol(arg)
- struct load_arg *arg;
-{
- char *buf;
- ID id;
-
- if (r_byte(arg) == TYPE_SYMLINK) {
- int num = r_long(arg);
-
- if (st_lookup(arg->symbol, num, &id)) {
- return id;
- }
- rb_raise(rb_eTypeError, "bad symbol");
- }
- r_bytes(buf, arg);
- id = rb_intern(buf);
- st_insert(arg->symbol, arg->symbol->num_entries, id);
-
- return id;
-}
-
-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;
- int len;
-
- r_bytes2(buf, len, arg);
- return rb_str_new(buf, len);
-}
-
-static VALUE
-r_regist(v, arg)
- VALUE v;
- struct load_arg *arg;
-{
- OBJ_TAINT(v);
- if (arg->proc) {
- rb_funcall(arg->proc, rb_intern("call"), 1, v);
- }
- rb_hash_aset(arg->data, INT2FIX(RHASH(arg->data)->tbl->num_entries), v);
- return v;
-}
-
-static VALUE
-r_object(arg)
- struct load_arg *arg;
-{
- VALUE v;
- 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;
- break;
-
- case TYPE_UCLASS:
- {
- VALUE c = rb_path2class(r_unique(arg));
- v = r_object(arg);
- if (rb_special_const_p(v)) {
- rb_raise(rb_eArgError, "dump format error (user class)");
- }
- RBASIC(v)->klass = c;
- return v;
- }
-
- case TYPE_NIL:
- return Qnil;
-
- case TYPE_TRUE:
- return Qtrue;
-
- case TYPE_FALSE:
- return Qfalse;
-
- case TYPE_FIXNUM:
- {
- int i = r_long(arg);
- return INT2FIX(i);
- }
-
- case TYPE_FLOAT:
- {
- char *buf;
-
- r_bytes(buf, arg);
- v = rb_float_new(strtod(buf, 0));
- return r_regist(v, arg);
- }
-
- case TYPE_BIGNUM:
- {
- int len;
- unsigned short *digits;
-
- NEWOBJ(big, struct RBignum);
- OBJSETUP(big, rb_cBignum, T_BIGNUM);
- big->sign = (r_byte(arg) == '+');
- big->len = len = r_long(arg);
- big->digits = digits = ALLOC_N(unsigned short, len);
- while (len--) {
- *digits++ = r_short(arg);
- }
- big = RBIGNUM(rb_big_norm((VALUE)big));
- if (TYPE(big) == T_BIGNUM) {
- r_regist((VALUE)big, arg);
- }
- return (VALUE)big;
- }
-
- case TYPE_STRING:
- return r_regist(r_string(arg), arg);
-
- case TYPE_REGEXP:
- {
- char *buf;
- int len;
- int options;
-
- r_bytes2(buf, len, arg);
- options = r_byte(arg);
- return r_regist(rb_reg_new(buf, len, options), arg);
- }
-
- case TYPE_ARRAY:
- {
- volatile int 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));
- }
- return v;
- }
-
- case TYPE_HASH:
- case TYPE_HASH_DEF:
- {
- int 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);
- }
- return v;
- }
-
- case TYPE_STRUCT:
- {
- VALUE klass, mem, values;
- volatile int i; /* gcc 2.7.2.3 -O2 bug?? */
- int len;
- ID slot;
-
- klass = rb_path2class(r_unique(arg));
- mem = rb_ivar_get(klass, rb_intern("__member__"));
- if (mem == Qnil) {
- rb_raise(rb_eTypeError, "non-initialized 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] != INT2FIX(slot)) {
- rb_raise(rb_eTypeError, "struct %s not compatible (:%s for :%s)",
- rb_class2name(klass),
- rb_id2name(slot),
- rb_id2name(FIX2INT(RARRAY(mem)->ptr[i])));
- }
- rb_struct_aset(v, INT2FIX(i), r_object(arg));
- }
- return v;
- }
- break;
-
- case TYPE_USERDEF:
- {
- VALUE klass;
-
- klass = rb_path2class(r_unique(arg));
- if (rb_respond_to(klass, s_load)) {
- v = rb_funcall(klass, s_load, 1, r_string(arg));
- return r_regist(v, arg);
- }
- rb_raise(rb_eTypeError, "class %s needs to have method `_load'",
- rb_class2name(klass));
- }
- break;
-
- case TYPE_OBJECT:
- {
- VALUE klass;
- int len;
-
- klass = rb_path2class(r_unique(arg));
- len = r_long(arg);
- v = rb_obj_alloc(klass);
- r_regist(v, arg);
- if (len > 0) {
- while (len--) {
- ID id = r_symbol(arg);
- VALUE val = r_object(arg);
- rb_ivar_set(v, id, val);
- }
- }
- return v;
- }
- break;
-
- case TYPE_MODULE_OLD:
- {
- char *buf;
- r_bytes(buf, arg);
- return r_regist(rb_path2class(buf), arg);
- }
-
- case TYPE_CLASS:
- {
- VALUE c;
-
- char *buf;
- r_bytes(buf, arg);
- c = rb_path2class(buf);
- if (TYPE(c) != T_CLASS) {
- rb_raise(rb_eTypeError, "%s is not a class", buf);
- }
- return r_regist(c, arg);
- }
-
- case TYPE_MODULE:
- {
- VALUE m;
-
- char *buf;
- r_bytes(buf, arg);
- m = rb_path2class(buf);
- if (TYPE(m) != T_CLASS) {
- rb_raise(rb_eTypeError, "%s is not a module", buf);
- }
- return r_regist(m, arg);
- }
-
- default:
- rb_raise(rb_eArgError, "dump format error(0x%x)", type);
- break;
- }
- return Qnil; /* not reached */
-}
-
-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;
- VALUE v;
- OpenFile *fptr;
- struct load_arg arg;
-
- 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;
- }
- else if (rb_respond_to(port, rb_intern("to_str"))) {
- int len;
-
- arg.fp = 0;
- arg.ptr = str2cstr(port, &len);
- arg.end = arg.ptr + len;
- }
- else {
- rb_raise(rb_eTypeError, "instance of IO needed");
- }
-
- major = r_byte(&arg);
- if (major == MARSHAL_MAJOR) {
- volatile VALUE hash; /* protect from GC */
-
- if (r_byte(&arg) != MARSHAL_MINOR) {
- rb_warn("Old marshal file format (can be read)");
- }
- 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);
- }
- else {
- rb_raise(rb_eTypeError, "old marshal file format (can't read)");
- }
-
- 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_provide("marshal.so"); /* for backward compatibility */
-}
diff --git a/math.c b/math.c
deleted file mode 100644
index 978a23c73c..0000000000
--- a/math.c
+++ /dev/null
@@ -1,145 +0,0 @@
-/************************************************
-
- math.c -
-
- $Author$
- $Date$
- created at: Tue Jan 25 14:12:56 JST 1994
-
- Copyright (C) 1993-1999 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, x, y)
- VALUE obj, x, y;
-{
- Need_Float2(x, y);
- return rb_float_new(atan2(RFLOAT(x)->value, RFLOAT(y)->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_exp(obj, x)
- VALUE obj, x;
-{
- Need_Float(x);
- return rb_float_new(exp(RFLOAT(x)->value));
-}
-
-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)));
-}
-
-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, "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);
-}
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 dab2d51743..0000000000
--- a/misc/inf-ruby.el
+++ /dev/null
@@ -1,325 +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")
-;;; (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.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 098ddd5e04..0000000000
--- a/misc/ruby-mode.el
+++ /dev/null
@@ -1,721 +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-indent-beg-re
- "\\(\\s *\\(class\\|module\\|def\\)\\)\\|if\\|unless\\|case\\|while\\|until\\|for\\|begin"
- )
-
-(defconst ruby-modifier-re
- "if\\|unless\\|while\\|until"
- )
-
-(defconst ruby-block-mid-re
- "then\\|else\\|elsif\\|when\\|rescue\\|ensure"
- )
-
-(defconst ruby-block-op-re
- "and\\|or\\|not"
- )
-
-(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.")
-
-(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)
-
- (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)))
- (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 modifier)
- (save-excursion
- (if (looking-at "\\?")
- (progn
- (or (bolp) (forward-char -1))
- (not (looking-at "\\sw")))
- (store-match-data nil)
- (skip-chars-backward " \t")
- (or (bolp) (forward-char -1))
- (or (bolp)
- (looking-at ruby-operator-re)
- (looking-at "[\\[({]")
- (and (not modifier) (looking-at "[!?]"))
- (and (looking-at ruby-symbol-re)
- (save-restriction
- (let ((p (point)))
- (beginning-of-line)
- (narrow-to-region (point) p)
- (goto-char p)
- (forward-word -1)))
- (if (and (not modifier) (bolp))
- t
- (if (or (looking-at ruby-block-beg-re)
- (looking-at ruby-block-op-re)
- (looking-at ruby-block-mid-re))
- (progn
- (goto-char (match-end 0))
- (looking-at "\\>"))
- (looking-at "[a-zA-Z][a-zA-z0-9_]* +/[^ \t]"))))))))
-
-(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)
- (goto-char (match-beginning 0))
- (cond
- ((or (looking-at "\"") ;skip string
- (looking-at "'")
- (looking-at "`"))
- (setq w (char-after (point)))
- (cond
- ((and (not (eobp))
- (re-search-forward (format "[^\\]\\(\\\\\\\\\\)*%c" w) indent-point t))
- nil)
- (t
- (setq in-string (point))
- (goto-char indent-point))))
- ((looking-at "/")
- (cond
- ((and (not (eobp)) (ruby-expr-beg))
- (if (re-search-forward "[^\\]/" indent-point t)
- nil
- (setq in-string (point))
- (goto-char indent-point)))
- (t
- (goto-char pnt))))
- ((looking-at "%")
- (cond
- ((and (not (eobp)) (ruby-expr-beg)
- (not (looking-at "%="))
- (looking-at "%[Qqrxw]?\\(.\\)"))
- (setq w (buffer-substring (match-beginning 1)
- (match-end 1)))
- (cond
- ((string= w "[") (setq w "]"))
- ((string= w "{") (setq w "}"))
- ((string= w "(") (setq w ")"))
- ((string= w "<") (setq w ">")))
- (goto-char (match-end 0))
- (if (search-forward w indent-point t)
- nil
- (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)
- (eq ?_ (char-after (point)))))
- (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
- (or (bolp)
- (progn
- (forward-char -1)
- (not (eq ?_ (char-after (point))))))
- (goto-char pnt)
- (setq w (char-after (point)))
- (not (eq ?_ w))
- (not (eq ?! w))
- (not (eq ?? w))
- (skip-chars-forward " \t")
- (if (not (eolp))
- (progn
- (goto-char (match-beginning 0))
- (if (looking-at ruby-modifier-re)
- (ruby-expr-beg t)
- t))
- t)
- (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")
- (and (re-search-backward "#" (save-excursion
- (beginning-of-line)
- (point)) t)
- (setq state (ruby-parse-region parse-start (point)))
- (nth 0 state)
- (goto-char (nth 0 state)))
- (or (bobp) (forward-char -1))
- (and
- (or (and (looking-at ruby-symbol-re)
- (skip-chars-backward ruby-symbol-chars)
- (looking-at ruby-block-op-re)
- (save-excursion
- (goto-char (match-end 0))
- (not (looking-at "[a-z_]"))))
- (and (looking-at ruby-operator-re)
- (or (not (eq ?/ (char-after (point))))
- (null (nth 0 (ruby-parse-region parse-start (point)))))
- (not (eq (char-after (1- (point))) ?$))
- (or (not (eq ?| (char-after (point))))
- (save-excursion
- (or (eolp) (forward-char -1))
- (and (search-backward "|")
- (skip-chars-backward " \t\n")
- (and (not (eolp))
- (progn
- (forward-char -1)
- (not (looking-at "\\{")))
- (progn
- (forward-word -1)
- (not (looking-at "do\\>[^_]")))))))))
- (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 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))
-
-(cond
- ((featurep 'font-lock)
- (or (boundp 'font-lock-variable-name-face)
- (setq font-lock-variable-name-face font-lock-type-face))
-
- (add-hook 'ruby-mode-hook
- '(lambda ()
- (make-local-variable 'font-lock-syntactic-keywords)
- (setq font-lock-syntactic-keywords
- '(("\\$\\([#\"'`$\\]\\)" 1 (1 . nil))
- ("\\(#\\)[{$@]" 1 (1 . nil))))
- (make-local-variable 'font-lock-defaults)
- (setq font-lock-defaults '((ruby-font-lock-keywords) nil nil))
- (setq font-lock-keywords ruby-font-lock-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)))))
-
- (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"
- )
- "\\|")
- "\\)\\>[^_]")
- 2)
- ;; variables
- '("\\(^\\|[^_:.@$]\\|\\.\\.\\)\\b\\(nil\\|self\\|true\\|false\\)\\b[^_]"
- 2 font-lock-variable-name-face)
- ;; variables
- '("[$@].\\(\\w\\|_\\)*"
- 0 font-lock-variable-name-face)
- ;; embedded document
- '(ruby-font-lock-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"
- 2 font-lock-reference-face))
- "*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\\)\\>[^_]" 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 6879618c8a..0000000000
--- a/missing/alloca.c
+++ /dev/null
@@ -1,189 +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 */
-
-extern void free();
-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;
-
- free ((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/dir.h b/missing/dir.h
deleted file mode 100644
index 2e61f04443..0000000000
--- a/missing/dir.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/* $RCSfile: dir.h,v $$Revision: 4.0.1.1 $$Date: 91/06/07 11:22:10 $
- *
- * (C) Copyright 1987, 1990 Diomidis Spinellis.
- *
- * You may distribute under the terms of either the GNU General Public
- * License or the Artistic License, as specified in the README file.
- *
- * $Log: dir.h,v $
- * Revision 4.0.1.1 91/06/07 11:22:10 lwall
- * patch4: new copyright notice
- *
- * Revision 4.0 91/03/20 01:34:20 lwall
- * 4.0 baseline.
- *
- * Revision 3.0.1.1 90/03/27 16:07:08 lwall
- * patch16: MSDOS support
- *
- * Revision 1.1 90/03/18 20:32:29 dds
- * Initial revision
- *
- *
- */
-
-/*
- * defines the type returned by the directory(3) functions
- */
-
-#ifndef __DIR_INCLUDED
-#define __DIR_INCLUDED
-
-/*Directory entry size */
-#ifdef DIRSIZ
-#undef DIRSIZ
-#endif
-#define DIRSIZ(rp) (sizeof(struct direct))
-
-/*
- * Structure of a directory entry
- */
-struct direct {
- ino_t d_ino; /* inode number (not used by MS-DOS) */
- int d_namlen; /* Name length */
- char d_name[256]; /* file name */
-};
-
-struct _dir_struc { /* Structure used by dir operations */
- char *start; /* Starting position */
- char *curr; /* Current position */
- long size; /* Size of string table */
- long nfiles; /* number if filenames in table */
- struct direct dirstr; /* Directory structure to return */
-};
-
-typedef struct _dir_struc DIR; /* Type returned by dir operations */
-
-DIR *cdecl opendir(char *filename);
-struct direct *readdir(DIR *dirp);
-long telldir(DIR *dirp);
-void seekdir(DIR *dirp,long loc);
-void rewinddir(DIR *dirp);
-void closedir(DIR *dirp);
-
-#endif /* __DIR_INCLUDED */
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 79f5f65f5d..0000000000
--- a/missing/file.h
+++ /dev/null
@@ -1,31 +0,0 @@
-/* This is file FILE.H */
-/*
-** Copyright (C) 1991 DJ Delorie, 24 Kirsten Ave, Rochester NH 03867-2954
-**
-** This file is distributed under the terms listed in the document
-** "copying.dj", available from DJ Delorie at the address above.
-** A copy of "copying.dj" should accompany this file; if not, a copy
-** should be available from where this file was obtained. This file
-** may not be distributed without a verbatim copy of "copying.dj".
-**
-** This file is distributed WITHOUT ANY WARRANTY; without even the implied
-** warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-*/
-
-#ifndef _FILE_H_
-#define _FILE_H_
-
-#include <fcntl.h>
-
-#define L_SET 0
-#define L_CURR 1
-#define L_INCR 1
-#define L_XTND 2
-
-
-#define F_OK 0 /* does file exist */
-#define X_OK 1 /* is it executable by caller */
-#define W_OK 2 /* is it writable by caller */
-#define R_OK 4 /* is it readable by caller */
-
-#endif
diff --git a/missing/finite.c b/missing/finite.c
deleted file mode 100644
index 07fe3263e9..0000000000
--- a/missing/finite.c
+++ /dev/null
@@ -1,6 +0,0 @@
-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 a4a9544b56..0000000000
--- a/missing/flock.c
+++ /dev/null
@@ -1,90 +0,0 @@
-#include "config.h"
-
-#if 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;
-{
- int i;
- switch (operation) {
-
- /* LOCK_SH - get a shared lock */
- case LOCK_SH:
- /* LOCK_EX - get an exclusive lock */
- case LOCK_EX:
- i = lockf (fd, F_LOCK, 0);
- break;
-
- /* LOCK_SH|LOCK_NB - get a non-blocking shared lock */
- case LOCK_SH|LOCK_NB:
- /* LOCK_EX|LOCK_NB - get a non-blocking exclusive lock */
- case LOCK_EX|LOCK_NB:
- i = lockf (fd, F_TLOCK, 0);
- if (i == -1)
- if ((errno == EAGAIN) || (errno == EACCES))
- errno = EWOULDBLOCK;
- break;
-
- /* LOCK_UN - unlock */
- case LOCK_UN:
- i = lockf (fd, F_ULOCK, 0);
- break;
-
- /* Default - can't decipher operation */
- default:
- i = -1;
- errno = EINVAL;
- break;
- }
- return i;
-}
-#else
-int
-flock(fd, operation)
- int fd;
- int operation;
-{
- rb_notimplement();
- return -1;
-}
-#endif
diff --git a/missing/isinf.c b/missing/isinf.c
deleted file mode 100644
index e0cd6ac1a2..0000000000
--- a/missing/isinf.c
+++ /dev/null
@@ -1,44 +0,0 @@
-#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 96bb93ba6a..0000000000
--- a/missing/isnan.c
+++ /dev/null
@@ -1,16 +0,0 @@
-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;
-}
diff --git a/missing/memcmp.c b/missing/memcmp.c
deleted file mode 100644
index 762eaf5260..0000000000
--- a/missing/memcmp.c
+++ /dev/null
@@ -1,21 +0,0 @@
-/*
- * memcmp --- compare memories.
- *
- */
-
-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 09e64702b6..0000000000
--- a/missing/memmove.c
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * memmove --- move memories.
- *
- * We supply this routine for those systems that aren't standard yet.
- */
-
-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 aeb181f648..0000000000
--- a/missing/os2.c
+++ /dev/null
@@ -1,111 +0,0 @@
-#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 ba7bf78ea4..0000000000
--- a/missing/strcasecmp.c
+++ /dev/null
@@ -1,12 +0,0 @@
-#include <ctype.h>
-
-int
-strcasecmp(p1, p2)
- char *p1, *p2;
-{
- for ( ; *p1 && *p2; p1++, p2++) {
- if (toupper(*p1) != toupper(*p2))
- return toupper(*p1) - toupper(*p2);
- }
- return strlen(p1) - strlen(p2);
-}
diff --git a/missing/strchr.c b/missing/strchr.c
deleted file mode 100644
index 50714c9942..0000000000
--- a/missing/strchr.c
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * strchr --- search a string for a character
- *
- * We supply this routine for those systems that aren't standard yet.
- */
-
-#include <stdio.h>
-
-char *
-strchr(str, c)
-register const char *str, c;
-{
- if (c == '\0') {
- /* thanks to Mike Brennan ... */
- do {
- if (*str == c)
- return (char *) str;
- } while (*str++);
- } else {
- for (; *str; str++)
- if (*str == c)
- return (char *) str;
- }
-
- return NULL;
-}
-
-/*
- * strrchr --- find the last occurrence of a character in a string
- *
- * We supply this routine for those systems that aren't standard yet.
- */
-
-char *
-strrchr(str, c)
-register const char *str, c;
-{
- register const char *save = NULL;
-
- for (; *str; str++)
- if (*str == c)
- save = str;
-
- return (char *) save;
-}
diff --git a/missing/strdup.c b/missing/strdup.c
deleted file mode 100644
index 2e1fe90bbd..0000000000
--- a/missing/strdup.c
+++ /dev/null
@@ -1,25 +0,0 @@
-/************************************************
-
- strdup.c -
-
- $Author$
- $Date$
- created at: Wed Dec 7 15:34:01 JST 1994
-
-************************************************/
-#include <stdio.h>
-
-char *
-strdup(str)
- char *str;
-{
- extern char *xmalloc();
- char *tmp;
- int len = strlen(str) + 1;
-
- tmp = xmalloc(len);
- if (tmp == NULL) return NULL;
- memcpy(tmp, str, len);
-
- return tmp;
-}
diff --git a/missing/strerror.c b/missing/strerror.c
deleted file mode 100644
index 44013b3892..0000000000
--- a/missing/strerror.c
+++ /dev/null
@@ -1,19 +0,0 @@
-/*
- * strerror.c --- Map an integer error number into a printable string.
- */
-
-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 6bce490249..0000000000
--- a/missing/strftime.c
+++ /dev/null
@@ -1,894 +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
-
-#ifdef __GNUC__
-#define inline __inline__
-#else
-#define inline /**/
-#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, 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, "%d", 1900 + 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-%4d",
- range(1, timeptr->tm_mday, 31),
- months_a[range(0, timeptr->tm_mon, 11)],
- timeptr->tm_year + 1900);
- for (i = 3; i < 6; i++)
- if (islower(tbuf[i]))
- tbuf[i] = toupper(tbuf[i]);
- break;
-#endif
-
-
-#ifdef POSIX2_DATE
- case 'C':
- sprintf(tbuf, "%02d", (timeptr->tm_year + 1900) / 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 = 1900 + timeptr->tm_year + 1;
- else if (timeptr->tm_mon == 0 && w >= 52)
- y = 1900 + timeptr->tm_year - 1;
- else
- y = 1900 + timeptr->tm_year;
-
- if (*format == 'G')
- sprintf(tbuf, "%d", y);
- else
- sprintf(tbuf, "%02d", 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)
-int year;
-#else
-static int
-isleap(int 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 + 1900);
- 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 c136703415..0000000000
--- a/missing/strncasecmp.c
+++ /dev/null
@@ -1,18 +0,0 @@
-#include <ctype.h>
-
-int
-strncasecmp(p1, p2, len)
- char *p1;
- char *p2;
- int len;
-{
- for (; len != 0; len--, p1++, p2++) {
- if (toupper(*p1) != toupper(*p2)) {
- return toupper(*p1) - toupper(*p2);
- }
- if (*p1 == '\0') {
- return 0;
- }
- }
- return 0;
-}
diff --git a/missing/strstr.c b/missing/strstr.c
deleted file mode 100644
index c54349983e..0000000000
--- a/missing/strstr.c
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * strstr.c --
- *
- * Source code for the "strstr" library routine.
- *
- * Copyright 1988-1991 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 appears 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.
- */
-
-#ifndef lint
-static char rcsid[] = "$Header$ SPRITE (Berkeley)";
-#endif /* not lint */
-
-/*
- *----------------------------------------------------------------------
- *
- * strstr --
- *
- * Locate the first instance of a substring in a string.
- *
- * Results:
- * If string contains substring, the return value is the
- * location of the first matching instance of substring
- * in string. If string doesn't contain substring, the
- * return value is 0. Matching is done on an exact
- * character-for-character basis with no wildcards or special
- * characters.
- *
- * Side effects:
- * None.
- *
- *----------------------------------------------------------------------
- */
-
-char *
-strstr(string, substring)
- register char *string; /* String to search. */
- char *substring; /* Substring to try to find in string. */
-{
- register char *a, *b;
-
- /* First scan quickly through the two strings looking for a
- * single-character match. When it's found, then compare the
- * rest of the substring.
- */
-
- b = substring;
- if (*b == 0) {
- return string;
- }
- for ( ; *string != 0; string += 1) {
- if (*string != *b) {
- continue;
- }
- a = string;
- while (1) {
- if (*b == 0) {
- return string;
- }
- if (*a++ != *b++) {
- break;
- }
- }
- b = substring;
- }
- return (char *) 0;
-}
diff --git a/missing/strtod.c b/missing/strtod.c
deleted file mode 100644
index e052cbc067..0000000000
--- a/missing/strtod.c
+++ /dev/null
@@ -1,266 +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.
- *
- * See the file "license.terms" for information on usage and redistribution
- * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
- *
- * 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 4941f43b91..0000000000
--- a/missing/strtol.c
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * strtol.c --
- *
- * Source code for the "strtol" 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>
-
-
-/*
- *----------------------------------------------------------------------
- *
- * strtol --
- *
- * 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.
- *
- *----------------------------------------------------------------------
- */
-
-long int
-strtol(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;
- int result;
-
- /*
- * Skip any leading blanks.
- */
-
- p = string;
- while (isspace(*p)) {
- p += 1;
- }
-
- /*
- * Check for a sign.
- */
-
- if (*p == '-') {
- p += 1;
- result = -(strtoul(p, endPtr, base));
- } else {
- if (*p == '+') {
- p += 1;
- }
- result = strtoul(p, endPtr, base);
- }
- if ((result == 0) && (endPtr != 0) && (*endPtr == p)) {
- *endPtr = string;
- }
- 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 5865be7f9b..0000000000
--- a/missing/vsnprintf.c
+++ /dev/null
@@ -1,1128 +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.
- */
-
-/* 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 */
-
-#ifdef NT
-typedef long size_t;
-#endif
-
-#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 */
-
-#include <stddef.h>
-
-#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 dbfe662874..0000000000
--- a/missing/x68.c
+++ /dev/null
@@ -1,36 +0,0 @@
-#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);
-}
-
-#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;
-}
diff --git a/mkconfig.rb b/mkconfig.rb
deleted file mode 100644
index 671e9bdbe8..0000000000
--- a/mkconfig.rb
+++ /dev/null
@@ -1,98 +0,0 @@
-#!./miniruby
-
-require File.dirname($0)+"/lib/ftools"
-
-rbconfig_rb = ARGV[0] || 'rbconfig.rb'
-File.makedirs(File.dirname(rbconfig_rb), true)
-
-version = VERSION
-config = open(rbconfig_rb, "w")
-$stdout.reopen(config)
-
-fast = {'prefix'=>TRUE, 'INSTALL'=>TRUE, 'EXEEXT'=>TRUE}
-print %[
-module Config
-
- VERSION == "#{version}" or
- raise "ruby lib version (#{version}) doesn't match executable version (\#{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 " CONFIG = {}\n"
-v_fast = []
-v_others = []
-has_version = false
-File.foreach "config.status" do |$_|
- next if /^#/
- if /^s%@program_transform_name@%s,(.*)%g$/
- ptn = $1.sub(/\$\$/, '$').split(/,/) #'
- v_fast << " CONFIG[\"ruby_install_name\"] = \"" + "ruby".sub(ptn[0],ptn[1]) + "\"\n"
- elsif /^s%@(\w+)@%(.*)%g/
- name = $1
- val = $2 || ""
- next if name =~ /^(INSTALL|DEFS|configure_input|srcdir|top_srcdir)$/
- v = " CONFIG[\"" + name + "\"] = " +
- val.sub(/^\s*(.*)\s*$/, '"\1"').gsub(/\$\{?([^(){}]+)\}?/) {
- "\#{CONFIG[\\\"#{$1}\\\"]}"
- } + "\n"
- if fast[name]
- v_fast << v
- else
- v_others << v
- end
- has_version = true if name == "MAJOR"
- if /DEFS/
- val.split(/\s*-D/).each do |i|
- if i =~ /(.*)=(\\")?([^\\]*)(\\")?/
- key, val = $1, $3
- if val == '1'
- val = "TRUE"
- else
- val.sub! /^\s*(.*)\s*$/, '"\1"'
- end
- print " CONFIG[\"#{key}\"] = #{val}\n"
- end
- end
- end
- elsif /^ac_given_srcdir=(.*)/
- v_fast << " CONFIG[\"srcdir\"] = \"" + File.expand_path($1) + "\"\n"
- elsif /^ac_given_INSTALL=(.*)/
- v_fast << " CONFIG[\"INSTALL\"] = " + $1 + "\n"
- end
-# break if /^CEOF/
-end
-
-if not has_version
- VERSION.scan(/(\d+)\.(\d+)\.(\d+)/) {
- print " CONFIG[\"MAJOR\"] = \"" + $1 + "\"\n"
- print " CONFIG[\"MINOR\"] = \"" + $2 + "\"\n"
- print " CONFIG[\"TEENY\"] = \"" + $3 + "\"\n"
- }
-end
-
-print v_fast, v_others
-print <<EOS
- CONFIG["compile_dir"] = "#{Dir.pwd}"
- MAKEFILE_CONFIG = {}
- CONFIG.each{|k,v| MAKEFILE_CONFIG[k] = v.dup}
- def Config::expand(val)
- val.gsub!(/\\$\\(([^()]+)\\)/) do |var|
- key = $1
- if CONFIG.key? key
- "\#{Config::expand(CONFIG[\\\"\#{key}\\\"])}"
- else
- var
- end
- end
- val
- end
- CONFIG.each_value do |val|
- Config::expand(val)
- end
-end
-EOS
-config.close
-
-# vi:set sw=2:
diff --git a/node.h b/node.h
deleted file mode 100644
index e402d0f944..0000000000
--- a/node.h
+++ /dev/null
@@ -1,344 +0,0 @@
-/************************************************
-
- node.h -
-
- $Author$
- $Date$
- created at: Fri May 28 15:14:02 JST 1993
-
- Copyright (C) 1993-1999 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_PUSH,
- NODE_GASGN,
- NODE_IASGN,
- NODE_CASGN,
- NODE_CDECL,
- 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_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_RESTARGS,
- 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_CNAME,
- 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
-};
-
-typedef struct RNode {
- unsigned long flags;
- char *nd_file;
- union {
- struct RNode *node;
- ID id;
- VALUE value;
- VALUE (*cfunc)();
- ID *tbl;
- } u1;
- union {
- struct RNode *node;
- ID id;
- int argc;
- VALUE value;
- } u2;
- union {
- struct RNode *node;
- ID id;
- int state;
- struct global_entry *entry;
- int 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_RFUNC(b1,b2) NEW_SCOPE(block_append(b1,b2))
-#define NEW_SCOPE(b) rb_node_newnode(NODE_SCOPE,local_tbl(),cur_cref,(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() rb_node_newnode(NODE_BREAK,0,0,0)
-#define NEW_NEXT() rb_node_newnode(NODE_NEXT,0,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_PUSH(v,val) rb_node_newnode(NODE_DASGN_PUSH,v,val,0);
-#define NEW_IASGN(v,val) rb_node_newnode(NODE_IASGN,v,val,0)
-#define NEW_CASGN(v,val) rb_node_newnode(NODE_CASGN,v,val,0)
-#define NEW_CDECL(v,val) rb_node_newnode(NODE_CDECL,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_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_RESTARGS(a) rb_node_newnode(NODE_RESTARGS,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_CBODY(b),(s))
-#define NEW_SCLASS(r,b) rb_node_newnode(NODE_SCLASS,r,NEW_CBODY(b),0)
-#define NEW_MODULE(n,b) rb_node_newnode(NODE_MODULE,n,NEW_CBODY(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_CREF0() (cur_cref=rb_node_newnode(NODE_CREF,RNODE(ruby_frame->cbase)->nd_clss,0,0))
-#define NEW_CREF() (cur_cref=rb_node_newnode(NODE_CREF,0,0,cur_cref))
-#define NEW_CBODY(b) (cur_cref->nd_body=NEW_SCOPE(b),cur_cref)
-#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)
-
-NODE *rb_node_newnode();
-VALUE rb_method_booundp();
-
-#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();
-
-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 77b52ffec9..0000000000
--- a/numeric.c
+++ /dev/null
@@ -1,1537 +0,0 @@
-/************************************************
-
- numeric.c -
-
- $Author$
- $Date$
- created at: Fri Aug 13 18:33:09 JST 1993
-
- Copyright (C) 1993-1999 Yukihiro Matsumoto
-
-************************************************/
-
-#include "ruby.h"
-#include <math.h>
-#include <stdio.h>
-#ifdef __FreeBSD__
-#include <floatingpoint.h>
-#endif
-
-static ID coerce;
-static ID to_i;
-
-VALUE rb_cNumeric;
-VALUE rb_cFloat;
-VALUE rb_cInteger;
-VALUE rb_cFixnum;
-
-VALUE rb_eZeroDivError;
-VALUE rb_eFloatDomainError;
-
-ID rb_frame_last_func();
-VALUE rb_float_new();
-double rb_big2dbl();
-
-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(x, y);
- return rb_assoc_new(rb_Float(x), rb_Float(y));
-}
-
-static VALUE
-coerce_body(x)
- VALUE *x;
-{
- return rb_funcall(x[1], 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])?
- STR2CSTR(rb_inspect(x[1])):
- 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 need not to copy */
- return x;
-}
-
-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_divmod(x, y)
- VALUE x, y;
-{
- VALUE div, mod;
-
- div = rb_funcall(x, '/', 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_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 *s;
- double value = RFLOAT(flt)->value;
-
- if (isinf(value))
- return rb_str_new2(value < 0 ? "-Infinity" : "Infinity");
- else if(isnan(value))
- return rb_str_new2("NaN");
- else
- sprintf(buf, "%-.10g", value);
- if (s = strchr(buf, ' ')) *s = '\0';
- s = buf; if (s[0] == '-') s++;
- if (strchr(s, '.') == 0) {
- int len = strlen(buf);
- char *ind = strchr(buf, 'e');
-
- if (ind) {
- memmove(ind+2, ind, len-(ind-buf)+1);
- ind[0] = '.';
- ind[1] = '0';
- } else {
- strcat(buf, ".0");
- }
- }
-
- 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 VALUE
-flo_modulo(x, y, modulo)
- VALUE x, y;
- int modulo;
-{
- double value, result;
-
- switch (TYPE(y)) {
- case T_FIXNUM:
- value = (double)FIX2LONG(y);
- break;
- case T_BIGNUM:
- value = rb_big2dbl(y);
- break;
- case T_FLOAT:
- value = RFLOAT(y)->value;
- break;
- default:
- return rb_num_coerce_bin(x, y);
- }
-
-#ifdef HAVE_FMOD
- result = fmod(RFLOAT(x)->value, value);
-#else
- {
- double value1 = RFLOAT(x)->value;
- double value2;
-
- modf(value1/value, &value2);
- result = value1 - value2 * value;
- }
-#endif
- if (modulo &&
- (RFLOAT(x)->value < 0.0) != (result < 0.0) && result != 0.0) {
- result += value;
- }
- return rb_float_new(result);
-}
-
-static VALUE
-flo_mod(x, y)
- VALUE x, y;
-{
- return flo_modulo(x,y,1);
-}
-
-static VALUE
-flo_remainder(x, y)
- VALUE x, y;
-{
- return flo_modulo(x,y,0);
-}
-
-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;
- 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) {
- if (RFLOAT(x)->value == RFLOAT(y)->value) return Qtrue;
- }
- return Qfalse;
-}
-
-static VALUE
-flo_to_i(num)
- VALUE num;
-{
- double f = RFLOAT(num)->value;
- long val;
-
- if (!FIXABLE(f)) {
- return rb_dbl2big(f);
- }
- val = f;
- return INT2FIX(val);
-}
-
-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_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
-to_integer(val)
- VALUE val;
-{
- return rb_funcall(val, to_i, 0);
-}
-
-static VALUE
-fail_to_integer(val)
- VALUE val;
-{
- rb_raise(rb_eTypeError, "failed to convert %s into Integer",
- rb_class2name(CLASS_OF(val)));
- return Qnil; /* dummy */
-}
-
-long
-rb_num2long(val)
- VALUE val;
-{
- if (NIL_P(val)) {
- rb_raise(rb_eTypeError, "no implicit conversion 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_eTypeError, "float %s out of rang of integer", buf);
- }
-
- case T_BIGNUM:
- return rb_big2long(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_rescue(to_integer, val, fail_to_integer, val);
- if (!rb_obj_is_kind_of(val, rb_cInteger)) {
- rb_raise(rb_eTypeError, "`to_i' need to return integer");
- }
- 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_eArgError, "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_eArgError, "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_eTypeError, "integer %d out of range of fixnum", v);
- return INT2FIX(v);
-}
-
-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_eTypeError, "%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];
-
- 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_fatal("fixnum cannot treat base %d", base);
-
- snprintf(buf, 22, fmt, FIX2LONG(x));
- return rb_str_new2(buf);
-}
-
-static VALUE
-fix_to_s(in)
- VALUE in;
-{
- return rb_fix2str(in, 10);
-}
-
-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 VALUE
-fix_div(x, y)
- VALUE x, y;
-{
- if (FIXNUM_P(y)) {
- long i;
-
- i = FIX2LONG(y);
- if (i == 0) rb_num_zerodiv();
- i = FIX2LONG(x)/i;
- return INT2NUM(i); /* FIXNUM_MIN / -1 > FIXNUM_MAX */
- }
- return rb_num_coerce_bin(x, y);
-}
-
-static VALUE
-fix_modulo(x, y, modulo)
- VALUE x, y;
-{
- long i;
-
- if (FIXNUM_P(y)) {
- i = FIX2LONG(y);
- if (i == 0) rb_num_zerodiv();
- i = FIX2LONG(x)%i;
- if (modulo &&
- (FIX2LONG(x) < 0) != (FIX2LONG(y) < 0) &&
- i != 0) {
- i += FIX2LONG(y);
- }
- return INT2FIX(i);
- }
- return rb_num_coerce_bin(x, y);
-}
-
-static VALUE
-fix_mod(x, y)
- VALUE x, y;
-{
- return fix_modulo(x, y, 1);
-}
-
-static VALUE
-fix_remainder(x, y)
- VALUE x, y;
-{
- return fix_modulo(x, y, 0);
-}
-
-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;
- int width;
-
- val = NUM2LONG(x);
- width = NUM2INT(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));
- val = RSHIFT(FIX2LONG(x), i);
- return INT2FIX(val);
-}
-
-static VALUE
-fix_aref(fix, idx)
- VALUE fix, idx;
-{
- unsigned long val = FIX2LONG(fix);
- int i = FIX2LONG(idx);
-
- if (i < 0 || sizeof(VALUE)*CHAR_BIT-1 < i)
- return INT2FIX(0);
- if (val & (1<<i))
- return INT2FIX(1);
- return INT2FIX(0);
-}
-
-static VALUE
-fix_to_i(num)
- VALUE num;
-{
- return num;
-}
-
-static VALUE
-fix_to_f(num)
- VALUE num;
-{
- double val;
-
- val = (double)FIX2LONG(num);
-
- return rb_float_new(val);
-}
-
-static VALUE
-fix_type(fix)
- VALUE fix;
-{
- return rb_cFixnum;
-}
-
-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()
-{
-#ifdef __FreeBSD__
- /* allow divide by zero -- Inf */
- fpsetmask(fpgetmask() & ~(FP_X_DZ|FP_X_INV|FP_X_OFL));
-#endif
- coerce = rb_intern("coerce");
- to_i = rb_intern("to_i");
-
- rb_eZeroDivError = rb_define_class("ZeroDivisionError", rb_eStandardError);
- rb_eFloatDomainError = rb_define_class("FloatDomainError", rb_eStandardError);
- 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, "eql?", num_eql, 1);
- rb_define_method(rb_cNumeric, "divmod", num_divmod, 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_cInteger = rb_define_class("Integer", rb_cNumeric);
- 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_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_undef_method(CLASS_OF(rb_cFixnum), "new");
-
- rb_define_method(rb_cFixnum, "to_s", fix_to_s, 0);
- rb_define_method(rb_cFixnum, "type", fix_type, 0);
-
- 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, "%", fix_mod, 1);
- rb_define_method(rb_cFixnum, "remainder", fix_remainder, 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_i", fix_to_i, 0);
- 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), "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, "remainder", flo_remainder, 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_i", flo_to_i, 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, "floor", flo_floor, 0);
- rb_define_method(rb_cFloat, "ceil", flo_ceil, 0);
- rb_define_method(rb_cFloat, "round", flo_round, 0);
-}
diff --git a/object.c b/object.c
deleted file mode 100644
index 0851989184..0000000000
--- a/object.c
+++ /dev/null
@@ -1,1116 +0,0 @@
-/************************************************
-
- object.c -
-
- $Author$
- $Date$
- created at: Thu Jul 15 12:01:24 JST 1993
-
- Copyright (C) 1993-1999 Yukihiro Matsumoto
-
-************************************************/
-
-#include "ruby.h"
-#include "st.h"
-#include <stdio.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_f_sprintf();
-VALUE rb_obj_alloc();
-
-static ID eq, eql;
-static ID inspect;
-
-VALUE
-rb_equal(obj1, obj2)
- VALUE obj1, obj2;
-{
- VALUE result;
-
- if (obj1 == obj2) return Qtrue;
- result = rb_funcall(obj1, eq, 1, obj2);
- if (result == Qfalse || NIL_P(result))
- return Qfalse;
- return Qtrue;
-}
-
-int
-rb_eql(obj1, obj2)
- VALUE obj1, obj2;
-{
- return rb_funcall(obj1, eql, 1, obj2) == Qtrue;
-}
-
-static VALUE
-rb_obj_equal(obj1, obj2)
- VALUE obj1, obj2;
-{
- if (obj1 == obj2) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-rb_any_to_a(obj)
- VALUE obj;
-{
- return rb_ary_new3(1, obj);
-}
-
-static VALUE
-rb_obj_hash(obj)
- VALUE obj;
-{
- return (long)obj|FIXNUM_FLAG;
-}
-
-VALUE
-rb_obj_id(obj)
- VALUE obj;
-{
- if (rb_special_const_p(obj)) {
- return INT2NUM((long)obj);
- }
- return (long)obj|FIXNUM_FLAG;
-}
-
-static VALUE
-rb_obj_type(obj)
- VALUE obj;
-{
- VALUE cl = CLASS_OF(obj);
-
- while (FL_TEST(cl, FL_SINGLETON) || TYPE(cl) == T_ICLASS) {
- cl = RCLASS(cl)->super;
- }
- return cl;
-}
-
-VALUE
-rb_obj_clone(obj)
- VALUE obj;
-{
- VALUE clone;
-
- if (TYPE(obj) != T_OBJECT) {
- rb_raise(rb_eTypeError, "can't clone %s", rb_class2name(CLASS_OF(obj)));
- }
- clone = rb_obj_alloc(RBASIC(obj)->klass);
- CLONESETUP(clone,obj);
- if (ROBJECT(obj)->iv_tbl) {
- ROBJECT(clone)->iv_tbl = st_copy(ROBJECT(obj)->iv_tbl);
- RBASIC(clone)->klass = rb_singleton_class_clone(RBASIC(obj)->klass);
- RBASIC(clone)->flags = RBASIC(obj)->flags;
- }
-
- return clone;
-}
-
-static VALUE
-rb_obj_dup(obj)
- VALUE obj;
-{
- return rb_funcall(obj, rb_intern("clone"), 0, 0);
-}
-
-VALUE
-rb_any_to_s(obj)
- VALUE obj;
-{
- char *s;
- char *cname = rb_class2name(CLASS_OF(obj));
- VALUE str;
-
- s = ALLOCA_N(char, strlen(cname)+6+16+1); /* 6:tags 16:addr 1:eos */
- sprintf(s, "#<%s:0x%lx>", cname, obj);
- str = rb_str_new2(s);
- 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] == '-') {
- RSTRING(str)->ptr[0] = '#';
- rb_str_cat(str, ": ", 2);
- }
- else {
- rb_str_cat(str, ", ", 2);
- }
- ivname = rb_id2name(id);
- rb_str_cat(str, ivname, strlen(ivname));
- rb_str_cat(str, "=", 1);
- str2 = rb_inspect(value);
- rb_str_cat(str, RSTRING(str2)->ptr, RSTRING(str2)->len);
-
- return ST_CONTINUE;
-}
-
-static VALUE
-inspect_obj(obj, str)
- VALUE obj, str;
-{
- st_foreach(ROBJECT(obj)->iv_tbl, inspect_i, str);
- rb_str_cat(str, ">", 1);
-
- 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 *b;
-
- b = rb_class2name(CLASS_OF(obj));
- if (rb_inspecting_p(obj)) {
- char *buf = ALLOCA_N(char, strlen(b)+8);
- sprintf(buf, "#<%s:...>", b);
- return rb_str_new2(buf);
- }
- str = rb_str_new2("-<");
- rb_str_cat(str, b, strlen(b));
- 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;
-{
- VALUE cl;
-
- switch (TYPE(c)) {
- case T_MODULE:
- case T_CLASS:
- break;
-
- case T_NIL:
- if (NIL_P(obj)) return Qtrue;
- return Qfalse;
-
- case T_FALSE:
- if (obj) return Qfalse;
- return Qtrue;
-
- case T_TRUE:
- if (obj) return Qtrue;
- return Qfalse;
-
- default:
- rb_raise(rb_eTypeError, "class or module required");
- }
-
- cl = CLASS_OF(obj);
- while (FL_TEST(cl, FL_SINGLETON) || TYPE(cl) == T_ICLASS) {
- cl = RCLASS(cl)->super;
- }
- if (c == cl) 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:
- 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(obj)
- VALUE obj;
-{
- 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);
- OBJ_TAINT(obj);
- return obj;
-}
-
-VALUE
-rb_obj_untaint(obj)
- VALUE obj;
-{
- rb_secure(3);
- FL_UNSET(obj, FL_TAINT);
- return obj;
-}
-
-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");
-}
-
-static VALUE
-nil_type(obj)
- VALUE obj;
-{
- return rb_cNilClass;
-}
-
-#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",
- STR2CSTR(rb_inspect(y)),
- 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_type(obj)
- VALUE obj;
-{
- return rb_cTrueClass;
-}
-
-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_type(obj)
- VALUE obj;
-{
- return rb_cFalseClass;
-}
-
-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;
-}
-
-VALUE
-rb_obj_alloc(klass)
- VALUE klass;
-{
- NEWOBJ(obj, struct RObject);
- OBJSETUP(obj, klass, T_OBJECT);
- obj->iv_tbl = 0;
-
- return (VALUE)obj;
-}
-
-static VALUE
-rb_mod_clone(module)
- VALUE module;
-{
- NEWOBJ(clone, struct RClass);
- CLONESETUP(clone, module);
-
- clone->super = RCLASS(module)->super;
- clone->iv_tbl = 0;
- clone->m_tbl = 0; /* avoid GC crashing */
- if (RCLASS(module)->iv_tbl) {
- clone->iv_tbl = st_copy(RCLASS(module)->iv_tbl);
- }
- if (RCLASS(module)->m_tbl) {
- clone->m_tbl = st_copy(RCLASS(module)->m_tbl);
- }
-
- return (VALUE)clone;
-}
-
-static VALUE
-rb_mod_to_s(klass)
- VALUE klass;
-{
- 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;
-{
- 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;
-{
- 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);
- }
- return INT2FIX(1);
-}
-
-static VALUE
-rb_module_s_new(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;
- }
- Check_Type(super, T_CLASS);
- if (FL_TEST(super, FL_SINGLETON)) {
- rb_raise(rb_eTypeError, "can't make subclass of virtual class");
- }
- klass = rb_class_new(super);
- /* make metaclass */
- RBASIC(klass)->klass = rb_singleton_class_new(RBASIC(super)->klass);
- rb_singleton_class_attached(RBASIC(klass)->klass, klass);
-
- return klass;
-}
-
-static VALUE
-rb_class_s_inherited()
-{
- rb_raise(rb_eTypeError, "can't make subclass of Class");
- return Qnil; /* dummy */
-}
-
-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;
-
- if (TYPE(name) == T_STRING) {
- return rb_intern(RSTRING(name)->ptr);
- }
- id = NUM2UINT(name);
- if (!rb_id2name(id)) {
- rb_raise(rb_eArgError, "%d is not a symbol", id);
- }
- 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;
-{
- return rb_const_get(mod, rb_to_id(name));
-}
-
-static VALUE
-rb_mod_const_set(mod, name, value)
- VALUE mod, name, value;
-{
- rb_const_set(mod, rb_to_id(name), value);
- return value;
-}
-
-static VALUE
-rb_mod_const_defined(mod, name)
- VALUE mod, name;
-{
- return rb_const_defined_at(mod, rb_to_id(name));
-}
-
-static VALUE
-rb_obj_methods(obj)
- VALUE obj;
-{
- VALUE argv[1];
-
- argv[0] = Qtrue;
- return rb_class_instance_methods(1, argv, CLASS_OF(obj));
-}
-
-VALUE rb_obj_singleton_methods();
-
-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));
-}
-
-struct arg_to {
- VALUE val;
- const char *s;
-};
-
-static VALUE
-to_type(arg)
- struct arg_to *arg;
-{
- return rb_funcall(arg->val, rb_intern(arg->s), 0);
-}
-
-static VALUE
-fail_to_type(arg)
- struct arg_to *arg;
-{
- rb_raise(rb_eTypeError, "failed to convert %s into %s",
- NIL_P(arg->val) ? "nil" :
- arg->val == Qtrue ? "true" :
- arg->val == Qfalse ? "false" :
- rb_class2name(CLASS_OF(arg->val)),
- arg->s);
-}
-
-VALUE
-rb_convert_type(val, type, tname, method)
- VALUE val;
- int type;
- const char *tname, *method;
-{
- struct arg_to arg1, arg2;
-
- if (TYPE(val) == type) return val;
- arg1.val = arg2.val = val;
- arg1.s = method;
- arg2.s = tname;
- val = rb_rescue(to_type, (VALUE)&arg1, fail_to_type, (VALUE)&arg2);
- Check_Type(val, type);
- return val;
-}
-
-VALUE
-rb_Integer(val)
- VALUE val;
-{
- struct arg_to arg1, arg2;
-
- 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_str2inum(RSTRING(val)->ptr, 0);
-
- case T_NIL:
- return INT2FIX(0);
-
- default:
- break;
- }
-
- arg1.val = arg2.val = val;
- arg1.s = "to_i";
- arg2.s = "Integer";
- val = rb_rescue(to_type, (VALUE)&arg1, fail_to_type, (VALUE)&arg2);
- if (!rb_obj_is_kind_of(val, rb_cInteger)) {
- rb_raise(rb_eTypeError, "to_i should return Integer");
- }
- return val;
-}
-
-static VALUE
-rb_f_integer(obj, arg)
- VALUE obj, arg;
-{
- return rb_Integer(arg);
-}
-
-double rb_big2dbl _((VALUE));
-
-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_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 from String");
- break;
-
- case T_NIL:
- rb_raise(rb_eTypeError, "no implicit conversion from nil");
- break;
-
- default:
- break;
- }
-
- return RFLOAT(rb_Float(val))->value;
-}
-
-char*
-rb_str2cstr(str, len)
- VALUE str;
- int *len;
-{
- if (TYPE(str) != T_STRING) {
- str = rb_str_to_str(str);
- }
- if (len) *len = RSTRING(str)->len;
- 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;
-{
- if (TYPE(val) == T_ARRAY) return val;
- 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_new(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;
-
- rb_cObject = boot_defclass("Object", 0);
- rb_cModule = boot_defclass("Module", rb_cObject);
- rb_cClass = boot_defclass("Class", rb_cModule);
-
- metaclass = RBASIC(rb_cObject)->klass = rb_singleton_class_new(rb_cClass);
- rb_singleton_class_attached(metaclass, rb_cObject);
- metaclass = RBASIC(rb_cModule)->klass = rb_singleton_class_new(metaclass);
- rb_singleton_class_attached(metaclass, rb_cModule);
- metaclass = RBASIC(rb_cClass)->klass = rb_singleton_class_new(metaclass);
- rb_singleton_class_attached(metaclass, rb_cClass);
-
- rb_mKernel = rb_define_module("Kernel");
- rb_include_module(rb_cObject, rb_mKernel);
- rb_define_private_method(rb_cObject, "initialize", rb_obj_dummy, -1);
- rb_define_private_method(rb_cClass, "inherited", 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_alias(rb_mKernel, "equal?", "==");
- rb_define_alias(rb_mKernel, "===", "==");
- 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_hash, 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_type, 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, "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, 0);
- 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, 0);
-
- 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("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, "type", nil_type, 0);
- 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), "new");
- rb_define_global_const("NIL", Qnil);
-
- 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, "to_s", rb_mod_to_s, 0);
- rb_define_method(rb_cModule, "included_modules", rb_mod_included_modules, 0);
- 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, "new", rb_module_s_new, 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_private_method(rb_cModule, "method_added", rb_obj_dummy, 1);
-
- rb_define_method(rb_cClass, "new", rb_class_new_instance, -1);
- rb_define_method(rb_cClass, "superclass", rb_class_superclass, 0);
- 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_define_singleton_method(rb_cClass, "inherited", rb_class_s_inherited, 1);
-
- rb_cData = rb_define_class("Data", rb_cObject);
- rb_undef_method(CLASS_OF(rb_cData), "new");
-
- 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, "type", true_type, 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), "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, "type", false_type, 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), "new");
- rb_define_global_const("FALSE", Qfalse);
-
- eq = rb_intern("==");
- eql = rb_intern("eql?");
- inspect = rb_intern("inspect");
-}
diff --git a/pack.c b/pack.c
deleted file mode 100644
index 999f93a0e7..0000000000
--- a/pack.c
+++ /dev/null
@@ -1,1691 +0,0 @@
-/************************************************
-
- pack.c -
-
- $Author$
- $Date$
- created at: Thu Feb 10 15:17:05 JST 1994
-
- Copyright (C) 1993-1999 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 NATINT_LEN(type,len) (natint?sizeof(type):(len))
-# ifndef WORDS_BIGENDIAN
-# define OFF16(p) ((char*)(p) + (natint?(sizeof(short) - 2):0))
-# define OFF32(p) ((char*)(p) + (natint?(sizeof(long) - 4):0))
-# endif
-#else
-# define NATINT_LEN(type,len) sizeof(type)
-#endif
-
-#ifndef OFF16
-# define OFF16(p) (char*)(p)
-# define OFF32(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
-
-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 void
-pack_add_ptr(str, add)
- VALUE str, add;
-{
-#define STR_NO_ORIG FL_USER3 /* copied from string.c */
- if (!RSTRING(str)->orig) {
- RSTRING(str)->orig = rb_ary_new();
- FL_SET(str, STR_NO_ORIG);
- }
- rb_ary_push(RSTRING(str)->orig, add);
-}
-
-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;
- char type;
- int items, len, idx;
- char *ptr;
- int plen;
-#ifdef NATINT_PACK
- int natint; /* native integer */
-#endif
-
- p = str2cstr(fmt, &plen);
- pend = p + plen;
- res = rb_str_new(0, 0);
-
- items = RARRAY(ary)->len;
- idx = 0;
-
-#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 (*p == '_') {
- char *natstr = "sSiIlL";
-
- if (strchr(natstr, type)) {
-#ifdef NATINT_PACK
- natint = 1;
-#endif
- p++;
- }
- else {
- rb_raise(rb_eArgError, "'_' allowed only after types %s", 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 {
- ptr = str2cstr(from, &plen);
- }
-
- if (p[-1] == '*')
- len = plen;
-
- switch (type) {
- case 'a':
- case 'A':
- case 'Z':
- if (plen >= len)
- rb_str_cat(res, ptr, len);
- else {
- rb_str_cat(res, ptr, plen);
- len -= plen;
- while (len >= 10) {
- rb_str_cat(res, (type == 'A')?spc10:nul10, 10);
- len -= 10;
- }
- rb_str_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_cat(res, &c, 1);
- byte = 0;
- }
- }
- if (len & 7) {
- char c;
- byte >>= 7 - (len & 7);
- c = byte & 0xff;
- rb_str_cat(res, &c, 1);
- }
- len = RSTRING(res)->len;
- rb_str_resize(res, len+j);
- MEMZERO(RSTRING(res)->ptr+len, char, 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_cat(res, &c, 1);
- byte = 0;
- }
- }
- if (len & 7) {
- char c;
- byte <<= 7 - (len & 7);
- c = byte & 0xff;
- rb_str_cat(res, &c, 1);
- }
- len = RSTRING(res)->len;
- rb_str_resize(res, len+j);
- MEMZERO(RSTRING(res)->ptr+len, char, 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_cat(res, &c, 1);
- byte = 0;
- }
- }
- if (len & 1) {
- char c = byte & 0xff;
- rb_str_cat(res, &c, 1);
- }
- len = RSTRING(res)->len;
- rb_str_resize(res, len+j);
- MEMZERO(RSTRING(res)->ptr+len, char, 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_cat(res, &c, 1);
- byte = 0;
- }
- }
- if (len & 1) {
- char c = byte & 0xff;
- rb_str_cat(res, &c, 1);
- }
- len = RSTRING(res)->len;
- rb_str_resize(res, len+j);
- MEMZERO(RSTRING(res)->ptr+len, char, 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_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_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_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 = NUM2ULONG(from);
- }
- rb_str_cat(res, OFF32(&l), NATINT_LEN(long,4));
- }
- 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_cat(res, OFF16(&s), NATINT_LEN(short,2));
- }
- break;
-
- case 'N':
- while (len-- > 0) {
- unsigned long l;
-
- from = NEXTFROM;
- if (NIL_P(from)) l = 0;
- else {
- l = NUM2ULONG(from);
- }
- l = htonl(l);
- rb_str_cat(res, OFF32(&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_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 = NUM2ULONG(from);
- }
- l = htovl(l);
- rb_str_cat(res, OFF32(&l), NATINT_LEN(long,4));
- }
- break;
-
- case 'f':
- case 'F':
- while (len-- > 0) {
- float f;
-
- from = NEXTFROM;
- switch (TYPE(from)) {
- case T_FLOAT:
- f = RFLOAT(from)->value;
- break;
- case T_STRING:
- f = strtod(RSTRING(from)->ptr, 0);
- default:
- f = (float)NUM2INT(from);
- break;
- }
- rb_str_cat(res, (char*)&f, sizeof(float));
- }
- break;
-
- case 'e':
- while (len-- > 0) {
- float f;
- FLOAT_CONVWITH(ftmp);
-
- from = NEXTFROM;
- switch (TYPE(from)) {
- case T_FLOAT:
- f = RFLOAT(from)->value;
- break;
- case T_STRING:
- f = strtod(RSTRING(from)->ptr, 0);
- default:
- f = (float)NUM2INT(from);
- break;
- }
- f = HTOVF(f,ftmp);
- rb_str_cat(res, (char*)&f, sizeof(float));
- }
- break;
-
- case 'E':
- while (len-- > 0) {
- double d;
- DOUBLE_CONVWITH(dtmp);
-
- from = NEXTFROM;
- switch (TYPE(from)) {
- case T_FLOAT:
- d = RFLOAT(from)->value;
- break;
- case T_STRING:
- d = strtod(RSTRING(from)->ptr, 0);
- default:
- d = (double)NUM2INT(from);
- break;
- }
- d = HTOVD(d,dtmp);
- rb_str_cat(res, (char*)&d, sizeof(double));
- }
- break;
-
- case 'd':
- case 'D':
- while (len-- > 0) {
- double d;
-
- from = NEXTFROM;
- switch (TYPE(from)) {
- case T_FLOAT:
- d = RFLOAT(from)->value;
- break;
- case T_STRING:
- d = strtod(RSTRING(from)->ptr, 0);
- default:
- d = (double)NUM2INT(from);
- break;
- }
- rb_str_cat(res, (char*)&d, sizeof(double));
- }
- break;
-
- case 'g':
- while (len-- > 0) {
- float f;
- FLOAT_CONVWITH(ftmp);
-
- from = NEXTFROM;
- switch (TYPE(from)) {
- case T_FLOAT:
- f = RFLOAT(from)->value;
- break;
- case T_STRING:
- f = strtod(RSTRING(from)->ptr, 0);
- default:
- f = (float)NUM2INT(from);
- break;
- }
- f = HTONF(f,ftmp);
- rb_str_cat(res, (char*)&f, sizeof(float));
- }
- break;
-
- case 'G':
- while (len-- > 0) {
- double d;
- DOUBLE_CONVWITH(dtmp);
-
- from = NEXTFROM;
- switch (TYPE(from)) {
- case T_FLOAT:
- d = RFLOAT(from)->value;
- break;
- case T_STRING:
- d = strtod(RSTRING(from)->ptr, 0);
- default:
- d = (double)NUM2INT(from);
- break;
- }
- d = HTOND(d,dtmp);
- rb_str_cat(res, (char*)&d, sizeof(double));
- }
- break;
-
- case 'x':
- grow:
- while (len >= 10) {
- rb_str_cat(res, nul10, 10);
- len -= 10;
- }
- rb_str_cat(res, nul10, len);
- break;
-
- case 'X':
- shrink:
- if (RSTRING(res)->len < len)
- rb_raise(rb_eArgError, "X outside of string");
- RSTRING(res)->len -= len;
- RSTRING(res)->ptr[RSTRING(res)->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_cat(res, (char*)buf, le);
- }
- break;
-
- case 'u':
- case 'm':
- ptr = str2cstr(NEXTFROM, &plen);
-
- if (len <= 1)
- 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':
- len = 1;
- /* FALL THROUGH */
- case 'p':
- while (len-- > 0) {
- char *t;
- from = NEXTFROM;
- if (NIL_P(from)) t = "";
- else {
- t = STR2CSTR(from);
- pack_add_ptr(res, from);
- }
- rb_str_cat(res, (char*)&t, sizeof(char*));
- }
- break;
-
- default:
- break;
- }
- }
-
- 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_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_cat(str, buff, i);
- i = 0;
- }
- s++;
- }
- if (n > 0) {
- buff[i++] = '=';
- buff[i++] = '\n';
- }
- if (i > 0) {
- rb_str_cat(str, buff, i);
- }
-}
-
-#if defined(__GNUC__) && __GNUC__ >= 2 && !defined(RUBY_NO_INLINE)
-static __inline__ int
-#else
-static int
-#endif
-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;
- }
-}
-
-#ifdef NATINT_PACK
-#define PACK_LENGTH_ADJUST(type,sz) do { \
- int t__len = NATINT_LEN(type,(sz)); \
- tmp = 0; \
- if (len > (send-s)/t__len) { \
- if (!star) { \
- tmp = len-(send-s)/t__len; \
- } \
- len = (send-s)/t__len; \
- } \
-} while (0)
-#else
-#define PACK_LENGTH_ADJUST(type,sz) do { \
- tmp = 0; \
- if (len > (send-s)/sizeof(type)) { \
- if (!star) { \
- tmp = len - (send-s)/sizeof(type); \
- } \
- len = (send-s)/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
-
- s = str2cstr(str, &len);
- send = s + len;
- p = str2cstr(fmt, &len);
- pend = p + len;
-
- ary = rb_ary_new();
- while (p < pend) {
-#ifdef NATINT_PACK
- natint = 0;
-#endif
- star = 0;
- type = *p++;
- if (*p == '_') {
- char *natstr = "sSiIlL";
-
- if (strchr(natstr, type)) {
-#ifdef NATINT_PACK
- natint = 1;
-#endif
- p++;
- }
- else {
- rb_raise(rb_eArgError, "'_' allowed only after types %s", 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 'n':
- 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(ntohs(tmp)));
- }
- PACK_ITEM_ADJUST();
- break;
-
- case 'N':
- 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(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;
- unsigned long l;
-
- l = utf8_to_uv(s, &alen);
- s += 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 str = rb_str_new(0, 0);
- memcpy(&t, s, sizeof(char *));
- s += sizeof(char *);
- if (t)
- rb_str_cat(str, t, len);
- rb_ary_push(ary, str);
- }
- break;
-
- case 'p':
- if (len > (send - s) / sizeof(char *))
- len = (send - s) / sizeof(char *);
- while (len-- > 0) {
- if (send - s < sizeof(char *))
- break;
- else {
- char *t;
- VALUE str = rb_str_new(0, 0);
- memcpy(&t, s, sizeof(char *));
- s += sizeof(char *);
- if (t)
- rb_str_cat(str, t, strlen(t));
- rb_ary_push(ary, str);
- }
- }
- 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;
- *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 86cbf78362..0000000000
--- a/parse.y
+++ /dev/null
@@ -1,4619 +0,0 @@
-/************************************************
-
- parse.y -
-
- $Author$
- $Date$
- created at: Fri May 28 18:02:42 JST 1993
-
- Copyright (C) 1993-1999 Yukihiro Matsumoto
-
-************************************************/
-
-%{
-
-#define YYDEBUG 1
-#include "ruby.h"
-#include "env.h"
-#include "node.h"
-#include "st.h"
-#include <stdio.h>
-#include <errno.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 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)
-
-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_MID, /* newline significant, +/- is a sign. */
- EXPR_END, /* newline significant, +/- is a operator. */
- EXPR_PAREN, /* almost like EXPR_END, `do' works as `{'. */
- EXPR_ARG, /* 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;
-
-static int cond_nest = 0;
-static int class_nest = 0;
-static int in_single = 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 *call_op();
-static int in_defined = 0;
-
-static NODE *arg_blk_pass();
-static NODE *new_call();
-static NODE *new_fcall();
-
-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 struct RVarmap *dyna_push();
-static void dyna_pop();
-static int dyna_in_block();
-
-#define cref_push() NEW_CREF()
-static void cref_pop();
-static NODE *cur_cref;
-
-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
- kDO2
- 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
-%token <val> tINTEGER tFLOAT tSTRING tXSTRING tREGEXP
-%token <node> tDSTRING tDXSTRING tDREGEXP tNTH_REF tBACK_REF
-
-%type <node> singleton string
-%type <val> literal numeric
-%type <node> compstmt stmts stmt expr arg primary command_call method_call
-%type <node> if_tail opt_else case_body cases rescue ensure
-%type <node> opt_call_args call_args ret_args args when_args
-%type <node> aref_args opt_block_arg block_arg stmt_rhs
-%type <node> mrhs opt_list superclass generic_call block_call var_ref
-%type <node> f_arglist f_args f_optarg f_opt f_block_arg opt_f_block_arg
-%type <node> array 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_tail 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 tLBRACK /* [ */
-%token tLBRACE /* { */
-%token tSTAR /* * */
-%token tAMPER /* & */
-%token tSYMBEG
-
-/*
- * precedence table
- */
-
-%nonassoc kDO
-%nonassoc kDO2
-%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();
- NEW_CREF0(); /* initialize constant c-ref */
- 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();
- cur_cref = 0;
- 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 : block_call
- | kALIAS fitem {lex_state = EXPR_FNAME;} fitem
- {
- if (cur_mid || in_single)
- yyerror("alias within method");
- $$ = NEW_ALIAS($2, $4);
- }
- | kALIAS tGVAR tGVAR
- {
- if (cur_mid || in_single)
- yyerror("alias within method");
- $$ = NEW_VALIAS($2, $3);
- }
- | kALIAS tGVAR tBACK_REF
- {
- char buf[3];
-
- if (cur_mid || 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 (cur_mid || in_single)
- yyerror("undef within method");
- $$ = $2;
- }
- | stmt kIF_MOD expr
- {
- value_expr($3);
- $$ = NEW_IF(cond($3), $1, 0);
- fixpos($$, $3);
- }
- | stmt kUNLESS_MOD expr
- {
- value_expr($3);
- $$ = NEW_UNLESS(cond($3), $1, 0);
- fixpos($$, $3);
- }
- | stmt kWHILE_MOD expr
- {
- value_expr($3);
- if (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_expr($3);
- if (nd_type($1) == NODE_BEGIN) {
- $$ = NEW_UNTIL(cond($3), $1->nd_body, 0);
- }
- else {
- $$ = NEW_UNTIL(cond($3), $1, 1);
- }
- }
- | stmt kRESCUE_MOD expr
- {
- $$ = NEW_RESCUE($1, NEW_RESBODY(0,$3,0), 0);
- }
- | klBEGIN
- {
- if (cur_mid || in_single) {
- yyerror("BEGIN in method");
- }
- local_push();
- }
- '{' compstmt '}'
- {
- ruby_eval_tree_begin = block_append(ruby_eval_tree_begin,
- NEW_PREEXE($4));
- local_pop();
- $$ = 0;
- }
- | klEND '{' compstmt '}'
- {
- if (compile_for_eval && (cur_mid || in_single)) {
- yyerror("END in method; use at_exit");
- }
-
- $$ = NEW_ITER(0, NEW_POSTEXE(), $3);
- }
- | lhs '=' stmt_rhs
- {
- value_expr($3);
- $$ = node_assign($1, $3);
- }
- | expr
-
-expr : mlhs '=' mrhs
- {
- value_expr($3);
- $1->nd_value = $3;
- $$ = $1;
- }
- | kRETURN ret_args
- {
- value_expr($2);
- if (!compile_for_eval && !cur_mid && !in_single)
- yyerror("return appeared outside of method");
- $$ = NEW_RETURN($2);
- }
- | kYIELD ret_args
- {
- value_expr($2);
- $$ = NEW_YIELD($2);
- }
- | command_call
- | expr kAND expr
- {
- $$ = logop(NODE_AND, $1, $3);
- }
- | expr kOR expr
- {
- $$ = logop(NODE_OR, $1, $3);
- }
- | kNOT expr
- {
- value_expr($2);
- $$ = NEW_NOT(cond($2));
- }
- | '!' command_call
- {
- value_expr($2);
- $$ = NEW_NOT(cond($2));
- }
- | arg
-
-command_call : operation call_args
- {
- $$ = new_fcall($1, $2);
- fixpos($$, $2);
- }
- | primary '.' operation2 call_args
- {
- value_expr($1);
- $$ = new_call($1, $3, $4);
- fixpos($$, $1);
- }
- | primary tCOLON2 operation2 call_args
- {
- value_expr($1);
- $$ = new_call($1, $3, $4);
- fixpos($$, $1);
- }
- | kSUPER call_args
- {
- if (!compile_for_eval && !cur_mid && !in_single)
- yyerror("super called outside of method");
- $$ = NEW_SUPER($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(NEW_LIST($1), 0);
- }
- | mlhs_head tSTAR lhs
- {
- $$ = NEW_MASGN(NEW_LIST($1), $3);
- }
- | mlhs_head tSTAR
- {
- $$ = NEW_MASGN(NEW_LIST($1), -1);
- }
- | mlhs_head mlhs_tail
- {
- $$ = NEW_MASGN(list_concat(NEW_LIST($1),$2), 0);
- }
- | mlhs_head mlhs_tail ',' tSTAR lhs
- {
- $$ = NEW_MASGN(list_concat(NEW_LIST($1),$2),$5);
- }
- | mlhs_head mlhs_tail ',' tSTAR
- {
- $$ = NEW_MASGN(list_concat(NEW_LIST($1),$2),-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 ','
- {
- $$ = $1;
- }
-
-mlhs_tail : mlhs_item
- {
- $$ = NEW_LIST($1);
- }
- | mlhs_tail ',' mlhs_item
- {
- $$ = list_append($1, $3);
- }
-
-mlhs_node : variable
- {
- $$ = assignable($1, 0);
- }
- | primary '[' aref_args ']'
- {
- $$ = aryset($1, $3);
- }
- | primary '.' tIDENTIFIER
- {
- $$ = attrset($1, $3);
- }
- | backref
- {
- rb_backref_error($1);
- $$ = 0;
- }
-
-lhs : variable
- {
- $$ = assignable($1, 0);
- }
- | primary '[' aref_args ']'
- {
- $$ = aryset($1, $3);
- }
- | primary '.' tIDENTIFIER
- {
- $$ = 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 : tDOT2 { $$ = tDOT2; }
- | '|' { $$ = '|'; }
- | '^' { $$ = '^'; }
- | '&' { $$ = '&'; }
- | 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);
- }
- | variable tOP_ASGN {$$ = assignable($1, 0);} arg
- {
- if ($2 == tOROP) {
- $<node>3->nd_value = $4;
- $$ = NEW_OP_ASGN_OR(gettable($1), $<node>3);
- }
- else if ($2 == tANDOP) {
- $<node>3->nd_value = $4;
- $$ = NEW_OP_ASGN_AND(gettable($1), $<node>3);
- }
- else {
- $$ = $<node>3;
- if ($$) {
- $$->nd_value = call_op(gettable($1),$2,1,$4);
- }
- }
- fixpos($$, $4);
- }
- | primary '[' aref_args ']' tOP_ASGN arg
- {
- NODE *args = NEW_LIST($6);
-
- 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 '.' 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 '.' tCONSTANT 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
- {
- $$ = call_op($1, tPOW, 1, $3);
- }
- | tUPLUS arg
- {
- if (nd_type($2) == NODE_LIT) {
- $$ = $2;
- }
- else {
- $$ = call_op($2, tUPLUS, 0, 0);
- }
- }
- | tUMINUS arg
- {
- if (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
- {
- value_expr($1);
- $$ = NEW_IF(cond($1), $3, $5);
- fixpos($$, $1);
- }
- | primary
- {
- $$ = $1;
- }
-
-aref_args : opt_call_args
- {
- if ($1 && nd_type($1) == NODE_BLOCK_PASS) {
- rb_compile_error("block argument should not be given");
- }
- $$ = $1;
- }
-
-opt_call_args : none
- | call_args opt_nl
-
-call_args : command_call
- {
- value_expr($1);
- $$ = NEW_LIST($1);
- }
- | args ','
- {
- $$ = $1;
- }
- | args opt_block_arg
- {
- $$ = arg_blk_pass($1, $2);
- }
- | args ',' tSTAR arg opt_block_arg
- {
- $$ = arg_concat($1, $4);
- $$ = arg_blk_pass($$, $5);
- }
- | assocs ','
- {
- $$ = NEW_LIST(NEW_HASH($1));
- }
- | assocs opt_block_arg
- {
- $$ = NEW_LIST(NEW_HASH($1));
- $$ = arg_blk_pass($$, $2);
- }
- | assocs ',' tSTAR arg 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 ','
- {
- $$ = list_append($1, NEW_HASH($3));
- }
- | args ',' assocs ',' tSTAR arg opt_block_arg
- {
- $$ = arg_concat(list_append($1, NEW_HASH($3)), $6);
- $$ = arg_blk_pass($$, $7);
- }
- | tSTAR arg opt_block_arg
- {
- value_expr($2);
- $$ = arg_blk_pass(NEW_RESTARGS($2), $3);
- }
- | block_arg
-
-block_arg : tAMPER arg
- {
- value_expr($2);
- $$ = NEW_BLOCK_PASS($2);
- }
-
-opt_block_arg : ',' block_arg
- {
- $$ = $2;
- }
- | none
-
-opt_list : args
- | none
-
-args : arg
- {
- value_expr($1);
- $$ = NEW_LIST($1);
- }
- | args ',' arg
- {
- value_expr($3);
- $$ = list_append($1, $3);
- }
-
-mrhs : args
- {
- if ($1 &&
- nd_type($1) == NODE_ARRAY &&
- $1->nd_next == 0)
- {
- $$ = $1->nd_head;
- }
- else {
- $$ = $1;
- }
- }
- | args ',' tSTAR arg
- {
- value_expr($4);
- $$ = arg_concat($1, $4);
- }
- | tSTAR arg
- {
- value_expr($2);
- $$ = $2;
- }
-
-ret_args : call_args
- {
- $$ = $1;
- if ($1) {
- if (nd_type($1) == NODE_ARRAY &&
- $1->nd_next == 0) {
- $$ = $1->nd_head;
- }
- else if (nd_type($1) == NODE_BLOCK_PASS) {
- rb_compile_error("block argument should not be given");
- }
- }
- }
-
-array : none
- | args trailer
-
-primary : literal
- {
- $$ = NEW_LIT($1);
- }
- | primary tCOLON2 tCONSTANT
- {
- value_expr($1);
- $$ = NEW_COLON2($1, $3);
- }
- | tCOLON3 cname
- {
- $$ = NEW_COLON3($2);
- }
- | string
- | tXSTRING
- {
- $$ = NEW_XSTR($1);
- }
- | tDXSTRING
- | tDREGEXP
- | var_ref
- | backref
- | primary '[' aref_args ']'
- {
- value_expr($1);
- $$ = NEW_CALL($1, tAREF, $3);
- }
- | tLBRACK array ']'
- {
- if ($2 == 0)
- $$ = NEW_ZARRAY(); /* zero length array*/
- else {
- $$ = $2;
- }
- }
- | tLBRACE assoc_list '}'
- {
- $$ = NEW_HASH($2);
- }
- | kRETURN '(' ret_args ')'
- {
- if (!compile_for_eval && !cur_mid && !in_single)
- yyerror("return appeared outside of method");
- value_expr($3);
- $$ = NEW_RETURN($3);
- }
- | kRETURN '(' ')'
- {
- if (!compile_for_eval && !cur_mid && !in_single)
- yyerror("return appeared outside of method");
- $$ = NEW_RETURN(0);
- }
- | kRETURN
- {
- if (!compile_for_eval && !cur_mid && !in_single)
- yyerror("return appeared outside of method");
- $$ = NEW_RETURN(0);
- }
- | kYIELD '(' ret_args ')'
- {
- value_expr($3);
- $$ = NEW_YIELD($3);
- }
- | kYIELD '(' ')'
- {
- $$ = NEW_YIELD(0);
- }
- | kYIELD
- {
- $$ = NEW_YIELD(0);
- }
- | kDEFINED opt_nl '(' {in_defined = 1;} expr ')'
- {
- in_defined = 0;
- $$ = NEW_DEFINED($5);
- }
- | tFID
- {
- $$ = NEW_VCALL($1);
- }
- | 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 then
- compstmt
- if_tail
- kEND
- {
- value_expr($2);
- $$ = NEW_IF(cond($2), $4, $5);
- fixpos($$, $2);
- }
- | kUNLESS expr then
- compstmt
- opt_else
- kEND
- {
- value_expr($2);
- $$ = NEW_UNLESS(cond($2), $4, $5);
- fixpos($$, $2);
- }
- | kWHILE {cond_nest++;} expr do {cond_nest--;}
- compstmt
- kEND
- {
- value_expr($3);
- $$ = NEW_WHILE(cond($3), $6, 1);
- fixpos($$, $3);
- }
- | kUNTIL {cond_nest++;} expr do {cond_nest--;}
- compstmt
- kEND
- {
- value_expr($3);
- $$ = NEW_UNTIL(cond($3), $6, 1);
- fixpos($$, $3);
- }
- | kCASE compstmt
- case_body
- kEND
- {
- value_expr($2);
- $$ = NEW_CASE($2, $3);
- fixpos($$, $2);
- }
- | kFOR block_var kIN {cond_nest++;} expr do {cond_nest--;}
- compstmt
- kEND
- {
- value_expr($2);
- $$ = NEW_FOR($2, $5, $8);
- fixpos($$, $2);
- }
- | 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 compstmt ')'
- {
- $$ = $2;
- }
- | kCLASS cname superclass
- {
- if (cur_mid || in_single)
- yyerror("class definition in method body");
-
- class_nest++;
- cref_push();
- local_push();
- }
- compstmt
- kEND
- {
- $$ = NEW_CLASS($2, $5, $3);
- fixpos($$, $3);
- local_pop();
- cref_pop();
- class_nest--;
- }
- | kCLASS tLSHFT expr term
- {
- class_nest++;
- cref_push();
- local_push();
- }
- compstmt
- kEND
- {
- $$ = NEW_SCLASS($3, $6);
- fixpos($$, $3);
- local_pop();
- cref_pop();
- class_nest--;
- }
- | kMODULE cname
- {
- if (cur_mid || in_single)
- yyerror("module definition in method body");
- class_nest++;
- cref_push();
- local_push();
- }
- compstmt
- kEND
- {
- $$ = NEW_MODULE($2, $4);
- fixpos($$, $4);
- local_pop();
- cref_pop();
- class_nest--;
- }
- | kDEF fname
- {
- if (cur_mid || in_single)
- yyerror("nested method definition");
- cur_mid = $2;
- local_push();
- }
- 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?0:1);
- fixpos($$, $4);
- local_pop();
- cur_mid = 0;
- }
- | kDEF singleton dot_or_colon {lex_state = EXPR_FNAME;} fname
- {
- value_expr($2);
- in_single++;
- local_push();
- lex_state = EXPR_END; /* force for args */
- }
- f_arglist
- compstmt
- kEND
- {
- $$ = NEW_DEFS($2, $5, $7, $8);
- fixpos($$, $2);
- local_pop();
- in_single--;
- }
- | kBREAK
- {
- $$ = NEW_BREAK();
- }
- | kNEXT
- {
- $$ = NEW_NEXT();
- }
- | kREDO
- {
- $$ = NEW_REDO();
- }
- | kRETRY
- {
- $$ = NEW_RETRY();
- }
-
-then : term
- | kTHEN
- | term kTHEN
-
-do : term
- | kDO
-
-if_tail : opt_else
- | kELSIF expr then
- compstmt
- if_tail
- {
- value_expr($2);
- $$ = NEW_IF(cond($2), $4, $5);
- fixpos($$, $2);
- }
-
-opt_else : none
- | kELSE compstmt
- {
- $$ = $2;
- }
-
-block_var : lhs
- | mlhs
-
-opt_block_var : none
- | '|' /* none */ '|'
- {
- $$ = 0;
- }
- | tOROP
- {
- $$ = 0;
- }
- | '|' block_var '|'
- {
- $$ = $2;
- }
-
-do_block : kDO
- {
- $<vars>$ = dyna_push();
- }
- opt_block_var
- compstmt
- kEND
- {
- $$ = NEW_ITER($3, 0, $4);
- fixpos($$, $3?$3:$4);
- dyna_pop($<vars>2);
- }
-
-brace_block : '{'
- {
- $<vars>$ = dyna_push();
- }
- opt_block_var
- compstmt '}'
- {
- $$ = NEW_ITER($3, 0, $4);
- fixpos($$, $3?$3:$4);
- dyna_pop($<vars>2);
- }
- | kDO2
- {
- $<vars>$ = dyna_push();
- }
- opt_block_var
- compstmt
- kEND
- {
- $$ = NEW_ITER($3, 0, $4);
- fixpos($$, $3?$3:$4);
- dyna_pop($<vars>2);
- }
-
-
-generic_call : tIDENTIFIER
- {
- $$ = NEW_VCALL($1);
- }
- | tCONSTANT
- {
- $$ = NEW_VCALL($1);
- }
- | tFID
- {
- $$ = NEW_VCALL($1);
- }
- | method_call
- | command_call
-
-block_call : generic_call 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);
- }
-
-method_call : operation '(' opt_call_args close_paren
- {
- $$ = new_fcall($1, $3);
- fixpos($$, $3);
- }
- | primary '.' operation2 '(' opt_call_args close_paren
- {
- value_expr($1);
- $$ = new_call($1, $3, $5);
- fixpos($$, $1);
- }
- | primary '.' operation2
- {
- value_expr($1);
- $$ = new_call($1, $3, 0);
- fixpos($$, $1);
- }
- | primary tCOLON2 operation2 '(' opt_call_args close_paren
- {
- value_expr($1);
- $$ = new_call($1, $3, $5);
- fixpos($$, $1);
- }
- | primary tCOLON2 operation3
- {
- value_expr($1);
- $$ = new_call($1, $3, 0);
- }
- | kSUPER '(' opt_call_args close_paren
- {
- if (!compile_for_eval && !cur_mid &&
- !in_single && !in_defined)
- yyerror("super called outside of method");
- $$ = NEW_SUPER($3);
- }
- | kSUPER
- {
- if (!compile_for_eval && !cur_mid &&
- !in_single && !in_defined)
- yyerror("super called outside of method");
- $$ = NEW_ZSUPER();
- }
-
-close_paren : ')'
- {
- if (cond_nest == 0)
- lex_state = EXPR_PAREN;
- }
-
-stmt_rhs : block_call
- | command_call
-
-case_body : kWHEN when_args then
- compstmt
- cases
- {
- $$ = NEW_WHEN($2, $4, $5);
- }
-
-when_args : args
- | args ',' tSTAR arg
- {
- value_expr($4);
- $$ = list_append($1, NEW_WHEN($4, 0, 0));
- }
- | tSTAR arg
- {
- value_expr($2);
- $$ = NEW_LIST(NEW_WHEN($2, 0, 0));
- }
-
-cases : opt_else
- | case_body
-
-rescue : kRESCUE opt_list do
- compstmt
- rescue
- {
- $$ = NEW_RESBODY($2, $4, $5);
- fixpos($$, $2?$2:$4);
- }
- | none
-
-ensure : none
- | kENSURE compstmt
- {
- $$ = $2;
- }
-
-literal : numeric
- | symbol
- {
- $$ = INT2FIX($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
-
-
-numeric : tINTEGER
- | tFLOAT
-
-variable : tIDENTIFIER
- | tIVAR
- | tGVAR
- | tCONSTANT
- | kNIL {$$ = kNIL;}
- | kSELF {$$ = kSELF;}
- | kTRUE {$$ = kTRUE;}
- | kFALSE {$$ = kFALSE;}
- | k__FILE__ {$$ = k__FILE__;}
- | k__LINE__ {$$ = k__LINE__;}
-
-var_ref : variable
- {
- $$ = gettable($1);
- }
-
-backref : tNTH_REF
- | tBACK_REF
-
-superclass : term
- {
- $$ = 0;
- }
- | '<'
- {
- lex_state = EXPR_BEG;
- }
- expr 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 : 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
- {
- 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
- {
- $$ = 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 if (nd_type($1) == NODE_NIL) {
- yyerror("Can't define single method for nil.");
- $$ = 0;
- }
- else {
- $$ = $1;
- }
- }
- | '(' {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:
- 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 tASSOC arg
- {
- $$ = 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 <ctype.h>
-#include <sys/types.h>
-#include "regex.h"
-#include "util.h"
-#ifndef strdup
-char *strdup();
-#endif
-
-#define is_identchar(c) (((int)(c))!=-1&&(ISALNUM(c) || (c) == '_' || ismbchar(c)))
-
-static char *tokenbuf = NULL;
-static int tokidx, toksiz = 0;
-
-static NODE *str_extend();
-
-#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;
-
-int ruby_in_compile = 0;
-int ruby__end__seen;
-
-static VALUE ruby_debug_lines;
-
-static NODE*
-yycompile(f)
- char *f;
-{
- int n;
-
- if (!ruby_in_eval && rb_safe_level() == 0 &&
- rb_const_defined(rb_cObject, rb_intern("LINES__"))) {
- VALUE hash, fname;
-
- hash = rb_const_get(rb_cObject, rb_intern("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);
- }
- }
- }
-
- ruby__end__seen = 0;
- ruby_eval_tree = 0;
- heredoc_end = 0;
- ruby_sourcefile = f;
- ruby_in_compile = 1;
- n = yyparse();
- ruby_debug_lines = 0;
- compile_for_eval = 0;
- ruby_in_compile = 0;
- cond_nest = 0;
- class_nest = 0;
- in_single = 0;
- cur_mid = 0;
- if (n == 0) return ruby_eval_tree;
-
- return 0;
-}
-
-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 = 1;
-
- return yycompile(f);
-}
-
-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(strdup(f));
-}
-
-#if defined(__GNUC__) && __GNUC__ >= 2
-__inline__
-#endif
-static 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':
- {
- char buf[3];
- int i;
-
- pushback(c);
- for (i=0; i<3; i++) {
- c = nextc();
- if (c == -1) goto eof;
- if (c < '0' || '7' < c) {
- pushback(c);
- break;
- }
- buf[i] = c;
- }
- c = scan_oct(buf, i, &i);
- }
- return c;
-
- case 'x': /* hex constant */
- {
- char buf[2];
- int i;
-
- for (i=0; i<2; i++) {
- int cc = nextc();
-
- if (cc == -1) goto eof;
- buf[i] = cc;
- if (!ISXDIGIT(buf[i])) {
- pushback(buf[i]);
- break;
- }
- }
- c = scan_hex(buf, i, &i);
- }
- 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
-parse_regx(term, paren)
- int term, paren;
-{
- register int c;
- char kcode = 0;
- int once = 0;
- int nest = 0;
- int options = 0;
- int in_brack = 0;
- int re_start = ruby_sourceline;
- NODE *list = 0;
-
- newtok();
- while ((c = nextc()) != -1) {
- if (!in_brack && c == term && nest == 0) {
- goto regx_end;
- }
-
- switch (c) {
- case '[':
- in_brack = 1;
- break;
- case ']':
- in_brack = 0;
- break;
-
- case '#':
- list = str_extend(list, term);
- if (list == (NODE*)-1) return 0;
- continue;
-
- case '\\':
- switch (c = nextc()) {
- case -1:
- ruby_sourceline = re_start;
- rb_compile_error("unterminated regexp meets end of file");
- return 0;
-
- case '\n':
- break;
-
- case '\\':
- case '^':
- case 's':
- tokadd('\\');
- tokadd(c);
- break;
-
- case '1': case '2': case '3':
- case '4': case '5': case '6':
- case '7': case '8': case '9':
- case '0': case 'x':
- tokadd('\\');
- tokadd(c);
- break;
-
- case 'b':
- if (!in_brack) {
- tokadd('\\');
- tokadd('b');
- break;
- }
- /* fall through */
- default:
- if (c == term) {
- tokadd(c);
- }
- else {
- tokadd('\\');
- tokadd(c);
- }
- }
- continue;
-
- case -1:
- rb_compile_error("unterminated regexp");
- return 0;
-
- default:
- if (paren && !in_brack) {
- 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':
- options |= RE_OPTION_POSIXLINE;
- break;
- case 'o':
- once = 1;
- break;
- case 'n':
- kcode = 8;
- break;
- case 'e':
- kcode = 16;
- break;
- case 's':
- kcode = 24;
- break;
- case 'u':
- kcode = 32;
- 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);
- }
- rb_compile_error("unterminated regexp");
- 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 (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);
- 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;
- }
- if (paren) {
- if (c == paren) nest++;
- if (c == term && nest-- == 0) break;
- }
- 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 (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;
-
- case '\'':
- if (term == '\'') {
- c = '\'';
- break;
- }
- /* fall through */
- default:
- tokadd('\\');
- }
- }
- if (paren) {
- if (c == paren) nest++;
- if (c == term && nest-- == 0) break;
- }
- tokadd(c);
- }
-
- tokfix();
- yylval.val = rb_str_new(tok(), toklen());
- lex_state = EXPR_END;
- return tSTRING;
-}
-
-static int
-parse_quotedword(term, paren)
- int term, paren;
-{
- if (parse_qstring(term, paren) == 0) return 0;
- yylval.node = NEW_CALL(NEW_STR(yylval.val), rb_intern("split"), 0);
- return tDSTRING;
-}
-
-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 && (p[len] == '\n' || p[len] == '\r')) {
- break;
- }
-
- lex_pbeg = lex_p = RSTRING(line)->ptr;
- lex_pend = lex_p + RSTRING(line)->len;
-#if 0
- if (indent) {
- while (*lex_p && *lex_p == '\t') {
- lex_p++;
- }
- }
-#endif
- retry:
- switch (parse_string(term, '\n', '\n')) {
- case tSTRING:
- case tXSTRING:
- rb_str_cat(yylval.val, "\n", 1);
- if (!list) {
- rb_str_cat(str, RSTRING(yylval.val)->ptr, RSTRING(yylval.val)->len);
- }
- 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");
-}
-
-#ifndef strtod
-double strtod ();
-#endif
-
-static int
-yylex()
-{
- register int c;
- int space_seen = 0;
- struct kwtable *kw;
-
- 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 = 1;
- 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:
- goto retry;
- default:
- break;
- }
- lex_state = EXPR_BEG;
- return '\n';
-
- case '*':
- if ((c = nextc()) == '*') {
- lex_state = EXPR_BEG;
- if (nextc() == '=') {
- yylval.id = tPOW;
- return tOP_ASGN;
- }
- pushback(c);
- return tPOW;
- }
- if (c == '=') {
- yylval.id = '*';
- lex_state = EXPR_BEG;
- return tOP_ASGN;
- }
- pushback(c);
- if (lex_state == EXPR_ARG && space_seen && !ISSPACE(c)){
- lex_state = EXPR_BEG;
- return tSTAR;
- }
- if (lex_state == EXPR_BEG || lex_state == EXPR_MID) {
- lex_state = EXPR_BEG;
- return tSTAR;
- }
- lex_state = EXPR_BEG;
- return '*';
-
- 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 && ISSPACE(lex_p[3])) {
- break;
- }
- }
- lex_p = lex_pend;
- goto retry;
- }
- }
-
- lex_state = EXPR_BEG;
- 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_PAREN &&
- lex_state != EXPR_CLASS &&
- (lex_state != EXPR_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);
- }
- lex_state = EXPR_BEG;
- if (c == '=') {
- if ((c = nextc()) == '>') {
- return tCMP;
- }
- pushback(c);
- return tLEQ;
- }
- if (c == '<') {
- if (nextc() == '=') {
- yylval.id = tLSHFT;
- return tOP_ASGN;
- }
- pushback(c);
- return tLSHFT;
- }
- pushback(c);
- return '<';
-
- case '>':
- lex_state = EXPR_BEG;
- if ((c = nextc()) == '=') {
- return tGEQ;
- }
- if (c == '>') {
- if ((c = nextc()) == '=') {
- 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_PAREN) {
- lex_state = EXPR_BEG;
- return '?';
- }
- c = nextc();
- if (lex_state == EXPR_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 (lex_state == EXPR_ARG && space_seen && !ISSPACE(c)){
- lex_state = EXPR_BEG;
- return tAMPER;
- }
- if (lex_state == EXPR_BEG || lex_state == EXPR_MID) {
- lex_state = EXPR_BEG;
- return tAMPER;
- }
- lex_state = EXPR_BEG;
- return '&';
-
- case '|':
- lex_state = EXPR_BEG;
- if ((c = nextc()) == '|') {
- if ((c = nextc()) == '=') {
- yylval.id = tOROP;
- return tOP_ASGN;
- }
- pushback(c);
- return tOROP;
- }
- else if (c == '=') {
- yylval.id = '|';
- return tOP_ASGN;
- }
- pushback(c);
- return '|';
-
- case '+':
- c = nextc();
- if (lex_state == EXPR_FNAME || lex_state == EXPR_DOT) {
- 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 ||
- (lex_state == EXPR_ARG && space_seen && !ISSPACE(c))) {
- pushback(c);
- lex_state = EXPR_BEG;
- return tUPLUS;
- }
- lex_state = EXPR_BEG;
- pushback(c);
- return '+';
-
- case '-':
- c = nextc();
- if (lex_state == EXPR_FNAME || lex_state == EXPR_DOT) {
- 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 ||
- (lex_state == EXPR_ARG && space_seen && !ISSPACE(c))) {
- lex_state = EXPR_BEG;
- pushback(c);
- 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;
-
- is_float = seen_point = seen_e = 0;
- lex_state = EXPR_END;
- newtok();
- if (c == '-' || c == '+') {
- tokadd(c);
- c = nextc();
- }
- if (c == '0') {
- c = nextc();
- if (c == 'x' || c == 'X') {
- /* hexadecimal */
- c = nextc();
- if (!ISXDIGIT(c)) {
- yyerror("hexadecimal number without hex-digits");
- }
- do {
- if (c == '_') continue;
- if (!ISXDIGIT(c)) break;
- tokadd(c);
- } while (c = nextc());
- pushback(c);
- tokfix();
- yylval.val = rb_str2inum(tok(), 16);
- return tINTEGER;
- }
- if (c == 'b' || c == 'B') {
- /* binary */
- c = nextc();
- if (c != '0' && c != '1') {
- yyerror("numeric literal without digits");
- }
- do {
- if (c == '_') continue;
- if (c != '0'&& c != '1') break;
- tokadd(c);
- } while (c = nextc());
- pushback(c);
- tokfix();
- yylval.val = rb_str2inum(tok(), 2);
- return tINTEGER;
- }
- if (c >= '0' && c <= '7' || c == '_') {
- /* octal */
- do {
- if (c == '_') continue;
- if (c < '0' || c > '7') break;
- tokadd(c);
- } while (c = nextc());
- pushback(c);
- tokfix();
- yylval.val = rb_str2inum(tok(), 8);
- return tINTEGER;
- }
- if (c > '7' && c <= '9') {
- yyerror("Illegal octal digit");
- }
- else if (c == '.') {
- 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':
- tokadd(c);
- break;
-
- case '.':
- 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++;
- break;
-
- case 'e':
- case 'E':
- if (seen_e) {
- goto decode_num;
- }
- tokadd(c);
- seen_e++;
- is_float++;
- if ((c = nextc()) == '-' || c == '+')
- tokadd(c);
- else
- continue;
- break;
-
- case '_': /* `_' in decimal just ignored */
- break;
-
- default:
- goto decode_num;
- }
- c = nextc();
- }
-
- decode_num:
- pushback(c);
- tokfix();
- 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_str2inum(tok(), 10);
- return tINTEGER;
- }
-
- case ']':
- case '}':
- case ')':
- lex_state = EXPR_END;
- return c;
-
- case ':':
- c = nextc();
- if (c == ':') {
- if (lex_state == EXPR_BEG || lex_state == EXPR_MID) {
- lex_state = EXPR_BEG;
- return tCOLON3;
- }
- if (lex_state == EXPR_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_PAREN || 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;
- }
- if (lex_state == EXPR_ARG) {
- if (space_seen && !ISSPACE(c)) {
- pushback(c);
- arg_ambiguous();
- return parse_regx('/', '/');
- }
- }
- lex_state = EXPR_BEG;
- pushback(c);
- return '/';
-
- case '^':
- lex_state = EXPR_BEG;
- if (nextc() == '=') {
- yylval.id = '^';
- return tOP_ASGN;
- }
- pushback(c);
- return c;
-
- case ',':
- case ';':
- lex_state = EXPR_BEG;
- return c;
-
- case '~':
- if (lex_state == EXPR_FNAME || lex_state == EXPR_DOT) {
- if ((c = nextc()) != '@') {
- pushback(c);
- }
- }
- lex_state = EXPR_BEG;
- return '~';
-
- case '(':
- if (lex_state == EXPR_BEG || lex_state == EXPR_MID) {
- c = tLPAREN;
- lex_state = EXPR_BEG;
- }
- else {
- lex_state = EXPR_BEG;
- }
- return c;
-
- case '[':
- if (lex_state == EXPR_FNAME || lex_state == EXPR_DOT) {
- 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 (lex_state == EXPR_ARG && space_seen) {
- c = tLBRACK;
- }
- lex_state = EXPR_BEG;
- return c;
-
- case '{':
- if (lex_state != EXPR_END &&
- lex_state != EXPR_PAREN &&
- lex_state != EXPR_ARG)
- c = tLBRACE;
- 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 (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_quotedword(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 (lex_state == EXPR_ARG && space_seen && !ISSPACE(c)) {
- goto quotation;
- }
- lex_state = EXPR_BEG;
- pushback(c);
- return '%';
-
- case '$':
- lex_state = EXPR_END;
- newtok();
- c = nextc();
- switch (c) {
- case '~': /* $~: match-data */
- /* fall through */
- case '_': /* $_: last read line string */
- 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());
- 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':
- while (ISDIGIT(c)) {
- tokadd(c);
- c = nextc();
- }
- pushback(c);
- tokfix();
- yylval.node = NEW_NTH_REF(atoi(tok()));
- return tNTH_REF;
-
- default:
- if (!is_identchar(c)) {
- pushback(c);
- return '$';
- }
- case '0':
- tokadd('$');
- }
- break;
-
- case '@':
- c = nextc();
- if (!is_identchar(c)) {
- pushback(c);
- return '@';
- }
- newtok();
- tokadd('@');
- break;
-
- default:
- if (c != '_' && !ISALPHA(c) && !ismbchar(c)) {
- rb_compile_error("Invalid char '%c' 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;
-
- switch (tok()[0]) {
- case '$':
- lex_state = EXPR_END;
- result = tGVAR;
- break;
- case '@':
- lex_state = EXPR_END;
- result = tIVAR;
- break;
- default:
- if (lex_state != EXPR_DOT) {
- /* 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 (state == EXPR_PAREN && kw->id[0] == kDO) {
- return kDO2;
- }
- return kw->id[state != EXPR_BEG];
- }
- }
-
- if (ISUPPER(tok()[0])) {
- result = tCONSTANT;
- }
- else if (toklast() == '!' || toklast() == '?') {
- result = tFID;
- }
- else {
- result = tIDENTIFIER;
- if (lex_state == EXPR_FNAME || lex_state == EXPR_DOT) {
- if ((c = nextc()) == '=' && !peek('=')) {
- tokadd(c);
- }
- else {
- pushback(c);
- }
- }
- }
- if (lex_state == EXPR_BEG ||
- lex_state == EXPR_DOT ||
- lex_state == EXPR_ARG) {
- lex_state = EXPR_ARG;
- }
- else {
- lex_state = EXPR_END;
- }
- }
- tokfix();
- yylval.id = rb_intern(tok());
- return result;
- }
-}
-
-static NODE*
-str_extend(list, term)
- NODE *list;
- char term;
-{
- int c;
- int brace = -1;
- VALUE ss;
- NODE *node;
- int nest;
-
- 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 '\\':
- refetch:
- 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)) {
- yyerror("bad global variable in string");
- 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();
- 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 '{':
- if (c == '{') brace = '}';
- nest = 0;
- do {
- loop_again:
- c = nextc();
- switch (c) {
- case -1:
- if (nest > 0) {
- yyerror("bad substitution in string");
- newtok();
- return list;
- }
- return (NODE*)-1;
- case '}':
- if (c == brace) {
- if (nest == 0) break;
- nest--;
- }
- tokadd(c);
- goto loop_again;
- case '\\':
- c = read_escape();
- tokadd(c);
- goto loop_again;
- case '{':
- if (brace != -1) nest++;
- case '\"':
- case '/':
- case '`':
- if (c == term) {
- pushback(c);
- list_append(list, NEW_STR(rb_str_new2("#")));
- rb_warning("bad substitution in string");
- tokfix();
- list_append(list, NEW_STR(rb_str_new(tok(), toklen())));
- newtok();
- return list;
- }
- default:
- 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;
- 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 */
- 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_CVAR(id);
- }
- rb_bug("invalid id for gettable");
- return 0;
-}
-
-static NODE*
-assignable(id, val)
- ID id;
- NODE *val;
-{
- NODE *lhs = 0;
-
- 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_defined(id)) {
- lhs = NEW_DASGN(id, val);
- }
- else if (local_id(id) || !dyna_in_block()) {
- lhs = NEW_LASGN(id, val);
- }
- else{
- rb_dvar_push(id, 0);
- lhs = NEW_DASGN_PUSH(id, val);
- }
- }
- else if (is_global_id(id)) {
- lhs = NEW_GASGN(id, val);
- }
- else if (is_instance_id(id)) {
- lhs = NEW_IASGN(id, val);
- }
- else if (is_const_id(id)) {
- if (cur_mid || in_single)
- yyerror("dynamic constant assignment");
- lhs = NEW_CDECL(id, val);
- }
- else {
- rb_bug("bad id for variable");
- }
- return lhs;
-}
-
-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;
-{
- 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_ARGSCAT(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_PUSH:
- case NODE_MASGN:
- case NODE_CASGN:
- case NODE_CDECL:
- 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_RETURN:
- case NODE_BREAK:
- case NODE_NEXT:
- case NODE_REDO:
- case NODE_RETRY:
- case NODE_WHILE:
- case NODE_UNTIL:
- case NODE_CLASS:
- case NODE_MODULE:
- case NODE_DEFN:
- case NODE_DEFS:
- yyerror("void value expression");
- return Qfalse;
- break;
-
- case NODE_BLOCK:
- while (node->nd_next) {
- node = node->nd_next;
- }
- return value_expr(node->nd_head);
-
- 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:
- case tAREF:
- case tRSHFT:
- case tCOLON2:
- case tCOLON3:
- useless = rb_id2name(node->nd_mid);
- break;
- }
- break;
-
- case NODE_LVAR:
- case NODE_DVAR:
- case NODE_GVAR:
- case NODE_IVAR:
- case NODE_NTH_REF:
- case NODE_BACK_REF:
- useless = "a variable";
- break;
- case NODE_CVAR:
- 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 NODE *cond2();
-
-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:
- case NODE_CASGN:
- break;
-
- case NODE_NEWLINE:
- default:
- return 0;
- }
-
- switch (nd_type(node->nd_value)) {
- case NODE_LIT:
- case NODE_STR:
- case NODE_DSTR:
- case NODE_XSTR:
- case NODE_DXSTR:
- case NODE_EVSTR:
- case NODE_DREGX:
- case NODE_NIL:
- case NODE_TRUE:
- case NODE_FALSE:
- /* reports always */
- rb_warn("found = in conditional, should be ==");
- return 1;
-
- default:
- break;
- }
- if (assign_in_cond(node->nd_value) == 0) {
- rb_warning("assignment in condition");
- }
- return 1;
-}
-
-static NODE*
-cond0(node)
- NODE *node;
-{
- enum node_type type = nd_type(node);
-
- assign_in_cond(node);
- switch (type) {
- case NODE_DREGX:
- case NODE_DREGX_ONCE:
- local_cnt('_');
- local_cnt('~');
- return NEW_MATCH2(node, NEW_GVAR(rb_intern("$_")));
-
- case NODE_DOT2:
- case NODE_DOT3:
- node->nd_beg = cond2(node->nd_beg);
- node->nd_end = cond2(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(0);
- return node;
-
- case NODE_LIT:
- if (TYPE(node->nd_lit) == T_REGEXP) {
- local_cnt('_');
- local_cnt('~');
- return NEW_MATCH(node);
- }
- if (TYPE(node->nd_lit) == T_STRING) {
- local_cnt('_');
- local_cnt('~');
- return NEW_MATCH(rb_reg_new(RSTRING(node)->ptr,RSTRING(node)->len,0));
- }
- default:
- 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*
-cond2(node)
- NODE *node;
-{
- enum node_type type;
-
- node = cond(node);
- type = nd_type(node);
- if (type == NODE_NEWLINE) node = node->nd_next;
- if (type == NODE_LIT && FIXNUM_P(node->nd_lit)) {
- return call_op(node,tEQ,1,NEW_GVAR(rb_intern("$.")));
- }
- return node;
-}
-
-static NODE*
-logop(type, left, right)
- enum node_type type;
- NODE *left, *right;
-{
- value_expr(left);
- return rb_node_newnode(type, cond(left), cond(right), 0);
-}
-
-static NODE *
-arg_blk_pass(node1, node2)
- NODE *node1;
- NODE *node2;
-{
- if (node2) {
- node2->nd_head = node1;
- return node2;
- }
- return node1;
-}
-
-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 struct local_vars {
- ID *tbl;
- int nofree;
- int cnt;
- int dlev;
- struct local_vars *prev;
-} *lvtbl;
-
-static void
-local_push()
-{
- struct local_vars *local;
-
- local = ALLOC(struct local_vars);
- local->prev = lvtbl;
- local->nofree = 0;
- local->cnt = 0;
- local->tbl = 0;
- local->dlev = 0;
- lvtbl = local;
-}
-
-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;
- }
- 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();
- 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->flag == SCOPE_ALLOCA) {
- 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->flag |= 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()
-{
- lvtbl->dlev++;
- return ruby_dyna_vars;
-}
-
-static void
-dyna_pop(vars)
- struct RVarmap* vars;
-{
- lvtbl->dlev--;
- ruby_dyna_vars = vars;
-}
-
-static int
-dyna_in_block()
-{
- return (lvtbl->dlev > 0);
-}
-
-static void
-cref_pop()
-{
- cur_cref = cur_cref->nd_next;
-}
-
-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, "::",
- tCOLON3, "::",
- '`', "`",
- 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*)&cur_cref);
- rb_global_variable((VALUE*)&lex_lastline);
-}
-
-ID
-rb_intern(name)
- const char *name;
-{
- static ID last_id = LAST_TOKEN;
- int id;
- int last;
-
- if (st_lookup(sym_tbl, name, &id))
- return id;
-
- id = 0;
- switch (name[0]) {
- case '$':
- id |= ID_GLOBAL;
- break;
- case '@':
- id |= ID_INSTANCE;
- break;
- default:
- if (name[0] != '_' && !ISALPHA(name[0]) && !ismbchar(name[0])) {
- /* operator */
- 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;
- }
- 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)) {
- char *res;
- ID id2;
-
- id2 = (id & ~ID_SCOPE_MASK) | ID_LOCAL;
- res = rb_id2name(id2);
-
- if (res) {
- char *buf = ALLOCA_N(char, strlen(res)+2);
-
- strcpy(buf, res);
- strcat(buf, "=");
- rb_intern(buf);
- return rb_id2name(id);
- }
- }
- return 0;
-}
-
-int
-rb_is_const_id(id)
- ID id;
-{
- if (is_const_id(id)) return Qtrue;
- return Qfalse;
-}
-
-int
-rb_is_instance_id(id)
- ID id;
-{
- if (is_instance_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_backref_get()
-{
- if (ruby_scope->local_vars) {
- return ruby_scope->local_vars[1];
- }
- return Qnil;
-}
-
-void
-rb_backref_set(val)
- VALUE val;
-{
- if (ruby_scope->local_vars) {
- ruby_scope->local_vars[1] = val;
- }
- else {
- special_local_set('~', val);
- }
-}
-
-VALUE
-rb_lastline_get()
-{
- if (ruby_scope->local_vars) {
- return ruby_scope->local_vars[0];
- }
- return Qnil;
-}
-
-void
-rb_lastline_set(val)
- VALUE val;
-{
- if (ruby_scope->local_vars) {
- ruby_scope->local_vars[0] = val;
- }
- else {
- special_local_set('_', val);
- }
-}
diff --git a/prec.c b/prec.c
deleted file mode 100644
index e4e116c347..0000000000
--- a/prec.c
+++ /dev/null
@@ -1,81 +0,0 @@
-/************************************************
-
- prec.c -
-
- $Author$
- $Date$
- created at: Tue Jan 26 02:40:41 1999
-
- Copyright (C) 1993-1999 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)
-
-{
- rb_raise(rb_eTypeError, "undefined conversion from %s into %s",
- rb_class2name(CLASS_OF(x)), rb_class2name(module));
-}
-
-static VALUE
-prec_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);
- 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, "append_features", prec_append_features, 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 c134a9e95a..0000000000
--- a/process.c
+++ /dev/null
@@ -1,1092 +0,0 @@
-/************************************************
-
- process.c -
-
- $Author$
- $Date$
- created at: Tue Aug 10 14:30:50 JST 1993
-
- Copyright (C) 1993-1999 Yukihiro Matsumoto
-
-************************************************/
-
-#include "ruby.h"
-#include "rubysig.h"
-#include <stdio.h>
-#include <errno.h>
-#include <signal.h>
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-#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
-#ifdef HAVE_VFORK_H
-#include <vfork.h>
-#endif
-#include "st.h"
-
-#ifdef USE_CWGUSI
-# include <sys/errno.h>
-# include "macruby_missing.h"
-#endif
-
-#ifdef __EMX__
-#undef HAVE_GETPGRP
-#endif
-
-static VALUE
-get_pid()
-{
- return INT2FIX(getpid());
-}
-
-static VALUE
-get_ppid()
-{
-#ifdef NT
- return INT2FIX(0);
-#else
- return INT2FIX(getppid());
-#endif
-}
-
-VALUE rb_last_status = Qnil;
-
-#if !defined(HAVE_WAITPID) && !defined(HAVE_WAIT4)
-#define NO_WAITPID
-static st_table *pid_tbl;
-#endif
-
-static int
-rb_waitpid(pid, flags, st)
- int pid;
- int flags;
- int *st;
-{
- int result;
-#ifndef NO_WAITPID
- int oflags = flags;
- if (!rb_thread_alone()) { /* there're other threads to run */
- flags |= WNOHANG;
- }
-
- retry:
-#ifdef HAVE_WAITPID
- result = waitpid(pid, st, flags);
-#else /* HAVE_WAIT4 */
- result = wait4(pid, st, flags, NULL);
-#endif
- if (result < 0) {
- if (errno == EINTR) {
- rb_thread_schedule();
- goto retry;
- }
- return -1;
- }
- if (result == 0) {
- if (oflags & WNOHANG) return 0;
- rb_thread_schedule();
- if (rb_thread_alone()) flags = oflags;
- goto retry;
- }
-#else /* NO_WAITPID */
- if (pid_tbl && st_lookup(pid_tbl, pid, st)) {
- rb_last_status = INT2FIX(*st);
- st_delete(pid_tbl, &pid, NULL);
- return pid;
- }
-
- if (flags) {
- rb_raise(rb_eArgError, "can't do waitpid with flags");
- }
-
- for (;;) {
- result = wait(st);
- 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
- rb_last_status = INT2FIX(*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;
-}
-#endif
-
-static VALUE
-rb_f_wait()
-{
- int pid, state;
-#ifdef NO_WAITPID
- struct wait_data data;
-
- data.status = -1;
- st_foreach(pid_tbl, wait_each, &data);
- if (data.status != -1) {
- rb_last_status = data.status;
- return INT2FIX(data.pid);
- }
-
- while ((pid = wait(&state)) < 0) {
- if (errno == EINTR) {
- rb_thread_schedule();
- continue;
- }
- rb_sys_fail(0);
- }
- rb_last_status = INT2FIX(state);
-#else
- if ((pid = rb_waitpid(-1, 0, &state)) < 0)
- rb_sys_fail(0);
-#endif
- return INT2FIX(pid);
-}
-
-static VALUE
-rb_f_waitpid(obj, vpid, vflags)
- VALUE obj, vpid, vflags;
-{
- int pid, flags, status;
-
- if (NIL_P(vflags)) flags = 0;
- else flags = FIX2UINT(vflags);
-
- if ((pid = rb_waitpid(FIX2UINT(vpid), flags, &status)) < 0)
- rb_sys_fail(0);
- return INT2FIX(pid);
-}
-
-char *strtok();
-
-#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_safe_level() > 0) {
-#ifndef USE_CWGUSI
- if (rb_env_path_tainted()) {
- rb_raise(rb_eSecurityError, "Insecure PATH - %s", str);
- }
-#endif
- }
-}
-
-static int
-proc_exec_v(argv, prog)
- char **argv;
- char *prog;
-{
-#ifndef USE_CWGUSI
- 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;
-#else /* USE_CWGUSI */
- rb_notimplement();
-#endif /* USE_CWGUSI */
-}
-
-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++) {
- 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;
-{
-#ifndef USE_CWGUSI
- const char *s = str;
- char *ss, *t;
- char **argv, **a;
-
- security(str);
- for (s=str; *s; s++) {
- if (*s != ' ' && !ISALPHA(*s) && strchr("*?{}[]<>()~&|\\$;'`\"\n",*s)) {
-#if defined(MSDOS)
- int state;
- before_exec();
- state = system(str);
- after_exec();
- if (state != -1)
- exit(state);
-#else
-#if defined(__human68k__) || defined(__CYGWIN32__) || defined(__EMX__)
- char *shell = dln_find_exe("sh", 0);
- int state = -1;
- before_exec();
- if (shell)
- execl(shell, "sh", "-c", str, (char *) NULL);
- else
- state = system(str);
- after_exec();
- if (state != -1)
- exit(state);
-#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;
-#else /* USE_CWGUSI */
- rb_notimplement();
-#endif /* USE_CWGUSI */
-}
-
-#if defined(__human68k__)
-static int
-proc_spawn_v(argv, prog)
- char **argv;
- char *prog;
-{
- char *extension;
- int state;
-
- 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();
- state = spawnv(P_WAIT, prog, argv);
- after_exec();
- return state;
-}
-
-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++) {
- Check_SafeStr(argv[i]);
- args[i] = RSTRING(argv[i])->ptr;
- }
- Check_SafeStr(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 state;
-
- Check_SafeStr(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();
- state = shell?spawnl(P_WAIT,shell,"sh","-c",str,(char*)NULL):system(str);
- after_exec();
- return state;
- }
- }
- 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__ */
-
-static VALUE
-rb_f_exec(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE prog = 0;
- int i;
-
- if (argc == 0) {
- rb_raise(rb_eArgError, "wrong # 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) {
- Check_SafeStr(prog);
- }
- for (i = 0; i < argc; i++) {
- Check_SafeStr(argv[i]);
- }
- if (argc == 1 && prog == 0) {
- rb_proc_exec(RSTRING(argv[0])->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
- if (rb_iterator_p()) {
- rb_yield(Qnil);
- _exit(0);
- }
- 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;
- }
-#ifdef USE_CWGUSI
- exit(istatus);
-#else
- _exit(istatus);
-#endif
- return Qnil; /* not reached */
-}
-
-void
-rb_syswait(pid)
- int pid;
-{
- RETSIGTYPE (*hfunc)(), (*qfunc)(), (*ifunc)();
- int status;
- int i;
-
-#ifdef SIGHUP
- hfunc = signal(SIGHUP, SIG_IGN);
-#endif
-#ifdef SIGQUIT
- qfunc = signal(SIGQUIT, SIG_IGN);
-#endif
- ifunc = signal(SIGINT, SIG_IGN);
-
- do {
- i = rb_waitpid(pid, 0, &status);
- } while (i == -1 && errno == EINTR);
-
-#ifdef SIGHUP
- signal(SIGHUP, hfunc);
-#endif
-#ifdef SIGQUIT
- signal(SIGQUIT, qfunc);
-#endif
- signal(SIGINT, ifunc);
-}
-
-static VALUE
-rb_f_system(argc, argv)
- int argc;
- VALUE *argv;
-{
-#if defined(NT) || defined(__EMX__)
- VALUE cmd;
- int state;
-
- fflush(stdout);
- fflush(stderr);
- if (argc == 0) {
- rb_last_status = INT2FIX(0);
- rb_raise(rb_eArgError, "wrong # 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(" "));
-
- Check_SafeStr(cmd);
- state = do_spawn(RSTRING(cmd)->ptr);
- rb_last_status = INT2FIX(state);
-
- if (state == 0) return Qtrue;
- return Qfalse;
-#else
-#ifdef DJGPP
- VALUE cmd;
- int state;
-
- if (argc == 0) {
- rb_last_status = INT2FIX(0);
- rb_raise(rb_eArgError, "wrong # 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(" "));
-
- Check_SafeStr(cmd);
- state = system(RSTRING(cmd)->ptr);
- rb_last_status = INT2FIX(state);
-
- if (state == 0) return Qtrue;
- return Qfalse;
-#else
-#if defined(__human68k__)
- VALUE prog = 0;
- int i;
- int state;
-
- fflush(stdin);
- fflush(stdout);
- fflush(stderr);
- if (argc == 0) {
- rb_last_status = INT2FIX(0);
- rb_raise(rb_eArgError, "wrong # 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) {
- state = proc_spawn(argv[0]);
- }
- else {
- state = proc_spawn_n(argc, argv, prog);
- }
- rb_last_status = state == -1 ? INT2FIX(127) : INT2FIX(state);
- return state == 0 ? Qtrue : Qfalse;
-#else
-#if defined(USE_CWGUSI)
- rb_notimplement();
-#else
- volatile VALUE prog = 0;
- int pid;
- int i;
-
- fflush(stdout);
- fflush(stderr);
- if (argc == 0) {
- rb_last_status = INT2FIX(0);
- rb_raise(rb_eArgError, "wrong # 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) {
- Check_SafeStr(prog);
- }
- for (i = 0; i < argc; i++) {
- Check_SafeStr(argv[i]);
- }
- retry:
- switch (pid = vfork()) {
- 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 (rb_last_status == INT2FIX(0)) return Qtrue;
- return Qfalse;
-#endif /* USE_CWGUSI */
-#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 # of arguments");
- }
-
- end = time(0) - beg;
-
- return INT2FIX(end);
-}
-
-static VALUE
-proc_getpgrp(argc, argv)
- int argc;
- VALUE *argv;
-{
-#ifdef HAVE_GETPGRP
- int pgrp;
-#ifndef GETPGRP_VOID
- VALUE vpid;
- int pid;
-
- rb_scan_args(argc, argv, "01", &vpid);
- pid = NIL_P(vpid)?0:NUM2INT(vpid);
- pgrp = getpgrp(pid);
-#else
- rb_scan_args(argc, argv, "0");
- pgrp = getpgrp();
-#endif
- if (pgrp < 0) rb_sys_fail(0);
- return INT2FIX(pgrp);
-#else
- rb_notimplement();
-#endif
-}
-
-static VALUE
-proc_setpgrp(argc, argv)
- int argc;
- VALUE *argv;
-{
-#ifdef HAVE_SETPGRP
-#ifndef SETPGRP_VOID
- VALUE pid, pgrp;
- int ipid, ipgrp;
-
- rb_scan_args(argc, argv, "02", &pid, &pgrp);
-
- ipid = NIL_P(pid)?0:NUM2INT(pid);
- ipgrp = NIL_P(pgrp)?0:NUM2INT(pgrp);
- if (setpgrp(ipid, ipgrp) < 0) rb_sys_fail(0);
-#else
- rb_scan_args(argc, argv, "0");
- if (setpgrp() < 0) rb_sys_fail(0);
-#endif
- return Qnil;
-#else
- rb_notimplement();
-#endif
-}
-
-static VALUE
-proc_getpgid(obj, pid)
- VALUE obj, pid;
-{
-#ifdef HAVE_GETPGID
- int i;
-
- i = getpgid(NUM2INT(pid));
- 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 Qnil;
-#else
- rb_notimplement();
-#endif
-}
-
-static VALUE
-proc_setsid()
-{
-#ifdef HAVE_SETSID
- int pid;
-
- rb_secure(2);
- pid = setsid();
- if (pid < 0) rb_sys_fail(0);
- 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);
-
- prio = getpriority(iwhich, iwho);
- if (prio < 0) 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);
-#ifdef HAVE_SETREUID
- setreuid(uid, -1);
-#else
-#ifdef HAVE_SETRUID
- setruid(uid);
-#else
- {
- if (geteuid() == uid)
- setuid(uid);
- else
- rb_notimplement();
- }
-#endif
-#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);
-#ifdef HAS_SETRGID
- setrgid((GIDTYPE)gid);
-#else
-#ifdef HAVE_SETREGID
- setregid(gid, -1);
-#else
- {
- if (getegid() == gid)
- setgid(gid);
- else
- rb_notimplement();
- }
-#endif
-#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;
-{
-#ifdef HAVE_SETEUID
- if (seteuid(NUM2INT(euid)) < 0) rb_sys_fail(0);
-#else
-#ifdef HAVE_SETREUID
- if (setreuid(-1, NUM2INT(euid)) < 0) rb_sys_fail(0);
-#else
- euid = NUM2INT(euid);
- if (euid == getuid())
- setuid(euid);
- else
- rb_notimplement();
-#endif
-#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);
-#ifdef HAVE_SETEGID
- if (setegid(NUM2INT(egid)) < 0) rb_sys_fail(0);
-#else
-#ifdef HAVE_SETREGID
- if (setregid(-1, NUM2INT(egid)) < 0) rb_sys_fail(0);
-#else
- egid = NUM2INT(egid);
- if (egid == getgid())
- setgid(egid);
- else
- rb_notimplement();
-#endif
-#endif
- return egid;
-}
-
-VALUE rb_mProcess;
-
-void
-Init_process()
-{
-#ifndef USE_CWGUSI
- rb_define_virtual_variable("$$", get_pid, 0);
-#endif
- rb_define_readonly_variable("$?", &rb_last_status);
-#ifndef USE_CWGUSI
- rb_define_global_function("exec", rb_f_exec, -1);
-#endif
- 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
-
-#if !defined(NT)
- rb_define_singleton_method(rb_mProcess, "fork", rb_f_fork, 0);
-#endif
- rb_define_singleton_method(rb_mProcess, "exit!", rb_f_exit_bang, -1);
-#ifndef USE_CWGUSI
- rb_define_module_function(rb_mProcess, "kill", rb_f_kill, -1);
-#endif
-#ifndef NT
- rb_define_module_function(rb_mProcess, "wait", rb_f_wait, 0);
- rb_define_module_function(rb_mProcess, "waitpid", rb_f_waitpid, 2);
-
-#ifndef USE_CWGUSI
- rb_define_module_function(rb_mProcess, "pid", get_pid, 0);
- rb_define_module_function(rb_mProcess, "ppid", get_ppid, 0);
-#endif /* ifndef USE_CWGUSI */
-#endif /* ifndef NT */
-
- rb_define_module_function(rb_mProcess, "getpgrp", proc_getpgrp, -1);
- rb_define_module_function(rb_mProcess, "setpgrp", proc_setpgrp, -1);
- 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);
-}
diff --git a/random.c b/random.c
deleted file mode 100644
index 67c752d0f7..0000000000
--- a/random.c
+++ /dev/null
@@ -1,152 +0,0 @@
-/************************************************
-
- random.c -
-
- $Author$
- $Date$
- created at: Fri Dec 24 16:39:21 JST 1993
-
- Copyright (C) 1993-1999 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 */
-
-#ifdef HAVE_RANDOM
-static int first = 1;
-static char state[256];
-#endif
-
-static VALUE
-rb_f_srand(argc, argv, obj)
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- VALUE a;
- unsigned int seed, old;
- static unsigned int saved_seed;
-
- 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);
- }
-
-#ifdef HAVE_RANDOM
- if (first == 1) {
- initstate(1, state, sizeof state);
- first = 0;
- }
- else {
- setstate(state);
- }
-#endif
-
- SRANDOM(seed);
- old = saved_seed;
- saved_seed = seed;
-
- return rb_uint2inum(old);
-}
-
-static VALUE
-rb_f_rand(obj, vmax)
- VALUE obj, vmax;
-{
- long val, max;
-
- switch (TYPE(vmax)) {
- case T_FLOAT:
- if (RFLOAT(vmax)->value <= LONG_MAX && RFLOAT(vmax)->value >= LONG_MIN)
- break;
- /* fall through */
- case T_BIGNUM:
- return rb_big_rand(vmax, RANDOM_NUMBER);
- }
-
- max = NUM2LONG(vmax);
- 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 b6cda5dc1e..0000000000
--- a/range.c
+++ /dev/null
@@ -1,349 +0,0 @@
-/************************************************
-
- range.c -
-
- $Author$
- $Date$
- created at: Thu Aug 19 17:46:47 JST 1993
-
- Copyright (C) 1993-1999 Yukihiro Matsumoto
-
-************************************************/
-
-#include "ruby.h"
-
-VALUE rb_cRange;
-static ID id_cmp, id_beg, id_end;
-
-#define EXCL(r) FL_TEST((r), FL_USER1)
-#define SET_EXCL(r) FL_SET((r), FL_USER1)
-
-static VALUE
-range_check(args)
- VALUE *args;
-{
- rb_funcall(args[0], id_cmp, 1, args[1]);
- return Qnil;
-}
-
-static VALUE
-range_failed()
-{
- rb_raise(rb_eArgError, "bad value for range");
- return Qnil; /* dummy */
-}
-
-static VALUE
-range_new(klass, beg, end, exclude_end)
- VALUE klass, beg, end;
- int exclude_end;
-{
- VALUE obj;
- 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);
- }
-
- obj = rb_obj_alloc(klass);
- if (exclude_end) {
- SET_EXCL(obj);
- }
-
- rb_ivar_set(obj, id_beg, beg);
- rb_ivar_set(obj, id_end, end);
-
- return obj;
-}
-
-VALUE
-rb_range_new(beg, end, exclude_end)
- VALUE beg, end;
- int exclude_end;
-{
- return range_new(rb_cRange, beg, end, exclude_end);
-}
-
-static VALUE
-range_s_new(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- VALUE beg, end, flag;
-
- rb_scan_args(argc, argv, "21", &beg, &end, &flag);
- return range_new(klass, beg, end, RTEST(flag));
-}
-
-static VALUE
-range_exclude_end_p(range)
- VALUE range;
-{
- return EXCL(range)?Qtrue:Qfalse;
-}
-
-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 (NUM2LONG(beg) <= NUM2LONG(obj)) {
- if (EXCL(range)) {
- if (NUM2LONG(obj) < NUM2LONG(end)) return Qtrue;
- }
- else {
- if (NUM2LONG(obj) <= NUM2LONG(end)) return Qtrue;
- }
- }
- return Qfalse;
- }
- else if (RTEST(rb_funcall(beg, rb_intern("<="), 1, obj))) {
- if (EXCL(range)) {
- if (RTEST(rb_funcall(end, rb_intern(">"), 1, obj)))
- return Qtrue;
- }
- else {
- if (RTEST(rb_funcall(end, rb_intern(">="), 1, obj)))
- return Qtrue;
- }
- }
- return Qfalse;
-}
-
-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;
- ID succ = rb_intern("succ");
-
- if (EXCL(range)) {
- while (RTEST(rb_funcall(v, '<', 1, e))) {
- if (rb_equal(v, e)) break;
- rb_yield(v);
- v = rb_funcall(v, succ, 0, 0);
- }
- }
- else {
- ID le = rb_intern("<=");
-
- while (RTEST(rb_funcall(v, le, 1, e))) {
- rb_yield(v);
- if (rb_equal(v, e)) break;
- v = rb_funcall(v, 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_eIndexError, "%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));
- rb_str_cat(str, "...", EXCL(range)?3:2);
- rb_str_cat(str, RSTRING(str2)->ptr, RSTRING(str2)->len);
-
- 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));
- rb_str_cat(str, "...", EXCL(range)?3:2);
- rb_str_cat(str, RSTRING(str2)->ptr, RSTRING(str2)->len);
-
- 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 (RTEST(rb_funcall(beg, '>', 1, 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));
- }
-
- return size;
-}
-
-void
-Init_Range()
-{
- rb_cRange = rb_define_class("Range", rb_cObject);
- rb_include_module(rb_cRange, rb_mEnumerable);
- rb_define_singleton_method(rb_cRange, "new", range_s_new, -1);
- rb_define_method(rb_cRange, "===", range_eqq, 1);
- rb_define_method(rb_cRange, "each", range_each, 0);
- 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_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);
-
- id_cmp = rb_intern("<=>");
- id_beg = rb_intern("begin");
- id_end = rb_intern("end");
-}
diff --git a/re.c b/re.c
deleted file mode 100644
index 46ed3ef4a9..0000000000
--- a/re.c
+++ /dev/null
@@ -1,1324 +0,0 @@
-/************************************************
-
- re.c -
-
- $Author$
- created at: Mon Aug 9 18:24:49 JST 1993
-
- Copyright (C) 1993-1999 Yukihiro Matsumoto
-
-************************************************/
-
-#include "ruby.h"
-#include "re.h"
-
-static VALUE rb_eRegxpError;
-
-#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_str_cicmp(str1, str2)
- VALUE str1, str2;
-{
- int len, i;
- char *p1, *p2;
-
- len = MIN(RSTRING(str1)->len, RSTRING(str2)->len);
- p1 = RSTRING(str1)->ptr; p2 = RSTRING(str2)->ptr;
-
- for (i = 0; i < len; i++, p1++, p2++) {
- if (casetable[(unsigned)*p1] != casetable[(unsigned)*p2])
- return casetable[(unsigned)*p1] - casetable[(unsigned)*p2];
- }
- return RSTRING(str1)->len - RSTRING(str2)->len;
-}
-
-#define REG_CASESTATE FL_USER0
-#define REG_IGNORECASE FL_USER1
-#define REG_EXTENDED FL_USER2
-#define REG_POSIXLINE FL_USER3
-
-#define KCODE_NONE 0
-#define KCODE_EUC FL_USER4
-#define KCODE_SJIS FL_USER5
-#define KCODE_UTF8 FL_USER6
-#define KCODE_FIXED FL_USER7
-#define KCODE_MASK (KCODE_EUC|KCODE_SJIS|KCODE_UTF8)
-
-static int reg_kcode = DEFAULT_KCODE;
-
-static void
-kcode_euc(reg)
- struct RRegexp *reg;
-{
- FL_UNSET(reg, KCODE_MASK);
- FL_SET(reg, KCODE_EUC);
- FL_SET(reg, KCODE_FIXED);
-}
-
-static void
-kcode_sjis(reg)
- struct RRegexp *reg;
-{
- FL_UNSET(reg, KCODE_MASK);
- FL_SET(reg, KCODE_SJIS);
- FL_SET(reg, KCODE_FIXED);
-}
-
-static void
-kcode_utf8(reg)
- struct RRegexp *reg;
-{
- FL_UNSET(reg, KCODE_MASK);
- FL_SET(reg, KCODE_UTF8);
- FL_SET(reg, KCODE_FIXED);
-}
-
-static void
-kcode_none(reg)
- struct RRegexp *reg;
-{
- FL_UNSET(reg, KCODE_MASK);
- FL_SET(reg, KCODE_FIXED);
-}
-
-static int curr_kcode;
-
-static void
-kcode_set_option(reg)
- VALUE reg;
-{
- if (!FL_TEST(reg, KCODE_FIXED)) return;
-
- curr_kcode = RBASIC(reg)->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_mbclen2(c, re)
- unsigned char 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;
-}
-
-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 slash = 0;
-
- p = s; pend = p + len;
- while (p<pend) {
- if (*p == '/') {
- slash = 1;
- break;
- }
- p++;
- }
- if (!slash) {
- rb_str_cat(str, s, len);
- }
- else {
- p = s;
- while (p<pend) {
- if (*p == '/') {
- char c = '\\';
- rb_str_cat(str, &c, 1);
- rb_str_cat(str, p, 1);
- }
- else {
- rb_str_cat(str, p, 1);
- }
- p++;
- }
- }
-}
-
-static VALUE
-rb_reg_desc(s, len, re)
- const char *s;
- int len;
- VALUE re;
-{
- VALUE str = rb_str_new2("/");
- rb_reg_expr_str(str, s, len);
- rb_str_cat(str, "/", 1);
- if (re) {
- if (FL_TEST(re, REG_IGNORECASE))
- rb_str_cat(str, "i", 1);
- if (FL_TEST(re, REG_EXTENDED))
- rb_str_cat(str, "x", 1);
- if (FL_TEST(re, REG_POSIXLINE))
- rb_str_cat(str, "p", 1);
- if (FL_TEST(re, KCODE_FIXED)) {
- switch ((RBASIC(re)->flags & KCODE_MASK)) {
- case KCODE_NONE:
- rb_str_cat(str, "n", 1);
- break;
- case KCODE_EUC:
- rb_str_cat(str, "e", 1);
- break;
- case KCODE_SJIS:
- rb_str_cat(str, "s", 1);
- break;
- case KCODE_UTF8:
- rb_str_cat(str, "u", 1);
- break;
- }
- }
- }
- return str;
-}
-
-static VALUE
-rb_reg_source(re)
- VALUE re;
-{
- VALUE 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;
-{
- 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_eRegxpError, "%s: %s", err, RSTRING(desc)->ptr);
-}
-
-static VALUE
-rb_reg_casefold_p(re)
- VALUE re;
-{
- if (FL_TEST(re, REG_IGNORECASE)) return Qtrue;
- return Qfalse;
-}
-
-static VALUE
-rb_reg_kcode_method(re)
- VALUE re;
-{
- char *kcode = "$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:
- break;
- }
- }
-
- return rb_str_new2(kcode);
-}
-
-static Regexp*
-make_regexp(s, len, flag)
- const char *s;
- int len, flag;
-{
- 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 (flag) {
- rp->options = flag;
- }
- 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(orig)
- VALUE orig;
-{
- NEWOBJ(match, struct RMatch);
- OBJSETUP(match, rb_cMatch, T_MATCH);
-
- match->str = RMATCH(orig)->str;
- match->regs = 0;
-
- match->regs = ALLOC(struct re_registers);
- match->regs->allocated = 0;
- re_copy_registers(match->regs, RMATCH(orig)->regs);
- CLONESETUP(match, orig);
-
- return (VALUE)match;
-}
-
-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, busy)
- VALUE match;
- int busy;
-{
- if (busy) {
- FL_SET(match, MATCH_BUSY);
- }
- else {
- FL_UNSET(match, MATCH_BUSY);
- }
-}
-
-int ruby_ignorecase;
-static int may_need_recompile;
-static VALUE matchcache;
-
-static void
-rb_reg_prepare_re(reg)
- VALUE reg;
-{
- int need_recompile = 0;
-
- /* case-flag not set for the object */
- if (!FL_TEST(reg, REG_IGNORECASE)) {
- int state = FL_TEST(reg, REG_CASESTATE);
-
- if ((ruby_ignorecase || state) && !(ruby_ignorecase && state)) {
- RBASIC(reg)->flags ^= REG_CASESTATE;
- need_recompile = 1;
- }
- }
-
- if (!FL_TEST(reg, KCODE_FIXED) &&
- (RBASIC(reg)->flags & KCODE_MASK) != reg_kcode) {
- need_recompile = 1;
- RBASIC(reg)->flags &= ~KCODE_MASK;
- RBASIC(reg)->flags |= reg_kcode;
- }
-
- if (need_recompile) {
- char *err;
-
- if (FL_TEST(reg, KCODE_FIXED))
- kcode_set_option(reg);
- RREGEXP(reg)->ptr->fastmap_accurate = 0;
- err = re_compile_pattern(RREGEXP(reg)->str, RREGEXP(reg)->len, RREGEXP(reg)->ptr);
- if (err != NULL) {
- rb_reg_raise(RREGEXP(reg)->str, RREGEXP(reg)->len, err, reg);
- }
- }
-}
-
-int
-rb_reg_adjust_startpos(reg, str, pos, reverse)
- VALUE reg, str;
- int pos, reverse;
-{
- int range;
-
- if (may_need_recompile)
- rb_reg_prepare_re(reg);
-
- if (FL_TEST(reg, KCODE_FIXED))
- kcode_set_option(reg);
- else if (reg_kcode != curr_kcode)
- kcode_reset_option();
-
- if (reverse) {
- range = -pos;
- }
- else {
- range = RSTRING(str)->len - pos;
- }
- return re_adjust_startpos(RREGEXP(reg)->ptr,
- RSTRING(str)->ptr, RSTRING(str)->len,
- pos, range);
-}
-
-int
-rb_reg_search(reg, str, pos, reverse)
- VALUE reg, str;
- int pos, reverse;
-{
- int result;
- VALUE match;
- struct re_registers *regs = 0;
- int range;
-
- if (pos > RSTRING(str)->len) return -1;
-
- if (may_need_recompile)
- rb_reg_prepare_re(reg);
-
- if (FL_TEST(reg, KCODE_FIXED))
- kcode_set_option(reg);
- else if (reg_kcode != curr_kcode)
- kcode_reset_option();
-
- if (rb_thread_scope_shared_p()) {
- match = Qnil;
- }
- else {
- match = rb_backref_get();
- }
- if (NIL_P(match) || FL_TEST(match, MATCH_BUSY)) {
- if (matchcache) {
- match = matchcache;
- matchcache = 0;
- }
- else {
- match = match_alloc();
- }
- }
- regs = RMATCH(match)->regs;
-
- if (reverse) {
- range = -pos;
- }
- else {
- range = RSTRING(str)->len - pos;
- }
- result = re_search(RREGEXP(reg)->ptr,RSTRING(str)->ptr,RSTRING(str)->len,
- pos, range, regs);
-
- if (FL_TEST(reg, KCODE_FIXED))
- kcode_reset_option();
-
- if (result == -2) {
- rb_reg_raise(RREGEXP(reg)->str, RREGEXP(reg)->len,
- "Stack overfow in regexp matcher", reg);
- }
- if (result < 0) {
- matchcache = match;
- rb_backref_set(Qnil);
- }
- else {
- RMATCH(match)->str = rb_str_new4(str);
- rb_backref_set(match);
- }
-
- 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 Qfalse;
- }
- if (RMATCH(match)->BEG(nth) == -1) return Qfalse;
- return Qtrue;
-}
-
-VALUE
-rb_reg_nth_match(nth, match)
- int nth;
- VALUE match;
-{
- int start, end, len;
-
- if (NIL_P(match)) return Qnil;
- if (nth >= RMATCH(match)->regs->num_regs) {
- return Qnil;
- }
- start = RMATCH(match)->BEG(nth);
- if (start == -1) return Qnil;
- end = RMATCH(match)->END(nth);
- len = end - start;
- return rb_str_new(RSTRING(RMATCH(match)->str)->ptr + start, len);
-}
-
-VALUE
-rb_reg_last_match(match)
- VALUE match;
-{
- return rb_reg_nth_match(0, match);
-}
-
-VALUE
-rb_reg_match_pre(match)
- VALUE match;
-{
- if (NIL_P(match)) return Qnil;
- if (RMATCH(match)->BEG(0) == -1) return Qnil;
- return rb_str_new(RSTRING(RMATCH(match)->str)->ptr, RMATCH(match)->BEG(0));
-}
-
-VALUE
-rb_reg_match_post(match)
- VALUE match;
-{
- if (NIL_P(match)) return Qnil;
- if (RMATCH(match)->BEG(0) == -1) return Qnil;
- return rb_str_new(RSTRING(RMATCH(match)->str)->ptr+RMATCH(match)->END(0),
- RSTRING(RMATCH(match)->str)->len-RMATCH(match)->END(0));
-}
-
-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;
-
- for (i=0; i<regs->num_regs; i++) {
- if (regs->beg[i] == -1) rb_ary_push(ary, Qnil);
- else rb_ary_push(ary, rb_str_new(ptr+regs->beg[i],
- regs->end[i]-regs->beg[i]));
- }
- return ary;
-}
-
-static VALUE
-match_aref(argc, argv, match)
- int argc;
- VALUE *argv;
- VALUE match;
-{
- VALUE idx, rest;
- struct re_registers *regs;
- char *ptr;
- int i;
-
- 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));
- }
-
- regs = RMATCH(match)->regs;
- i = FIX2INT(idx);
-
- if (i >= regs->num_regs) return Qnil;
-
- ptr = RSTRING(RMATCH(match)->str)->ptr;
- return rb_str_new(ptr+regs->beg[i], regs->end[i]-regs->beg[i]);
-}
-
-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);
- return str;
-}
-
-static VALUE
-match_string(match)
- VALUE match;
-{
- return RMATCH(match)->str; /* str is frozen */
-}
-
-VALUE rb_cRegexp;
-
-static VALUE
-rb_reg_new_1(klass, s, len, options)
- VALUE klass;
- const char *s;
- int len;
- int options; /* CASEFOLD = 1 */
- /* EXTENDED = 2 */
- /* POSIXLINE = 4 */
- /* CODE_NONE = 8 */
- /* CODE_EUC = 16 */
- /* CODE_SJIS = 24 */
- /* CODE_UTF8 = 32 */
-{
- NEWOBJ(re, struct RRegexp);
- OBJSETUP(re, klass, T_REGEXP);
- re->ptr = 0;
- re->str = 0;
-
- if (options & RE_OPTION_IGNORECASE) {
- FL_SET(re, REG_IGNORECASE);
- }
- if (options & RE_OPTION_EXTENDED) {
- FL_SET(re, REG_EXTENDED);
- }
- if (options & RE_OPTION_POSIXLINE) {
- FL_SET(re, REG_POSIXLINE);
- }
- switch (options & ~0x7) {
- case 0:
- default:
- FL_SET(re, reg_kcode);
- break;
- case 8:
- kcode_none(re);
- break;
- case 16:
- kcode_euc(re);
- break;
- case 24:
- kcode_sjis(re);
- break;
- case 32:
- kcode_utf8(re);
- break;
- }
-
- if (options & ~0x7) {
- kcode_set_option((VALUE)re);
- }
- if (ruby_ignorecase) {
- options |= RE_OPTION_IGNORECASE;
- FL_SET(re, REG_CASESTATE);
- }
- re->ptr = make_regexp(s, len, options & 0x7);
- re->str = ALLOC_N(char, len+1);
- memcpy(re->str, s, len);
- re->str[len] = '\0';
- re->len = len;
- if (options & ~0x7) {
- kcode_reset_option();
- }
-
- return (VALUE)re;
-}
-
-VALUE
-rb_reg_new(s, len, options)
- const char *s;
- long len;
- int options;
-{
- return rb_reg_new_1(rb_cRegexp, s, len, options);
-}
-
-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;
-{
- int min;
-
- if (re1 == re2) return Qtrue;
- if (TYPE(re2) != T_REGEXP) return Qfalse;
- if (RREGEXP(re1)->len != RREGEXP(re2)->len) return Qfalse;
- min = RREGEXP(re1)->len;
- if (min > RREGEXP(re2)->len) min = RREGEXP(re2)->len;
- if (memcmp(RREGEXP(re1)->str, RREGEXP(re2)->str, min) == 0 &&
- rb_reg_cur_kcode(re1) == rb_reg_cur_kcode(re2) &&
- !(FL_TEST(re1,REG_IGNORECASE) ^ FL_TEST(re2,REG_IGNORECASE))) {
- return Qtrue;
- }
- return Qfalse;
-}
-
-VALUE
-rb_reg_match(re, str)
- VALUE re, str;
-{
- int start;
-
- if (NIL_P(str)) return Qnil;
- str = rb_str_to_str(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)
- return Qnil;
-
- start = rb_reg_search(re, line, 0, 0);
- if (start < 0) {
- return Qnil;
- }
- return INT2FIX(start);
-}
-
-static VALUE
-rb_reg_match_method(re, str)
- VALUE re, str;
-{
- VALUE result = rb_reg_match(re, str);
-
- if (NIL_P(result)) return Qnil;
- return rb_backref_get();
-}
-
-static VALUE
-rb_reg_s_new(argc, argv, self)
- int argc;
- VALUE *argv;
- VALUE self;
-{
- VALUE src;
- int flag = 0;
-
- if (argc == 0 || argc > 3) {
- rb_raise(rb_eArgError, "wrong # of argument");
- }
- if (argc >= 2) {
- if (FIXNUM_P(argv[1])) flag = FIX2INT(argv[1]);
- else if (RTEST(argv[1])) flag = RE_OPTION_IGNORECASE;
- }
- if (argc == 3) {
- char *kcode = STR2CSTR(argv[2]);
-
- switch (kcode[0]) {
- case 'n': case 'N':
- flag |= 8;
- break;
- case 'e': case 'E':
- flag |= 16;
- break;
- case 's': case 'S':
- flag |= 24;
- break;
- case 'u': case 'U':
- flag |= 32;
- break;
- default:
- break;
- }
- }
-
- src = argv[0];
- if (TYPE(src) == T_REGEXP) {
- return rb_reg_new_1(self, RREGEXP(src)->str, RREGEXP(src)->len, flag);
- }
- else {
- char *p;
- int len;
-
- p = str2cstr(src, &len);
- return rb_reg_new_1(self, p, len, flag);
- }
-}
-
-static VALUE
-rb_reg_s_quote(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE str, kcode;
- int kcode_saved = reg_kcode;
- char *s, *send, *t;
- char *tmp;
- int len;
-
- rb_scan_args(argc, argv, "11", &str, &kcode);
- if (!NIL_P(kcode)) {
- rb_set_kcode(STR2CSTR(kcode));
- curr_kcode = reg_kcode;
- reg_kcode = kcode_saved;
- }
- s = str2cstr(str, &len);
- send = s + len;
- tmp = ALLOCA_N(char, len*2);
- t = tmp;
-
- for (; s != send; s++) {
- if (ismbchar(*s)) {
- size_t n = mbclen(*s);
-
- while (n--)
- *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();
-
- return rb_str_new(tmp, t - 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;
-{
- int kcode = 0;
-
- switch (RBASIC(re)->flags & KCODE_MASK) {
- case KCODE_NONE:
- kcode |= 4; break;
- case KCODE_EUC:
- kcode |= 8; break;
- case KCODE_SJIS:
- kcode |= 12; break;
- case KCODE_UTF8:
- kcode |= 16; break;
- default:
- break;
- }
-
- return kcode;
-}
-
-int
-rb_reg_options(re)
- VALUE re;
-{
- int options = 0;
-
- if (FL_TEST(re, REG_IGNORECASE))
- options |= RE_OPTION_IGNORECASE;
- if (FL_TEST(re, KCODE_FIXED)) {
- options |= rb_reg_get_kcode(re);
- }
- return options;
-}
-
-static VALUE
-rb_reg_clone(orig)
- VALUE orig;
-{
- VALUE reg;
-
- reg = rb_reg_new_1(CLASS_OF(orig), RREGEXP(orig)->str, RREGEXP(orig)->len,
- rb_reg_options(orig));
- CLONESETUP(reg, orig);
- return reg;
-}
-
-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_new(p, ss-p);
- else rb_str_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_cat(val, RSTRING(src)->ptr, BEG(0));
- continue;
-
- case '\'':
- rb_str_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_cat(val, s-1, 1);
- continue;
-
- default:
- rb_str_cat(val, s-2, 2);
- continue;
- }
-
- if (no >= 0) {
- if (BEG(no) == -1) continue;
- rb_str_cat(val, RSTRING(src)->ptr+BEG(no), END(no)-BEG(no));
- }
- }
-
- if (p < e) {
- if (!val) val = rb_str_new(p, e-p);
- else rb_str_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)
- struct RString *val;
-{
- may_need_recompile = 1;
- rb_set_kcode(STR2CSTR(val));
-}
-
-static VALUE
-ignorecase_getter()
-{
- return ruby_ignorecase?Qtrue:Qfalse;
-}
-
-static void
-ignorecase_setter(val)
- VALUE val;
-{
- may_need_recompile = 1;
- ruby_ignorecase = RTEST(val);
-}
-
-static VALUE
-match_getter()
-{
- VALUE match = rb_backref_get();
-
- if (NIL_P(match)) return Qnil;
- return match_clone(match);
-}
-
-static void
-match_setter(val)
- VALUE val;
-{
- Check_Type(val, T_MATCH);
- rb_backref_set(val);
-}
-
-void
-Init_Regexp()
-{
- rb_eRegxpError = rb_define_class("RegxpError", 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, "new", rb_reg_s_new, -1);
- rb_define_singleton_method(rb_cRegexp, "compile", rb_reg_s_new, -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_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_method, 1);
- 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, "kcode", rb_reg_kcode_method, 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, "POSIXLINE", INT2FIX(RE_OPTION_POSIXLINE));
-
- rb_global_variable(&reg_cache);
- rb_global_variable(&matchcache);
-
- rb_cMatch = rb_define_class("MatchingData", rb_cObject);
- 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, "[]", match_aref, -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, "string", match_string, 0);
- rb_define_method(rb_cMatch, "inspect", rb_any_to_s, 0);
-}
diff --git a/re.h b/re.h
deleted file mode 100644
index 2ce2134ccc..0000000000
--- a/re.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/************************************************
-
- re.h -
-
- $Author$
- $Date$
- created at: Thu Sep 30 14:18:32 JST 1993
-
- Copyright (C) 1993-1999 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))
-
-int rb_str_cicmp _((VALUE, VALUE));
-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));
-
-int rb_kcode _((void));
-
-extern int ruby_ignorecase;
-
-int rb_mbclen2 _((unsigned char, VALUE));
-#define mbclen2(c,re) rb_mbclen2((c),(re))
-#endif
diff --git a/regex.c b/regex.c
deleted file mode 100644
index ea08cb5ede..0000000000
--- a/regex.c
+++ /dev/null
@@ -1,4334 +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 COPYING.LIB. 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 RUBY_PLATFORM
-# define RUBY
-#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
-
-#ifndef __STDC__
-# define volatile
-#endif
-
-#ifdef HAVE_PROTOTYPES
-# define _(args) args
-#else
-# define _(args) ()
-#endif
-
-#ifndef xmalloc
-void *xmalloc _((unsigned long));
-void *xcalloc _((unsigned long,unsigned long));
-void *xrealloc _((void*,unsigned long));
-void free _((void*));
-#endif
-
-/* #define NO_ALLOCA */ /* try it out for now */
-#ifndef NO_ALLOCA
-/* 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>
-# else
-char *alloca();
-# endif
-#endif /* __GNUC__ */
-
-#ifdef _AIX
-#pragma alloca
-#endif
-
-#ifdef HAVE_STRING_H
-# include <string.h>
-#else
-# include <strings.h>
-#endif
-
-#define RE_ALLOCATE alloca
-#ifdef C_ALLOCA
-#define FREE_VARIABLES() alloca(0)
-#else
-#define FREE_VARIABLES()
-#endif
-
-#define FREE_AND_RETURN_VOID(stackb) return
-#define FREE_AND_RETURN(stackb,val) return(val)
-#define DOUBLE_STACK(stackx,stackb,len,type) \
- (stackx = (type*)alloca(2 * len * sizeof(type)), \
- /* Only copy what is in use. */ \
- (type*)memcpy(stackx, stackb, len * sizeof (type)))
-#else /* NO_ALLOCA defined */
-
-#define RE_ALLOCATE xmalloc
-
-#define FREE_VAR(var) do { if (var) free(var); var = NULL; } while(0)
-#define FREE_VARIABLES()
-
-#define FREE_AND_RETURN_VOID(stackb) do { free(stackb); return; } while(0)
-#define FREE_AND_RETURN(stackb,val) do { free(stackb); return(val); } while(0)
-#define DOUBLE_STACK(stackx,stackb,len,type) \
- (type*)xrealloc(stackb, 2 * len * sizeof(type))
-#endif /* NO_ALLOCA */
-
-#define RE_TALLOC(n,t) ((t*)RE_ALLOCATE((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(stackx,stackb,len) \
- do { \
- /* Roughly double the size of the stack. */ \
- stackx = DOUBLE_STACK(stackx,stackb,len,unsigned char*); \
- /* Rearrange the pointers. */ \
- stackp = stackx + (stackp - stackb); \
- stackb = stackx; \
- stacke = stackb + 2 * len; \
- } 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 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. */
- 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. */
- posix_on, /* Turn on POSIXified line match (match with newlines). */
- posix_off, /* Turn off POSIXified line match. */
- 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. */
- 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 80
-#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) \
- ((c<0x100)?(c):((current_mbctype != MBCTYPE_UTF8)?(((c)>>8)&0xff):utf8_firstbyte(c)))
-
-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 long c;
-{
- if (current_mbctype == MBCTYPE_UTF8) {
- if (c < 0x80)
- printf("%c", c);
- else if (c <= 0x7ff)
- printf("%c%c", utf8_firstbyte(c), c&0x3f);
- else if (c <= 0xffff)
- printf("%c%c%c", utf8_firstbyte(c), (c>>6)&0x3f, c&0x3f);
- else if (c <= 0x1fffff)
- printf("%c%c%c%c", utf8_firstbyte(c), (c>>12)&0x3f, (c>>6)&0x3f, c&0x3f);
- else if (c <= 0x3ffffff)
- printf("%c%c%c%c%c", utf8_firstbyte(c), (c>>18)&0x3f, (c>>12)&0x3f, (c>>6)&0x3f, c&0x3f);
- else if (c <= 0x7fffffff)
- printf("%c%c%c%c%c%c", utf8_firstbyte(c), (c>>24)&0x3f, (c>>18)&0x3f, (c>>12)&0x3f, (c>>6)&0x3f, c&0x3f);
- }
- else if (c < 0xff) {
- printf("\\%o", c);
- }
- else {
- printf("%c%c", c>>BYTEWIDTH, 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 long)((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 long)((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 posix_on:
- printf("/posix_on");
- break;
-
- case posix_off:
- printf("/posix_off");
- 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 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;
-
- 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 push_dummy_failure:
- case start_paren:
- case stop_paren:
- case posix_on:
- case posix_off:
- 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 -= 3;
- 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 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 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;
-}
-
-/* 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;
- const char *p0;
- int numlen;
-
- /* 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 *stackb = RE_TALLOC(40, int);
- int *stackp = stackb;
- int *stacke = stackb + 40;
- int *stackt;
-
- /* 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;
- bufp->stclass = 0;
-
- /* Initialize the syntax table. */
- init_syntax_once();
-
- if (bufp->allocated == 0) {
- bufp->allocated = INIT_BUF_SIZE;
- if (bufp->buffer)
- /* EXTEND_BUFFER loses when bufp->allocated is 0. */
- bufp->buffer = (char*)xrealloc (bufp->buffer, INIT_BUF_SIZE);
- else
- /* Caller did not allocate a buffer. Do it for them. */
- bufp->buffer = (char*)xmalloc(INIT_BUF_SIZE);
- if (!bufp->buffer) goto memory_exhausted;
- begalt = b = bufp->buffer;
- }
-
- while (p != pend) {
- PATFETCH(c);
-
- switch (c) {
- case '$':
- if (bufp->options & RE_OPTION_POSIXLINE) {
- 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_POSIXLINE)
- BUFPUSH(begbuf);
- else
- BUFPUSH(begline);
- break;
-
- case '+':
- case '?':
- case '*':
- /* If there is no previous pattern, char not special. */
- if (!laststart) {
- goto invalid_pattern;
- }
- /* 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)
- goto invalid_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;
-
- /* charset_not matches newline according to a syntax bit. */
- if ((enum regexpcode)b[-2] == charset_not) {
- if (bufp->options & RE_OPTION_POSIXLINE)
- SET_LIST_BIT ('\n');
- }
-
- /* 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:
- PATFETCH(c);
-
- if (c == ']') {
- if (p == p0 + 1) {
- if (p == pend)
- goto invalid_pattern;
- }
- 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 != ']')
- goto invalid_pattern;
- if (ismbchar(c)) {
- PATFETCH_MBC(c);
- had_mbchar++;
- }
-
- /* \ 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);
- }
- 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);
- }
- last = -1;
- continue;
-
- case 's':
- for (c = 0; c < 256; c++)
- if (ISSPACE(c))
- SET_LIST_BIT(c);
- 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);
- last = -1;
- continue;
-
- case 'd':
- for (c = '0'; c <= '9'; c++)
- SET_LIST_BIT(c);
- 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);
- 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;
-
- 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)
- goto invalid_pattern;
-
- 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))
- goto invalid_pattern;
-
- /* Throw away the ] at the end of the character class. */
- PATFETCH (c);
-
- if (p == pend)
- goto invalid_pattern;
-
- 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 '(':
- PATFETCH(c);
- if (c == '?') {
- int negative = 0;
- PATFETCH_RAW(c);
- switch (c) {
- case 'x': case 'p': 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) {
- options &= ~RE_OPTION_POSIXLINE;
- BUFPUSH(posix_off);
- }
- }
- else if (!(options&RE_OPTION_POSIXLINE)) {
- options |= RE_OPTION_POSIXLINE;
- BUFPUSH(posix_on);
- }
- break;
- case 'i':
- if (negative) {
- if (options&RE_OPTION_IGNORECASE) {
- options &= ~RE_OPTION_IGNORECASE;
- BUFPUSH(casefold_off);
- }
- }
- else if (!(options&RE_OPTION_IGNORECASE)) {
- options |= RE_OPTION_IGNORECASE;
- BUFPUSH(casefold_on);
- }
- 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 '!':
- break;
-
- default:
- FREE_AND_RETURN(stackb, "undefined (?...) sequence");
- }
- }
- else {
- PATUNFETCH;
- c = '(';
- }
- if (c == '#') break;
- if (stackp+8 >= stacke) {
- int *stackx;
- unsigned int len = stacke - stackb;
-
- stackx = DOUBLE_STACK(stackx,stackb,len,int);
- /* Rearrange the pointers. */
- stackp = stackx + (stackp - stackb);
- stackb = stackx;
- stacke = stackb + 2 * len;
- }
-
- /* 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 '!':
- 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;
- }
- *stackp++ = c;
- *stackp++ = options;
- fixup_alt_jump = 0;
- laststart = 0;
- begalt = b;
- break;
-
- case ')':
- if (stackp == stackb)
- FREE_AND_RETURN(stackb, "unmatched )");
- if ((options ^ stackp[-1]) & RE_OPTION_IGNORECASE) {
- BUFPUSH((options&RE_OPTION_IGNORECASE)?casefold_off:casefold_on);
- }
- if ((options ^ stackp[-1]) & RE_OPTION_POSIXLINE) {
- BUFPUSH((options&RE_OPTION_POSIXLINE)?posix_off:posix_on);
- }
- 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);
- }
- 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_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 || p == pend) {
- goto invalid_pattern;
- }
-
- 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 cound 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) goto invalid_pattern;
- /* 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_POSIXLINE) == 0) {
- BUFPUSH(endbuf2);
- break;
- }
- /* fall through */
- case 'z':
- BUFPUSH(endbuf);
- 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, 3, &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':
- {
- const char *p_save;
-
- PATUNFETCH;
- p_save = p;
-
- had_mbchar = 0;
- c1 = 0;
- GET_UNSIGNED_NUMBER(c1);
- if (!ISDIGIT(c)) PATUNFETCH;
-
- if (c1 >= regnum) {
- /* need to get octal */
- p = p_save;
- c = scan_oct(p_save, 3, &numlen) & 0xff;
- p = p_save + numlen;
- c1 = 0;
- had_num_literal = 1;
- goto numeric_char;
- }
- }
-
- /* Can't back reference to a subexpression if inside of it. */
- for (stackt = stackp - 2; stackt > stackb; stackt -= 5)
- if (*stackt == c1)
- goto normal_char;
- laststart = b;
- BUFPUSH(duplicate);
- BUFPUSH(c1);
- break;
-
- 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;
- }
- else if (*laststart == on_failure_jump) {
- int mcnt;
-
- laststart++;
- EXTRACT_NUMBER_AND_INCR(mcnt, laststart);
- if (mcnt == 4 && *laststart == anychar) {
- switch ((enum regexpcode)laststart[1]) {
- case jump_n:
- case finalize_jump:
- case maybe_finalize_jump:
- case jump:
- case jump_past_alt:
- case dummy_failure_jump:
- bufp->options |= RE_OPTIMIZE_ANCHOR;
- break;
- }
- }
- else if (*laststart == charset || *laststart == charset_not) {
- p0 = laststart;
- mcnt = *++p0;
- p0 += mcnt+1;
- mcnt = EXTRACT_UNSIGNED_AND_INCR(p0);
- p0 += 8*mcnt;
- if (*p0 == maybe_finalize_jump) {
- bufp->stclass = laststart;
- }
- }
- }
- }
-
- 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;
- }
- }
- else {
- 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");
-}
-
-void
-re_free_pattern(bufp)
- struct re_pattern_buffer *bufp;
-{
- free(bufp->buffer);
- free(bufp->fastmap);
- if (bufp->must_skip) free(bufp->must_skip);
-
- free(bufp->regstart);
- free(bufp->regend);
- free(bufp->old_regstart);
- free(bufp->old_regend);
- free(bufp->best_regstart);
- free(bufp->best_regend);
- free(bufp->reg_info);
- free(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 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 **stackb = RE_TALLOC(NFAILURES, unsigned char*);
- 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 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 posix_on:
- case posix_off:
- options ^= RE_OPTION_POSIXLINE;
- continue;
-
- case endline:
- if (TRANSLATE_P())
- fastmap[translate['\n']] = 1;
- else
- fastmap['\n'] = 1;
- if ((options & RE_OPTION_POSIXLINE) == 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:
- 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) {
- unsigned char **stackx;
- unsigned int len = stacke - stackb;
-
- EXPAND_FAIL_STACK(stackx, stackb, len);
- }
- *++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;
- fastmap['\n'] = 1;
- case anychar_repeat:
- case anychar:
- for (j = 0; j < (1 << BYTEWIDTH); j++) {
- if (j != '\n' || (options & RE_OPTION_POSIXLINE))
- 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]);
- beg = WC2MBC1ST(cc);
- if (cc < 0xff) {
- num_literal = 1;
- while (c <= beg) {
- if (ismbchar(c))
- fastmap[c] = 1;
- c++;
- }
- }
- c = beg + 1;
- }
-
- 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 = 0;
-
- if (range > 0) {
- while (i<size) {
- i += mbclen(string[i]);
- if (startpos <= i) {
- startpos = i;
- break;
- }
- }
- }
- else {
- int w;
-
- while (i<size) {
- w = mbclen(string[i]);
- if (startpos < i + w) {
- startpos = i;
- break;
- }
- i += w;
- }
- }
- }
- 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 if (re_match(bufp, string, size, 0, regs) >= 0)
- return 0;
- return -1;
- }
- break;
-
- case begline:
- anchor = 1;
- break;
-
- default:
- break;
- }
- }
- if (bufp->options & RE_OPTIMIZE_ANCHOR) {
- if (bufp->options&RE_OPTION_POSIXLINE) {
- 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;
- }
- }
-
- 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 && 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++;
- }
- }
- else if (fastmap && (bufp->stclass)) {
- register unsigned char *p;
- unsigned long c;
- int irange = range;
-
- p = (unsigned char*)string+startpos;
- while (range > 0) {
- c = *p++;
- if (ismbchar(c) && fastmap[c] != 2) {
- MBC2WC(c, p);
- }
- else if (MAY_TRANSLATE())
- c = translate[c];
- if (*bufp->stclass == charset) {
- if (!is_in_list(c, bufp->stclass+1)) break;
- }
- else {
- if (is_in_list(c, bufp->stclass+1)) break;
- }
- range--;
- if (c > 256) range--;
- }
- startpos += irange - range;
- }
- }
-
- 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
-
-/* Individual items aside from the registers. */
-#define NUM_NONREG_ITEMS 3
-
-/* 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_REG_ITEMS)
-
-
-/* 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; \
- \
- if (stacke - stackp <= NUM_FAILURE_ITEMS) { \
- unsigned char **stackx; \
- unsigned int len = stacke - stackb; \
- /* if (len > re_max_failures * MAX_NUM_FAILURE_ITEMS) \
- { \
- FREE_VARIABLES(); \
- FREE_AND_RETURN(stackb,(-2)); \
- }*/ \
- \
- /* Roughly double the size of the stack. */ \
- EXPAND_FAIL_STACK(stackx, stackb, len); \
- } \
- \
- /* 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*)0; /* non-greedy flag */ \
- } while(0)
-
-#define NON_GREEDY ((unsigned char*)1)
-
- /* 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. */ \
- } 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)): \
- ((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);
- }
- 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 **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;
-
- if (regs) {
- init_regs(regs, num_regs);
- }
-
- /* Initialize the stack. */
- stackb = RE_TALLOC(MAX_NUM_FAILURE_ITEMS * NFAILURES, unsigned char*);
- stackp = stackb;
- stacke = &stackb[MAX_NUM_FAILURE_ITEMS * NFAILURES];
-
-#ifdef DEBUG_REGEX
- fprintf(stderr, "Entering re_match(%s%s)\n", string1_arg, string2_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_VARIABLES();
- 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;
-
- if (IS_ACTIVE(reg_info[regno])) break;
-
- /* Where in input to try to start matching. */
- d2 = regstart[regno];
- if (REG_UNSET(d2)) break;
-
- /* 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)) break;
- 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_VARIABLES();
- 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[-2];
- 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_POSIXLINE) &&
- (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_POSIXLINE) &&
- (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 (*(p - 1) == (unsigned char)charset_not) {
- not = !not;
- }
- else if (!not && cc != c) {
- part = not = is_in_list(cc, p);
- }
- 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. */
-
- 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 pop_failure_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[-2] == d) {
- p = stackp[-3];
- 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[-2] == d) /* avoid infinit 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;
- STORE_NUMBER_AND_INCR(p, mcnt);
- PUSH_FAILURE_POINT(0, 0);
- }
- else if (mcnt == 0) {
- p[2] = unused;
- p[3] = unused;
- goto on_failure;
- }
- continue;
-
- case jump_n:
- EXTRACT_NUMBER(mcnt, p + 2);
- /* Originally, this is how many times we CAN jump. */
- if (mcnt) {
- mcnt--;
- 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[-2] == d) /* avoid infinit 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 posix_on:
- options |= RE_OPTION_POSIXLINE;
- continue;
-
- case posix_off:
- options &= ~RE_OPTION_POSIXLINE;
- continue;
-
- case wordbound:
- if (AT_STRINGS_BEG(d)) {
- if (IS_A_LETTER(d)) break;
- else goto fail;
- }
- if (AT_STRINGS_BEG(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;
- c = *d++;
- if (*p == 0xff) {
- p++;
- if (!--mcnt
- || AT_STRINGS_END(d)
- || (unsigned char)*d++ != (unsigned char)*p++)
- goto fail;
- continue;
- }
- 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;
- }
- 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[-3] == 0 || (best_regs_set && stackp[-1] == NON_GREEDY)) {
- POP_FAILURE_POINT();
- goto fail;
- }
- stackp--; /* discard flag */
- 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;
- }
- 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. */
- pop_loop:
- 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);
- p1 += mcnt;
-
- if (p1 >= pend) break;
- 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_VARIABLES();
- 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) free(regs->beg);
- if (regs->end) free(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, 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,
- 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-0xFF */
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 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, 1, 1, 1
-};
-
-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;
- }
-}
diff --git a/regex.h b/regex.h
deleted file mode 100644
index 2386d2daa8..0000000000
--- a/regex.h
+++ /dev/null
@@ -1,221 +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 COPYING.LIB. 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 . and invert charclass matches */
-#define RE_OPTION_POSIXLINE (RE_OPTION_EXTENDED<<1)
-/* search for longest match, in accord with POSIX regexp */
-#define RE_OPTION_LONGEST (RE_OPTION_POSIXLINE<<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
-
-extern 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 */
- char *stclass; /* Pointer to character class list at top */
- 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 NeXT
-#define re_match rre_match
-#endif
-
-#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 3c71b9c0be..0000000000
--- a/ruby.1
+++ /dev/null
@@ -1,291 +0,0 @@
-.\"Ruby is copyrighted by Yukihiro Matsumoto <matz@netlab.co.jp>.
-.na
-.TH RUBY 1 "ruby 1.5" "5/Nov/99" "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 -X "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) code-set.
-.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 -X 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.co.jp>.
diff --git a/ruby.c b/ruby.c
deleted file mode 100644
index 50e425b562..0000000000
--- a/ruby.c
+++ /dev/null
@@ -1,1009 +0,0 @@
-/************************************************
-
- ruby.c -
-
- $Author$
- $Date$
- created at: Tue Aug 10 12:47:31 JST 1993
-
- Copyright (C) 1993-1999 Yukihiro Matsumoto
-
-************************************************/
-
-#ifdef _WIN32
-#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
-
-#ifdef USE_CWGUSI
-#include "macruby_missing.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;
-# ifndef strdup
-char *strdup();
-# endif
-
-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",
-"-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 enables verbose mode",
-"-w turn warnings on for compilation of your script",
-"-x[directory] strip off text before #!ruby line and perhaps cd to directory",
-"-Xdirectory cd to directory, before executing your script",
-"--copyright print the copyright",
-"--version print the version",
-"\n",
-NULL
-};
- char **p = usage_msg;
-
- printf("\nUsage: %s [switches] [--] [programfile] [arguments]", name);
- while (*p)
- printf("\n %s", *p++);
-}
-
-#ifndef RUBY_LIB
-#define RUBY_LIB "/usr/local/lib/ruby"
-#endif
-#ifndef RUBY_SITE_LIB
-#define RUBY_SITE_LIB "/usr/local/lib/site_ruby"
-#endif
-
-extern VALUE rb_load_path;
-
-#define STATIC_FILE_LENGTH 255
-
-#if defined(_WIN32) || defined(DJGPP)
-static char *
-rubylib_mangle(s, l)
- char *s;
- unsigned int l;
-{
- static char *newp, *oldp;
- static int newl, oldl, notfound;
- static char ret[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(ret, newp);
- s = ret;
- while (*s) {
- if (*s == '\\') *s = '/';
- s++;
- }
- } else {
- notfound = 1;
- }
- }
- if (!newp) {
- return s;
- }
- if (l == 0) {
- l = strlen(s);
- }
- if (l < oldl || strncasecmp(oldp, s, oldl) != 0) {
- return s;
- }
- if (l + newl - oldl > STATIC_FILE_LENGTH || newl > STATIC_FILE_LENGTH) {
- rb_fatal("malformed RUBYLIB_PREFIX");
- }
- strcpy(ret + newl, s + oldl);
- return ret;
-}
-#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
-
-static void
-addpath(path)
- const char *path;
-{
- const char sep = PATH_SEP_CHAR;
-
- if (path == 0) return;
-#if defined(__CYGWIN32__)
- {
- 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_load_path = rb_ary_plus(ary, rb_load_path);
- }
- else {
- rb_ary_unshift(rb_load_path, rubylib_mangled_path2(path));
- }
-}
-
-struct req_list {
- const char *name;
- struct req_list *next;
-} req_list_head;
-struct req_list *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 = mod;
- list->next = 0;
- req_list_last->next = list;
- req_list_last = list;
-}
-
-void
-require_libraries()
-{
- extern NODE *ruby_eval_tree;
- char *orig_sourcefile = ruby_sourcefile;
- NODE *save;
- struct req_list *list = req_list_head.next;
- struct req_list *tmp;
-
- ruby_sourcefile = 0;
- save = ruby_eval_tree;
- req_list_last = 0;
- while (list) {
- rb_require(list->name);
- tmp = list->next;
- free(list);
- list = tmp;
- }
- ruby_eval_tree = save;
- ruby_sourcefile = orig_sourcefile;
-}
-
-extern void Init_ext _((void));
-
-static void
-process_sflag()
-{
- if (sflag) {
- int n;
- VALUE *args;
-
- n = RARRAY(rb_argv)->len;
- args = RARRAY(rb_argv)->ptr;
- while (n > 0) {
- char *s = STR2CSTR(*args++);
- 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 **argvp = argv;
- 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;
-
- version = Qfalse;
- 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':
- 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_cat(e_script, s, strlen(s));
- rb_str_cat(e_script, "\n", 1);
- 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 'X':
- s++;
- if (!*s) {
- s = argv[1];
- argc--,argv++;
- }
- if (*s && 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)
- addpath(s);
- else if (argv[1]) {
- addpath(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]) {
- argc--,argv++;
- goto switch_end;
- }
- s++;
- if (strcmp("copyright", s) == 0)
- copyright = 1;
- else if (strcmp("debug", s) == 0)
- ruby_debug = 1;
- 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 (e_script) {
- argc++, argv--;
- argv[0] = script;
- }
-
- if (version) {
- ruby_show_version();
- exit(0);
- }
- if (copyright) {
- ruby_show_copyright();
- }
-
- if (!e_script && argc == 0) { /* no more args */
- if (verbose) exit(0);
- script = "-";
- }
- else {
- 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];
- }
- }
- argc--; argv++;
- }
-
- ruby_script(script);
- ruby_set_argv(argc, argv);
- process_sflag();
-
- Init_ext(); /* should be called here for some reason :-( */
- require_libraries();
-
- ruby_sourcefile = argv0;
- if (e_script) {
- 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;
-}
-
-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_raise(rb_eLoadError, "No such file to load -- %s", fname);
- }
- fclose(fp);
-
- f = rb_file_open(fname, "r");
- }
-
- if (script) {
- VALUE c;
- 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);
- 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 */
-#ifndef USE_CWGUSI
- 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);
-#endif
- ruby_sourcefile = 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);
- }
- }
- 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);
- }
-}
-
-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");
-#ifndef __hpux
- if (len == 0) {
- s = origargv[0];
- s += strlen(s);
- /* See if all the arguments are contiguous in memory */
- for (i = 1; i < origargc; i++) {
- if (origargv[i] == s + 1)
- s += strlen(++s); /* this one is ok too */
- }
- len = s - origargv[0];
- }
-#endif
- s = rb_str2cstr(val, &i);
-#ifndef __hpux
- if (i > len) {
- memcpy(origargv[0], s, len);
- origargv[0][len] = '\0';
- }
- else {
- memcpy(origargv[0], s, i);
- s = origargv[0]+i;
- *s++ = '\0';
- while (++i < len)
- *s++ = ' ';
- }
- rb_progname = rb_tainted_str_new2(origargv[0]);
-#else
- 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);
-#endif
-}
-
-void
-ruby_script(name)
- char *name;
-{
- if (name) {
- rb_progname = rb_tainted_str_new2(name);
- ruby_sourcefile = 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);
-}
-
-#if defined(_WIN32) || defined(DJGPP)
-static char *
-ruby_libpath()
-{
- static char libpath[FILENAME_MAX+1];
- char *p;
-#if defined(_WIN32)
- GetModuleFileName(NULL, libpath, sizeof libpath);
-#elif defined(DJGPP)
- extern char *__dos_argv0;
- strcpy(libpath, __dos_argv0);
-#endif
- p = strrchr(libpath, '\\');
- if (p) {
- *p = 0;
- if (!strcasecmp(p-4, "\\bin"))
- p -= 4;
- } else {
- strcpy(libpath, ".");
- p = libpath + 1;
- }
-
- strcpy(p, "\\lib");
-#if defined(__CYGWIN32__)
- p = (char *)malloc(strlen(libpath)+10);
- if (!p)
- return 0;
- cygwin32_conv_to_posix_path(libpath, p);
- strcpy(libpath, p);
- free(p);
-#else
- for (p = libpath; *p; p++)
- if (*p == '\\')
- *p = '/';
-#endif
- return libpath;
-}
-#endif
-
-void
-ruby_prog_init()
-{
- init_ids();
-
- ruby_sourcefile = "ruby";
- rb_define_variable("$VERBOSE", &ruby_verbose);
- rb_define_variable("$-v", &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);
-
- if (rb_safe_level() == 0) {
- addpath(".");
- }
-
- addpath(RUBY_LIB);
-#if defined(_WIN32) || defined(DJGPP)
- addpath(ruby_libpath());
-#endif
-
-#ifdef RUBY_ARCHLIB
- addpath(RUBY_ARCHLIB);
-#endif
-#ifdef RUBY_THIN_ARCHLIB
- addpath(RUBY_THIN_ARCHLIB);
-#endif
-
- addpath(RUBY_SITE_LIB);
-#ifdef RUBY_SITE_ARCHLIB
- addpath(RUBY_SITE_ARCHLIB);
-#endif
-#ifdef RUBY_SITE_THIN_ARCHLIB
- addpath(RUBY_SITE_THIN_ARCHLIB);
-#endif
-
-#ifdef RUBY_SEARCH_PATH
- addpath(RUBY_SEARCH_PATH);
-#endif
-
- if (rb_safe_level() == 0) {
- addpath(getenv("RUBYLIB"));
- }
-
- 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
- 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 fd87c0bcb2..0000000000
--- a/ruby.h
+++ /dev/null
@@ -1,562 +0,0 @@
-/************************************************
-
- ruby.h -
-
- $Author$
- created at: Thu Jun 10 14:26:32 JST 1993
-
- Copyright (C) 1993-1999 Yukihiro Matsumoto
-
-*************************************************/
-
-#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 */
-#undef ISPRINT
-#define ISPRINT(c) isprint((unsigned char)(c))
-#define ISSPACE(c) isspace((unsigned char)(c))
-#define ISUPPER(c) isupper((unsigned char)(c))
-#define ISLOWER(c) islower((unsigned char)(c))
-#define ISALNUM(c) isalnum((unsigned char)(c))
-#define ISALPHA(c) isalpha((unsigned char)(c))
-#define ISDIGIT(c) isdigit((unsigned char)(c))
-#define ISXDIGIT(c) isxdigit((unsigned char)(c))
-
-#ifndef __STDC__
-# define volatile
-#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 HAVE_ATTR_NORETURN
-# define NORETURN __attribute__ ((noreturn))
-#else
-# define NORETURN
-#endif
-
-#if defined(HAVE_ALLOCA_H) && !defined(__GNUC__)
-#include <alloca.h>
-#endif
-
-#if defined(__CYGWIN32__)
-#if defined(USEIMPORTLIB)
-#include "import.h"
-#else
-#if !defined(__CYGWIN__)
-#define environ (*__imp___cygwin_environ)
-#endif
-#endif
-#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
-
-#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)
-VALUE rb_int2inum _((long));
-#define INT2NUM(v) rb_int2inum(v)
-VALUE rb_uint2inum _((unsigned long));
-#define UINT2NUM(v) rb_uint2inum(v)
-
-#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))
-
-/* special contants - i.e. non-zero and non-fixnum constants */
-#define Qfalse 0
-#define Qtrue 2
-#define Qnil 4
-
-#define RTEST(v) rb_test_false_or_nil((VALUE)(v))
-#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_VARMAP 0x7d
-#define T_SCOPE 0x7e
-#define T_NODE 0x7f
-
-#define T_MASK 0x7f
-
-#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)
-void rb_check_safe_str _((VALUE));
-#define Check_SafeStr(v) rb_check_safe_str((VALUE)(v))
-void rb_secure _((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)NUM2ULONG(x))
-#define FIX2UINT(x) ((unsigned int)FIX2ULONG(x))
-#else
-#define NUM2INT(x) NUM2LONG(x)
-#define NUM2UINT(x) NUM2ULONG(x)
-#define FIX2INT(x) FIX2LONG(x)
-#define FIX2UINT(x) FIX2ULONG(x)
-#endif
-
-double rb_num2dbl _((VALUE));
-#define NUM2DBL(x) rb_num2dbl((VALUE)(x))
-
-char *rb_str2cstr _((VALUE,int*));
-#define str2cstr(x,l) rb_str2cstr((VALUE)(x),(l))
-#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)->klass = (c);\
- RBASIC(obj)->flags = (t);\
- 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_clone_generic_ivar((VALUE)clone,(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;
-};
-
-struct RString {
- struct RBasic basic;
- long len;
- char *ptr;
- VALUE orig;
-};
-
-struct RArray {
- struct RBasic basic;
- long len, capa;
- 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)
-
-VALUE rb_data_object_alloc _((VALUE,void*,void (*) _((void*)),void (*) _((void*))));
-#define Data_Make_Struct(klass,type,mark,free,sval) (\
- sval = ALLOC(type),\
- memset(sval, 0, sizeof(type)),\
- rb_data_object_alloc(klass,sval,mark,free)\
-)
-
-#define Data_Wrap_Struct(klass,mark,free,sval) (\
- rb_data_object_alloc(klass,sval,mark,free)\
-)
-
-#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;
- unsigned short *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<<7)
-#define FL_FINALIZE (1<<8)
-#define FL_TAINT (1<<9)
-#define FL_EXIVAR (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 FL_ABLE(x) (!(FIXNUM_P(x)||rb_special_const_p((VALUE)(x))))
-#define FL_TEST(x,f) (FL_ABLE(x)?(RBASIC(x)->flags&(f)):0)
-#define FL_SET(x,f) if (FL_ABLE(x)) {RBASIC(x)->flags |= (f);}
-#define FL_UNSET(x,f) if(FL_ABLE(x)){RBASIC(x)->flags &= ~(f);}
-#define FL_REVERSE(x,f) if(FL_ABLE(x)){RBASIC(x)->flags ^= f;}
-
-#define OBJ_TAINTED(x) FL_TEST((x), FL_TAINT)
-#define OBJ_TAINT(x) FL_SET((x), FL_TAINT)
-
-void *xmalloc _((size_t));
-void *xcalloc _((size_t,size_t));
-void *xrealloc _((void*,size_t));
-#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))
-
-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(*)(),void(*)()));
-void rb_define_hooked_variable _((const char*,VALUE*,VALUE(*)(),void(*)()));
-void rb_define_readonly_variable _((const char*,VALUE*));
-void rb_define_constants _((VALUE,const char*,VALUE));
-void rb_define_global_constants _((const char*,VALUE));
-
-void rb_define_method _((VALUE,const char*,VALUE(*)(),int));
-void rb_define_module_function _((VALUE,const char*,VALUE(*)(),int));
-void rb_define_global_function _((const char*,VALUE(*)(),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));
-
-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_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;
-
-int rb_safe_level _((void));
-void rb_set_safe_level _((int));
-
-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)) NORETURN;
-
-void rb_warn __((const char*, ...));
-void rb_warning __((const char*, ...)); /* reports if `-w' specified */
-
-VALUE rb_each _((VALUE));
-VALUE rb_yield _((VALUE));
-int rb_iterator_p _((void));
-VALUE rb_iterate _((VALUE(*)(),VALUE,VALUE(*)(),VALUE));
-VALUE rb_rescue _((VALUE(*)(),VALUE,VALUE(*)(),VALUE));
-VALUE rb_ensure _((VALUE(*)(),VALUE,VALUE(*)(),VALUE));
-VALUE rb_catch _((const char*,VALUE(*)(),VALUE));
-void rb_throw _((const char*,VALUE)) NORETURN;
-
-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_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_eIOError;
-EXTERN VALUE rb_eLoadError;
-EXTERN VALUE rb_eNameError;
-EXTERN VALUE rb_eRuntimeError;
-EXTERN VALUE rb_eSecurityError;
-EXTERN VALUE rb_eSyntaxError;
-EXTERN VALUE rb_eSystemCallError;
-EXTERN VALUE rb_eTypeError;
-EXTERN VALUE rb_eZeroDivError;
-EXTERN VALUE rb_eNotImpError;
-EXTERN VALUE rb_eNoMemError;
-EXTERN VALUE rb_eFloatDomainError;
-
-#if defined(__GNUC__) && __GNUC__ >= 2 && !defined(RUBY_NO_INLINE)
-extern __inline__ VALUE rb_class_of _((VALUE));
-extern __inline__ int rb_type _((VALUE));
-extern __inline__ int rb_special_const_p _((VALUE));
-extern __inline__ int rb_test_false_or_nil _((VALUE));
-
-extern __inline__ VALUE
-rb_class_of(VALUE obj)
-{
- 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;
-
- return RBASIC(obj)->klass;
-}
-
-extern __inline__ int
-rb_type(VALUE obj)
-{
- 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;
- return BUILTIN_TYPE(obj);
-}
-
-extern __inline__ int
-rb_special_const_p(VALUE obj)
-{
- if (FIXNUM_P(obj)) return Qtrue;
- if (obj == Qnil) return Qtrue;
- if (obj == Qfalse) return Qtrue;
- if (obj == Qtrue) return Qtrue;;
- return Qfalse;
-}
-
-extern __inline__ int
-rb_test_false_or_nil(VALUE v)
-{
- return (v != Qnil) && (v != Qfalse);
-}
-#else
-VALUE rb_class_of _((VALUE));
-int rb_type _((VALUE));
-int rb_special_const_p _((VALUE));
-int rb_test_false_or_nil _((VALUE));
-#endif
-
-#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 f4b72781e5..0000000000
--- a/rubyio.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/************************************************
-
- rubyio.h -
-
- $Author$
- $Date$
- created at: Fri Nov 12 16:47:09 JST 1993
-
- Copyright (C) 1993-1999 Yukihiro Matsumoto
-
-************************************************/
-
-#ifndef IO_H
-#define IO_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)(); /* finalize proc */
-} OpenFile;
-
-#define FMODE_READABLE 1
-#define FMODE_WRITABLE 2
-#define FMODE_READWRITE 3
-#define FMODE_BINMODE 4
-#define FMODE_SYNC 8
-
-#define GetOpenFile(obj,fp) rb_io_check_closed((fp) = RFILE(obj)->fptr)
-
-#define MakeOpenFile(obj, fp) do {\
- 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*));
-void rb_eof_error _((void));
-
-void rb_read_check _((FILE*)); /* thread aware check */
-
-#endif
diff --git a/rubysig.h b/rubysig.h
deleted file mode 100644
index 97de44216b..0000000000
--- a/rubysig.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/************************************************
-
- rubysig.h -
-
- $Author$
- $Date$
- created at: Wed Aug 16 01:15:38 JST 1995
-
-************************************************/
-#ifndef SIG_H
-#define SIG_H
-
-EXTERN int rb_trap_immediate;
-#define TRAP_BEG (rb_trap_immediate=1)
-#define TRAP_END (rb_trap_immediate=0)
-
-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(*)(),VALUE));
-
-EXTERN int 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 20032e303e..0000000000
--- a/rubytest.rb
+++ /dev/null
@@ -1,37 +0,0 @@
-#! ./miniruby -I.
-
-require 'rbconfig'
-include Config
-
-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["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 d2cbb113ec..0000000000
--- a/sample/biorhythm.rb
+++ /dev/null
@@ -1,138 +0,0 @@
-#!/usr/local/bin/ruby
-#
-# biorhythm.rb -
-# $Release Version: $
-# $Revision$
-# $Date$
-# by Yasuo OHBA(STAFS Development Room)
-#
-# --
-#
-#
-#
-
-include Math
-require "date.rb"
-require "parsearg.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 = 3.14159265
- 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
-
-#
-# main program
-#
-parseArgs(0, nil, "vg", "D:", "sdate", "date:", "birthday:", "days:")
-
-if $OPT_D
- dd = Date.new(Time.now.strftime("%Y%m%d"))
- bd = Date.new($OPT_D)
- ausgabeart = "g"
-else
- if $OPT_birthday
- bd = Date.new($OPT_birthday)
- else
- printf(STDERR, "Birthday (YYYYMMDD) : ")
- if (si = STDIN.gets.chop) != ""
- bd = Date.new(si)
- end
- end
- if !bd
- printf STDERR, "BAD Input Birthday!!\n"
- exit()
- end
-
- if $OPT_sdate
- dd = Date.new(Time.now.strftime("%Y%m%d"))
- elsif $OPT_date
- dd = Date.new($OPT_date)
- else
- printf(STDERR, "Date [<RETURN> for Systemdate] (YYYYMMDD) : ")
- if (si = STDIN.gets.chop) != ""
- dd = Date.new(si)
- end
- end
- if !dd
- dd = Date.new(Time.now.strftime("%Y%m%d"))
- 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.period - bd.period, bd.name_of_week)
- print "\n"
-
- phys, emot, geist = getPosition(dd.period - bd.period)
- 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.period - bd.period, bd.name_of_week)
- print " P=physical, E=emotional, M=mental\n"
- print " -------------------------+-------------------------\n"
- print " Bad Condition | Good Condition\n"
- print " -------------------------+-------------------------\n"
-
- for z in (dd.period - bd.period)..(dd.period - bd.period + 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 8eea4abfdb..0000000000
--- a/sample/cal.rb
+++ /dev/null
@@ -1,119 +0,0 @@
-#! /usr/local/bin/ruby
-
-# cal.rb: Written by Tadayoshi Funaba 1998, 1999
-# $Id: cal.rb,v 1.6 1999/09/15 05:35:25 tadf Exp $
-
-require 'date2'
-
-$tab =
-{
- 'cn' => true, # China
- 'de' => 2342032, # Germany (protestant states)
- 'dk' => 2342032, # Denmark
- 'es' => 2299161, # Spain
- 'fi' => 2361390, # Finland
- 'fr' => 2299227, # France
- 'gb' => 2361222, # United Kingdom
- 'gr' => 2423868, # Greece
- 'hu' => 2301004, # Hungary
- 'it' => 2299161, # Italy
- 'jp' => true, # Japan
- 'no' => 2342032, # Norway
- 'pl' => 2299161, # Poland
- 'pt' => 2299161, # Portugal
- 'ru' => 2421639, # Russia
- 'se' => 2361390, # Sweden
- 'us' => 2361222, # United States
- 'os' => false, # (old style)
- 'ns' => true # (new style)
-}
-
-$cc = 'gb'
-
-def usage
- $stderr.puts 'usage: cal [-c iso3166] [-jy] [[month] year]'
- exit 1
-end
-
-def cal(m, y, sg)
- for d in 1..31
- break if jd = Date.exist?(y, m, d, sg)
- end
- fst = cur = Date.new1(jd, sg)
- ti = Date::MONTHNAMES[m]
- ti << ' ' << y.to_s unless $yr
- mo = ti.center((($w + 1) * 7) - 1) << "\n"
- mo << ['S', 'M', 'Tu', 'W', 'Th', 'F', 'S'].
- collect{|x| x.rjust($w)}.join(' ') << "\n"
- mo << ' ' * (($w + 1) * fst.wday)
- while cur.mon == fst.mon
- mo << (if $jd then cur.yday else cur.mday end).to_s.rjust($w)
- mo << (if (cur += 1).wday != 0 then "\s" else "\n" end)
- end
- mo << "\n" * (6 - ((fst.wday + (cur - fst)) / 7))
- mo
-end
-
-def zip(xs)
- yr = ''
- until xs.empty?
- ln = (if $jd then l, r, *xs = xs; [l, r]
- else l, c, r, *xs = xs; [l, c, r] end).
- collect{|x| x.split(/\n/no, -1)}
- 8.times do
- yr << ln.collect{|x|
- x.shift.ljust((($w + 1) * 7) - 1)}.join(' ') << "\n"
- end
- end
- yr
-end
-
-while /^-([^-].*)$/no =~ $*[0]
- a = $1
- if /^c(.+)?$/no =~ a
- if $1
- $cc = $1.downcase
- elsif $*.length >= 2
- $cc = $*[1].downcase
- $*.shift
- else
- usage
- end
- else
- a.scan(/./no) do |c|
- case c
- when 'j'; $jd = true
- when 'y'; $yr = true
- else usage
- end
- end
- end
- $*.shift
-end
-$*.shift if /^--/no =~ $*[0]
-usage if (sg = $tab[$cc]).nil?
-case $*.length
-when 0
- td = Date.today
- m = td.mon
- y = td.year
-when 1
- y = $*[0].to_i
- $yr = true
-when 2
- m = $*[0].to_i
- y = $*[1].to_i
-else
- usage
-end
-usage unless m.nil? or (1..12) === m
-usage unless y >= -4712
-$w = if $jd then 3 else 2 end
-unless $yr
- print cal(m, y, sg)
-else
- print y.to_s.center(((($w + 1) * 7) - 1) *
- (if $jd then 2 else 3 end) +
- (if $jd then 2 else 4 end)), "\n\n",
- zip((1..12).collect{|m| cal(m, y, sg)}), "\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/eval.rb b/sample/eval.rb
deleted file mode 100644
index 216bf8ca39..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|case|while|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
- $! = '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 c5593764aa..0000000000
--- a/sample/fib.pl
+++ /dev/null
@@ -1,10 +0,0 @@
- sub fib {
- local($n)=@_;
- if( $n<2 ){
- return $n;
- } {
- 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 5c2b86e656..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)
-
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 bed3433f1e..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 = 0
- y, m, d = parsedate(date) if date
- 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 ce268e20b9..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 !~ /\/$/
- path += "/"
-end
-
-while gets()
- if /:$/
- path = $_.chop.chop + "/"
- elsif /^total/ || /^d/
- elsif /^(.*\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 f0027ec5dd..0000000000
--- a/sample/goodfriday.rb
+++ /dev/null
@@ -1,48 +0,0 @@
-#! /usr/local/bin/ruby
-
-# goodfriday.rb: Written by Tadayoshi Funaba 1998
-# $Id: goodfriday.rb,v 1.1 1998/03/08 09:44:44 tadf Exp $
-
-require 'date2'
-
-def easter(y)
- g = (y % 19) + 1
- c = (y / 100) + 1
- x = (3 * c / 4) - 12
- z = ((8 * c + 5) / 25) - 5
- d = (5 * y / 4) - x - 10
- e = (11 * g + 20 + z - x) % 30
- e += 1 if e == 25 and g > 11 or e == 24
- n = 44 - e
- n += 30 if n < 21
- n = n + 7 - ((d + n) % 7)
- if n <= 31 then [y, 3, n] else [y, 4, n - 31] end
-end
-
-es = Date.new3(*easter(Time.now.year))
-[[-9*7, 'Septuagesima Sunday'],
- [-8*7, 'Sexagesima Sunday'],
- [-7*7, 'Quinquagesima Sunday (Shrove Sunday)'],
- [-48, 'Shrove Monday'],
- [-47, 'Shrove Tuesday'],
- [-46, 'Ash Wednesday'],
- [-6*7, 'Quadragesima Sunday'],
- [-3*7, 'Mothering Sunday'],
- [-2*7, 'Passion Sunday'],
- [-7, 'Palm Sunday'],
- [-3, 'Maunday Thursday'],
- [-2, 'Good Friday'],
- [-1, 'Easter Eve'],
- [0, 'Easter Day'],
- [1, 'Easter Monday'],
- [7, 'Low Sunday'],
- [5*7, 'Rogation Sunday'],
- [39, 'Ascension Day (Holy Thursday)'],
- [42, 'Sunday after Ascension Day'],
- [7*7, 'Pentecost (Whitsunday)'],
- [50, 'Whitmonday'],
- [8*7, 'Trinity Sunday'],
- [60, 'Corpus Christi (Thursday after Trinity)']].
-each do |xs|
- puts ((es + xs.shift).to_s + ' ' + xs.shift)
-end
diff --git a/sample/io.rb b/sample/io.rb
deleted file mode 100644
index 0b38d2112d..0000000000
--- a/sample/io.rb
+++ /dev/null
@@ -1,44 +0,0 @@
-# IO test
-# usage: ruby io.rb file..
-
-home = ENV["HOME"]
-home.sub("m", "&&")
-print(home, "\n")
-print(home.reverse, "\n")
-
-if File.s("io.rb")
- print(File.s("io.rb"), ": io.rb\n")
-end
-
-$/="f\n"
-for i in "abc\n\ndef\nghi\n"
- print("tt: ", i)
-end
-
-printf("%s:(%d)%s\n", $0, ARGV.length, ARGV[0])
-passwd = open(ARGV[0], "r")
-#printf("%s", passwd.find{i|i =~ /\*/})
-
-n = 1
-for i in passwd #.grep(/^\*/)
- printf("%6d: %s", n, i)
- n = n + 1;
-end
-
-fp = open("|-", "r")
-
-if fp == nil
- for i in 1..5
- print(i, "\n")
- end
-else
- for line in fp
- print(line)
- end
-end
-
-def printUsage()
- if $USAGE
- apply($USAGE);
- 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 8661240085..0000000000
--- a/sample/mkproto.rb
+++ /dev/null
@@ -1,27 +0,0 @@
-$/ = nil
-while gets()
- if /^((void|VALUE|int|char *\*|ID|struct [\w_]+ *\*|st_table *\*) *)?\n([\w\d_]+)\(.*\)\n\s*((.+;\n)*)\{/
- $_ = $'
- 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 6c40d50e18..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
- 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 402b35ad55..0000000000
--- a/sample/mrshtest.rb
+++ /dev/null
@@ -1,14 +0,0 @@
-require "marshal"
-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 c450c30b0f..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
- 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 3ccb052532..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 i in 0..N-1
- Thread.start{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/rbc.rb b/sample/rbc.rb
deleted file mode 100644
index 9f1ab9443d..0000000000
--- a/sample/rbc.rb
+++ /dev/null
@@ -1,1015 +0,0 @@
-#!/usr/local/bin/ruby
-#
-# rbc.rb -
-# $Release Version: 0.8 $
-# $Revision: 1.8 $
-# $Date: 1998/03/11 05:43:00 $
-# by Keiju ISHITSUKA(Nippon Rational Inc.)
-#
-# --
-# Usage:
-#
-# rbc.rb [options] file_name opts
-# options:
-# -d debug mode (not recommended)
-# -f does not read ~/.irbrc
-# -m bc mode (rational/matrix calc)
-# -r load-module same as `ruby -r'
-# --inspect use inspect for result output
-# (default for non-bc mode)
-# --noinspect does not use inspect for result output
-# --noreadline does not use readline library
-# (default: try to use readline)
-#
-# additional private method (as function):
-# exit, quit terminate the interpreter
-# inspect_mode(sw = nil) toggle inspect mode
-# trace_load(sw = nil) change trace mode for file loading using
-# load/require. (default: trace-mode on)
-#
-require "e2mmap.rb"
-
-$stdout.sync = TRUE
-
-module BC_APPLICATION__
- RCS_ID='-$Id: rbc.rb,v 1.8 1998/03/11 05:43:00 keiju Exp keiju $-'
-
- extend Exception2MessageMapper
- def_exception :UnrecognizedSwitch, "Unrecognized switch: %s"
-
- CONFIG = {}
- CONFIG[0] = $0
- CONFIG[:USE_READLINE] = TRUE
- CONFIG[:LOAD_MODULES] = []
- CONFIG[:INSPECT] = nil
- CONFIG[:TRACE_LOAD] = FALSE
- CONFIG[:RC] = TRUE
-
- CONFIG[:DEBUG] = FALSE
-
- while opt = ARGV.shift
- case opt
- when "-d"
- CONFIG[:DEBUG] = TRUE
- when "-m"
- CONFIG[:INSPECT] = FALSE if CONFIG[:INSPECT].nil?
- require "mathn.rb"
- include Math
- when "-r"
- opt = ARGV.shift
- CONFIG[:LOAD_MODULES].push opt if opt
- when "-f"
- opt = ARGV.shift
- CONFIG[:RC] = FALSE
- when "--inspect"
- CONFIG[:INSPECT] = TRUE
- when "--noinspect"
- CONFIG[:INSPECT] = FALSE
- when "--noreadline"
- CONFIG[:USE_READLINE] = FALSE
- when /^-/
- # print UnrecognizedSwitch.inspect, "\n"
- BC_APPLICATION__.fail UnrecognizedSwitch, opt
- else
- CONFIG[:USE_READLINE] = FALSE
- $0 = opt
- break
- end
- end
- CONFIG[:INSPECT] = TRUE if CONFIG[:INSPECT].nil?
-
- PROMPTi = "rbc%d> "
- PROMPTs = "rbc%d%s "
- PROMPTe = "rbc%d* "
-
- class BC
- def initialize
- lex_init
- end
-
- def eval_input(io, cont, bind)
- line = ''
- @io = io
- @ltype = nil
- @quoted = nil
- @indent = 0
- @lex_state = EXPR_BEG
-
- @io.prompt = format(PROMPTi, @indent)
-
- loop do
- @continue = FALSE
- l = @io.gets
-
- unless l
- break if line == ''
- else
- line = line + l
-
- lex(l) if l != "\n"
- print @quoted.inspect, "\n" if CONFIG[:DEBUG]
- if @ltype
- @io.prompt = format(PROMPTs, @indent, @ltype)
- next
- elsif @continue
- @io.prompt = format(PROMPTe, @indent)
- next
- elsif @indent > 0
- @io.prompt = format(PROMPTi, @indent)
- next
- end
- end
-
- if line != "\n"
- begin
- if CONFIG[:INSPECT]
- print((cont._=eval(line, bind)).inspect, "\n")
- else
- print((cont._=eval(line, bind)), "\n")
- end
- rescue
- # $! = 'exception raised' unless $!
- # print "ERR: ", $!, "\n"
- $! = RuntimeError.new("exception raised") unless $!
- print $!.type, ": ", $!, "\n"
- end
- end
- break if not l
- line = ''
- indent = 0
- @io.prompt = format(PROMPTi, indent)
- end
- print "\n"
- end
-
- EXPR_BEG = :EXPR_BEG
- EXPR_MID = :EXPR_MID
- EXPR_END = :EXPR_END
- EXPR_ARG = :EXPR_ARG
- EXPR_FNAME = :EXPR_FNAME
-
- CLAUSE_STATE_TRANS = {
- "alias" => EXPR_FNAME,
- "and" => EXPR_BEG,
- "begin" => EXPR_BEG,
- "case" => EXPR_BEG,
- "class" => EXPR_BEG,
- "def" => EXPR_FNAME,
- "defined?" => EXPR_END,
- "do" => EXPR_BEG,
- "else" => EXPR_BEG,
- "elsif" => EXPR_BEG,
- "end" => EXPR_END,
- "ensure" => EXPR_BEG,
- "for" => EXPR_BEG,
- "if" => EXPR_BEG,
- "in" => EXPR_BEG,
- "module" => EXPR_BEG,
- "nil" => EXPR_END,
- "not" => EXPR_BEG,
- "or" => EXPR_BEG,
- "rescue" => EXPR_MID,
- "return" => EXPR_MID,
- "self" => EXPR_END,
- "super" => EXPR_END,
- "then" => EXPR_BEG,
- "undef" => EXPR_FNAME,
- "unless" => EXPR_BEG,
- "until" => EXPR_BEG,
- "when" => EXPR_BEG,
- "while" => EXPR_BEG,
- "yield" => EXPR_END
- }
-
- ENINDENT_CLAUSE = [
- "case", "class", "def", "do", "for", "if",
- "module", "unless", "until", "while", "begin" #, "when"
- ]
- DEINDENT_CLAUSE = ["end" #, "when"
- ]
-
- PARCENT_LTYPE = {
- "q" => "\'",
- "Q" => "\"",
- "x" => "\`",
- "r" => "\/"
- }
-
- PARCENT_PAREN = {
- "{" => "}",
- "[" => "]",
- "<" => ">",
- "(" => ")"
- }
-
- def lex_init()
- @OP = Trie.new
- @OP.def_rules("\0", "\004", "\032"){}
- @OP.def_rules(" ", "\t", "\f", "\r", "\13") do
- @space_seen = TRUE
- next
- end
- @OP.def_rule("#") do
- |op, rests|
- @ltype = "#"
- identify_comment(rests)
- end
- @OP.def_rule("\n") do
- print "\\n\n" if CONFIG[:DEBUG]
- if @lex_state == EXPR_BEG || @lex_state == EXPR_FNAME
- @continue = TRUE
- else
- @lex_state = EXPR_BEG
- end
- end
- @OP.def_rules("*", "*=", "**=", "**") {@lex_state = EXPR_BEG}
- @OP.def_rules("!", "!=", "!~") {@lex_state = EXPR_BEG}
- @OP.def_rules("=", "==", "===", "=~", "<=>") {@lex_state = EXPR_BEG}
- @OP.def_rules("<", "<=", "<<") {@lex_state = EXPR_BEG}
- @OP.def_rules(">", ">=", ">>") {@lex_state = EXPR_BEG}
- @OP.def_rules("'", '"') do
- |op, rests|
- @ltype = op
- @quoted = op
- identify_string(rests)
- end
- @OP.def_rules("`") do
- |op, rests|
- if @lex_state != EXPR_FNAME
- @ltype = op
- @quoted = op
- identify_string(rests)
- end
- end
- @OP.def_rules('?') do
- |op, rests|
- @lex_state = EXPR_END
- identify_question(rests)
- end
- @OP.def_rules("&", "&&", "&=", "|", "||", "|=") do
- @lex_state = EXPR_BEG
- end
- @OP.def_rule("+@", proc{@lex_state == EXPR_FNAME}) {}
- @OP.def_rule("-@", proc{@lex_state == EXPR_FNAME}) {}
- @OP.def_rules("+=", "-=") {@lex_state = EXPR_BEG}
- @OP.def_rules("+", "-") do
- |op, rests|
- if @lex_state == EXPR_ARG
- if @space_seen and rests[0] =~ /[0-9]/
- identify_number(rests)
- else
- @lex_state = EXPR_BEG
- end
- elsif @lex_state != EXPR_END and rests[0] =~ /[0-9]/
- identify_number(rests)
- else
- @lex_state = EXPR_BEG
- end
- end
- @OP.def_rule(".") do
- |op, rests|
- @lex_state = EXPR_BEG
- if rests[0] =~ /[0-9]/
- rests.unshift op
- identify_number(rests)
- else
- # handle ``obj.if'' and such
- identify_identifier(rests, TRUE)
- @lex_state = EXPR_ARG
- end
- end
- @OP.def_rules("..", "...") {@lex_state = EXPR_BEG}
-
- lex_int2
- end
-
- def lex_int2
- @OP.def_rules("]", "}", ")") do
- @lex_state = EXPR_END
- @indent -= 1
- end
- @OP.def_rule(":") {|op,rests|
- identify_identifier(rests, TRUE)
- }
- @OP.def_rule("::") {|op,rests|
- identify_identifier(rests, TRUE);
- }
- @OP.def_rule("/") do
- |op, rests|
- if @lex_state == EXPR_BEG || @lex_state == EXPR_MID
- @ltype = op
- @quoted = op
- identify_string(rests)
- elsif rests[0] == '='
- rests.shift
- @lex_state = EXPR_BEG
- elsif @lex_state == EXPR_ARG and @space_seen and rests[0] =~ /\s/
- @ltype = op
- @quoted = op
- identify_string(rests)
- else
- @lex_state = EXPR_BEG
- end
- end
- @OP.def_rules("^", "^=") {@lex_state = EXPR_BEG}
- @OP.def_rules(",", ";") {@lex_state = EXPR_BEG}
- @OP.def_rule("~") {@lex_state = EXPR_BEG}
- @OP.def_rule("~@", proc{@lex_state = EXPR_FNAME}) {}
- @OP.def_rule("(") do
- @lex_state = EXPR_BEG
- @indent += 1
- end
- @OP.def_rule("[]", proc{@lex_state == EXPR_FNAME}) {}
- @OP.def_rule("[]=", proc{@lex_state == EXPR_FNAME}) {}
- @OP.def_rule("[") do
- @indent += 1
- if @lex_state != EXPR_FNAME
- @lex_state = EXPR_BEG
- end
- end
- @OP.def_rule("{") do
- @lex_state = EXPR_BEG
- @indent += 1
- end
- @OP.def_rule('\\') {|op, rests| identify_escape(rests)} #')
- @OP.def_rule('%') do
- |op, rests|
- if @lex_state == EXPR_BEG || @lex_state == EXPR_MID
- identify_quotation(rests)
- elsif rests[0] == '='
- rests.shift
- elsif @lex_state == EXPR_ARG and @space_seen and rests[0] =~ /\s/
- identify_quotation(rests)
- else
- @lex_state = EXPR_BEG
- end
- end
- @OP.def_rule('$') do #'
- |op, rests|
- identify_gvar(rests)
- end
- @OP.def_rule('@') do
- |op, rests|
- if rests[0] =~ /[\w_]/
- rests.unshift op
- identify_identifier(rests)
- end
- end
- @OP.def_rule("def", proc{|op, chrs| /\s/ =~ chrs[0]}) do
- |op, rests|
- @indent += 1
- @lex_state = EXPR_END
- until rests[0] == "\n" or rests[0] == ";"
- rests.shift
- end
- end
- @OP.def_rule("") do
- |op, rests|
- printf "MATCH: start %s: %s\n", op, rests.inspect if CONFIG[:DEBUG]
- if rests[0] =~ /[0-9]/
- identify_number(rests)
- elsif rests[0] =~ /[\w_]/
- identify_identifier(rests)
- end
- printf "MATCH: end %s: %s\n", op, rests.inspect if CONFIG[:DEBUG]
- end
-
- p @OP if CONFIG[:DEBUG]
- end
-
- def lex(l)
- chrs = l.split(//)
- tokens = []
-
- case @ltype
- when "'", '"', '`', '/'
- identify_string(chrs)
- return if chrs.empty?
- when "#"
- identify_comment(chrs)
- return
- when "="
- if l =~ /^=end/
- $ltype = nil
- return
- end
- else
- if l =~ /^=begin/
- $ltype = "="
- return
- end
- end
-
- until chrs.empty?
- @space_seen = FALSE
- printf "perse: %s\n", chrs.join("") if CONFIG[:DEBUG]
- @OP.match(chrs)
- printf "lex_state: %s continue: %s\n", @lex_state.id2name, @continue if CONFIG[:DEBUG]
- end
- end
-
- def identify_gvar(chrs)
- @lex_state = EXPR_END
-
- ch = chrs.shift
- case ch
- when /[_~*$?!@/\\;,.=:<>"]/ #"
- return
-
- when "-"
- ch = chrs.shift
- return
-
- when "&", "`", "'", "+"
- return
-
- when /[1-9]/
- chrs.unshift ch
- v = "$"
- while (ch = chrs.shift) =~ /[0-9]/
- end
- chrs.unshift ch
- return
-
- when /\w/
- chrs.unshift ch
- chrs.unshift "$"
- identify_identifier(chrs)
- return
-
- else
- chrs.unshift ch
- return
- end
- end
-
- def identify_identifier(chrs, escaped = FALSE)
- token = ""
- token.concat chrs.shift if chrs[0] =~ /[$@]/ or escaped
- while (ch = chrs.shift) =~ /\w|_/
- print ":", ch, ":" if CONFIG[:DEBUG]
- token.concat ch
- end
- chrs.unshift ch
-
- if ch == "!" or ch == "?"
- chrs.shift
- token.concat ch
- end
- # fix token
-
- if token =~ /^[$@]/ or escaped
- @lex_state = EXPR_END
- return
- end
-
- print token, "\n" if CONFIG[:DEBUG]
- if state = CLAUSE_STATE_TRANS[token]
- if @lex_state != EXPR_BEG and token =~ /^(if|unless|while|until)/
- # modifiers
- else
- if ENINDENT_CLAUSE.include?(token)
- @indent += 1
- elsif DEINDENT_CLAUSE.include?(token)
- @indent -= 1
- end
- end
- @lex_state = state
- return
- end
- if @lex_state == EXPR_FNAME
- @lex_state = EXPR_END
- if chrs[0] == '='
- chrs.shift
- end
- elsif @lex_state == EXPR_BEG
- @lex_state = EXPR_ARG
- else
- @lex_state = EXPR_END
- end
- end
-
- def identify_quotation(chrs)
- ch = chrs.shift
- if lt = PARCENT_LTYPE[ch]
- ch = chrs.shift
- else
- lt = "\""
- end
- if ch !~ /\W/
- chrs.unshift ch
- next
- end
- @ltype = lt
- unless @quoted = PARCENT_PAREN[ch]
- @quoted = ch
- end
- identify_string(chrs)
- end
-
- def identify_number(chrs)
- @lex_state = EXPR_END
-
- ch = chrs.shift
- case ch
- when /0/
- if (ch = chrs[0]) == "x"
- chrs.shift
- match = /[0-9a-f_]/
- else
- match = /[0-7_]/
- end
- while ch = chrs.shift
- if ch !~ match
- chrs.unshift ch
- break
- end
- end
- return
- end
-
- while ch = chrs.shift
- case ch
- when /[0-9]/
- when "e", "E"
- # type = FLOAT
- unless (ch = chrs.shift) == "+" or ch == "-"
- chrs.unshift ch
- end
- when "."
- # type = FLOAT
- when "_"
- else
- chrs.unshift ch
- return
- end
- end
- end
-
- def identify_question(chrs)
- @lex_state = EXPR_END
-
- if chrs.shift == "\\" #"
- identify_escape(chrs)
- end
- end
-
- def identify_string(chrs)
- while ch = chrs.shift
- if @quoted == ch
- if @ltype == "/"
- if chrs[0] =~ /i|o|n|e|s/
- chrs.shift
- end
- end
- @ltype = nil
- @quoted = nil
- @lex_state = EXPR_END
- break
- elsif ch == '\\' #'
- identify_escape(chrs)
- end
- end
- end
-
- def identify_comment(chrs)
- while ch = chrs.shift
- if ch == "\\" #"
- identify_escape(chrs)
- end
- if ch == "\n"
- @ltype = nil
- chrs.unshift ch
- break
- end
- end
- end
-
- def identify_escape(chrs)
- ch = chrs.shift
- case ch
- when "\n", "\r", "\f"
- @continue = TRUE
- when "\\", "n", "t", "r", "f", "v", "a", "e", "b" #"
- when /[0-7]/
- chrs.unshift ch
- 3.times do
- ch = chrs.shift
- case ch
- when /[0-7]/
- when nil
- break
- else
- chrs.unshift ch
- break
- end
- end
- when "x"
- 2.times do
- ch = chrs.shift
- case ch
- when /[0-9a-fA-F]/
- when nil
- break
- else
- chrs.unshift ch
- break
- end
- end
- when "M"
- if (ch = chrs.shift) != '-'
- chrs.unshift ch
- elsif (ch = chrs.shift) == "\\" #"
- identify_escape(chrs)
- end
- return
- when "C", "c", "^"
- if ch == "C" and (ch = chrs.shift) != "-"
- chrs.unshift ch
- elsif (ch = chrs.shift) == "\\" #"
- identify_escape(chrs)
- end
- return
- end
- end
- end
-
- class Trie
- extend Exception2MessageMapper
- def_exception :ErrNodeNothing, "node nothing"
- def_exception :ErrNodeAlreadyExists, "node already exists"
-
- class Node
- # abstract node if postproc is nil.
- def initialize(preproc = nil, postproc = nil)
- @Tree = {}
- @preproc = preproc
- @postproc = postproc
- end
-
- attr :preproc, TRUE
- attr :postproc, TRUE
-
- def search(chrs, opt = nil)
- return self if chrs.empty?
- ch = chrs.shift
- if node = @Tree[ch]
- node.search(chrs, opt)
- else
- if opt
- chrs.unshift ch
- self.create_subnode(chrs)
- else
- Trie.fail ErrNodeNothing
- end
- end
- end
-
- def create_subnode(chrs, preproc = nil, postproc = nil)
- if chrs.empty?
- if @postproc
- p node
- Trie.fail ErrNodeAlreadyExists
- else
- print "Warn: change abstruct node to real node\n" if CONFIG[:DEBUG]
- @preproc = preproc
- @postproc = postproc
- end
- return self
- end
-
- ch = chrs.shift
- if node = @Tree[ch]
- if chrs.empty?
- if node.postproc
- p node
- Trie.fail ErrNodeAlreadyExists
- else
- print "Warn: change abstruct node to real node\n" if CONFIG[:DEBUG]
- node.preproc = preproc
- node.postproc = postproc
- end
- else
- node.create_subnode(chrs, preproc, postproc)
- end
- else
- if chrs.empty?
- node = Node.new(preproc, postproc)
- else
- node = Node.new
- node.create_subnode(chrs, preproc, postproc)
- end
- @Tree[ch] = node
- end
- node
- end
-
- def match(chrs, op = "")
- print "match>: ", chrs, "op:", op, "\n" if CONFIG[:DEBUG]
- if chrs.empty?
- if @preproc.nil? || @preproc.call(op, chrs)
- printf "op1: %s\n", op if CONFIG[:DEBUG]
- @postproc.call(op, chrs)
- ""
- else
- nil
- end
- else
- ch = chrs.shift
- if node = @Tree[ch]
- if ret = node.match(chrs, op+ch)
- return ch+ret
- else
- chrs.unshift ch
- if @postproc and @preproc.nil? || @preproc.call(op, chrs)
- printf "op2: %s\n", op.inspect if CONFIG[:DEBUG]
- @postproc.call(op, chrs)
- return ""
- else
- return nil
- end
- end
- else
- chrs.unshift ch
- if @postproc and @preproc.nil? || @preproc.call(op, chrs)
- printf "op3: %s\n", op if CONFIG[:DEBUG]
- @postproc.call(op, chrs)
- return ""
- else
- return nil
- end
- end
- end
- end
- end
-
- def initialize
- @head = Node.new("")
- end
-
- def def_rule(token, preproc = nil, postproc = nil)
-# print node.inspect, "\n" if CONFIG[: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)
- token = token.split(//) if token.kind_of?(String)
- ret = @head.match(token)
- printf "match end: %s:%s", ret, token.inspect if CONFIG[:DEBUG]
- ret
- end
-
- def inspect
- format("<Trie: @head = %s>", @head.inspect)
- end
- end
-
- if /^-tt(.*)$/ =~ ARGV[0]
-# Tracer.on
- case $1
- when "1"
- tr = Trie.new
- print "0: ", tr.inspect, "\n"
- tr.def_rule("=") {print "=\n"}
- print "1: ", tr.inspect, "\n"
- tr.def_rule("==") {print "==\n"}
- print "2: ", tr.inspect, "\n"
-
- print "case 1:\n"
- print tr.match("="), "\n"
- print "case 2:\n"
- print tr.match("=="), "\n"
- print "case 3:\n"
- print tr.match("=>"), "\n"
-
- when "2"
- tr = Trie.new
- print "0: ", tr.inspect, "\n"
- tr.def_rule("=") {print "=\n"}
- print "1: ", tr.inspect, "\n"
- tr.def_rule("==", proc{FALSE}) {print "==\n"}
- print "2: ", tr.inspect, "\n"
-
- print "case 1:\n"
- print tr.match("="), "\n"
- print "case 2:\n"
- print tr.match("=="), "\n"
- print "case 3:\n"
- print tr.match("=>"), "\n"
- end
- exit
- end
-
- module CONTEXT
- def _=(value)
- CONFIG[:_] = value
- eval "_=BC_APPLICATION__::CONFIG[:_]", CONFIG[:BIND]
- end
-
-# def _
-# eval "_", CONFIG[:BIND]
-# end
-
- def quit
- exit
- end
-
- def trace_load(opt = nil)
- if !opt.nil?
- CONFIG[:TRACE_LOAD] = opt
- else
- CONFIG[:TRACE_LOAD] = !CONFIG[:TRACE_LOAD]
- end
- print "Switch to load/require #{unless CONFIG[:TRACE_LOAD]; ' non';end} trace mode.\n"
- if CONFIG[:TRACE_LOAD]
- eval %{
- class << self
- alias load rbc_load
- alias require rbc_require
- end
- }
- else
- eval %{
- class << self
- alias load rbc_load_org
- alias require rbc_require_org
- end
- }
- end
- CONFIG[:TRACE_LOAD]
- end
-
- alias rbc_load_org load
- def rbc_load(file_name)
- return true if load_sub(file_name)
- raise LoadError, "No such file to load -- #{file_name}"
- end
-
- alias rbc_require_org require
- def rbc_require(file_name)
- rex = Regexp.new("#{Regexp.quote(file_name)}(\.o|\.rb)?")
- return false if $".find{|f| f =~ rex}
-
- case file_name
- when /\.rb$/
- if load_sub(file_name)
- $".push file_name
- return true
- end
- when /\.(so|o|sl)$/
- rbc_require_org(file_name)
- end
-
- if load_sub(f = file_name + ".rb")
- $".push f
- return true
- end
- rbc_require_org(file_name)
- end
-
- def load_sub(fn)
- if fn =~ /^#{Regexp.quote(File::Separator)}/
- return false unless File.exist?(fn)
- BC.new.eval_input FileInputMethod.new(fn), self, CONFIG[:BIND]
- return true
- end
-
- for path in $:
- if File.exist?(f = File.join(path, fn))
- BC.new.eval_input FileInputMethod.new(f), self, CONFIG[:BIND]
- return true
- end
- end
- return false
- end
-
- def inspect_mode(opt = nil)
- if opt
- CONFIG[:INSPECT] = opt
- else
- CONFIG[:INSPECT] = !CONFIG[:INSPECT]
- end
- print "Switch to#{unless CONFIG[:INSPECT]; ' non';end} inspect mode.\n"
- CONFIG[:INSPECT]
- end
-
- def run(bind)
- CONFIG[:BIND] = bind
-
- if CONFIG[:RC]
- rc = File.expand_path("~/.irbrc")
- if File.exists?(rc)
- begin
- load rc
- rescue
- print "load error: #{rc}\n"
- print $!.type, ": ", $!, "\n"
- for err in $@[0, $@.size - 2]
- print "\t", err, "\n"
- end
- end
- end
- end
-
- if CONFIG[:TRACE_LOAD]
- trace_load true
- end
-
- for m in CONFIG[:LOAD_MODULES]
- begin
- require m
- rescue
- print $@[0], ":", $!.type, ": ", $!, "\n"
- end
- end
-
- if !$0.equal?(CONFIG[0])
- io = FileInputMethod.new($0)
- elsif defined? Readline
- io = ReadlineInputMethod.new
- else
- io = StdioInputMethod.new
- end
-
- BC.new.eval_input io, self, CONFIG[:BIND]
- end
- end
-
- class InputMethod
- attr :prompt, TRUE
-
- def gets
- end
- public :gets
- end
-
- class StdioInputMethod < InputMethod
- def gets
- print @prompt
- $stdin.gets
- end
- end
-
- class FileInputMethod < InputMethod
- def initialize(file)
- @io = open(file)
- end
-
- def gets
- l = @io.gets
- print @prompt, l
- l
- end
- end
-
- if CONFIG[:USE_READLINE]
- begin
- require "readline"
- print "use readline module\n"
- class ReadlineInputMethod < InputMethod
- include Readline
- def gets
- if l = readline(@prompt, TRUE)
- l + "\n"
- else
- l
- end
- end
- end
- rescue
- CONFIG[:USE_READLINE] = FALSE
- end
- end
-end
-
-extend BC_APPLICATION__::CONTEXT
-run(binding)
-
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/rename.rb b/sample/rename.rb
deleted file mode 100644
index 2d1b62ea8f..0000000000
--- a/sample/rename.rb
+++ /dev/null
@@ -1,297 +0,0 @@
-#! /usr/local/bin/ruby -p
-gsub!(/\bary_aref\b/,"rb_ary_aref")
-gsub!(/\bary_assoc\b/,"rb_ary_assoc")
-gsub!(/\bary_concat\b/,"rb_ary_concat")
-gsub!(/\bary_delete\b/,"rb_ary_delete")
-gsub!(/\bary_delete_at\b/,"rb_ary_delete_at")
-gsub!(/\bary_each\b/,"rb_ary_each")
-gsub!(/\bary_entry\b/,"rb_ary_entry")
-gsub!(/\bary_freeze\b/,"rb_ary_freeze")
-gsub!(/\bary_includes\b/,"rb_ary_includes")
-gsub!(/\bary_join\b/,"rb_ary_join")
-gsub!(/\bary_new([234])?\b/,"rb_ary_new\\1")
-gsub!(/\bary_plus\b/,"rb_ary_plus")
-gsub!(/\bary_pop\b/,"rb_ary_pop")
-gsub!(/\bary_push\b/,"rb_ary_push")
-gsub!(/\bary_rassoc\b/,"rb_ary_rassoc")
-gsub!(/\bary_reverse\b/,"rb_ary_reverse")
-gsub!(/\bary_shift\b/,"rb_ary_shift")
-gsub!(/\bary_sort\b/,"rb_ary_sort")
-gsub!(/\bary_store\b/,"rb_ary_store")
-gsub!(/\bary_to_s\b/,"rb_ary_to_s")
-gsub!(/\bary_unshift\b/,"rb_ary_unshift")
-gsub!(/\bassoc_new\b/,"rb_assoc_new")
-gsub!(/\bcArray\b/,"rb_cArray")
-gsub!(/\bmemclear\b/,"rb_mem_clear")
-gsub!(/\bbig2dbl\b/,"rb_big2dbl")
-gsub!(/\bbig2long\b/,"rb_big2long")
-gsub!(/\bbig2str\b/,"rb_big2str")
-gsub!(/\bbig2ulong\b/,"rb_big2ulong")
-gsub!(/\bbig_2comp\b/,"rb_big_2comp")
-gsub!(/\bbig_and\b/,"rb_big_and")
-gsub!(/\bbig_clone\b/,"rb_big_clone")
-gsub!(/\bbig_lshift\b/,"rb_big_lshift")
-gsub!(/\bbig_minus\b/,"rb_big_minus")
-gsub!(/\bbig_mul\b/,"rb_big_mul")
-gsub!(/\bbig_norm\b/,"rb_big_norm")
-gsub!(/\bbig_or\b/,"rb_big_or")
-gsub!(/\bbig_plus\b/,"rb_big_plus")
-gsub!(/\bbig_pow\b/,"rb_big_pow")
-gsub!(/\bbig_rand\b/,"rb_big_rand")
-gsub!(/\bbig_xor\b/,"rb_big_xor")
-gsub!(/\bcBignum\b/,"rb_cBignum")
-gsub!(/\bdbl2big\b/,"rb_dbl2big")
-gsub!(/\bint2big\b/,"rb_int2big")
-gsub!(/\bint2inum\b/,"rb_int2inum")
-gsub!(/\bstr2inum\b/,"rb_str2inum")
-gsub!(/\buint2big\b/,"rb_uint2big")
-gsub!(/\buint2inum\b/,"rb_uint2inum")
-gsub!(/\bclass_instance_methods\b/,"rb_class_instance_methods")
-gsub!(/\bclass_new\b/,"rb_class_new")
-gsub!(/\bclass_private_instance_methods\b/,"rb_class_private_instance_methods")
-gsub!(/\bclass_protected_instance_methods\b/,"rb_class_protected_instance_methods")
-gsub!(/\bmod_ancestors\b/,"rb_mod_ancestors")
-gsub!(/\bmod_included_modules\b/,"rb_mod_included_modules")
-gsub!(/\bmodule_new\b/,"rb_module_new")
-gsub!(/\bobj_singleton_methods\b/,"rb_obj_singleton_methods")
-gsub!(/\bsingleton_class\b/,"rb_singleton_class")
-gsub!(/\bmComparable\b/,"rb_mComparable")
-gsub!(/\bcDir\b/,"rb_cDir")
-gsub!(/\benum_length\b/,"rb_enum_length")
-gsub!(/\bmEnumerable\b/,"rb_mEnumerable")
-gsub!(/\bBug\b/,"rb_bug")
-gsub!(/\brb_check_type\b/,"rb_check_type")
-gsub!(/\beArgError\b/,"rb_eArgError")
-gsub!(/\beException\b/,"rb_eException")
-gsub!(/\beFatal\b/,"rb_eFatal")
-gsub!(/\beIndexError\b/,"rb_eIndexError")
-gsub!(/\beInterrupt\b/,"rb_eInterrupt")
-gsub!(/\beLoadError\b/,"rb_eLoadError")
-gsub!(/\beNameError\b/,"rb_eNameError")
-gsub!(/\beNotImpError\b/,"rb_eNotImpError")
-gsub!(/\beRuntimeError\b/,"rb_eRuntimeError")
-gsub!(/\beSecurityError\b/,"rb_eSecurityError")
-gsub!(/\beStandardError\b/,"rb_eStandardError")
-gsub!(/\beSyntaxError\b/,"rb_eSyntaxError")
-gsub!(/\beSystemCallError\b/,"rb_eSystemCallError")
-gsub!(/\beSystemExit\b/,"rb_eSystemExit")
-gsub!(/\beTypeError\b/,"rb_eTypeError")
-gsub!(/\bexc_new([23]?)\b/,"rb_exc_new\\1")
-gsub!(/\bFatal\b/,"rb_fatal")
-gsub!(/\bLoadError\b/,"rb_loaderror")
-gsub!(/\bmErrno\b/,"rb_mErrno")
-gsub!(/\bRaise\b/,"rb_raise")
-gsub!(/\bWarn(ing)?\b/,"rb_warn\\1")
-gsub!(/\bnerrs\b/,"ruby_nerrs")
-gsub!(/\bcProc\b/,"rb_cProc")
-gsub!(/\bcThread\b/,"rb_cThread")
-gsub!(/\brb_check_safe_str\b/,"rb_check_safe_str")
-gsub!(/\bclass_new_instance\b/,"rb_class_new_instance")
-gsub!(/\bdyna_var_asgn\b/,"rb_dvar_asgn")
-gsub!(/\bdyna_var_defined\b/,"rb_dvar_defined")
-gsub!(/\bdyna_var_push\b/,"rb_dvar_push")
-gsub!(/\bdyna_var_ref\b/,"rb_dvar_ref")
-gsub!(/\bf_lambda\b/,"rb_f_lambda")
-gsub!(/\bf_load\b/,";xxx_need_modify;rb_load")
-gsub!(/\bf_require\b/,"rb_f_require")
-gsub!(/\bgc_mark_threads\b/,"rb_gc_mark_threads")
-gsub!(/\biterator_p\b/,"rb_iterator_p")
-gsub!(/\bobj_call_init\b/,"rb_obj_call_init")
-gsub!(/\brb_set_end_proc\b/,"rb_set_end_proc")
-gsub!(/\brb_set_safe_level\b/,"rb_set_safe_level")
-gsub!(/\bthread_alone\b/,"rb_thread_alone")
-gsub!(/\bthread_create\b/,"rb_thread_create")
-gsub!(/\bthread_critical\b/,"rb_thread_critical")
-gsub!(/\bthread_fd_writable\b/,"rb_thread_fd_writable")
-gsub!(/\bthread_interrupt\b/,"rb_thread_interrupt")
-gsub!(/\bthread_schedule\b/,"rb_thread_schedule")
-gsub!(/\bthread_select\b/,"rb_thread_select")
-gsub!(/\bthread_sleep\b/,"rb_thread_sleep")
-gsub!(/\bthread_sleep_forever\b/,"rb_thread_sleep_forever")
-gsub!(/\bthread_trap_eval\b/,"rb_thread_trap_eval")
-gsub!(/\bthread_wait_fd\b/,"rb_thread_wait_fd")
-gsub!(/\bthread_wait_for\b/,"rb_thread_wait_for")
-gsub!(/\bthe_class\b/,"ruby_class")
-gsub!(/\bthe_dyna_vars\b/,"ruby_dyna_vars")
-gsub!(/\bthe_frame\b/,"ruby_frame")
-gsub!(/\bthe_init\b/,"ruby_init")
-gsub!(/\bthe_scope\b/,"ruby_scope")
-gsub!(/\bcFile\b/,"rb_cFile")
-gsub!(/\bfile_open\b/,"rb_file_open")
-gsub!(/\bfile_s_expand_path\b/,"rb_file_s_expand_path")
-gsub!(/\bmFileTest\b/,"rb_mFileTest")
-gsub!(/\bdata_object_alloc\b/,"rb_data_object_alloc")
-gsub!(/\bgc_call_finalizer_at_exit\b/,"rb_gc_call_finalizer_at_exit")
-gsub!(/\bgc_force_recycle\b/,"rb_gc_force_recycle")
-gsub!(/\bgc_gc\b/,"rb_gc")
-gsub!(/\bgc_mark\b/,"rb_gc_mark")
-gsub!(/\bgc_stack_start\b/,"rb_gc_stack_start")
-gsub!(/\bmGC\b/,"rb_mGC")
-gsub!(/\bcHash\b/,"rb_cHash")
-gsub!(/\benv_path_tainted\b/,"rb_env_path_tainted")
-gsub!(/\bhash_aref\b/,"rb_hash_aref")
-gsub!(/\bhash_aset\b/,"rb_hash_aset")
-gsub!(/\bhash_freeze\b/,"rb_hash_freeze")
-gsub!(/\bhash_new\b/,"rb_hash_new")
-gsub!(/\bcIO\b/,"rb_cIO")
-gsub!(/\beEOFError\b/,"rb_eEOFError")
-gsub!(/\beIOError\b/,"rb_eIOError")
-gsub!(/\beof_error\b/,"rb_eof_error")
-gsub!(/\bf_gets\b/,"rb_f_gets")
-gsub!(/\bio_binmode\b/,"rb_io_binmode")
-gsub!(/\bio_check_closed\b/,"rb_io_check_closed")
-gsub!(/\bio_readable\b/,"rb_io_check_readable")
-gsub!(/\bio_writable\b/,"rb_io_check_writable")
-gsub!(/\bio_close\b/,"rb_io_close")
-gsub!(/\bio_fptr_finalize\b/,"rb_io_fptr_finalize")
-gsub!(/\bio_getc\b/,"rb_io_getc")
-gsub!(/\bio_gets\b/,"rb_io_gets")
-gsub!(/\bio_gets_method\b/,"rb_io_gets_method")
-gsub!(/\bio_mode_flags\b/,"rb_io_mode_flags")
-gsub!(/\bio_reopen\b/,"rb_io_reopen")
-gsub!(/\bio_unbuffered\b/,"rb_io_unbuffered")
-gsub!(/\bio_ungetc\b/,"rb_io_ungetc")
-gsub!(/\bio_write\b/,"rb_io_write")
-gsub!(/\bRS_default\b/,"ruby_default_rs")
-gsub!(/\bOFS\b/,"ruby_output_fs")
-gsub!(/\bORS\b/,"ruby_output_rs")
-gsub!(/\bFS\b/,"ruby_fs")
-gsub!(/\bRS\b/,"ruby_rs")
-gsub!(/\bmMath\b/,"rb_mMath")
-gsub!(/\bcFixnum\b/,"rb_cFixnum")
-gsub!(/\bcFloat\b/,"rb_cFloat")
-gsub!(/\bcInteger\b/,"rb_cInteger")
-gsub!(/\bcNumeric\b/,"rb_cNumeric")
-gsub!(/\beZeroDiv\b/,"rb_eZeroDiv")
-gsub!(/\bfix2int\b/,"rb_fix2int")
-gsub!(/\bfix2str\b/,"rb_fix2str")
-gsub!(/\bfix_upto\b/,"rb_fix_upto")
-gsub!(/\bfloat_new\b/,"rb_float_new")
-gsub!(/\bnum2fix\b/,"rb_num2fix")
-gsub!(/\bnum2int\b/,"rb_num2int")
-gsub!(/\bnum2long\b/,"rb_num2long")
-gsub!(/\bnum2ulong\b/,"rb_num2ulong")
-gsub!(/\bnum_coerce_bin\b/,"rb_num_coerce_bin")
-gsub!(/\bnum_zerodiv\b/,"rb_num_zerodiv")
-gsub!(/\bany_to_s\b/,"rb_any_to_s")
-gsub!(/\bcClass\b/,"rb_cClass")
-gsub!(/\bcData\b/,"rb_cData")
-gsub!(/\bcFalseClass\b/,"rb_cFalseClass")
-gsub!(/\bcModule\b/,"rb_cModule")
-gsub!(/\bcNilClass\b/,"rb_cNilClass")
-gsub!(/\bcObject\b/,"rb_cObject")
-gsub!(/\bcTrueClass\b/,"rb_cTrueClass")
-gsub!(/\bmKernel\b/,"rb_mKernel")
-gsub!(/\bnum2dbl\b/,"rb_num2dbl")
-gsub!(/\bobj_alloc\b/,"rb_obj_alloc")
-gsub!(/\bobj_equal\b/,"rb_obj_equal")
-gsub!(/\bobj_is_instance_of\b/,"rb_obj_is_instance_of")
-gsub!(/\bobj_is_kind_of\b/,"rb_obj_is_kind_of")
-gsub!(/\bstr2cstr\b/,"rb_str2cstr")
-gsub!(/\bTopSelf\b/,"rb_top_self")
-gsub!(/\bbackref_get\b/,"rb_backref_get")
-gsub!(/\bbackref_set\b/,"rb_backref_set")
-gsub!(/\bcompile_file\b/,"rb_compile_file")
-gsub!(/\bcompile_string\b/,"rb_compile_string")
-gsub!(/\bid_attrset\b/,"rb_id_attrset")
-gsub!(/\bis_const_id\b/,"rb_is_const_id")
-gsub!(/\bis_instance_id\b/,"rb_is_instance_id")
-gsub!(/\blastline_get\b/,"rb_lastline_get")
-gsub!(/\blastline_set\b/,"rb_lastline_set")
-gsub!(/\bnode_newnode\b/,"rb_node_newnode")
-gsub!(/\byyappend_print\b/,"rb_parser_append_print")
-gsub!(/\byywhile_loop\b/,"rb_parser_while_loop")
-gsub!(/\brb_reserved_word\b/,"rb_reserved_word")
-gsub!(/\bsourcefile\b/,"ruby_sourcefile")
-gsub!(/\bsourceline\b/,"ruby_sourceline")
-gsub!(/\bmProcess\b/,"rb_mProcess")
-gsub!(/\bcRange\b/,"rb_cRange")
-gsub!(/\brange_beg_end\b/,"rb_range_beg_end")
-gsub!(/\brange_new\b/,"rb_range_new")
-gsub!(/\bcRegexp\b/,"rb_cRegexp")
-gsub!(/\bignorecase\b/,"rb_ignorecase")
-gsub!(/\breg_free\b/,"rb_reg_free")
-gsub!(/\breg_last_match\b/,"rb_reg_last_match")
-gsub!(/\breg_match\b/,"rb_reg_match")
-gsub!(/\breg_new\b/,"rb_reg_new")
-gsub!(/\breg_nth_defined\b/,"rb_reg_nth_defined")
-gsub!(/\breg_nth_match\b/,"rb_reg_nth_match")
-gsub!(/\breg_options\b/,"rb_reg_options")
-gsub!(/\breg_prepare_re\b/,"rb_reg_prepare_re")
-gsub!(/\breg_regcomp\b/,"rb_reg_regcomp")
-gsub!(/\breg_regsub\b/,"rb_reg_regsub")
-gsub!(/\breg_search\b/,"rb_reg_search")
-gsub!(/\bstr_cicmp\b/,"rb_str_cicmp")
-gsub!(/\bf_kill\b/,"rb_f_kill")
-gsub!(/\bgc_mark_trap_list\b/,"rb_gc_mark_trap_list")
-gsub!(/\bprohibit_interrupt\b/,"rb_prohibit_interrupt")
-gsub!(/\btrap_exec\b/,"rb_trap_exec")
-gsub!(/\btrap_exit\b/,"rb_trap_exit")
-gsub!(/\btrap_immediate\b/,"rb_trap_immediate")
-gsub!(/\btrap_pending\b/,"rb_trap_pending")
-gsub!(/\btrap_restore_mask\b/,"rb_trap_restore_mask")
-gsub!(/\bposix_signal\b/,"ruby_posix_signal")
-gsub!(/\bf_sprintf\b/,"rb_f_sprintf")
-gsub!(/\bcString\b/,"rb_cString")
-gsub!(/\bobj_as_string\b/,"rb_obj_as_string")
-gsub!(/\bstr_cat\b/,"rb_str_cat")
-gsub!(/\bstr_cmp\b/,"rb_str_cmp")
-gsub!(/\bstr_concat\b/,"rb_str_concat")
-gsub!(/\bstr_dup\b/,"rb_str_dup")
-gsub!(/\bstr_dup_frozen\b/,"rb_str_dup_frozen")
-gsub!(/\bstr_freeze\b/,"rb_str_freeze")
-gsub!(/\bstr_hash\b/,"rb_str_hash")
-gsub!(/\bstr_inspect\b/,"rb_str_inspect")
-gsub!(/\bstr_modify\b/,"rb_str_modify")
-gsub!(/\bstr_new([234]?)\b/,"rb_str_new\\1")
-gsub!(/\bstr_plus\b/,"rb_str_plus")
-gsub!(/\bstr_resize\b/,"rb_str_resize")
-gsub!(/\bstr_split\b/,"rb_str_split")
-gsub!(/\bstr_substr\b/,"rb_str_substr")
-gsub!(/\bstr_taint\b/,"rb_obj_taint")
-gsub!(/\bstr_tainted\b/,"rb_obj_tainted")
-gsub!(/\bstr_times\b/,"rb_str_times")
-gsub!(/\bstr_to_str\b/,"rb_str_to_str")
-gsub!(/\bstr_upto\b/,"rb_str_upto")
-gsub!(/\bcStruct\b/,"rb_cStruct")
-gsub!(/\bstruct_alloc\b/,"rb_struct_alloc")
-gsub!(/\bstruct_aref\b/,"rb_struct_aref")
-gsub!(/\bstruct_aset\b/,"rb_struct_aset")
-gsub!(/\bstruct_define\b/,"rb_struct_define")
-gsub!(/\bstruct_getmember\b/,"rb_struct_getmember")
-gsub!(/\bstruct_new\b/,"rb_struct_new")
-gsub!(/\bcTime\b/,"rb_cTime")
-gsub!(/\btime_new\b/,"rb_time_new")
-gsub!(/\btime_timeval\b/,"rb_time_timeval")
-gsub!(/\bscan_hex\b/,"ruby_scan_hex")
-gsub!(/\bscan_oct\b/,"ruby_scan_oct")
-gsub!(/\bconst_defined\b/,"rb_const_defined")
-gsub!(/\bconst_defined_at\b/,"rb_const_defined_at")
-gsub!(/\bconst_get\b/,"rb_const_get")
-gsub!(/\bconst_get_at\b/,"rb_const_get")
-gsub!(/\bconst_set\b/,"rb_const_set")
-gsub!(/\bf_autoload\b/,"rb_f_autoload")
-gsub!(/\bf_global_variables\b/,"rb_f_global_variables")
-gsub!(/\bf_trace_var\b/,"rb_f_trace_var")
-gsub!(/\bf_untrace_var\b/,"rb_f_untrace_var")
-gsub!(/\bmod_const_at\b/,"rb_mod_const_at")
-gsub!(/\bmod_const_of\b/,"rb_mod_const_of")
-gsub!(/\bmod_constants\b/,"rb_mod_constants")
-gsub!(/\bmod_name\b/,"rb_mod_name")
-gsub!(/\bmod_remove_const\b/,"rb_mod_remove_const")
-gsub!(/\bobj_instance_variables\b/,"rb_obj_instance_variables")
-gsub!(/\bobj_remove_instance_variable\b/,"rb_obj_remove_instance_variable")
-gsub!(/\bshow_copyright\b/,"ruby_show_copyright")
-gsub!(/\bshow_version\b/,"ruby_show_version")
-gsub!(/\bdebug\b/,"ruby_debug")
-gsub!(/\bverbose\b/,"ruby_verbose")
-gsub!(/\bFail\(/,"rb_raise(rb_eRuntimeError, ")
-gsub!(/\bArgError\(/,"rb_raise(rb_eArgError, ")
-gsub!(/\bTypeError\(/,"rb_raise(rb_eTypeError, ")
-gsub!(/\bNameError\(/,"rb_raise(rb_eNameError, ")
-gsub!(/\bIndexError\(/,"rb_raise(rb_eIndexError, ")
-gsub!(/\bError\b/,"rb_compile_error")
-gsub!(/\bErrorAppend\b/,"rb_compile_error_append")
-gsub!(/\bTRUE\b/,"Qtrue")
-gsub!(/\bFALSE\b/,"Qfalse")
-gsub!(/\berrinfo\b/,"ruby_errinfo")
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 c866407eb0..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 %d\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 e23c39f5e7..0000000000
--- a/sample/test.rb
+++ /dev/null
@@ -1,1157 +0,0 @@
-#! /usr/local/bin/ruby
-
-$testnum=0
-$ntest=0
-$failed = 0
-
-def check(what)
- printf "%s\n", what
- $what = what
- $testnum = 0
-end
-
-def 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
-
-check "assignment"
-
-a=[]; a[0] ||= "bar";
-ok(a[0] == "bar")
-h={}; h["foo"] ||= "bar";
-ok(h["foo"] == "bar")
-
-aa = 5
-aa ||= 25
-ok(aa == 5)
-bb ||= 25
-ok(bb == 25)
-cc &&=33
-ok(cc == nil)
-cc = 5
-cc &&=44
-ok(cc == 44)
-
-check "condition"
-
-$x = '0';
-
-$x == $x && ok(true)
-$x != $x && ok(false)
-$x == $x || ok(false)
-$x != $x || ok(true)
-
-# first test to see if we can run the tests.
-
-check "if/unless";
-
-$x = 'test';
-ok(if $x == $x then true else false end)
-$bad = false
-unless $x == $x
- $bad = true
-end
-ok(!$bad)
-ok(unless $x != $x then true else false end)
-
-check "case"
-
-case 5
-when 1, 2, 3, 4, 6, 7, 8
- ok(false)
-when 5
- ok(true)
-end
-
-case 5
-when 5
- ok(true)
-when 1..10
- ok(false)
-end
-
-case 5
-when 1..10
- ok(true)
-else
- ok(false)
-end
-
-case 5
-when 5
- ok(true)
-else
- ok(false)
-end
-
-case "foobar"
-when /^f.*r$/
- ok(true)
-else
- ok(false)
-end
-
-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")
-ok(tmp.kind_of?(File))
-
-while tmp.gets()
- break if /vt100/
-end
-
-ok(!tmp.eof? && /vt100/)
-tmp.close
-
-# test next
-$bad = false
-tmp = open("while_tmp", "r")
-while tmp.gets()
- next if /vt100/;
- $bad = 1 if /vt100/;
-end
-ok(!(!tmp.eof? || /vt100/ || $bad))
-tmp.close
-
-# test redo
-$bad = false
-tmp = open("while_tmp", "r")
-while tmp.gets()
- if gsub!('vt100', 'VT100')
- gsub!('VT100', 'Vt100')
- redo;
- end
- $bad = 1 if /vt100/;
- $bad = 1 if /VT100/;
-end
-ok(tmp.eof? && !$bad)
-tmp.close
-
-sum=0
-for i in 1..10
- sum += i
- i -= 1
- if i > 0
- redo
- end
-end
-ok(sum == 220)
-
-# test interval
-$bad = false
-tmp = open("while_tmp", "r")
-while tmp.gets()
- break unless 1..2
- if /vt100/ || /Amiga/ || /paper/
- $bad = true
- break
- end
-end
-ok(!$bad)
-tmp.close
-
-File.unlink "while_tmp" or `/bin/rm -f "while_tmp"`
-ok(!File.exist?("while_tmp"))
-
-i = 0
-until i>4
- i+=1
-end
-ok(i>4)
-
-# exception handling
-check "exception";
-
-begin
- raise "this must be handled"
- ok(false)
-rescue
- ok(true)
-end
-
-$bad = true
-begin
- raise "this must be handled no.2"
-rescue
- if $bad
- $bad = false
- retry
- ok(false)
- end
-end
-ok(true)
-
-# exception in rescue clause
-$string = "this must be handled no.3"
-begin
- begin
- raise "exception in rescue clause"
- rescue
- raise $string
- end
- ok(false)
-rescue
- 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
- ok(false)
-rescue
- ok(true)
-end
-
-$bad = true
-begin
- begin
- raise "this must be handled no.5"
- ensure
- $bad = false
- end
-rescue
-end
-ok(!$bad)
-
-$bad = true
-begin
- begin
- raise "this must be handled no.6"
- ensure
- $bad = false
- end
-rescue
-end
-ok(!$bad)
-
-$bad = true
-while true
- begin
- break
- ensure
- $bad = false
- end
-end
-ok(!$bad)
-
-ok(catch(:foo) {
- loop do
- loop do
- throw :foo, true
- break
- end
- break
- ok(false) # should no reach here
- end
- false
- })
-
-check "array"
-ok([1, 2] + [3, 4] == [1, 2, 3, 4])
-ok([1, 2] * 2 == [1, 2, 1, 2])
-ok([1, 2] * ":" == "1:2")
-
-ok([1, 2].hash == [1, 2].hash)
-
-ok([1,2,3] & [2,3,4] == [2,3])
-ok([1,2,3] | [2,3,4] == [1,2,3,4])
-ok([1,2,3] - [2,3] == [1])
-
-$x = [0, 1, 2, 3, 4, 5]
-ok($x[2] == 2)
-ok($x[1..3] == [1, 2, 3])
-ok($x[1,3] == [1, 2, 3])
-
-$x[0, 2] = 10
-ok($x[0] == 10 && $x[1] == 2)
-
-$x[0, 0] = -1
-ok($x[0] == -1 && $x[1] == 10)
-
-$x[-1, 1] = 20
-ok($x[-1] == 20 && $x.pop == 20)
-
-# array and/or
-ok(([1,2,3]&[2,4,6]) == [2])
-ok(([1,2,3]|[2,4,6]) == [1,2,3,4,6])
-
-# compact
-$x = [nil, 1, nil, nil, 5, nil, nil]
-$x.compact!
-ok($x == [1, 5])
-
-# uniq
-$x = [1, 1, 4, 2, 5, 4, 5, 1, 2]
-$x.uniq!
-ok($x == [1, 4, 2, 5])
-
-# empty?
-ok(!$x.empty?)
-$x = []
-ok($x.empty?)
-
-# sort
-$x = ["it", "came", "to", "pass", "that", "..."]
-$x = $x.sort.join(" ")
-ok($x == "... came it pass that to")
-$x = [2,5,3,1,7]
-$x.sort!{|a,b| a<=>b} # sort with condition
-ok($x == [1,2,3,5,7])
-$x.sort!{|a,b| b-a} # reverse sort
-ok($x == [7,5,3,2,1])
-
-# split test
-$x = "The Book of Mormon"
-ok($x.split(//).reverse!.join == $x.reverse)
-ok($x.reverse == $x.reverse!)
-ok("1 byte string".split(//).reverse.join(":") == "g:n:i:r:t:s: :e:t:y:b: :1")
-$x = "a b c d"
-ok($x.split == ['a', 'b', 'c', 'd'])
-ok($x.split(' ') == ['a', 'b', 'c', 'd'])
-ok(defined? "a".chomp)
-ok("abc".scan(/./) == ["a", "b", "c"])
-ok("1a2b3c".scan(/(\d.)/) == [["1a"], ["2b"], ["3c"]])
-# non-greedy match
-ok("a=12;b=22".scan(/(.*?)=(\d*);?/) == [["a", "12"], ["b", "22"]])
-
-$x = [1]
-ok(($x * 5).join(":") == '1:1:1:1:1')
-ok(($x * 1).join(":") == '1')
-ok(($x * 0).join(":") == '')
-
-*$x = 1..7
-ok($x.size == 7)
-ok($x == [1, 2, 3, 4, 5, 6, 7])
-
-check "hash"
-$x = {1=>2, 2=>4, 3=>6}
-$y = {1, 2, 2, 4, 3, 6}
-
-ok($x[1] == 2)
-
-ok(begin
- for k,v in $y
- raise if k*2 != v
- end
- true
- rescue
- false
- end)
-
-ok($x.length == 3)
-ok($x.has_key?(1))
-ok($x.has_value?(4))
-ok($x.indexes(2,3) == [4,6])
-ok($x == {1=>2, 2=>4, 3=>6})
-
-$z = $y.keys.join(":")
-ok($z == "1:2:3")
-
-$z = $y.values.join(":")
-ok($z == "2:4:6")
-ok($x == $y)
-
-$y.shift
-ok($y.length == 2)
-
-$z = [1,2]
-$y[$z] = 256
-ok($y[$z] == 256)
-
-check "iterator"
-
-ok(!iterator?)
-
-def ttt
- ok(iterator?)
-end
-ttt{}
-
-# yield at top level
-ok(!defined?(yield))
-
-$x = [1, 2, 3, 4]
-$y = []
-
-# iterator over array
-for i in $x
- $y.push i
-end
-ok($x == $y)
-
-# nested iterator
-def tt
- 1.upto(10) {|i|
- yield i
- }
-end
-
-tt{|i| break if i == 5}
-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
-ok($x)
-
-# iterator break/redo/next/retry
-done = true
-loop{
- break
- done = false # should not reach here
-}
-ok(done)
-
-done = false
-$bad = false
-loop {
- break if done
- done = true
- next
- $bad = true # should not reach here
-}
-ok(!$bad)
-
-done = false
-$bad = false
-loop {
- break if done
- done = true
- redo
- $bad = true # should not reach here
-}
-ok(!$bad)
-
-$x = []
-for i in 1 .. 7
- $x.push i
-end
-ok($x.size == 7)
-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
-ok($x.size == 10)
-ok($x == [1, 2, 3, 1, 2, 3, 4, 5, 6, 7])
-
-# append method to built-in class
-class Array
- def iter_test1
- collect{|e| [e, yield(e)]}.sort{|a,b|a[1]<=>b[1]}
- end
- def iter_test2
- a = collect{|e| [e, yield(e)]}
- a.sort{|a,b|a[1]<=>b[1]}
- end
-end
-$x = [[1,2],[3,4],[5,6]]
-ok($x.iter_test1{|x|x} == $x.iter_test2{|x|x})
-
-class IterTest
- def initialize(e); @body = e; end
-
- def each0(&block); @body.each(&block); end
- def each1(&block); @body.each { |*x| block.call(*x) } end
- def each2(&block); @body.each { |*x| block.call(x) } end
- def each3(&block); @body.each { |x| block.call(*x) } end
- def each4(&block); @body.each { |x| block.call(x) } end
- def each5; @body.each { |*x| yield(*x) } end
- def each6; @body.each { |*x| yield(x) } end
- def each7; @body.each { |x| yield(*x) } end
- def each8; @body.each { |x| yield(x) } end
-end
-
-IterTest.new([0]).each0 { |x| $x = x }
-ok($x == 0)
-IterTest.new([1]).each1 { |x| $x = x }
-ok($x == 1)
-IterTest.new([2]).each2 { |x| $x = x }
-ok($x == [2])
-IterTest.new([3]).each3 { |x| $x = x }
-ok($x == 3)
-IterTest.new([4]).each4 { |x| $x = x }
-ok($x == 4)
-IterTest.new([5]).each5 { |x| $x = x }
-ok($x == 5)
-IterTest.new([6]).each6 { |x| $x = x }
-ok($x == [6])
-IterTest.new([7]).each7 { |x| $x = x }
-ok($x == 7)
-IterTest.new([8]).each8 { |x| $x = x }
-ok($x == 8)
-
-IterTest.new([[0]]).each0 { |x| $x = x }
-ok($x == [0])
-IterTest.new([[1]]).each1 { |x| $x = x }
-ok($x == 1)
-IterTest.new([[2]]).each2 { |x| $x = x }
-ok($x == [2])
-IterTest.new([[3]]).each3 { |x| $x = x }
-ok($x == 3)
-IterTest.new([[4]]).each4 { |x| $x = x }
-ok($x == [4])
-IterTest.new([[5]]).each5 { |x| $x = x }
-ok($x == 5)
-IterTest.new([[6]]).each6 { |x| $x = x }
-ok($x == [6])
-IterTest.new([[7]]).each7 { |x| $x = x }
-ok($x == 7)
-IterTest.new([[8]]).each8 { |x| $x = x }
-ok($x == [8])
-
-IterTest.new([[0,0]]).each0 { |x| $x = x }
-ok($x == [0,0])
-IterTest.new([[8,8]]).each8 { |x| $x = x }
-ok($x == [8,8])
-
-check "bignum"
-def fact(n)
- return 1 if n == 0
- f = 1
- while n>0
- f *= n
- n -= 1
- end
- return f
-end
-fact(3)
-$x = fact(40)
-ok($x == $x)
-ok($x == fact(40))
-ok($x < $x+2)
-ok($x > $x-2)
-ok($x == 815915283247897734345611269596115894272000000000)
-ok($x != 815915283247897734345611269596115894272000000001)
-ok($x+1 == 815915283247897734345611269596115894272000000001)
-ok($x/fact(20) == 335367096786357081410764800000)
-$x = -$x
-ok($x == -815915283247897734345611269596115894272000000000)
-ok(2-(2**32) == -(2**32-2))
-ok(2**32 - 5 == (2**32-3)-2)
-
-$good = true;
-for i in 1000..1014
- $good = false if ((1<<i) != (2**i))
-end
-ok($good)
-
-$good = true;
-n1=1<<1000
-for i in 1000..1014
- $good = false if ((1<<i) != n1)
- n1 *= 2
-end
-ok($good)
-
-$good = true;
-n2=n1
-for i in 1..10
- n1 = n1 / 2
- n2 = n2 >> 1
- $good = false if (n1 != n2)
-end
-ok($good)
-
-$good = true;
-for i in 4000..4096
- n1 = 1 << i;
- if (n1**2-1) / (n1+1) != (n1-1)
- $good = false
- end
-end
-ok($good)
-
-check "string & char"
-
-ok("abcd" == "abcd")
-ok("abcd" =~ "abcd")
-ok("abcd" === "abcd")
-# compile time string concatenation
-ok("ab" "cd" == "abcd")
-ok("#{22}aa" "cd#{44}" == "22aacd44")
-ok("#{22}aa" "cd#{44}" "55" "#{66}" == "22aacd445566")
-ok("abc" !~ /^$/)
-ok("abc\n" !~ /^$/)
-ok("abc" !~ /^d*$/)
-ok(("abc" =~ /d*$/) == 3)
-ok("" =~ /^$/)
-ok("\n" =~ /^$/)
-ok("a\n\n" =~ /^$/)
-ok("abcabc" =~ /.*a/ && $& == "abca")
-ok("abcabc" =~ /.*c/ && $& == "abcabc")
-ok("abcabc" =~ /.*?a/ && $& == "a")
-ok("abcabc" =~ /.*?c/ && $& == "abc")
-ok(/(.|\n)*?\n(b|\n)/ =~ "a\nb\n\n" && $& == "a\nb")
-
-ok(/^(ab+)+b/ =~ "ababb" && $& == "ababb")
-ok(/^(?:ab+)+b/ =~ "ababb" && $& == "ababb")
-ok(/^(ab+)+/ =~ "ababb" && $& == "ababb")
-ok(/^(?:ab+)+/ =~ "ababb" && $& == "ababb")
-
-ok(/(\s+\d+){2}/ =~ " 1 2" && $& == " 1 2")
-ok(/(?:\s+\d+){2}/ =~ " 1 2" && $& == " 1 2")
-
-$x = <<END;
-ABCD
-ABCD
-END
-$x.gsub!(/((.|\n)*?)B((.|\n)*?)D/){$1+$3}
-ok($x == "AC\nAC\n")
-
-ok("foobar" =~ /foo(?=(bar)|(baz))/)
-ok("foobaz" =~ /foo(?=(bar)|(baz))/)
-
-$foo = "abc"
-ok("#$foo = abc" == "abc = abc")
-ok("#{$foo} = abc" == "abc = abc")
-
-foo = "abc"
-ok("#{foo} = abc" == "abc = abc")
-
-ok('-' * 5 == '-----')
-ok('-' * 1 == '-')
-ok('-' * 0 == '')
-
-foo = '-'
-ok(foo * 5 == '-----')
-ok(foo * 1 == '-')
-ok(foo * 0 == '')
-
-$x = "a.gif"
-ok($x.sub(/.*\.([^\.]+)$/, '\1') == "gif")
-ok($x.sub(/.*\.([^\.]+)$/, 'b.\1') == "b.gif")
-ok($x.sub(/.*\.([^\.]+)$/, '\2') == "")
-ok($x.sub(/.*\.([^\.]+)$/, 'a\2b') == "ab")
-ok($x.sub(/.*\.([^\.]+)$/, '<\&>') == "<a.gif>")
-
-# character constants(assumes ASCII)
-ok("a"[0] == ?a)
-ok(?a == ?a)
-ok(?\C-a == 1)
-ok(?\M-a == 225)
-ok(?\M-\C-a == 129)
-ok("a".upcase![0] == ?A)
-ok("A".downcase![0] == ?a)
-ok("abc".tr!("a-z", "A-Z") == "ABC")
-ok("aabbcccc".tr_s!("a-z", "A-Z") == "ABC")
-ok("abc".tr!("0-9", "A-Z") == nil)
-ok("abcc".squeeze!("a-z") == "abc")
-ok("abcd".delete!("bc") == "ad")
-
-$x = "abcdef"
-$y = [ ?a, ?b, ?c, ?d, ?e, ?f ]
-$bad = false
-$x.each_byte {|i|
- if i != $y.shift
- $bad = true
- break
- end
-}
-ok(!$bad)
-
-check "asignment"
-a = nil
-ok(defined?(a))
-ok(a == nil)
-
-# multiple asignment
-a, b = 1, 2
-ok(a == 1 && b == 2)
-
-a, b = b, a
-ok(a == 2 && b == 1)
-
-a, = 1,2
-ok(a == 1)
-
-a, *b = 1, 2, 3
-ok(a == 1 && b == [2, 3])
-
-a, (b, c), d = 1, [2, 3], 4
-ok(a == 1 && b == 2 && c == 3 && d == 4)
-
-*a = 1, 2, 3
-ok(a == [1, 2, 3])
-
-*a = 1..3 # array conversion
-ok(a == [1, 2, 3])
-
-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
- ok(false)
-rescue
- ok(true)
-end
-
-begin
- aaa # no arg given (exception raised)
- ok(false)
-rescue
- ok(true)
-end
-
-ok(aaa(1) == [1, 100])
-ok(aaa(1, 2) == [1, 2])
-ok(aaa(1, 2, 3, 4) == [1, 2, 3, 4])
-ok(aaa(1, *[2, 3, 4]) == [1, 2, 3, 4])
-
-check "proc"
-$proc = proc{|i| i}
-ok($proc.call(2) == 2)
-ok($proc.call(3) == 3)
-
-$proc = proc{|i| i*2}
-ok($proc.call(2) == 4)
-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
- ok(defined?(iii))
-}.call
-ok(!defined?(iii)) # out of scope
-
-$x=0
-$proc.call(5)
-$proc2.call
-ok($x == 5)
-
-if defined? Process.kill
- check "signal"
-
- $x = 0
- trap "SIGINT", proc{|sig| $x = 2}
- Process.kill "SIGINT", $$
- sleep 0.1
- ok($x == 2)
-
- trap "SIGINT", proc{raise "Interrupt"}
-
- x = false
- begin
- Process.kill "SIGINT", $$
- sleep 0.1
- rescue
- x = $!
- end
- ok(x && /Interrupt/ =~ x)
-end
-
-check "eval"
-ok(eval("") == nil)
-$bad=false
-eval 'while false; $bad = true; print "foo\n" end'
-ok(!$bad)
-
-ok(eval('TRUE'))
-ok(eval('true'))
-ok(!eval('NIL'))
-ok(!eval('nil'))
-ok(!eval('FALSE'))
-ok(!eval('false'))
-
-$foo = 'ok(true)'
-begin
- eval $foo
-rescue
- ok(false)
-end
-
-ok(eval("$foo") == 'ok(true)')
-ok(eval("true") == true)
-i = 5
-ok(eval("i == 5"))
-ok(eval("i") == 5)
-ok(eval("defined? i"))
-
-# eval with binding
-def test_ev
- local1 = "local1"
- lambda {
- local2 = "local2"
- return binding
- }.call
-end
-
-$x = test_ev
-ok(eval("local1", $x) == "local1") # normal local var
-ok(eval("local2", $x) == "local2") # nested local var
-$bad = true
-begin
- p eval("local1")
-rescue NameError # must raise error
- $bad = false
-end
-ok(!$bad)
-
-module EvTest
- EVTEST1 = 25
- evtest2 = 125
- $x = binding
-end
-ok(eval("EVTEST1", $x) == 25) # constant in module
-ok(eval("evtest2", $x) == 125) # local var in module
-$bad = true
-begin
- eval("EVTEST1")
-rescue NameError # must raise error
- $bad = false
-end
-ok(!$bad)
-
-x = proc{}
-eval "i4 = 1", x
-ok(eval("i4", x) == 1)
-x = proc{proc{}}.call
-eval "i4 = 22", x
-ok(eval("i4", x) == 22)
-$x = []
-x = proc{proc{}}.call
-eval "(0..9).each{|i5| $x[i5] = proc{i5*2}}", x
-ok($x[4].call == 8)
-
-x = binding
-eval "i = 1", x
-ok(eval("i", x) == 1)
-x = proc{binding}.call
-eval "i = 22", x
-ok(eval("i", x) == 22)
-$x = []
-x = proc{binding}.call
-eval "(0..9).each{|i5| $x[i5] = proc{i5*2}}", x
-ok($x[4].call == 8)
-x = proc{binding}.call
-eval "for i6 in 1..1; j6=i6; end", x
-ok(eval("defined? i6", x))
-ok(eval("defined? j6", x))
-
-proc {
- p = binding
- eval "foo11 = 1", p
- foo22 = 5
- proc{foo11=22}.call
- proc{foo22=55}.call
- ok(eval("foo11", p) == eval("foo11"))
- ok(eval("foo11") == 1)
- ok(eval("foo22", p) == eval("foo22"))
- ok(eval("foo22") == 55)
-}.call
-
-p1 = proc{i7 = 0; proc{i7}}.call
-ok(p1.call == 0)
-eval "i7=5", p1
-ok(p1.call == 5)
-ok(!defined?(i7))
-
-p1 = proc{i7 = 0; proc{i7}}.call
-i7 = nil
-ok(p1.call == 0)
-eval "i7=1", p1
-ok(p1.call == 1)
-eval "i7=5", p1
-ok(p1.call == 5)
-ok(i7 == nil)
-
-check "system"
-ok(`echo foobar` == "foobar\n")
-ok(`./miniruby -e 'print "foobar"'` == 'foobar')
-
-tmp = open("script_tmp", "w")
-tmp.print "print $zzz\n";
-tmp.close
-
-ok(`./miniruby -s script_tmp -zzz` == 'true')
-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
-
-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
-
-ok(`./miniruby -x script_tmp` == 'nil')
-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
-ok(done)
-
-File.unlink "script_tmp" or `/bin/rm -f "script_tmp"`
-File.unlink "script_tmp.bak" or `/bin/rm -f "script_tmp.bak"`
-
-$bad = false
-for script in Dir["{lib,sample}/*.rb"]
- unless `./miniruby -c #{script}`.chomp == "Syntax OK"
- $bad = true
- end
-end
-ok(!$bad)
-
-check "const"
-TEST1 = 1
-TEST2 = 2
-
-module Const
- TEST3 = 3
- TEST4 = 4
-end
-
-module Const2
- TEST3 = 6
- TEST4 = 8
-end
-
-include Const
-
-ok([TEST1,TEST2,TEST3,TEST4] == [1,2,3,4])
-
-include Const2
-STDERR.print "intentionally redefines TEST3, TEST4\n" if $VERBOSE
-ok([TEST1,TEST2,TEST3,TEST4] == [1,2,6,8])
-
-check "clone"
-foo = Object.new
-def foo.test
- "test"
-end
-bar = foo.clone
-def bar.test2
- "test2"
-end
-
-ok(bar.test2 == "test2")
-ok(bar.test == "test")
-ok(foo.test == "test")
-
-begin
- foo.test2
- ok false
-rescue
- ok true
-end
-
-check "marshal"
-$x = [1,2,3,[4,5,"foo"],{1=>"bar"},2.5,fact(30)]
-$y = Marshal.dump($x)
-ok($x == Marshal.load($y))
-
-check "pack"
-
-$format = "c2x5CCxsdila6";
-# 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,"abcdef"]
-$x = ary.pack($format)
-ary2 = $x.unpack($format)
-
-ok(ary.length == ary2.length)
-ok(ary.join(':') == ary2.join(':'))
-ok($x =~ /def/)
-
-check "math"
-ok(Math.sqrt(4) == 2)
-
-include Math
-ok(sqrt(4) == 2)
-
-check "struct"
-struct_test = Struct.new("Test", :foo, :bar)
-ok(struct_test == Struct::Test)
-
-test = struct_test.new(1, 2)
-ok(test.foo == 1 && test.bar == 2)
-ok(test[0] == 1 && test[1] == 2)
-
-a, b = test
-ok(a == 1 && b == 2)
-
-test[0] = 22
-ok(test.foo == 22)
-
-test.bar = 47
-ok(test.bar == 47)
-
-check "variable"
-ok($$.instance_of?(Fixnum))
-
-# read-only variable
-begin
- $$ = 5
- ok false
-rescue
- ok true
-end
-
-foobar = "foobar"
-$_ = foobar
-ok($_ == foobar)
-
-check "trace"
-$x = 1234
-$y = 0
-trace_var :$x, proc{$y = $x}
-$x = 40414
-ok($y == $x)
-
-untrace_var :$x
-$x = 19660208
-ok($y != $x)
-
-trace_var :$x, proc{$x *= 2}
-$x = 5
-ok($x == 10)
-
-untrace_var :$x
-
-check "defined?"
-
-ok(defined?($x)) # global variable
-ok(defined?($x) == 'global-variable')# returns description
-
-foo=5
-ok(defined?(foo)) # local variable
-
-ok(defined?(Array)) # constant
-ok(defined?(Object.new)) # method
-ok(!defined?(Object.print)) # private method
-ok(defined?(1 == 2)) # operator expression
-
-def defined_test
- return !defined?(yield)
-end
-
-ok(defined_test) # not iterator
-ok(!defined_test{}) # called as iterator
-
-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
-ok(x.bar == "foo")
-ok(x.baz == "foo+foo")
-
-# check for cache
-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
-ok(!x.foo)
-ok(x.bar)
-ok(!x.quux)
-
-check "gc"
-begin
- 1.upto(10000) {
- tmp = [0,1,2,3,4,5,6,7,8,9]
- }
- tmp = nil
- ok true
-rescue
- ok false
-end
-
-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 f4f4ec4883..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
-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 d6a5620d11..0000000000
--- a/sample/tsvr.rb
+++ /dev/null
@@ -1,23 +0,0 @@
-# socket example - server side using thread
-# usage: ruby tsvr.rb
-
-require "socket"
-require "thread"
-
-gs = TCPserver.open(0)
-addr = gs.addr
-addr.shift
-printf("server is on %d\n", addr.join(":"))
-
-while TRUE
- ns = gs.accept
- print(ns, " is accepted\n")
- Thread.start do
- s = ns # save to thread-local variable
- 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 418323c439..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 gets()
- if /^begin\s*(\d*)\s*(\S*)/
- $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 gets()
- if /^end/
- $sawend+=1
- out.close unless out_stdout
- File.chmod $mode.oct, $file unless out_stdout
- next
- end
- sub(/[a-z]+$/, "") # handle stupid trailing lowercase letters
- next if /[a-z]/
- 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 fe1107d46d..0000000000
--- a/signal.c
+++ /dev/null
@@ -1,646 +0,0 @@
-/************************************************
-
- signal.c -
-
- $Author$
- $Date$
- created at: Tue Dec 20 10:13:44 JST 1994
-
-************************************************/
-
-#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
-
-#ifdef USE_CWGUSI
-# undef NSIG
-# define NSIG __signal_max
-#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
- 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;
-{
-#ifdef USE_CWGUSI
- rb_notimplement();
-#else
- int negative = 0;
- int sig;
- int i;
- char *s;
-
- rb_secure(2);
- if (argc < 2)
- rb_raise(rb_eArgError, "wrong # of arguments -- kill(sig, pid...)");
- switch (TYPE(argv[0])) {
- case T_FIXNUM:
- sig = FIX2UINT(argv[0]);
- if (sig >= NSIG) {
- s = rb_id2name(sig);
- if (!s) rb_raise(rb_eArgError, "bad signal");
- goto str_signal;
- }
- break;
-
- 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, "unrecognized signal name `%s'", s);
-
- if (negative)
- sig = -sig;
- }
- break;
-
- default:
- 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(FIX2UINT(argv[i]), sig) < 0)
- rb_sys_fail(0);
- }
- }
- return INT2FIX(i-1);
-#endif /* USE_CWGUSI */
-}
-
-static VALUE trap_list[NSIG];
-static int trap_pending_list[NSIG];
-int rb_trap_pending;
-int 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 */
-}
-
-#ifdef POSIX_SIGNAL
-void
-posix_signal(signum, handler)
- int signum;
- RETSIGTYPE (*handler)();
-{
- struct sigaction sigact;
-
- sigact.sa_handler = handler;
- sigemptyset(&sigact.sa_mask);
- sigact.sa_flags = 0;
-#ifdef SA_RESTART
- 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, 0);
-}
-#define ruby_signal(sig,handle) posix_signal((sig),(handle))
-#else
-#define ruby_signal(sig,handle) signal((sig),(handle))
-#endif
-
-static void
-signal_exec(sig)
- int sig;
-{
- if (trap_list[sig] == 0) {
- switch (sig) {
- case SIGINT:
- rb_thread_interrupt();
- break;
-#ifndef NT
- 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
-sighandle(sig)
- int sig;
-{
- if (sig >= NSIG) {
- rb_bug("trap_handler: Bad signal %d", sig);
- }
-
-#if !defined(BSD_SIGNAL)
- ruby_signal(sig, sighandle);
-#endif
-
- if (rb_trap_immediate) {
- rb_trap_immediate = 0;
- signal_exec(sig);
- rb_trap_immediate = 1;
- }
- else {
- rb_trap_pending++;
- trap_pending_list[sig]++;
- }
-}
-
-#ifdef SIGBUS
-static RETSIGTYPE
-sigbus(sig)
- int sig;
-{
- rb_bug("Bus Error");
-}
-#endif
-
-#ifdef SIGSEGV
-static RETSIGTYPE
-sigsegv(sig)
- int sig;
-{
- rb_bug("Segmentation fault");
-}
-#endif
-
-void
-rb_trap_exit()
-{
-#ifndef MACOS_UNUSE_SIGNAL
- if (trap_list[0]) {
- rb_eval_cmd(trap_list[0], rb_ary_new3(1, INT2FIX(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) && !defined(USE_CWGUSI)
-# 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()
-{
- rb_exit(0);
-}
-
-static VALUE
-trap(arg)
- struct trap_arg *arg;
-{
- RETSIGTYPE (*func)();
- VALUE command, old;
- int sig;
-
- func = sighandle;
- command = arg->cmd;
- if (NIL_P(command)) {
- func = SIG_IGN;
- }
- else if (TYPE(command) == T_STRING) {
- Check_SafeStr(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;
- }
-
- if (TYPE(arg->sig) == T_STRING) {
- char *s = RSTRING(arg->sig)->ptr;
-
- if (strncmp("SIG", s, 3) == 0)
- s += 3;
- sig = signm2signo(s);
- if (sig == 0 && strcmp(s, "EXIT") != 0)
- rb_raise(rb_eArgError, "invalid signal SIG%s", s);
- }
- else {
- sig = NUM2INT(arg->sig);
- }
- 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:
-#ifndef NT
- case SIGHUP:
-#endif
-#ifdef SIGQUIT
- case SIGQUIT:
-#endif
-#ifdef SIGALRM
- case SIGALRM:
-#endif
-#ifdef SIGUSR1
- case SIGUSR1:
-#endif
-#ifdef SIGUSR2
- case SIGUSR2:
-#endif
- func = sighandle;
- break;
-#ifdef SIGBUS
- case SIGBUS:
- func = sigbus;
- break;
-#endif
-#ifdef SIGSEGV
- case SIGSEGV:
- func = sigsegv;
- break;
-#endif
-#ifdef SIGPIPE
- case SIGPIPE:
- func = SIG_IGN;
- 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) && !defined(USE_CWGUSI)
-#ifdef HAVE_SIGPROCMASK
- sigdelset(&arg->mask, sig);
-#else
- arg->mask &= ~sigmask(sig);
-#endif
-#endif
- return old;
-}
-
-#if !defined(NT) && !defined(USE_CWGUSI)
-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) && !defined(USE_CWGUSI)
-# ifdef HAVE_SIGPROCMASK
- sigprocmask(SIG_SETMASK, &trap_last_mask, NULL);
-# else
- sigsetmask(trap_last_mask);
-# endif
-#endif
-}
-
-static VALUE
-rb_f_trap(argc, argv)
- int argc;
- VALUE *argv;
-{
- struct trap_arg arg;
-
- rb_secure(2);
- if (argc == 0 || argc > 2) {
- rb_raise(rb_eArgError, "wrong # 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 !defined(NT) && !defined(USE_CWGUSI)
- /* 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
-}
-
-void
-Init_signal()
-{
-#ifndef MACOS_UNUSE_SIGNAL
- rb_define_global_function("trap", rb_f_trap, -1);
- ruby_signal(SIGINT, sighandle);
-#ifndef NT
- ruby_signal(SIGHUP, sighandle);
-#endif
-#ifdef SIGQUIT
- ruby_signal(SIGQUIT, sighandle);
-#endif
-#ifdef SIGALRM
- ruby_signal(SIGALRM, sighandle);
-#endif
-#ifdef SIGUSR1
- ruby_signal(SIGUSR1, sighandle);
-#endif
-#ifdef SIGUSR2
- ruby_signal(SIGUSR2, sighandle);
-#endif
-
-#ifdef SIGBUS
- ruby_signal(SIGBUS, sigbus);
-#endif
-#ifdef SIGSEGV
- ruby_signal(SIGSEGV, sigsegv);
-#endif
-#ifdef SIGPIPE
- ruby_signal(SIGPIPE, SIG_IGN);
-#endif
-#endif /* MACOS_UNUSE_SIGNAL */
-}
diff --git a/sprintf.c b/sprintf.c
deleted file mode 100644
index 5badb61f71..0000000000
--- a/sprintf.c
+++ /dev/null
@@ -1,686 +0,0 @@
-/************************************************
-
- sprintf.c -
-
- $Author$
- $Date$
- created at: Fri Oct 15 10:39:26 JST 1993
-
- Copyright (C) 1993-1999 Yukihiro Matsumoto
-
-************************************************/
-
-#include "ruby.h"
-#include <ctype.h>
-#include <math.h>
-
-#define BIT_DIGITS(N) (((N)*146)/485 + 1) /* log2(10) =~ 146/485 */
-
-#ifndef atof
-double strtod();
-#endif
-
-#ifdef USE_CWGUSI
-static void fmt_setup();
-#else
-static void fmt_setup _((char*,int,int,int,int));
-#endif
-
-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;
-}
-
-double rb_big2dbl _((VALUE));
-
-#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;
- p = str2cstr(fmt, &blen);
- end = p + blen;
- blen = 0;
- bsiz = 120;
- buf = ALLOC_N(char, bsiz);
-
- for (; p < end; p++) {
- char *t;
- int n;
-
- for (t = p; t < end && *t != '%'; t++) ;
- CHECK(t - p);
- 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");
- }
-
- prec = 0;
- p++;
- if (*p == '*') {
- GETASTER(prec);
- if (prec > 0)
- 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]");
- }
- if (prec > 0)
- flags |= FPREC;
- 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) {
- CHECK(prec);
- memcpy(&buf[blen], RSTRING(str)->ptr, prec);
- blen += prec;
- break;
- }
- }
- 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;
- }
- }
- CHECK(len);
- memcpy(&buf[blen], RSTRING(str)->ptr, len);
- blen += len;
- }
- break;
-
- case 'd':
- case 'i':
- case 'o':
- case 'x':
- case 'X':
- 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 '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";
- if (prefix) {
- width -= strlen(prefix);
- }
- }
-
- bin_retry:
- switch (TYPE(val)) {
- case T_FIXNUM:
- v = FIX2LONG(val);
- break;
- case T_FLOAT:
- val = rb_dbl2big(RFLOAT(val)->value);
- if (FIXNUM_P(val)) goto bin_retry;
- bignum = 1;
- break;
- case T_STRING:
- val = rb_str2inum(RSTRING(val)->ptr, 10);
- goto bin_retry;
- case T_BIGNUM:
- bignum = 1;
- break;
- default:
- Check_Type(val, T_FIXNUM);
- 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') 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);
- CHECK(plen);
- strcpy(&buf[blen], prefix);
- blen += 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';
- }
- CHECK(len);
- strcpy(&buf[blen], s);
- blen += 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];
-
- switch (TYPE(val)) {
- case T_FIXNUM:
- fval = (double)FIX2LONG(val);
- break;
- case T_FLOAT:
- fval = RFLOAT(val)->value;
- break;
- case T_BIGNUM:
- fval = rb_big2dbl(val);
- break;
- case T_STRING:
- fval = strtod(RSTRING(val)->ptr, 0);
- break;
- default:
- Check_Type(val, T_FLOAT);
- break;
- }
-
- 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 503686b111..0000000000
--- a/st.c
+++ /dev/null
@@ -1,500 +0,0 @@
-/* This is a 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 USE_CWGUSI
-#include <stdlib.h>
-#endif
-
-#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,
-};
-
-#ifndef xmalloc
-void *xmalloc();
-void *xcalloc();
-void *xrealloc();
-#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) ((*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 + 83,
- 8192 + 27,
- 16384 + 43,
- 32768 + 3,
- 65536 + 45,
- 131072 + 9,
- 262144 + 39,
- 524288 + 39,
- 1048576 + 9,
- 2097152 + 5,
- 4194304 + 3,
- 8388608 + 33,
- 16777216 + 27,
- 33554432 + 9,
- 67108864 + 71,
- 134217728 + 39,
- 268435456 + 9,
- 536870912 + 5,
- 1073741824 + 83,
- 0
-};
-
-static int
-new_size(size)
- int size;
-{
- int i, 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 */
-}
-
-st_table*
-st_init_table_with_size(type, size)
- struct st_hash_type *type;
- int size;
-{
- st_table *tbl;
-
- 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)))
-
-#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)) {\
- 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);
- 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 (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 val = 0;
- register int c;
-
- while ((c = *string++) != '\0') {
- val = val*997 + c;
- }
-
- return val;
-}
-
-static int
-numcmp(x, y)
- int x, y;
-{
- return x != y;
-}
-
-static int
-numhash(n)
- int n;
-{
- return n;
-}
diff --git a/st.h b/st.h
deleted file mode 100644
index b626969f83..0000000000
--- a/st.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/* This is a 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 97f4f89b69..0000000000
--- a/string.c
+++ /dev/null
@@ -1,2706 +0,0 @@
-/************************************************
-
- string.c -
-
- $Author$
- $Date$
- created at: Mon Aug 9 17:12:58 JST 1993
-
- Copyright (C) 1993-1999 Yukihiro Matsumoto
-
-************************************************/
-
-#include "ruby.h"
-#include "re.h"
-
-#define BEG(no) regs->beg[no]
-#define END(no) regs->end[no]
-
-#include <ctype.h>
-
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-
-#ifndef atof
-double strtod();
-#endif
-
-VALUE rb_cString;
-
-#define STR_FREEZE FL_USER1
-#define STR_NO_ORIG FL_USER3
-
-extern VALUE rb_rs;
-
-VALUE
-rb_str_new(ptr, len)
- const char *ptr;
- long len;
-{
- NEWOBJ(str, struct RString);
- OBJSETUP(str, rb_cString, T_STRING);
-
- str->ptr = 0;
- str->len = len;
- str->orig = 0;
- str->ptr = ALLOC_N(char,len+1);
- if (ptr) {
- memcpy(str->ptr, ptr, len);
- }
- str->ptr[len] = '\0';
- return (VALUE)str;
-}
-
-VALUE
-rb_str_new2(ptr)
- const char *ptr;
-{
- 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;
-}
-
-VALUE
-rb_str_new3(str)
- VALUE str;
-{
- NEWOBJ(str2, struct RString);
- OBJSETUP(str2, rb_cString, T_STRING);
-
- str2->len = RSTRING(str)->len;
- str2->ptr = RSTRING(str)->ptr;
- str2->orig = str;
-
- return (VALUE)str2;
-}
-
-VALUE
-rb_str_new4(orig)
- VALUE orig;
-{
- if (FL_TEST(orig, STR_FREEZE)) {
- return orig;
- }
- else if (RSTRING(orig)->orig && !FL_TEST(orig, STR_NO_ORIG)) {
- return rb_str_freeze(RSTRING(orig)->orig);
- }
- else {
- NEWOBJ(str, struct RString);
- OBJSETUP(str, rb_cString, T_STRING);
-
- str->len = RSTRING(orig)->len;
- str->ptr = RSTRING(orig)->ptr;
- RSTRING(orig)->orig = (VALUE)str;
- str->orig = 0;
- if (OBJ_TAINTED(orig)) {
- OBJ_TAINT(str);
- }
- FL_SET(str, STR_FREEZE);
- return (VALUE)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)->orig = 0;
- return;
- }
- if ((!RSTRING(str)->orig||FL_TEST(str, STR_NO_ORIG))&&RSTRING(str)->ptr)
- free(RSTRING(str)->ptr);
- RSTRING(str)->ptr = RSTRING(str2)->ptr;
- RSTRING(str)->len = RSTRING(str2)->len;
- RSTRING(str)->orig = RSTRING(str2)->orig;
- RSTRING(str2)->ptr = 0; /* abandon str2 */
- RSTRING(str2)->len = 0;
- if (OBJ_TAINTED(str2)) OBJ_TAINT(str);
-}
-
-static ID to_str;
-
-VALUE
-rb_obj_as_string(obj)
- VALUE obj;
-{
- VALUE str;
-
- if (TYPE(obj) == T_STRING) {
- return obj;
- }
- str = rb_funcall(obj, to_str, 0);
- if (TYPE(str) != T_STRING)
- return rb_any_to_s(obj);
- if (OBJ_TAINTED(obj)) OBJ_TAINT(str);
- return str;
-}
-
-static VALUE
-rb_str_clone(orig)
- VALUE orig;
-{
- VALUE str;
-
- if (RSTRING(orig)->orig && !FL_TEST(orig, STR_NO_ORIG))
- str = rb_str_new3(RSTRING(orig)->orig);
- else
- str = rb_str_new(RSTRING(orig)->ptr, RSTRING(orig)->len);
- if (RSTRING(orig)->orig && FL_TEST(orig, STR_NO_ORIG))
- RSTRING(str)->orig = RSTRING(orig)->orig;
- CLONESETUP(str, orig);
- return str;
-}
-
-VALUE
-rb_str_dup(str)
- VALUE str;
-{
- VALUE s;
-
- if (TYPE(str) != T_STRING) str = rb_str_to_str(str);
- s = rb_str_new(RSTRING(str)->ptr, RSTRING(str)->len);
- if (OBJ_TAINTED(str)) OBJ_TAINT(s);
-
- return s;
-}
-
-static VALUE
-rb_str_s_new(klass, orig)
- VALUE klass;
- VALUE orig;
-{
- NEWOBJ(str, struct RString);
- OBJSETUP(str, klass, T_STRING);
-
- str->orig = 0;
- orig = rb_obj_as_string(orig);
- str->len = RSTRING(orig)->len;
- if (RSTRING(orig)->ptr) {
- str->ptr = ALLOC_N(char, RSTRING(orig)->len+1);
- memcpy(str->ptr, RSTRING(orig)->ptr, RSTRING(orig)->len);
- str->ptr[RSTRING(orig)->len] = '\0';
- }
-
- if (rb_safe_level() >= 3) {
- OBJ_TAINT(str);
- }
-
- return (VALUE)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;
-
- if (TYPE(str2) != T_STRING) str2 = rb_str_to_str(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) {
- rb_raise(rb_eArgError, "negative argument");
- }
-
- str2 = rb_str_new(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';
-
- if (OBJ_TAINTED(str)) {
- OBJ_TAINT(str2);
- }
-
- 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);
-}
-
-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_new(0,0);
-
- str2 = rb_str_new(RSTRING(str)->ptr+beg, len);
- if (OBJ_TAINTED(str)) OBJ_TAINT(str2);
-
- return str2;
-}
-
-void
-rb_str_modify(str)
- VALUE str;
-{
- char *ptr;
-
- if (FL_TEST(str, STR_FREEZE))
- rb_raise(rb_eTypeError, "can't modify frozen string");
- if (!OBJ_TAINTED(str) && rb_safe_level() >= 4)
- rb_raise(rb_eSecurityError, "Insecure: can't modify string");
- if (!RSTRING(str)->orig || FL_TEST(str, STR_NO_ORIG)) return;
- ptr = RSTRING(str)->ptr;
- RSTRING(str)->ptr = ALLOC_N(char, RSTRING(str)->len+1);
- if (RSTRING(str)->ptr) {
- memcpy(RSTRING(str)->ptr, ptr, RSTRING(str)->len);
- RSTRING(str)->ptr[RSTRING(str)->len] = 0;
- }
- RSTRING(str)->orig = 0;
-}
-
-VALUE
-rb_str_freeze(str)
- VALUE str;
-{
- if (rb_safe_level() >= 4 && !OBJ_TAINTED(str))
- rb_raise(rb_eSecurityError, "Insecure: can't freeze string");
-
- FL_SET(str, STR_FREEZE);
- return str;
-}
-
-static VALUE
-rb_str_frozen_p(str)
- VALUE str;
-{
- if (FL_TEST(str, STR_FREEZE))
- return Qtrue;
- return Qfalse;
-}
-
-VALUE
-rb_str_dup_frozen(str)
- VALUE str;
-{
- if (RSTRING(str)->orig && !FL_TEST(str, STR_NO_ORIG)) {
- return rb_str_freeze(RSTRING(str)->orig);
- }
- if (FL_TEST(str, STR_FREEZE))
- return str;
- return rb_str_freeze(rb_str_dup(str));
-}
-
-VALUE
-rb_str_resize(str, len)
- VALUE str;
- long len;
-{
- rb_str_modify(str);
-
- if (len >= 0) {
- if (RSTRING(str)->len < len || RSTRING(str)->len - len > 1024) {
- REALLOC_N(RSTRING(str)->ptr, char, len + 1);
- }
- RSTRING(str)->len = len;
- RSTRING(str)->ptr[len] = '\0'; /* sentinel */
- }
- return str;
-}
-
-VALUE
-rb_str_cat(str, ptr, len)
- VALUE str;
- const char *ptr;
- long len;
-{
- if (len > 0) {
- rb_str_modify(str);
- REALLOC_N(RSTRING(str)->ptr, char, RSTRING(str)->len + len + 1);
- if (ptr)
- memcpy(RSTRING(str)->ptr + RSTRING(str)->len, ptr, len);
- RSTRING(str)->len += len;
- RSTRING(str)->ptr[RSTRING(str)->len] = '\0'; /* sentinel */
- }
- return str;
-}
-
-VALUE
-rb_str_concat(str1, str2)
- VALUE str1, str2;
-{
- rb_str_modify(str1);
- if (FIXNUM_P(str2)) {
- int i = FIX2INT(str2);
- if (0 <= i && i <= 0xff) { /* byte */
- char c = i;
- return rb_str_cat(str1, &c, 1);
- }
- }
- if (TYPE(str2) != T_STRING) str2 = rb_str_to_str(str2);
- str1 = rb_str_cat(str1, RSTRING(str2)->ptr, RSTRING(str2)->len);
- if (OBJ_TAINTED(str2)) OBJ_TAINT(str1);
- 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;
-
- if (ruby_ignorecase) {
- while (len--) {
- key = key*65599 + toupper(*p);
- p++;
- }
- }
- else {
- while (len--) {
- key = key*65599 + *p;
- p++;
- }
- }
- return key;
-}
-
-static VALUE
-rb_str_hash_method(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;
-
- if (ruby_ignorecase) {
- return rb_str_cicmp(str1, str2);
- }
-
- len = lesser(RSTRING(str1)->len, RSTRING(str2)->len);
- retval = 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 0;
- if (retval > 0) return 1;
- return -1;
-}
-
-static VALUE
-rb_str_equal(str1, str2)
- VALUE str1, str2;
-{
- if (TYPE(str2) != T_STRING)
- return Qfalse;
-
- if (RSTRING(str1)->len == RSTRING(str2)->len
- && rb_str_cmp(str1, str2) == 0) {
- return Qtrue;
- }
- return Qfalse;
-}
-
-static VALUE
-rb_str_cmp_method(str1, str2)
- VALUE str1, str2;
-{
- int result;
-
- if (TYPE(str2) != T_STRING) str2 = rb_str_to_str(str2);
- result = rb_str_cmp(str1, str2);
- return INT2FIX(result);
-}
-
-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;
-{
- return rb_reg_match2(rb_reg_regcomp(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 (*s == *(RSTRING(sub)->ptr) && memcmp(s, p, len) == 0) {
- return (s-(RSTRING(str)->ptr));
- }
- s++;
- }
- return -1;
-}
-
-static VALUE
-rb_str_index_method(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;
- }
-
- 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 > 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 (*s == *t && 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, str2;
- char *sbeg, *s;
- int c = -1;
-
- str = rb_str_new(RSTRING(orig)->ptr, RSTRING(orig)->len);
-
- sbeg = RSTRING(str)->ptr; s = sbeg + RSTRING(str)->len - 1;
-
- while (sbeg <= s) {
- if (ISALNUM(*s) && (c = succ_char(s)) == 0) break;
- s--;
- }
- if (s < sbeg) {
- if (c == -1 && RSTRING(str)->len > 0) {
- RSTRING(str)->ptr[RSTRING(str)->len-1] += 1;
- }
- else {
- str2 = rb_str_new(0, RSTRING(str)->len+1);
- RSTRING(str2)->ptr[0] = c;
- memcpy(RSTRING(str2)->ptr+1, RSTRING(str)->ptr, RSTRING(str)->len);
- str = str2;
- }
- }
-
- if (OBJ_TAINTED(orig)) {
- OBJ_TAINT(str);
- }
-
- 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");
-
- if (TYPE(end) != T_STRING) end = rb_str_to_str(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_method(beg, end)
- VALUE beg, end;
-{
- return rb_str_upto(beg, end, 0);
-}
-
-static VALUE
-rb_str_aref(str, indx)
- VALUE str;
- VALUE indx;
-{
- long idx;
-
- switch (TYPE(indx)) {
- case T_FIXNUM:
- idx = FIX2LONG(indx);
-
- 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:
- if (rb_reg_search(indx, str, 0, 0) >= 0)
- return rb_reg_last_match(rb_backref_get());
- return Qnil;
-
- case T_STRING:
- if (rb_str_index(str, indx, 0) != -1) return 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);
- }
- }
- rb_raise(rb_eIndexError, "invalid index for string");
- }
- return Qnil; /* not reached */
-}
-
-static VALUE
-rb_str_aref_method(argc, argv, str)
- int argc;
- VALUE *argv;
- VALUE str;
-{
- VALUE arg1, arg2;
-
- if (rb_scan_args(argc, argv, "11", &arg1, &arg2) == 2) {
- return rb_str_substr(str, NUM2INT(arg1), NUM2INT(arg2));
- }
- return rb_str_aref(str, arg1);
-}
-
-static void
-rb_str_replace(str, beg, len, val)
- VALUE str, val;
- int beg;
- int len;
-{
- if (len < RSTRING(val)->len) {
- /* expand string */
- REALLOC_N(RSTRING(str)->ptr, char, RSTRING(str)->len+RSTRING(val)->len-len+1);
- }
-
- if (len != RSTRING(val)->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);
- }
- memcpy(RSTRING(str)->ptr+beg, RSTRING(val)->ptr, RSTRING(val)->len);
- RSTRING(str)->len += RSTRING(val)->len - len;
- RSTRING(str)->ptr[RSTRING(str)->len] = '\0';
-}
-
-static VALUE rb_str_sub_bang _((int, VALUE*, VALUE));
-
-static VALUE
-rb_str_aset(str, indx, val)
- VALUE str;
- VALUE indx, val;
-{
- int idx;
- int beg;
-
- switch (TYPE(indx)) {
- case T_FIXNUM:
- beg = idx = NUM2INT(indx);
- if (idx < 0) {
- idx += RSTRING(str)->len;
- }
- if (idx < 0 || RSTRING(str)->len <= idx) {
- rb_raise(rb_eIndexError, "index %d out of string", idx);
- }
- if (FIXNUM_P(val)) {
- if (RSTRING(str)->len == idx) {
- RSTRING(str)->len += 1;
- REALLOC_N(RSTRING(str)->ptr, char, RSTRING(str)->len);
- }
- RSTRING(str)->ptr[idx] = NUM2INT(val) & 0xff;
- }
- else {
- if (TYPE(val) != T_STRING) val = rb_str_to_str(val);
- rb_str_replace(str, idx, 1, val);
- }
- return val;
-
- case T_REGEXP:
- {
- VALUE args[2];
- args[0] = indx;
- args[1] = val;
- rb_str_sub_bang(2, args, str);
- }
- return val;
-
- case T_STRING:
- beg = rb_str_index(str, indx, 0);
- if (beg != -1) {
- if (TYPE(val) != T_STRING) val = rb_str_to_str(val);
- rb_str_replace(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)) {
- if (TYPE(val) != T_STRING) val = rb_str_to_str(val);
- rb_str_replace(str, beg, len, val);
- return val;
- }
- }
- rb_raise(rb_eIndexError, "invalid index for string");
- }
-}
-
-static VALUE
-rb_str_aset_method(argc, argv, str)
- int argc;
- VALUE *argv;
- VALUE str;
-{
- VALUE arg1, arg2, arg3;
-
- rb_str_modify(str);
-
- if (rb_scan_args(argc, argv, "21", &arg1, &arg2, &arg3) == 3) {
- int beg, len;
-
- if (TYPE(arg3) != T_STRING) arg3 = rb_str_to_str(arg3);
- beg = NUM2INT(arg1);
- len = NUM2INT(arg2);
- if (len < 0) rb_raise(rb_eIndexError, "negative length %d", len);
- if (beg < 0) {
- beg += RSTRING(str)->len;
- }
- if (beg < 0 || RSTRING(str)->len < beg) {
- if (beg < 0) {
- beg -= RSTRING(str)->len;
- }
- rb_raise(rb_eIndexError, "index %d out of string", beg);
- }
- if (beg + len > RSTRING(str)->len) {
- len = RSTRING(str)->len - beg;
- }
- rb_str_replace(str, beg, len, arg3);
- return arg3;
- }
- return rb_str_aset(str, arg1, arg2);
-}
-
-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 plen;
-
- if (argc == 1 && rb_iterator_p()) {
- iter = 1;
- }
- else if (argc == 2) {
- repl = rb_obj_as_string(argv[1]);;
- }
- else {
- rb_raise(rb_eArgError, "wrong # 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, Qtrue);
- repl = rb_obj_as_string(rb_yield(rb_reg_nth_match(0, match)));
- rb_match_busy(match, Qfalse);
- rb_backref_set(match);
- }
- else {
- repl = rb_reg_regsub(repl, str, regs);
- }
- plen = END(0) - BEG(0);
- if (RSTRING(repl)->len > plen) {
- REALLOC_N(RSTRING(str)->ptr, char,
- RSTRING(str)->len + RSTRING(repl)->len - plen + 1);
- }
- 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';
- 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
-rb_str_gsub_bang(argc, argv, str)
- int argc;
- VALUE *argv;
- VALUE str;
-{
- VALUE pat, val, repl, match;
- struct re_registers *regs;
- int beg, n;
- int iter = 0;
- char *buf, *bp, *cp;
- int offset, blen, len;
-
- if (argc == 1 && rb_iterator_p()) {
- iter = 1;
- }
- else if (argc == 2) {
- repl = rb_obj_as_string(argv[1]);;
- }
- else {
- rb_raise(rb_eArgError, "wrong # 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) return Qnil; /* no match, no substitution */
-
- 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, Qtrue);
- val = rb_obj_as_string(rb_yield(rb_reg_nth_match(0, match)));
- rb_match_busy(match, Qfalse);
- rb_backref_set(match);
- }
- else {
- val = rb_reg_regsub(repl, str, regs);
- }
- 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_str_modify(str);
- free(RSTRING(str)->ptr);
- RSTRING(str)->ptr = buf;
- RSTRING(str)->len = len = bp - buf;
- RSTRING(str)->ptr[len] = '\0';
-
- return str;
-}
-
-static VALUE
-rb_str_gsub(argc, argv, str)
- int argc;
- VALUE *argv;
- VALUE str;
-{
- str = rb_str_dup(str);
- rb_str_gsub_bang(argc, argv, str);
- return str;
-}
-
-static VALUE
-rb_str_replace_method(str, str2)
- VALUE str, str2;
-{
- if (TYPE(str2) != T_STRING) str2 = rb_str_to_str(str2);
- rb_str_modify(str);
- rb_str_resize(str, RSTRING(str2)->len);
- memcpy(RSTRING(str)->ptr, RSTRING(str2)->ptr, RSTRING(str2)->len);
- if (OBJ_TAINTED(str2)) OBJ_TAINT(str);
-
- 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 line;
-
- line = rb_str_dup(uscore_get());
- if (!NIL_P(rb_str_sub_bang(argc, argv, line))) {
- rb_lastline_set(line);
- }
- return line;
-}
-
-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 line;
-
- line = rb_str_dup(uscore_get());
- if (!NIL_P(rb_str_gsub_bang(argc, argv, line = rb_str_dup(line)))) {
- rb_lastline_set(line);
- }
- return line;
-}
-
-static VALUE
-rb_str_reverse_bang(str)
- VALUE str;
-{
- char *s, *e, *p, *q;
-
- s = RSTRING(str)->ptr;
- e = s + RSTRING(str)->len - 1;
- p = q = ALLOCA_N(char, RSTRING(str)->len);
-
- while (e >= s) {
- *p++ = *e--;
- }
- MEMCPY(RSTRING(str)->ptr, q, char, RSTRING(str)->len);
-
- 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_new(0, RSTRING(str)->len);
- s = RSTRING(str)->ptr; e = s + RSTRING(str)->len - 1;
- p = RSTRING(obj)->ptr;
-
- while (e >= s) {
- *p++ = *e--;
- }
-
- 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;
- }
-
- if (TYPE(arg) != T_STRING) arg = rb_str_to_str(arg);
- i = rb_str_index(str, arg, 0);
-
- if (i == -1) return Qfalse;
- return Qtrue;
-}
-
-static VALUE
-rb_str_to_i(str)
- VALUE str;
-{
- return rb_str2inum(RSTRING(str)->ptr, 10);
-}
-
-static VALUE
-rb_str_to_f(str)
- VALUE str;
-{
- double f = strtod(RSTRING(str)->ptr, 0);
-
- return rb_float_new(f);
-}
-
-static VALUE
-rb_str_to_s(str)
- VALUE str;
-{
- return str;
-}
-
-VALUE
-rb_str_inspect(str)
- VALUE str;
-{
-#define STRMAX 80
- char buf[STRMAX];
- char *p, *pend;
- char *b;
-
- p = RSTRING(str)->ptr; pend = p + RSTRING(str)->len;
- b = buf;
- *b++ = '"';
-
-#define CHECK(n) {\
- if (b - buf + n > STRMAX - 4) {\
- strcpy(b, "...");\
- b += 3;\
- break;\
- }\
-}
-
- while (p < pend) {
- char c = *p++;
- if (ismbchar(c) && p < pend) {
- int len = mbclen(c);
-
- CHECK(len);
- *b++ = c;
- while (--len) {
- *b++ = *p++;
- }
- }
- else if (c == '"'|| c == '\\') {
- CHECK(2);
- *b++ = '\\';
- *b++ = c;
- }
- else if (ISPRINT(c)) {
- CHECK(1);
- *b++ = c;
- }
- else if (c == '\n') {
- CHECK(2);
- *b++ = '\\';
- *b++ = 'n';
- }
- else if (c == '\r') {
- CHECK(2);
- *b++ = '\\';
- *b++ = 'r';
- }
- else if (c == '\t') {
- CHECK(2);
- *b++ = '\\';
- *b++ = 't';
- }
- else if (c == '\f') {
- CHECK(2);
- *b++ = '\\';
- *b++ = 'f';
- }
- else if (c == '\013') {
- CHECK(2);
- *b++ = '\\';
- *b++ = 'v';
- }
- else if (c == '\007') {
- CHECK(2);
- *b++ = '\\';
- *b++ = 'a';
- }
- else if (c == 033) {
- CHECK(2);
- *b++ = '\\';
- *b++ = 'e';
- }
- else {
- CHECK(4);
- *b++ = '\\';
- sprintf(b, "%03o", c & 0377);
- b += 3;
- }
- }
- *b++ = '"';
- return rb_str_new(buf, b - buf);
-}
-
-static VALUE
-rb_str_dump(str)
- VALUE str;
-{
- int 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_new(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++ = '"';
-
- 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;
- t->now = *(USTR)t->p++;
- if (t->p < t->pend && *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);
- if (TYPE(src) != T_STRING) src = rb_str_to_str(src);
- 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 (TYPE(repl) != T_STRING) repl = rb_str_to_str(repl);
- 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;
-
- for (i=0; i<argc; i++) {
- VALUE s = argv[i];
-
- if (TYPE(s) != T_STRING)
- s = rb_str_to_str(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];
-
- if (TYPE(s) != T_STRING)
- s = rb_str_to_str(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 < 0) {
- rb_raise(rb_eArgError, "wrong # of arguments");
- }
- for (i=0; i<argc; i++) {
- VALUE s = argv[i];
-
- if (TYPE(s) != T_STRING)
- s = rb_str_to_str(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_method(argc, argv, str)
- int argc;
- VALUE *argv;
- VALUE str;
-{
- VALUE spat;
- VALUE limit;
- int char_sep = -1;
- int 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 {
- switch (TYPE(spat)) {
- case T_STRING:
- fs_set:
- 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;
- int 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++;
- if (ismbchar(*ptr)) {ptr++; end++;}
- }
- }
- }
- else {
- int start = beg;
- int last_null = 0;
- int idx;
- 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_new(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) {
- rb_ary_push(result, rb_str_substr(str, beg, RSTRING(str)->len-beg));
- }
- 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;
-
- if (TYPE(str) != T_STRING) str = rb_str_to_str(str);
- sep = rb_str_new2(sep0);
- return rb_str_split_method(1, &sep, str);
-}
-
-static VALUE
-rb_f_split(argc, argv)
- int argc;
- VALUE *argv;
-{
- return rb_str_split_method(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;
- int 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;
- }
- if (TYPE(rs) != T_STRING) {
- rs = rb_str_to_str(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 ||
- memcmp(RSTRING(rs)->ptr, p-rslen, rslen) == 0)) {
- line = rb_str_new(s, p - s);
- 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_new(s, p - s);
- rb_yield(line);
- }
-
- return str;
-}
-
-static VALUE
-rb_str_each_byte(str)
- VALUE str;
-{
- int 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 = rb_str_dup(uscore_get());
-
- if (!NIL_P(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;
- int len = RSTRING(str)->len;
-
- if (rb_scan_args(argc, argv, "01", &rs) == 0) {
- rs = rb_rs;
- }
- if (NIL_P(rs)) return Qnil;
-
- if (TYPE(rs) != T_STRING) rs = rb_str_to_str(rs);
- rslen = RSTRING(rs)->len;
- if (rslen == 0) {
- while (len>0 && p[len-1] == '\n') {
- len--;
- }
- if (len < RSTRING(str)->len) {
- 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 (p[len-1] == newline &&
- (rslen <= 1 ||
- memcmp(RSTRING(rs)->ptr, p+len-rslen, rslen) == 0)) {
- 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 = rb_str_dup(uscore_get());
- if (!NIL_P(rb_str_chomp_bang(argc, argv, str))) {
- rb_lastline_set(str);
- }
- return str;
-}
-
-static VALUE
-rb_str_strip_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++;
-
- /* remove trailing spaces */
- t--;
- while (s <= t && ISSPACE(*t)) t--;
- t++;
-
- RSTRING(str)->len = t-s;
- if (s > RSTRING(str)->ptr) {
- char *p = RSTRING(str)->ptr;
-
- RSTRING(str)->ptr = ALLOC_N(char, RSTRING(str)->len+1);
- memcpy(RSTRING(str)->ptr, s, RSTRING(str)->len);
- RSTRING(str)->ptr[RSTRING(str)->len] = '\0';
- free(p);
- }
- else if (t < e) {
- RSTRING(str)->ptr[RSTRING(str)->len] = '\0';
- }
- else {
- 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;
-
- pat = get_pat(pat);
- if (!rb_iterator_p()) {
- VALUE ary = rb_ary_new();
-
- while (!NIL_P(result = scan_once(str, pat, &start))) {
- rb_ary_push(ary, result);
- }
- return ary;
- }
-
- while (!NIL_P(result = scan_once(str, pat, &start))) {
- rb_yield(result);
- }
- return str;
-}
-
-static VALUE
-rb_str_hex(str)
- VALUE str;
-{
- return rb_str2inum(RSTRING(str)->ptr, 16);
-}
-
-static VALUE
-rb_str_oct(str)
- VALUE str;
-{
- int base = 8;
-
- if (RSTRING(str)->len > 2 && RSTRING(str)->ptr[0] == '0') {
- switch (RSTRING(str)->ptr[1]) {
- case 'x':
- case 'X':
- base = 16;
- break;
- case 'b':
- case 'B':
- base = 2;
- break;
- }
- }
- return rb_str2inum(RSTRING(str)->ptr, base);
-}
-
-static VALUE
-rb_str_crypt(str, salt)
- VALUE str, salt;
-{
- extern char *crypt();
-
- if (TYPE(salt) != T_STRING) salt = rb_str_to_str(salt);
- if (RSTRING(salt)->len < 2)
- rb_raise(rb_eArgError, "salt too short(need >=2 bytes)");
- return rb_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 INT2FIX(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 str;
- res = rb_str_new(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++ = ' ';
- }
- 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 str;
- res = rb_str_new(0, width);
- p = RSTRING(res)->ptr; pend = p + width - RSTRING(str)->len;
- while (p < pend) {
- *p++ = ' ';
- }
- memcpy(pend, RSTRING(str)->ptr, RSTRING(str)->len);
- 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 str;
- res = rb_str_new(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++ = ' ';
- }
- return res;
-}
-
-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, "new", rb_str_s_new, 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_method, 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_equal, 1);
- rb_define_method(rb_cString, "hash", rb_str_hash_method, 0);
- 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_method, -1);
- rb_define_method(rb_cString, "[]=", rb_str_aset_method, -1);
- 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, "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_method, 1);
- rb_define_method(rb_cString, "index", rb_str_index_method, -1);
- rb_define_method(rb_cString, "rindex", rb_str_rindex, -1);
- rb_define_method(rb_cString, "replace", rb_str_replace_method, 1);
-
- rb_define_method(rb_cString, "freeze", rb_str_freeze, 0);
- rb_define_method(rb_cString, "frozen?", rb_str_frozen_p, 0);
-
- rb_define_method(rb_cString, "to_i", rb_str_to_i, 0);
- 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_method, -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, "sub!", rb_str_sub_bang, -1);
- rb_define_method(rb_cString, "gsub!", rb_str_gsub_bang, -1);
- rb_define_method(rb_cString, "strip!", rb_str_strip_bang, 0);
- 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, "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);
-
- to_str = rb_intern("to_s");
-}
diff --git a/struct.c b/struct.c
deleted file mode 100644
index 1114577729..0000000000
--- a/struct.c
+++ /dev/null
@@ -1,592 +0,0 @@
-/************************************************
-
- struct.c -
-
- $Author$
- $Date$
- created at: Tue Mar 22 18:44:30 JST 1995
-
-************************************************/
-
-#include "ruby.h"
-
-#ifdef USE_CWGUSI
-#include <stdio.h>
-#endif
-
-VALUE rb_cStruct;
-
-static VALUE struct_alloc _((int, VALUE*, VALUE));
-
-static VALUE
-class_of(obj)
- VALUE obj;
-{
- obj = CLASS_OF(obj);
- if (FL_TEST(obj, FL_SINGLETON))
- return RCLASS(obj)->super;
- return obj;
-}
-
-static VALUE
-iv_get(obj, name)
- VALUE obj;
- char *name;
-{
- ID id;
-
- id = rb_intern(name);
- for (;;) {
- if (rb_ivar_defined(obj, id))
- return rb_ivar_get(obj, id);
- obj = RCLASS(obj)->super;
- if (obj == 0 || obj == rb_cStruct)
- return Qnil;
- }
-}
-
-static VALUE
-rb_struct_s_members(obj)
- VALUE obj;
-{
- VALUE member, ary;
- VALUE *p, *pend;
-
- member = iv_get(obj, "__member__");
- if (NIL_P(member)) {
- rb_bug("non-initialized 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(FIX2INT(*p))));
- p++;
- }
-
- return ary;
-}
-
-static VALUE
-rb_struct_members(obj)
- VALUE obj;
-{
- return rb_struct_s_members(class_of(obj));
-}
-
-VALUE
-rb_struct_getmember(obj, id)
- VALUE obj;
- ID id;
-{
- VALUE member, slot;
- long i;
-
- member = iv_get(class_of(obj), "__member__");
- if (NIL_P(member)) {
- rb_bug("non-initialized struct");
- }
- slot = INT2NUM(id);
- for (i=0; i<RARRAY(member)->len; i++) {
- if (RARRAY(member)->ptr[i] == slot) {
- return RSTRUCT(obj)->ptr[i];
- }
- }
- rb_raise(rb_eNameError, "%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 VALUE
-rb_struct_set(obj, val)
- VALUE obj, val;
-{
- VALUE member, slot;
- long i;
-
- member = iv_get(class_of(obj), "__member__");
- if (NIL_P(member)) {
- rb_bug("non-initialized struct");
- }
- for (i=0; i<RARRAY(member)->len; i++) {
- slot = RARRAY(member)->ptr[i];
- if (rb_id_attrset(FIX2INT(slot)) == rb_frame_last_func()) {
- return RSTRUCT(obj)->ptr[i] = val;
- }
- }
- rb_raise(rb_eNameError, "not struct member");
- 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);
- }
- else {
- char *cname = STR2CSTR(name);
- id = rb_intern(cname);
- if (!rb_is_const_id(id)) {
- rb_raise(rb_eNameError, "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, "new", struct_alloc, -1);
- rb_define_singleton_method(nstr, "[]", struct_alloc, -1);
- rb_define_singleton_method(nstr, "members", rb_struct_s_members, 0);
- for (i=0; i< RARRAY(member)->len; i++) {
- ID id = FIX2INT(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, INT2FIX(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] = INT2FIX(id);
- }
- if (TYPE(name) != T_STRING) {
- id = rb_to_id(name);
- rb_ary_unshift(rest, INT2FIX(id));
- name = Qnil;
- }
- st = make_struct(name, rest, klass);
-
- return st;
-}
-
-static VALUE
-rb_struct_initialize(self, values)
- VALUE self, values;
-{
- VALUE klass = CLASS_OF(self);
- VALUE size;
- long n;
-
- size = iv_get(klass, "__size__");
- n = FIX2INT(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(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- VALUE size;
- long n;
-
- NEWOBJ(st, struct RStruct);
- OBJSETUP(st, klass, T_STRUCT);
-
- size = iv_get(klass, "__size__");
- n = FIX2LONG(size);
-
- st->len = 0; /* avoid GC crashing */
- st->ptr = ALLOC_N(VALUE, n);
- rb_mem_clear(st->ptr, n);
- st->len = n;
- rb_obj_call_init((VALUE)st, argc, argv);
-
- return (VALUE)st;
-}
-
-VALUE
-rb_struct_alloc(klass, values)
- VALUE klass, values;
-{
- return struct_alloc(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 = 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 struct_alloc(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(CLASS_OF(s));
- char *buf = ALLOCA_N(char, strlen(cname) + 4);
-
- sprintf(buf, "#<%s>", cname);
- return rb_str_new2(buf);
-}
-
-static VALUE
-inspect_struct(s)
- VALUE s;
-{
- char *cname = rb_class2name(CLASS_OF(s));
- VALUE str, member;
- long i;
-
- member = iv_get(CLASS_OF(s), "__member__");
- if (NIL_P(member)) {
- rb_bug("non-initialized struct");
- }
-
- str = rb_str_new2("#<");
- rb_str_cat(str, cname, strlen(cname));
- rb_str_cat(str, " ", 1);
- for (i=0; i<RSTRUCT(s)->len; i++) {
- VALUE str2, slot;
- char *p;
-
- if (i > 0) {
- rb_str_cat(str, ", ", 2);
- }
- slot = RARRAY(member)->ptr[i];
- p = rb_id2name(FIX2LONG(slot));
- rb_str_cat(str, p, strlen(p));
- rb_str_cat(str, "=", 1);
- str2 = rb_inspect(RSTRUCT(s)->ptr[i]);
- rb_str_cat(str, RSTRING(str2)->ptr, RSTRING(str2)->len);
- }
- rb_str_cat(str, ">", 1);
-
- return str;
-}
-
-static VALUE
-rb_struct_inspect(s)
- VALUE s;
-{
- if (rb_inspecting_p(s)) {
- char *cname = rb_class2name(CLASS_OF(s));
- char *buf = ALLOCA_N(char, strlen(cname) + 8);
-
- sprintf(buf, "#<%s:...>", cname);
- return rb_str_new2(buf);
- }
- 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;
-{
- NEWOBJ(st, struct RStruct);
- CLONESETUP(st, s);
- st->len = 0; /* avoid GC crashing */
- st->ptr = ALLOC_N(VALUE, RSTRUCT(s)->len);
- st->len = RSTRUCT(s)->len;
- MEMCPY(st->ptr, RSTRUCT(s)->ptr, VALUE, st->len);
-
- return (VALUE)st;
-}
-
-static VALUE
-rb_struct_aref_id(s, id)
- VALUE s;
- ID id;
-{
- VALUE member;
- long i, len;
-
- member = iv_get(CLASS_OF(s), "__member__");
- if (NIL_P(member)) {
- rb_bug("non-initialized struct");
- }
-
- len = RARRAY(member)->len;
- for (i=0; i<len; i++) {
- if (FIX2UINT(RARRAY(member)->ptr[i]) == id) {
- return RSTRUCT(s)->ptr[i];
- }
- }
- rb_raise(rb_eNameError, "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) {
- 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 = iv_get(CLASS_OF(s), "__member__");
- if (NIL_P(member)) {
- rb_bug("non-initialized struct");
- }
-
- len = RARRAY(member)->len;
- for (i=0; i<len; i++) {
- if (FIX2UINT(RARRAY(member)->ptr[i]) == id) {
- RSTRUCT(s)->ptr[i] = val;
- return val;
- }
- }
- rb_raise(rb_eNameError, "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) {
- 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);
- return RSTRUCT(s)->ptr[i] = val;
-}
-
-static VALUE
-rb_struct_equal(s, s2)
- VALUE s, s2;
-{
- long i;
-
- if (TYPE(s2) != T_STRUCT) return Qfalse;
- if (CLASS_OF(s) != CLASS_OF(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_eql(s, s2)
- VALUE s, s2;
-{
- long i;
-
- if (TYPE(s2) != T_STRUCT) return Qfalse;
- if (CLASS_OF(s) != CLASS_OF(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_eql(RSTRUCT(s)->ptr[i], RSTRUCT(s2)->ptr[i])) return Qfalse;
- }
- return Qtrue;
-}
-
-static VALUE
-rb_struct_hash(s)
- VALUE s;
-{
- long i;
- int h;
-
- h = CLASS_OF(s);
- for (i=0; i<RSTRUCT(s)->len; i++) {
- h ^= rb_hash(RSTRUCT(s)->ptr[i]);
- }
- return INT2FIX(h);
-}
-
-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_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, "eql?", rb_struct_eql, 1);
- rb_define_method(rb_cStruct, "hash", rb_struct_hash, 0);
-
- 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, "members", rb_struct_members, 0);
-}
diff --git a/time.c b/time.c
deleted file mode 100644
index 4d18827597..0000000000
--- a/time.c
+++ /dev/null
@@ -1,1042 +0,0 @@
-/************************************************
-
- time.c -
-
- $Author$
- $Date$
- created at: Tue Dec 28 14:31:59 JST 1993
-
- Copyright (C) 1993-1999 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_SYS_TIMES_H
-#include <sys/times.h>
-#endif
-
-#ifdef USE_CWGUSI
-#define time_t long
-int gettimeofday(struct timeval*, struct timezone*);
-int strcasecmp(char*, char*);
-#endif
-
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-
-VALUE rb_cTime;
-#if defined(HAVE_TIMES) || defined(NT)
-static VALUE S_Tms;
-#endif
-
-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_now(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_new_internal(klass, sec, usec)
- VALUE klass;
- time_t sec, usec;
-{
- VALUE obj;
- struct time_object *tobj;
-
-#ifndef USE_CWGUSI
- 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);
-}
-
-struct timeval
-rb_time_interval(time)
- VALUE time;
-{
- struct timeval t;
-
- switch (TYPE(time)) {
- case T_FIXNUM:
- t.tv_sec = FIX2LONG(time);
- if (t.tv_sec < 0)
- rb_raise(rb_eArgError, "time must be positive");
- t.tv_usec = 0;
- break;
-
- case T_FLOAT:
- if (RFLOAT(time)->value < 0.0)
- rb_raise(rb_eArgError, "time must be positive");
- t.tv_sec = (time_t)RFLOAT(time)->value;
- t.tv_usec = (time_t)((RFLOAT(time)->value - (double)t.tv_sec)*1e6);
- break;
-
- case T_BIGNUM:
- t.tv_sec = NUM2LONG(time);
- if (t.tv_sec < 0)
- rb_raise(rb_eArgError, "time must be positive");
- t.tv_usec = 0;
- break;
-
- default:
- rb_raise(rb_eTypeError, "can't convert %s into Time interval",
- rb_class2name(CLASS_OF(time)));
- break;
- }
- return t;
-}
-
-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 rb_time_interval(time);
-}
-
-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 = NUM2INT(time);
- tv.tv_usec = NUM2INT(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_str2inum(RSTRING(obj)->ptr, 10);
- }
-
- return NUM2LONG(obj);
-}
-
-static void
-time_arg(argc, argv, tm)
- int argc;
- VALUE *argv;
- struct tm *tm;
-{
- VALUE v[6];
- int i;
-
- 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];
- }
- else {
- rb_scan_args(argc, argv, "15", &v[0],&v[1],&v[2],&v[3],&v[4],&v[5]);
- }
-
- tm->tm_year = obj2long(v[0]);
- if (0 <= tm->tm_year && tm->tm_year < 69) tm->tm_year += 100;
- if (tm->tm_year >= 1900) tm->tm_year -= 1900;
- 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 < 69
- || 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 time_t
-make_time_t(tptr, fn)
- struct tm *tptr;
- struct tm *(*fn)();
-{
- struct timeval tv;
- time_t oguess, guess;
- struct tm *tm;
- long t, diff;
-
- if (gettimeofday(&tv, 0) < 0) {
- rb_sys_fail("gettimeofday");
- }
- guess = tv.tv_sec;
-
- tm = (*fn)(&guess);
- if (!tm) goto error;
- t = tptr->tm_year;
- if (t < 69) goto out_of_range;
- while (diff = t - tm->tm_year) {
- oguess = guess;
- guess += diff * 364 * 24 * 3600;
- if (diff > 0 && guess <= oguess) goto out_of_range;
- tm = (*fn)(&guess);
- if (!tm) goto error;
- }
- t = tptr->tm_mon;
- while (diff = t - tm->tm_mon) {
- guess += diff * 27 * 24 * 3600;
- tm = (*fn)(&guess);
- if (!tm) goto error;
- if (tptr->tm_year != tm->tm_year) goto out_of_range;
- }
- guess += (tptr->tm_mday - tm->tm_mday) * 3600 * 24;
- guess += (tptr->tm_hour - tm->tm_hour) * 3600;
- guess += (tptr->tm_min - tm->tm_min) * 60;
- guess += (tptr->tm_sec - tm->tm_sec);
- if (guess < 0) goto out_of_range;
-
- return guess;
-
- out_of_range:
- rb_raise(rb_eArgError, "time out of range");
-
- error:
- rb_raise(rb_eArgError, "gmtime/localtime error");
- return 0; /* not reached */
-}
-
-static VALUE
-time_gm_or_local(argc, argv, gm_or_local, klass)
- int argc;
- VALUE *argv;
- int gm_or_local;
- VALUE klass;
-{
- struct tm tm;
- struct tm *(*fn)();
- VALUE time;
-
- fn = (gm_or_local) ? gmtime : localtime;
- time_arg(argc, argv, &tm);
-
- time = time_new_internal(klass, make_time_t(&tm, fn), 0);
- if (gm_or_local) return time_gmtime(time);
- return time_localtime(time);
-}
-
-static VALUE
-time_s_timegm(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- return time_gm_or_local(argc, argv, 1, klass);
-}
-
-static VALUE
-time_s_timelocal(argc, argv, klass)
- int argc;
- VALUE *argv;
- VALUE klass;
-{
- return time_gm_or_local(argc, argv, 0, klass);
-}
-
-static VALUE
-time_to_i(time)
- VALUE time;
-{
- struct time_object *tobj;
-
- GetTimeval(time, tobj);
- return INT2NUM(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/1000000);
-}
-
-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) return INT2FIX(0);
- if (tobj1->tv.tv_sec > i) return INT2FIX(1);
- return FIX2INT(-1);
-
- case T_FLOAT:
- {
- double t;
-
- if (tobj1->tv.tv_sec == (time_t)RFLOAT(time2)->value)
- return INT2FIX(0);
- t = (double)tobj1->tv.tv_sec + (double)tobj1->tv.tv_usec*1e-6;
- if (tobj1->tv.tv_sec == (time_t)RFLOAT(time2)->value)
- return INT2FIX(0);
- if (tobj1->tv.tv_sec > (time_t)RFLOAT(time2)->value)
- return INT2FIX(1);
- return FIX2INT(-1);
- }
- }
-
- if (rb_obj_is_instance_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 FIX2INT(-1);
- }
- if (tobj1->tv.tv_sec > tobj2->tv.tv_sec) return INT2FIX(1);
- return FIX2INT(-1);
- }
- i = NUM2LONG(time2);
- if (tobj1->tv.tv_sec == i) return INT2FIX(0);
- if (tobj1->tv.tv_sec > i) return INT2FIX(1);
- return FIX2INT(-1);
-}
-
-static VALUE
-time_eql(time1, time2)
- VALUE time1, time2;
-{
- struct time_object *tobj1, *tobj2;
-
- GetTimeval(time1, tobj1);
- if (rb_obj_is_instance_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_gmt_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 obj;
- struct time_object *tobj, *newtobj;
-
- GetTimeval(time, tobj);
- obj = Data_Make_Struct(0, struct time_object, 0, free, newtobj);
- CLONESETUP(obj, time);
- MEMCPY(newtobj, tobj, struct time_object, 1);
-
- return obj;
-}
-
-static VALUE
-time_localtime(time)
- VALUE time;
-{
- struct time_object *tobj;
- struct tm *tm_tmp;
- time_t t;
-
- GetTimeval(time, tobj);
- t = tobj->tv.tv_sec;
- tm_tmp = localtime(&t);
- 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);
- t = tobj->tv.tv_sec;
- tm_tmp = gmtime(&t);
- tobj->tm = *tm_tmp;
- tobj->tm_got = 1;
- tobj->gmt = 1;
- return 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);
- }
-#ifndef HAVE_TM_ZONE
- if (tobj->gmt == 1) {
- len = strftime(buf, 128, "%a %b %d %H:%M:%S GMT %Y", &tobj->tm);
- }
- else
-#endif
- {
- 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;
-
- GetTimeval(time1, tobj);
-
- if (rb_obj_is_kind_of(time2, rb_cTime)) {
- rb_raise(rb_eTypeError, "time + time?");
- }
- f = NUM2DBL(time2);
- sec = (time_t)f;
- usec = tobj->tv.tv_usec + (time_t)((f - (double)sec)*1e6);
- sec = tobj->tv.tv_sec + sec;
-
- if (usec >= 1000000) { /* usec overflow */
- sec++;
- usec -= 1000000;
- }
- 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;
-
- GetTimeval(time1, tobj);
- if (rb_obj_is_instance_of(time2, rb_cTime)) {
- struct time_object *tobj2;
-
- GetTimeval(time2, tobj2);
- f = tobj->tv.tv_sec - tobj2->tv.tv_sec;
- f += (tobj->tv.tv_usec - tobj2->tv.tv_usec)*1e-6;
-
- return rb_float_new(f);
- }
- else {
- f = NUM2DBL(time2);
- sec = (time_t)f;
- usec = tobj->tv.tv_usec - (time_t)((f - (double)sec)*1e6);
- sec = tobj->tv.tv_sec - sec;
- }
-
- if (usec < 0) { /* usec underflow */
- sec--;
- usec += 1000000;
- }
- 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 INT2FIX(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);
- }
-
- len = strftime(buf, 64, "%Z", &tobj->tm);
- return rb_str_new(buf, len);
-}
-
-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),
- INT2FIX(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) 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 || len >= 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);
- }
- fmt = str2cstr(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 (len > SMALLBUF) free(buf);
- }
- 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;
-{
-#ifdef HAVE_TIMES
-#ifndef HZ
-#define HZ 60 /* Universal constant :-) */
-#endif /* HZ */
- struct tms buf;
-
- if (times(&buf) == -1) rb_sys_fail(0);
- 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
-#ifdef NT
- FILETIME create, exit, kernel, user;
- HANDLE hProc;
-
- hProc = GetCurrentProcess();
- GetProcessTimes(hProc,&create, &exit, &kernel, &user);
- return rb_struct_new(S_Tms,
- rb_float_new((double)(kernel.dwHighDateTime*2e32+kernel.dwLowDateTime)/2e6),
- rb_float_new((double)(user.dwHighDateTime*2e32+user.dwLowDateTime)/2e6),
- rb_float_new((double)0),
- rb_float_new((double)0));
-#else
- rb_notimplement();
-#endif
-#endif
-}
-
-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);
-
- 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;
-
- buf = str2cstr(str, &i);
- if (i != 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;
-
- sec = make_time_t(&tm, gmtime);
- 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, "new", time_s_now, 0);
- rb_define_singleton_method(rb_cTime, "at", time_s_at, -1);
- rb_define_singleton_method(rb_cTime, "gm", time_s_timegm, -1);
- rb_define_singleton_method(rb_cTime, "local", time_s_timelocal, -1);
- rb_define_singleton_method(rb_cTime, "mktime", time_s_timelocal, -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, "localtime", time_localtime, 0);
- rb_define_method(rb_cTime, "gmtime", time_gmtime, 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, "zone", time_zone, 0);
-
- rb_define_method(rb_cTime, "gmt?", time_gmt_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);
-
-#if defined(HAVE_TIMES) || defined(NT)
- S_Tms = rb_struct_define("Tms", "utime", "stime", "cutime", "cstime", 0);
-#endif
-
- /* 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/top.sed b/top.sed
deleted file mode 100644
index feef9006ba..0000000000
--- a/top.sed
+++ /dev/null
@@ -1,68 +0,0 @@
-/^SHELL/s,/bin/sh,$(COMPSEC),
-s/@srcdir@/./g
-s/@top_srcdir@/../
-s%@CFLAGS@%-O2%g
-s%@CPPFLAGS@%%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-djgpp%g
-s%@host_alias@%i386-djgpp%g
-s%@host_cpu@%i386%g
-s%@host_vendor@%pc%g
-s%@host_os@%djgpp%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 fnmatch.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%@RUBY_INSTALL_NAME@%ruby%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-djgpp%g
-s%/bin/rm%rm%
-s%|| true%%
-s%@archlib@%/usr/local/lib/ruby/i386-djgpp%
-/\/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%
diff --git a/util.c b/util.c
deleted file mode 100644
index 04b3dd6dbe..0000000000
--- a/util.c
+++ /dev/null
@@ -1,811 +0,0 @@
-/************************************************
-
- util.c -
-
- $Author$
- $Date$
- created at: Fri Mar 10 17:22:34 JST 1995
-
- Copyright (C) 1993-1999 Yukihiro Matsumoto
-
-************************************************/
-
-#include <stdio.h>
-
-#ifdef NT
-#include "missing/file.h"
-#endif
-
-#define RUBY_NO_INLINE
-#include "ruby.h"
-
-#ifdef USE_CWGUSI
-extern char* mktemp(char*);
-#endif
-
-VALUE
-rb_class_of(obj)
- VALUE obj;
-{
- 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;
-
- return RBASIC(obj)->klass;
-}
-
-int
-rb_type(obj)
- VALUE obj;
-{
- 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;
-
- return BUILTIN_TYPE(obj);
-}
-
-int
-rb_special_const_p(obj)
- VALUE obj;
-{
- if (FIXNUM_P(obj)) return Qtrue;
- if (obj == Qnil) return Qtrue;
- if (obj == Qfalse) return Qtrue;
- if (obj == Qtrue) return Qtrue;
-
- return Qfalse;
-}
-
-int
-rb_test_false_or_nil(v)
- VALUE v;
-{
- return (v != Qnil) && (v != Qfalse);
-}
-
-#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[] = "0123456789abcdef0123456789ABCDEFx";
- 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
-
-static char *
-check_dir(dir)
- char *dir;
-{
- struct stat st;
-
- if (dir == NULL) return NULL;
- if (stat(dir, &st) < 0) return NULL;
- if (!S_ISDIR(st.st_mode)) return NULL;
- if (eaccess(dir, W_OK) < 0) return NULL;
- return dir;
-}
-
-char *
-ruby_mktemp()
-{
- char *dir;
- char *buf;
-
- dir = check_dir(getenv("TMP"));
- if (!dir) dir = check_dir(getenv("TMPDIR"));
- if (!dir) dir = "/tmp";
-
- buf = ALLOC_N(char,strlen(dir)+10);
- sprintf(buf, "%s/rbXXXXXX", dir);
- dir = mktemp(buf);
- if (dir == NULL) free(buf);
-
- return dir;
-}
-
-#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
-
-#ifdef DJGPP
-/* Copyright (C) 1995 DJ Delorie, see COPYING.DJ for details */
-#include <libc/stubs.h>
-#include <stdio.h> /* For FILENAME_MAX */
-#include <errno.h> /* For errno */
-#include <fcntl.h> /* For LFN stuff */
-#include <go32.h>
-#include <dpmi.h> /* For dpmisim */
-#include <crt0.h> /* For crt0 flags */
-#include <libc/dosio.h>
-
-static unsigned use_lfn;
-
-static char *__get_current_directory(char *out, int drive_number);
-
-static char *
-__get_current_directory(char *out, int drive_number)
-{
- __dpmi_regs r;
- char tmpbuf[FILENAME_MAX];
-
- memset(&r, 0, sizeof(r));
- if(use_lfn)
- r.x.ax = 0x7147;
- else
- r.h.ah = 0x47;
- r.h.dl = drive_number + 1;
- r.x.si = __tb_offset;
- r.x.ds = __tb_segment;
- __dpmi_int(0x21, &r);
-
- if (r.x.flags & 1)
- {
- errno = r.x.ax;
- return out;
- }
- else
- {
- dosmemget(__tb, sizeof(tmpbuf), tmpbuf);
- strcpy(out+1,tmpbuf);
-
- /* Root path, don't insert "/", it'll be added later */
- if (*(out + 1) != '\0')
- *out = '/';
- else
- *out = '\0';
- return out + strlen(out);
- }
-}
-
-__inline__ static int
-is_slash(int c)
-{
- return c == '/' || c == '\\';
-}
-
-__inline__ static int
-is_term(int c)
-{
- return c == '/' || c == '\\' || c == '\0';
-}
-
-#ifdef SJIS
-__inline__ static int
-is_sjis1(int c)
-{
- return 0x81 <= c && (c <= 0x9f || 0xe0 <= c);
-}
-#endif
-
-/* Takes as input an arbitrary path. Fixes up the path by:
- 1. Removing consecutive slashes
- 2. Removing trailing slashes
- 3. Making the path absolute if it wasn't already
- 4. Removing "." in the path
- 5. Removing ".." entries in the path (and the directory above them)
- 6. Adding a drive specification if one wasn't there
- 7. Converting all slashes to '/'
- */
-void
-_fixpath(const char *in, char *out)
-{
- int drive_number;
- const char *ip = in;
- char *op = out;
- int preserve_case = _preserve_fncase();
- char *name_start;
-
- use_lfn = _USE_LFN;
-
- /* Add drive specification to output string */
- if (((*ip >= 'a' && *ip <= 'z') ||
- (*ip >= 'A' && *ip <= 'Z'))
- && (*(ip + 1) == ':'))
- {
- if (*ip >= 'a' && *ip <= 'z')
- {
- drive_number = *ip - 'a';
- *op++ = *ip++;
- }
- else
- {
- drive_number = *ip - 'A';
- if (*ip <= 'Z')
- *op++ = drive_number + 'a';
- else
- *op++ = *ip;
- ++ip;
- }
- *op++ = *ip++;
- }
- else
- {
- __dpmi_regs r;
- r.h.ah = 0x19;
- __dpmi_int(0x21, &r);
- drive_number = r.h.al;
- *op++ = drive_number + (drive_number < 26 ? 'a' : 'A');
- *op++ = ':';
- }
-
- /* Convert relative path to absolute */
- if (!is_slash(*ip))
- op = __get_current_directory(op, drive_number);
-
- /* Step through the input path */
- while (*ip)
- {
- /* Skip input slashes */
- if (is_slash(*ip))
- {
- ip++;
- continue;
- }
-
- /* Skip "." and output nothing */
- if (*ip == '.' && is_term(*(ip + 1)))
- {
- ip++;
- continue;
- }
-
- /* Skip ".." and remove previous output directory */
- if (*ip == '.' && *(ip + 1) == '.' && is_term(*(ip + 2)))
- {
- ip += 2;
- /* Don't back up over drive spec */
- if (op > out + 2)
- /* This requires "/" to follow drive spec */
- while (!is_slash(*--op));
- continue;
- }
-
- /* Copy path component from in to out */
- *op++ = '/';
-#ifndef SJIS
- while (!is_term(*ip)) *op++ = *ip++;
-#else
- while (!is_term(*ip)) {
- if (is_sjis1((unsigned char)*ip))
- *op++ = *ip++;
- *op++ = *ip++;
- }
-#endif
- }
-
- /* If root directory, insert trailing slash */
- if (op == out + 2) *op++ = '/';
-
- /* Null terminate the output */
- *op = '\0';
-
- /* switch FOO\BAR to foo/bar, downcase where appropriate */
- for (op = out + 3, name_start = op - 1; *name_start; op++)
- {
- char long_name[FILENAME_MAX], short_name[13];
-
-#ifdef SJIS
- if (is_sjis1((unsigned char)*op)) {
- op++;
- continue;
- }
-#endif
- if (*op == '\\')
- *op = '/';
- if (!preserve_case && (*op == '/' || *op == '\0'))
- {
- memcpy(long_name, name_start+1, op - name_start - 1);
- long_name[op - name_start - 1] = '\0';
- if (!strcmp(_lfn_gen_short_fname(long_name, short_name), long_name))
- {
-#ifndef SJIS
- while (++name_start < op)
- if (*name_start >= 'A' && *name_start <= 'Z')
- *name_start += 'a' - 'A';
-#else
- while (++name_start < op) {
- if (is_sjis1((unsigned char)*name_start))
- name_start++;
- else if (*name_start >= 'A' && *name_start <= 'Z')
- *name_start += 'a' - 'A';
- }
-#endif
- }
- else
- name_start = op;
- }
- else if (*op == '\0')
- break;
- }
-}
-
-#ifdef TEST
-
-int main (int argc, char *argv[])
-{
- char fixed[FILENAME_MAX];
- if (argc > 1)
- {
- _fixpath (argv[1], fixed);
- printf ("You mean %s?\n", fixed);
- }
- return 0;
-}
-
-#endif
-#endif
-
-/* mm.c */
-
-static int mmkind, mmsize, high, low;
-
-#define A ((int*)a)
-#define B ((int*)b)
-#define C ((int*)c)
-#define D ((int*)d)
-
-static void mmprepare(base, size) void *base; int size;
-{
-#ifdef DEBUG
- if (sizeof(int) != 4) die("sizeof(int) != 4");
- if (size <= 0) die("mmsize <= 0");
-#endif
-
- if (((long)base & (4-1)) == 0 && ((long)base & (4-1)) == 0)
- if (size >= 16) mmkind = 1;
- else mmkind = 0;
- else mmkind = -1;
-
- mmsize = size;
- high = (size & (-16));
- low = (size & 0x0c);
-}
-
-static void mmswap(a, b) register char *a, *b;
-{
- 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 + mmsize;
- do {s = *a; *a++ = *b; *b++ = s;} while (a < t);
- }
-}
-
-static void mmswapblock(a, b, size) register char *a, *b; int size;
-{
- register int s;
- if (mmkind >= 0) {
- register char *t = a + (size & (-16)); register int lo = (size & 0x0C);
- if (size >= 16) {
- 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 (lo != 0) { s = A[0]; A[0] = B[0]; B[0] = s;
- if (lo >= 8) { s = A[1]; A[1] = B[1]; B[1] = s;
- if (lo == 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);
- }
-}
-
-static void mmrot3(a, b, c) register char *a, *b, *c;
-{
- 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 + mmsize;
- do {s = *a; *a++ = *b; *b++ = *c; *c++ = s;} while (a < t);
- }
-}
-
-/* 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; int nel; 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 */
-
- 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) {if ((*cmp)(L,R) > 0) mmswap(L,R); goto nxt;}/* 2 elements */
-
- 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*/
-
- /* deteming 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 */
- }
-}
-
diff --git a/util.h b/util.h
deleted file mode 100644
index 41ce2a5a19..0000000000
--- a/util.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/************************************************
-
- util.h -
-
- $Author$
- $Date$
- created at: Thu Mar 9 11:55:53 JST 1995
-
- Copyright (C) 1993-1999 Yukihiro Matsumoto
-
-************************************************/
-#ifndef UTIL_H
-#define UTIL_H
-
-#ifndef _
-#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
-
-char *ruby_mktemp _((void));
-
-void ruby_qsort _((void*, int, 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));
-
-#endif /* UTIL_H */
diff --git a/variable.c b/variable.c
deleted file mode 100644
index fef84f7128..0000000000
--- a/variable.c
+++ /dev/null
@@ -1,1305 +0,0 @@
-/************************************************
-
- variable.c -
-
- $Author$
- $Date$
- created at: Tue Apr 19 23:55:15 JST 1994
-
-************************************************/
-
-#include "ruby.h"
-#include "env.h"
-#include "node.h"
-#include "st.h"
-
-#ifndef strdup
-char *strdup();
-#endif
-
-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 int
-fc_i(key, value, res)
- ID key;
- VALUE value;
- struct fc_result *res;
-{
- VALUE path;
- char *name;
-
- if (!rb_is_const_id(key)) return ST_CONTINUE;
-
- name = rb_id2name(key);
- if (res->path) {
- path = rb_str_dup(res->path);
- rb_str_cat(path, "::", 2);
- rb_str_cat(path, name, strlen(name));
- }
- else {
- path = rb_str_new2(name);
- }
- if (value == res->klass) {
- res->name = key;
- res->path = path;
- return ST_STOP;
- }
- if (rb_obj_is_kind_of(value, rb_cModule)) {
- struct fc_result arg;
- struct fc_result *list;
-
-
- if (!RCLASS(value)->iv_tbl) return ST_CONTINUE;
-
- list = res;
- while (list) {
- if (list->track == value) return ST_CONTINUE;
- list = list->prev;
- }
-
- arg.name = 0;
- arg.path = path;
- arg.klass = res->klass;
- arg.track = value;
- arg.prev = res;
- st_foreach(RCLASS(value)->iv_tbl, fc_i, &arg);
- if (arg.name) {
- res->name = arg.name;
- res->path = arg.path;
- return ST_STOP;
- }
- }
- 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.name == 0) {
- st_foreach(rb_class_tbl, fc_i, &arg);
- }
- if (arg.name) {
- 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__");
-
- while (TYPE(klass) == T_ICLASS || FL_TEST(klass, FL_SINGLETON)) {
- klass = (VALUE)RCLASS(klass)->super;
- }
- if (!klass) klass = rb_cObject;
- if (!ROBJECT(klass)->iv_tbl)
- ROBJECT(klass)->iv_tbl = st_init_numtable();
- else if (!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(FIX2INT(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) s = "Module";
- sprintf(buf, "#<%s 0lx%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_cat(str, "::", 2);
- rb_str_cat(str, name, strlen(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__", INT2FIX(id));
-}
-
-static st_table *autoload_tbl = 0;
-
-static void
-rb_autoload_id(id, filename)
- ID id;
- const char *filename;
-{
- if (!rb_is_const_id(id)) {
- rb_raise(rb_eNameError, "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), STR2CSTR(file));
- return Qnil;
-}
-
-char *
-rb_class2name(klass)
- VALUE klass;
-{
- if (klass == rb_cNilClass) return "nil";
- if (klass == rb_cTrueClass) return "true";
- if (klass == rb_cFalseClass) return "false";
- return RSTRING(rb_class_path(klass))->ptr;
-}
-
-struct trace_var {
- int removed;
- void (*func)();
- void *data;
- struct trace_var *next;
-};
-
-struct global_entry {
- ID id;
- void *data;
- VALUE (*getter)();
- void (*setter)();
- void (*marker)();
- int block_trace;
- struct trace_var *trace;
-};
-
-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)) {
- entry = ALLOC(struct global_entry);
- st_add_direct(rb_global_tbl, id, entry);
- entry->id = id;
- entry->data = 0;
- entry->getter = undef_getter;
- entry->setter = undef_setter;
- entry->marker = undef_marker;
-
- entry->block_trace = 0;
- entry->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, entry)
- VALUE val;
- ID id;
- void *data;
- struct global_entry *entry;
-{
- entry->getter = val_getter;
- entry->setter = val_setter;
- entry->marker = val_marker;
-
- entry->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, entry)
- VALUE val;
- ID id;
- void *data;
- struct global_entry *entry;
-{
- entry->data = (void*)val;
-}
-
-static void
-val_marker(data)
- void *data;
-{
- if (data) rb_gc_mark_maybe(data);
-}
-
-static VALUE
-var_getter(id, var)
- ID id;
- VALUE *var;
-{
- if (!var || !*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_raise(rb_eNameError, "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;
-
- (*entry->marker)(entry->data);
- trace = entry->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_entry *entry;
- ID id = global_id(name);
-
- entry = rb_global_entry(id);
- entry->data = (void*)var;
- entry->getter = getter?getter:var_getter;
- entry->setter = setter?setter:var_setter;
- entry->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));
-}
-
-VALUE
-rb_f_trace_var(argc, argv)
- int argc;
- VALUE *argv;
-{
- VALUE var, cmd;
- ID id;
- struct global_entry *entry;
- struct trace_var *trace;
-
- 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);
- }
- id = rb_to_id(var);
- if (!st_lookup(rb_global_tbl, id, &entry)) {
- rb_raise(rb_eNameError, "undefined global variable %s",
- rb_id2name(id));
- }
- trace = ALLOC(struct trace_var);
- trace->next = entry->trace;
- trace->func = rb_trace_eval;
- trace->data = (void*)cmd;
- trace->removed = 0;
- entry->trace = trace;
-
- return Qnil;
-}
-
-static void
-remove_trace(entry)
- struct global_entry *entry;
-{
- struct trace_var *trace = entry->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);
- }
- trace = next;
- }
- entry->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_raise(rb_eNameError, "undefined global variable %s",
- rb_id2name(id));
- }
-
- trace = entry->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;
- }
- entry->trace = 0;
-
- if (!entry->block_trace) remove_trace(entry);
- return ary;
- }
- else {
- while (trace) {
- if (trace->data == (void*)cmd) {
- trace->removed = 1;
- if (!entry->block_trace) remove_trace(entry);
- return rb_ary_new3(1, cmd);
- }
- trace = trace->next;
- }
- }
- return Qnil;
-}
-VALUE
-rb_gvar_get(entry)
- struct global_entry *entry;
-{
- return (*entry->getter)(entry->id, entry->data, entry);
-}
-
-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(entry)
- struct global_entry *entry;
-{
- entry->block_trace = 0;
- remove_trace(entry);
- return Qnil; /* not reached */
-}
-
-VALUE
-rb_gvar_set(entry, val)
- struct global_entry *entry;
- VALUE val;
-{
- struct trace_data trace;
-
- if (rb_safe_level() >= 4)
- rb_raise(rb_eSecurityError, "Insecure: can't change global variable value");
- (*entry->setter)(val, entry->id, entry->data, entry);
-
- if (entry->trace && !entry->block_trace) {
- entry->block_trace = 1;
- trace.trace = entry->trace;
- trace.val = val;
- rb_ensure(trace_ev, (VALUE)&trace, trace_en, (VALUE)entry);
- }
- 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->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;
-
- entry1 = rb_global_entry(name1);
- entry2 = rb_global_entry(name2);
-
- entry1->data = entry2->data;
- entry1->getter = entry2->getter;
- entry1->setter = entry2->setter;
- entry1->marker = entry2->marker;
-}
-
-static int special_generic_ivar = 0;
-static st_table *generic_iv_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_clone_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;
-
- if (!OBJ_TAINTED(obj) && rb_safe_level() >= 4)
- rb_raise(rb_eSecurityError, "Insecure: can't access instance variable");
- 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");
- 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;
-
- if (!OBJ_TAINTED(obj) && rb_safe_level() >= 4)
- rb_raise(rb_eSecurityError, "Insecure: can't get metainfo");
- 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 (!rb_is_instance_id(id)) {
- rb_raise(rb_eNameError, "`%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;
-}
-
-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) {
- return rb_const_get(klass, id);
- }
- rb_raise(rb_eNameError, "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);
- module = rb_str_new2(modname);
- free(modname);
- rb_f_require(Qnil, module);
-}
-
-VALUE
-rb_const_get(klass, id)
- VALUE klass;
- ID id;
-{
- VALUE value;
- VALUE tmp;
-
- tmp = klass;
- while (tmp) {
- if (RCLASS(tmp)->iv_tbl && st_lookup(RCLASS(tmp)->iv_tbl,id,&value)) {
- return value;
- }
- tmp = RCLASS(tmp)->super;
- }
- if (BUILTIN_TYPE(klass) == T_MODULE) {
- return rb_const_get(rb_cObject, id);
- }
-
- /* pre-defined class */
- if (st_lookup(rb_class_tbl, id, &value)) return value;
-
- /* autoload */
- if (autoload_tbl && st_lookup(autoload_tbl, id, 0)) {
- rb_autoload_load(id);
- return rb_const_get(klass, id);
- }
-
- /* Uninitialized constant */
- if (klass && klass != rb_cObject)
- rb_raise(rb_eNameError, "uninitialized constant %s::%s",
- RSTRING(rb_class_path(klass))->ptr,
- rb_id2name(id));
- else {
- rb_raise(rb_eNameError, "uninitialized constant %s",rb_id2name(id));
- }
- return Qnil; /* not reached */
-}
-
-static int
-sv_i(key, value, ary)
- ID key;
- VALUE value;
- VALUE ary;
-{
- if (rb_is_const_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_remove_const(mod, name)
- VALUE mod, name;
-{
- ID id = rb_to_id(name);
- VALUE val;
-
- if (!OBJ_TAINTED(mod) && rb_safe_level() >= 4)
- rb_raise(rb_eSecurityError, "Insecure: can't remove constant");
- if (!rb_is_const_id(id)) {
- rb_raise(rb_eNameError, "`%s' is not constant", rb_id2name(id));
- }
-
- if (RCLASS(mod)->iv_tbl && st_delete(ROBJECT(mod)->iv_tbl, &id, &val)) {
- return val;
- }
- if (rb_const_defined_at(mod, id)) {
- rb_raise(rb_eNameError, "cannot remove %s::%s",
- rb_class2name(mod), rb_id2name(id));
- }
- rb_raise(rb_eNameError, "constant %s::%s not defined",
- rb_class2name(mod), rb_id2name(id));
- return Qnil; /* not reached */
-}
-
-static int
-autoload_i(key, name, ary)
- ID key;
- const char *name;
- VALUE ary;
-{
- 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_const_at(mod, ary)
- VALUE mod, ary;
-{
- if (!OBJ_TAINTED(mod) && rb_safe_level() >= 4)
- rb_raise(rb_eSecurityError, "Insecure: can't get metainfo");
- if (RCLASS(mod)->iv_tbl) {
- st_foreach(RCLASS(mod)->iv_tbl, sv_i, ary);
- }
- if ((VALUE)mod == rb_cObject) {
- st_foreach(rb_class_tbl, sv_i, ary);
- if (autoload_tbl) {
- st_foreach(autoload_tbl, autoload_i, ary);
- }
- }
- return ary;
-}
-
-VALUE
-rb_mod_const_of(mod, ary)
- VALUE mod;
- VALUE ary;
-{
- rb_mod_const_at(mod, ary);
- for (;;) {
- mod = RCLASS(mod)->super;
- if (!mod) break;
- rb_mod_const_at(mod, ary);
- }
- return ary;
-}
-
-VALUE
-rb_mod_constants(mod)
- VALUE mod;
-{
- return rb_mod_const_of(mod, rb_ary_new());
-}
-
-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);
-}
-
-void
-rb_const_set(klass, id, val)
- VALUE klass;
- ID id;
- VALUE val;
-{
- if (!OBJ_TAINTED(klass) && rb_safe_level() >= 4)
- rb_raise(rb_eSecurityError, "Insecure: can't set constant");
- if (!RCLASS(klass)->iv_tbl) {
- RCLASS(klass)->iv_tbl = st_init_numtable();
- }
-
- st_insert(RCLASS(klass)->iv_tbl, id, val);
-}
-
-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_raise(rb_eNameError, "uninitialized constant %s::%s",
- RSTRING(rb_class_path(klass))->ptr,
- rb_id2name(id));
- else {
- rb_raise(rb_eNameError, "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);
- }
- if (!rb_is_const_id(id)) {
- rb_raise(rb_eNameError, "wrong constant name %s", name);
- }
- 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);
-}
-
-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 6cd9943430..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-1999 Yukihiro Matsumoto
-
-************************************************/
-
-#include "ruby.h"
-#include "version.h"
-#include <stdio.h>
-
-void
-Init_version()
-{
- VALUE v = rb_str_new2(RUBY_VERSION);
- VALUE d = rb_str_new2(RUBY_RELEASE_DATE);
- VALUE p = 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-1999 Yukihiro Matsumoto\n");
- exit(0);
-}
diff --git a/version.h b/version.h
deleted file mode 100644
index f8418db95a..0000000000
--- a/version.h
+++ /dev/null
@@ -1,4 +0,0 @@
-#define RUBY_VERSION "1.5.0"
-#define RUBY_RELEASE_DATE "1999-12-14"
-#define RUBY_VERSION_CODE 150
-#define RUBY_RELEASE_CODE 19991214
diff --git a/win32/Makefile b/win32/Makefile
deleted file mode 100644
index 24148b3c87..0000000000
--- a/win32/Makefile
+++ /dev/null
@@ -1,270 +0,0 @@
-SHELL = $(COMPSEC)
-
-#### Start of system configuration section. ####
-
-srcdir = .
-VPATH = .:./missing
-
-CC = cl
-YACC = byacc
-PURIFY =
-AUTOCONF = autoconf
-
-
-prefix =
-CFLAGS = -nologo -DNT=1 -Ox -I. -I./missing
-LDFLAGS = $(CFLAGS) -Fm
-#CFLAGS = -nologo -DNT=1 -Zi -I. -I./missing
-#LDFLAGS = $(CFLAGS) -Fm
-XLDFLAGS =
-#EXTLIBS =
-LIBS = advapi32.lib wsock32.lib $(EXTLIBS)
-MISSING = crypt.obj alloca.obj win32.obj isinf.obj isnan.obj
-LDSHARED =
-DLDFLAGS =
-SOLIBS =
-
-RUBY_INSTALL_NAME=ruby
-EXEEXT = .exe
-PROGRAM=$(RUBY_INSTALL_NAME)$(EXEEXT)
-
-STACK = 0x200000
-ORGLIBPATH = $(LIB)
-
-#### End of system configuration section. ####
-
-LIBRUBY_A = libruby.lib
-LIBRUBY_SO = rubymw.dll
-LIBRUBY = $(LIBRUBY_SO)
-LIBRUBYARG = rubymw.lib
-
-EXTOBJS = dmyext.obj
-
-MAINOBJ = main.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 ext/Setup rubymw.lib $(MISCLIBS)
- set LIB=..\..\win32;$(ORGLIBPATH)
- @.\miniruby$(EXEEXT) -Xext extmk.rb
-
-ext/extmk.rb: ext/extmk.rb.in rbconfig.rb
- @echo Creating ext/extmk.rb
- @.\miniruby$(EXEEXT) -Xext mswin32_extmk.rb
-
-miniruby$(EXEEXT): $(OBJS) $(MAINOBJ) $(EXTOBJS)
- @echo $(EXTOBJS)
- @echo $(LIBS)
- @rm -f $@
- $(PURIFY) $(CC) $(LDFLAGS) $(MAINOBJ) $(EXTOBJS) $(OBJS) $(LIBS) -o $@
-
-$(PROGRAM): $(LIBRUBY) $(MAINOBJ) $(LIBRUBY_SO)
- @rm -f $@
- $(PURIFY) $(CC) $(LDFLAGS) $(XLDFLAGS) $(MAINOBJ) -o $@ $(LIBRUBYARG) -link /STACK:$(STACK)
-
-$(LIBRUBY_A): $(OBJS) dmyext.obj
- lib -nologo /OUT:$@ $(OBJS) dmyext.obj
-
-rubymw.lib: ruby.def
- lib -nologo /OUT:$@ /DEF:ruby.def
-
-$(LIBRUBY_SO): $(LIBRUBY_A) $(EXTOBJS) ruby.def
- set LIB=.\win32;$(ORGLIBPATH)
- @rm -f $@
- $(CC) $(LDFLAGS) $(MAINOBJ) $(EXTOBJS) $(LIBRUBY_A) $(LIBS) -o $@ -link /DLL /DEF:ruby.def
- @mv rubymw.map rubydll.map
-
-install: rbconfig.rb
- .\miniruby.exe $(srcdir)/instruby.rb $(DESTDIR)
-
-clean:; @rm -f $(OBJS) $(LIBRUBY_A) $(MAINOBJ) rbconfig.rb
- @rm -f ext/extinit.c ext/extinit.obj ext/vc*.pdb *.obj
- @-.\miniruby$(EXEEXT) -Xext extmk.rb clean
-
-distclean: clean
- @rm -f Makefile ext/extmk.rb config.h
- @rm -f ext/config.cache config.cache config.log config.status
- @rm -f *~ core *.core gmon.out y.tab.c y.output ruby.imp
- @rm -f *.map *.pdb *.ilk rubymw.* ruby.def
- @rm -f $(PROGRAM) miniruby$(EXEEXT)
-
-realclean: distclean
- @rm -f parse.c
- @rm -f lex.c
-
-test: miniruby$(EXEEXT)
- @.\miniruby$(EXEEXT) $(srcdir)/rubytest.rb
-
-rbconfig.rb: miniruby$(EXEEXT)
- @.\miniruby$(EXEEXT) $(srcdir)/mkconfig.rb rbconfig.rb
-
-config.status: $(srcdir)/configure
-# $(SHELL) ./config.status --recheck
-
-.c.obj:
- $(CC) $(CFLAGS) $(CPPFLAGS) -c $<
-
-parse.c: parse.y
- $(YACC) $(YFLAGS) parse.y
- sed -e "s!^extern char \*getenv();!/* & */!" y.tab.c > parse.c
- @rm y.tab.c
-
-alloca.obj: missing/alloca.c
- $(CC) -I. $(CFLAGS) $(CPPFLAGS) -c missing/alloca.c
-
-crypt.obj: missing/crypt.c
- $(CC) -I. $(CFLAGS) $(CPPFLAGS) -c missing/crypt.c
-
-dup2.obj: missing/dup2.c
- $(CC) -I. $(CFLAGS) $(CPPFLAGS) -c missing/dup2.c
-
-finite.obj: missing/finite.c
- $(CC) -I. $(CFLAGS) $(CPPFLAGS) -c missing/finite.c
-
-flock.obj: missing/flock.c
- $(CC) -I. $(CFLAGS) $(CPPFLAGS) -c missing/flock.c
-
-isinf.obj: missing/isinf.c
- $(CC) -I. $(CFLAGS) $(CPPFLAGS) -c missing/isinf.c
-
-isnan.obj: missing/isnan.c
- $(CC) -I. $(CFLAGS) $(CPPFLAGS) -c missing/isnan.c
-
-memcmp.obj: missing/memcmp.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c missing/memcmp.c
-
-memmove.obj: missing/memmove.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c missing/memmove.c
-
-mkdir.obj: missing/mkdir.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c missing/mkdir.c
-
-vsnprintf.obj: missing/vsnprintf.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c missing/vsnprintf.c
-
-strcasecmp.obj: missing/strcasecmp.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c missing/strcasecmp.c
-
-strncasecmp.obj: missing/strncasecmp.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c missing/strncasecmp.c
-
-strchr.obj: missing/strchr.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c missing/strchr.c
-
-strdup.obj: missing/strdup.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c missing/strdup.c
-
-strerror.obj: missing/strerror.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c missing/strerror.c
-
-strftime.obj: missing/strftime.c
- $(CC) -I. $(CFLAGS) $(CPPFLAGS) -c missing/strftime.c
-
-strstr.obj: missing/strstr.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c missing/strstr.c
-
-strtod.obj: missing/strtod.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c missing/strtod.c
-
-strtol.obj: missing/strtol.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c missing/strtol.c
-
-strtoul.obj: missing/strtoul.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c missing/strtoul.c
-
-nt.obj: missing/nt.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c missing/nt.c
-
-x68.obj: missing/x68.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c missing/x68.c
-
-os2.obj: missing/os2.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c missing/os2.c
-
-dl_os2.obj: missing/dl_os2.c
- $(CC) $(CFLAGS) $(CPPFLAGS) -c missing/dl_os2.c
-
-# when I use -I., there is confliction at "OpenFile"
-# so, set . into environment varible "include"
-win32.obj: win32/win32.c
- @set include=$(INCLUDE);.
- $(CC) $(CFLAGS) $(CPPFLAGS) -c win32/win32.c
-
-# Prevent GNU make v3 from overflowing arg limit on SysV.
-.NOEXPORT:
-###
-parse.obj: parse.y ruby.h config.h defines.h intern.h env.h node.h st.h regex.h util.h lex.c
-###
-array.obj: array.c ruby.h config.h defines.h intern.h
-bignum.obj: bignum.c ruby.h config.h defines.h intern.h
-class.obj: class.c ruby.h config.h defines.h intern.h node.h st.h
-compar.obj: compar.c ruby.h config.h defines.h intern.h
-dir.obj: dir.c ruby.h config.h defines.h intern.h
-dln.obj: dln.c config.h defines.h dln.h
-dmyext.obj: dmyext.c
-enum.obj: enum.c ruby.h config.h defines.h intern.h
-error.obj: error.c ruby.h config.h defines.h intern.h env.h
-eval.obj: eval.c ruby.h config.h defines.h intern.h node.h env.h rubysig.h st.h dln.h
-file.obj: file.c ruby.h config.h defines.h intern.h rubyio.h rubysig.h
-gc.obj: gc.c ruby.h config.h defines.h intern.h rubysig.h st.h node.h env.h re.h regex.h
-hash.obj: hash.c ruby.h config.h defines.h intern.h st.h rubysig.h util.h
-inits.obj: inits.c ruby.h config.h defines.h intern.h
-io.obj: io.c ruby.h config.h defines.h intern.h rubyio.h rubysig.h env.h
-main.obj: main.c ruby.h config.h defines.h intern.h
-marshal.obj: marshal.c ruby.h config.h defines.h intern.h rubyio.h st.h
-prec.obj: prec.c ruby.h config.h defines.h intern.h
-math.obj: math.c ruby.h config.h defines.h intern.h
-numeric.obj: numeric.c ruby.h config.h defines.h intern.h
-object.obj: object.c ruby.h config.h defines.h intern.h st.h
-pack.obj: pack.c ruby.h config.h defines.h intern.h
-process.obj: process.c ruby.h config.h defines.h intern.h rubysig.h st.h
-random.obj: random.c ruby.h config.h defines.h intern.h
-range.obj: range.c ruby.h config.h defines.h intern.h
-re.obj: re.c ruby.h config.h defines.h intern.h re.h regex.h
-regex.obj: regex.c config.h regex.h util.h
-ruby.obj: ruby.c ruby.h config.h defines.h intern.h dln.h util.h
-signal.obj: signal.c ruby.h config.h defines.h intern.h rubysig.h
-sprintf.obj: sprintf.c ruby.h config.h defines.h intern.h
-st.obj: st.c config.h st.h
-string.obj: string.c ruby.h config.h defines.h intern.h re.h regex.h
-struct.obj: struct.c ruby.h config.h defines.h intern.h
-time.obj: time.c ruby.h config.h defines.h intern.h
-util.obj: util.c ruby.h config.h defines.h intern.h util.h
-variable.obj: variable.c ruby.h config.h defines.h intern.h env.h node.h st.h
-version.obj: version.c ruby.h config.h defines.h intern.h version.h
diff --git a/win32/config.h b/win32/config.h
deleted file mode 100644
index fe550654c2..0000000000
--- a/win32/config.h
+++ /dev/null
@@ -1,53 +0,0 @@
-#define HAVE_PROTOTYPES 1
-#define HAVE_STDARG_PROTOTYPES 1
-/* #define HAVE_ATTR_NORETURN 1 */
-/* #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 RSHIFT(x,y) ((x)>>y)
-#define FILE_COUNT _cnt
-#define DLEXT ".dll"
-#define RUBY_LIB "/usr/local/lib/ruby/1.5"
-#define RUBY_ARCHLIB "/usr/local/lib/ruby/1.5/i386-mswin32"
-#define RUBY_SITE_LIB "/usr/local/lib/ruby/1.5/site_ruby"
-#define RUBY_SITE_ARCHLIB "/usr/local/lib/ruby/1.5/site_ruby/i386-mswin32"
-#define RUBY_PLATFORM "i386-mswin32"
-
-#define SIZEOF_INT 4
-#define SIZEOF_SHORT 2
-#define SIZEOF_LONG 4
-#define SIZEOF_VOIDP 4
-#define SIZEOF_FLOAT 4
-#define SIZEOF_DOUBLE 8
diff --git a/win32/config.status b/win32/config.status
deleted file mode 100644
index 0e79324ae6..0000000000
--- a/win32/config.status
+++ /dev/null
@@ -1,65 +0,0 @@
-ac_given_srcdir=.
-s%@SHELL@%%g
-s%@CFLAGS@%-nologo -DNT=1 -Ox%g
-s%@CPPFLAGS@%%g
-s%@CXXFLAGS@%%g
-s%@FFLAGS@%%g
-s%@DEFS@%
- -DUSE_THREAD -DSIZEOF_INT=4 -DSIZEOF_SHORT=2 -DSIZEOF_LONG=4 -DSIZEOF_VOIDP=4 -DSIZEOF_FLOAT=4 -DSIZEOF_DOUBLE=8 -DHAVE_PROTOTYPES=1 -DHAVE_STDARG_PROTOTYPES=1 -DHAVE_STDLIB_H=1 -DHAVE_LIMITS_H=1 -DHAVE_SYS_FILE_H=1 -DHAVE_STRING_H=1 -DHAVE_MEMORY_H=1 -DHAVE_ST_RDEV=1 -DGETGROUPS_T=int -DRETSIGTYPE=void -DHAVE_ALLOCA=1 -DHAVE_FMOD=1 -DHAVE_WAITPID=1 -DHAVE_GETCWD=1 -DHAVE_CHSIZE=1 -DHAVE_GETGROUPS=1 -DHAVE_GETLOGIN=1 -DRSHIFT=\(x,y\)\ \(\(x\)\>\>y\) -DFILE_COUNT=_cnt -DDLEXT=\".dll\" -DRUBY_PLATFORM=\"i386-mswin32\" %g
-s%@LDFLAGS@%%g
-s%@LIBS@%advapi32.lib wsock32.lib%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-mswin32%g
-s%@host_alias@%i386-mswin32%g
-s%@host_cpu@%i386%g
-s%@host_vendor@%pc%g
-s%@host_os@%mswin32%g
-s%@CC@%cl%g
-s%@CPP@%cl -E%g
-s%@YACC@%byacc%g
-s%@RANLIB@%rem%g
-s%@AR@%lib -nologo%g
-s%@LN_S@%%g
-s%@SET_MAKE@%%g
-s%@LIBOBJS@% crypt.obj alloca.obj win32.obj isinf.obj isnan.obj%g
-s%@ALLOCA@%%g
-s%@DEFAULT_KCODE@%%g
-s%@EXEEXT@%.exe%g
-s%@OBJEXT@%obj%g
-s%@XLDFLAGS@%%g
-s%@DLDFLAGS@%%g
-s%@STATIC@%%g
-s%@CCDLFLAGS@%-DIMPORT%g
-s%@LDSHARED@%cl -LD%g
-s%@DLEXT@%dll%g
-s%@STRIP@%%g
-s%@EXTSTATIC@%%g
-s%@setup@%Setup%g
-s%@LIBRUBY_LDSHARED@%%g
-s%@LIBRUBY_DLDFLAGS@%%g
-s%@RUBY_INSTALL_NAME@%ruby%g
-s%@LIBRUBY_A@%lib$(RUBY_INSTALL_NAME).lib%g
-s%@LIBRUBY_SO@%%g
-s%@LIBRUBY_ALIASES@%%g
-s%@LIBRUBY@%libruby.lib%g
-s%@LIBRUBYARG@%libruby.lib%g
-s%@SOLIBS@%%g
-s%@arch@%i386-mswin32%g
-s%@configure_args@%--with-make-prog=nmake%g
-s%@configure_input@%$configure_input%g
-s%@srcdir@%$srcdir%g
-s%@top_srcdir@%$top_srcdir%g
diff --git a/win32/ntsetup.bat b/win32/ntsetup.bat
deleted file mode 100755
index dc67b70673..0000000000
--- a/win32/ntsetup.bat
+++ /dev/null
@@ -1,8 +0,0 @@
-@echo off
-copy config.h ..
-copy Makefile ..
-copy ruby.def ..
-copy config.status ..
-
-cd ..
-echo type `nmake' to make ruby for mswin32.
diff --git a/win32/ruby.def b/win32/ruby.def
deleted file mode 100644
index 8f1fc4800c..0000000000
--- a/win32/ruby.def
+++ /dev/null
@@ -1,574 +0,0 @@
-LIBRARY rubymw.dll
-DESCRIPTION 'win32 rubymw.dll'
-EXPORTS
-;;global objects
-;array.c
- rb_cArray
-;bignum.c
- rb_cBignum
-;compar.c
- rb_mComparable
-;dir.c
- rb_cDir
-;enum.c
- rb_mEnumerable
-;error.c
- rb_eException
- rb_eSystemExit
- rb_eInterrupt
- rb_eSignal
- rb_eFatal
- rb_eStandardError
- rb_eRuntimeError
- rb_eSyntaxError
- rb_eTypeError
- rb_eArgError
- rb_eNameError
- rb_eIndexError
- rb_eLoadError
- rb_eSecurityError
- rb_eNotImpError
- rb_eSystemCallError
- rb_eZeroDivError
- rb_mErrno
- ruby_nerrs
-;eval.c
- rb_cProc
- ruby_frame
- rb_cThread
- rb_thread_tick
- rb_thread_critical
-;file.c
- rb_cFile
- rb_mFileTest
-;gc.c
- rb_mGC
-;hash.c
- rb_cHash
-;io.c
- rb_cIO
- rb_eEOFError
- rb_eIOError
-;math.c
- rb_mMath
-;numeric.c
- rb_cNumeric
- rb_cFloat
- rb_cInteger
- rb_cFixnum
- rb_eFloatDomainError
-;object.c
- rb_mKernel
- rb_cObject
- rb_cModule
- rb_cClass
- rb_cData
- rb_cNilClass
- rb_cTrueClass
- rb_cFalseClass
-;prec.c
- rb_mPrecision
-;process.c
- rb_mProcess
-;range.c
- rb_cRange
-;re.c
- rb_cRegexp
-;regex.c
- re_mbctab
-;ruby.c
- ruby_debug
- ruby_verbose
- rb_progname
- rb_argv
- rb_argv0
-;signal.c
- rb_trap_pending
- rb_trap_immediate
- rb_prohibit_interrupt
-;string.c
- rb_cString
- rb_cStruct
-;time.c
- rb_cTime
-
-;;procedures/methods
-;missing/alloca.c
- alloca
-;missing/crypt.c
- definekey
- encrypt
- crypt
-;missing/isinf.c
- isinf
-;missing/isnan.c
- isnan
-;win32/win32.c
- NtInitialize
- myfdopen
- myfdclose
- myaccept
- mybind
- myconnect
- myfdset
- myfdisset
- myselect
- mygetpeername
- mygetsockname
- mygetsockopt
- myioctlsocket
- mylisten
- myrecv
- myrecvfrom
- mysend
- mysendto
- mysetsockopt
- myshutdown
- mysocket
- mygethostbyaddr
- mygethostbyname
- mygethostname
- mygetprotobyname
- mygetprotobynumber
- mygetservbyname
- mygetservbyport
- myget_osfhandle
- win32_getenv
-;array.c
- rb_mem_clear
- rb_ary_freeze
- rb_ary_new
- rb_ary_new2
- rb_ary_new3
- rb_ary_new4
- rb_assoc_new
- rb_ary_store
- rb_ary_push
- rb_ary_pop
- rb_ary_shift
- rb_ary_unshift
- rb_ary_entry
- rb_ary_aref
- rb_ary_each
- rb_ary_join
- rb_ary_to_s
- rb_protect_inspect
- rb_inspecting_p
- rb_ary_reverse
- rb_ary_sort_bang
- rb_ary_sort
- rb_ary_delete
- rb_ary_delete_at
- rb_ary_plus
- rb_ary_concat
- rb_ary_assoc
- rb_ary_rassoc
- rb_ary_includes
-;bignum.c
- rb_big_clone
- rb_big_2comp
- rb_big_norm
- rb_uint2big
- rb_int2big
- rb_uint2inum
- rb_int2inum
- rb_str2inum
- rb_big2str
- rb_big2ulong
- rb_big2long
- rb_dbl2big
- rb_big2dbl
- rb_big_plus
- rb_big_minus
- rb_big_mul
- rb_big_pow
- rb_big_and
- rb_big_or
- rb_big_xor
- rb_big_lshift
- rb_big_rand
-;class.c
- rb_class_new
- rb_singleton_class_new
- rb_singleton_class_clone
- rb_singleton_class_attached
- rb_define_class_id
- rb_define_class
- rb_define_class_under
- rb_module_new
- rb_define_module_id
- rb_define_module
- rb_define_module_under
- rb_include_module
- rb_mod_included_modules
- rb_mod_ancestors
- rb_class_instance_methods
- rb_class_protected_instance_methods
- rb_class_private_instance_methods
- rb_obj_singleton_methods
- rb_define_method_id
- rb_define_method
- rb_define_protected_method
- rb_define_private_method
- rb_undef_method
- rb_singleton_class
- rb_define_singleton_method
- rb_define_module_function
- rb_define_global_function
- rb_define_alias
- rb_define_attr
- rb_scan_args
-;dln.c
- dln_load
- dln_find_exe
- dln_find_file
-;enum.c
- rb_each
- rb_enum_length
-;error.c
- rb_compile_error
- rb_compile_error_append
- rb_warn
- rb_warning
- rb_bug
- rb_check_type
- rb_exc_new
- rb_exc_new2
- rb_exc_new3
- rb_raise
- rb_loaderror
- rb_notimplement
- rb_fatal
- rb_sys_fail
-;eval.c
- rb_clear_cache
- rb_add_method
- rb_alias
- rb_remove_method
- rb_disable_super
- rb_enable_super
- rb_method_boundp
- rb_attr
- rb_dvar_defined
- rb_dvar_ref
- rb_dvar_push
- rb_dvar_asgn
- rb_safe_level
- rb_set_safe_level
- rb_check_safe_str
- rb_secure
- ruby_init
- ruby_options
- ruby_run
- rb_eval_string
- rb_eval_string_protect
- rb_eval_string_wrap
- rb_eval_cmd
- rb_respond_to
- rb_exit
- rb_iter_break
- rb_exc_raise
- rb_exc_fatal
- rb_interrupt
- rb_jump_tag
- rb_iterator_p
- rb_yield
- rb_iterate
- rb_rescue
- rb_protect
- rb_ensure
- rb_with_disable_interrupt
- rb_apply
- rb_funcall
- rb_funcall2
- rb_funcall3
- rb_backtrace
- rb_frame_last_func
- rb_obj_instance_eval
- rb_load
- rb_load_protect
- rb_provide
- rb_f_require
- rb_require
- rb_obj_call_init
- rb_class_new_instance
- rb_extend_object
- rb_set_end_proc
- rb_exec_end_proc
- rb_f_lambda
- rb_gc_mark_threads
- rb_thread_fd_close
- rb_thread_schedule
- rb_thread_wait_fd
- rb_thread_fd_writable
- rb_thread_wait_for
- rb_thread_alone
- rb_thread_select
- rb_thread_current
- rb_thread_main
- rb_thread_wakeup
- rb_thread_run
- rb_thread_stop
- rb_thread_sleep
- rb_thread_sleep_forever
- rb_thread_create
- rb_thread_scope_shared_p
- rb_thread_interrupt
- rb_thread_signal_raise
- rb_thread_trap_eval
- rb_thread_local_aref
- rb_thread_local_aset
- rb_catch
- rb_throw
-;file.c
- eaccess
- rb_file_s_expand_path
-;gc.c
- xmalloc
- xcalloc
- xrealloc
- rb_global_variable
- rb_newobj
- rb_data_object_alloc
- rb_gc_mark_locations
- rb_mark_tbl
- rb_mark_hash
- rb_gc_mark_maybe
- rb_gc_mark
- rb_gc_force_recycle
- rb_gc_mark_frame
- rb_gc
- rb_gc_call_finalizer_at_exit
-;hash.c
- rb_hash_freeze
- rb_hash
- rb_hash_new
- rb_hash_aref
- rb_hash_aset
- rb_path_check
- rb_env_path_tainted
- ruby_setenv
- ruby_unsetenv
-;inits.c
- rb_call_inits
-;io.c
- rb_eof_error
- rb_io_check_closed
- rb_io_check_readable
- rb_io_check_writable
- rb_read_check
- rb_io_write
- rb_io_eof
- rb_io_gets
- rb_io_getc
- rb_getc
- rb_io_ungetc
- rb_io_fptr_finalize
- rb_io_close
- rb_io_close_read
- rb_io_binmode
- rb_io_mode_flags
- rb_fopen
- rb_fdopen
- rb_file_open
- rb_file_sysopen
- rb_io_synchronized
- rb_p
- rb_gets
- rb_str_setter
-;numeric.c
- rb_num_zerodiv
- rb_num_coerce_bin
- rb_float_new
- rb_num2long
- rb_num2ulong
- rb_num2int
- rb_fix2int
- rb_num2fix
- rb_fix2str
- rb_fix_upto
-;object.c
- rb_equal
- rb_eql
- rb_obj_id
- rb_obj_clone
- rb_any_to_s
- rb_inspect
- rb_obj_is_instance_of
- rb_obj_is_kind_of
- rb_obj_tainted
- rb_obj_taint
- rb_obj_untaint
- rb_obj_alloc
- rb_to_id
- rb_convert_type
- rb_Integer
- rb_Float
- rb_num2dbl
- rb_str2cstr
- rb_String
- rb_Array
-;parse.c
- rb_compile_string
- rb_compile_cstr
- rb_compile_file
- rb_node_newnode
- rb_id_attrset
- rb_parser_append_print
- rb_parser_while_loop
- rb_intern
- rb_id2name
- rb_is_const_id
- rb_is_instance_id
- rb_backref_get
- rb_backref_set
- rb_lastline_get
- rb_lastline_set
-;process.c
- rb_proc_exec
- rb_syswait
-;range.c
- rb_range_new
- rb_range_beg_len
-;re.c
- rb_str_cicmp
- rb_match_busy
- rb_reg_search
- rb_reg_nth_defined
- rb_reg_nth_match
- rb_reg_last_match
- rb_reg_match_pre
- rb_reg_match_post
- rb_reg_match_last
- rb_reg_new
- rb_reg_regcomp
- rb_reg_match
- rb_reg_match2
- rb_kcode
- rb_reg_options
- rb_reg_regsub
- rb_get_kcode
- rb_set_kcode
-;ruby.c
- rb_load_file
- ruby_script
- ruby_prog_init
- ruby_set_argv
- ruby_process_options
-;signal.c
- rb_f_kill
- rb_gc_mark_trap_list
- rb_trap_exit
- rb_trap_exec
- rb_trap_restore_mask
-;sprintf.c
- rb_f_sprintf
-;st.c
- st_init_table_with_size
- st_init_table
- st_init_numtable
- st_init_numtable_with_size
- st_init_strtable
- st_init_strtable_with_size
- st_free_table
- st_lookup
- st_insert
- st_add_direct
- st_copy
- st_delete
- st_delete_safe
- st_cleanup_safe
- st_foreach
-;string.c
- rb_str_new
- rb_str_new2
- rb_tainted_str_new
- rb_tainted_str_new2
- rb_str_new3
- rb_str_new4
- rb_str_to_str
- rb_obj_as_string
- rb_str_dup
- rb_str_plus
- rb_str_times
- rb_str_substr
- rb_str_modify
- rb_str_freeze
- rb_str_dup_frozen
- rb_str_resize
- rb_str_cat
- rb_str_concat
- rb_str_hash
- rb_str_cmp
- rb_str_upto
- rb_str_inspect
- rb_str_split
-;struct.c
- rb_struct_getmember
- rb_struct_define
- rb_struct_alloc
- rb_struct_new
- rb_struct_aref
- rb_struct_aset
-;time.c
- rb_time_new
- rb_time_interval
- rb_time_timeval
-;util.c
- rb_class_of
- rb_type
- rb_special_const_p
- rb_test_false_or_nil
- ruby_scan_oct
- ruby_scan_hex
- ruby_mktemp
- ruby_qsort
-;variable.c
- rb_mod_name
- rb_class_path
- rb_set_class_path
- rb_path2class
- rb_name_class
- rb_autoload
- rb_f_autoload
- rb_class2name
- rb_global_entry
- rb_gc_mark_global_tbl
- rb_define_hooked_variable
- rb_define_variable
- rb_define_readonly_variable
- rb_define_virtual_variable
- rb_f_trace_var
- rb_f_untrace_var
- rb_gvar_get
- rb_gvar_set
- rb_gvar_set2
- rb_gvar_defined
- rb_f_global_variables
- rb_alias_variable
- rb_mark_generic_ivar
- rb_mark_generic_ivar_tbl
- rb_free_generic_ivar
- rb_clone_generic_ivar
- rb_ivar_get
- rb_ivar_set
- rb_ivar_defined
- rb_obj_instance_variables
- rb_obj_remove_instance_variable
- rb_const_get_at
- rb_const_get
- rb_mod_remove_const
- rb_mod_const_at
- rb_mod_constants
- rb_mod_const_of
- rb_const_defined_at
- rb_autoload_defined
- rb_const_defined
- rb_const_set
- rb_define_const
- rb_define_global_const
- rb_iv_get
- rb_iv_set
-;version.c
- ruby_show_version
- ruby_show_copyright
diff --git a/win32/win32.c b/win32/win32.c
deleted file mode 100644
index 864fbfb5df..0000000000
--- a/win32/win32.c
+++ /dev/null
@@ -1,2340 +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 <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 "dir.h"
-#ifndef index
-#define index(x, y) strchr((x), (y))
-#endif
-
-#ifndef bool
-#define bool int
-#endif
-
-#define TO_SOCKET(x) _get_osfhandle(x)
-
-bool NtSyncProcess = TRUE;
-#if 0 // declared in header file
-extern char **environ;
-#define environ _environ
-#endif
-
-static bool NtHasRedirection (char *);
-static int valid_filename(char *s);
-static void StartSockets ();
-static char *str_grow(struct RString *str, size_t new_size);
-
-char *NTLoginName;
-
-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);
-}
-
-
-/* simulate flock by locking a range on the file */
-
-
-#define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
-#define LK_LEN 0xffff0000
-
-int
-flock(int fd, int oper)
-{
- OVERLAPPED o;
- int i = -1;
- HANDLE fh;
-
- fh = (HANDLE)_get_osfhandle(fd);
- memset(&o, 0, sizeof(o));
-
- if(IsWinNT()) {
- 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;
- }
- else {
- /* GetLastError() must returns `ERROR_NOT_LOCKED' */
- errno = EWOULDBLOCK;
- }
- if(errno == EDOM) errno = EWOULDBLOCK;
- break;
- default: /* unknown */
- errno = EINVAL;
- break;
- }
- }
- else if(IsWin95()) {
- 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;
-}
-
-#undef LK_ERR
-#undef LK_LEN
-
-
-//#undef const
-//FILE *fdopen(int, const char *);
-
-#if 0
-void
-sleep(unsigned int len)
-{
- time_t end;
-
- end = time((time_t *)0) + len;
- while (time((time_t *)0) < end)
- ;
-}
-#endif
-
-//
-// 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];
- int 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;
-}
-
-
-
-#if 1
-// popen stuff
-
-//
-// use these so I can remember which index is which
-//
-
-#define NtPipeRead 0 // index of pipe read descriptor
-#define NtPipeWrite 1 // index of pipe write descriptor
-
-#define NtPipeSize 1024 // size of pipe buffer
-
-#define MYPOPENSIZE 256 // size of book keeping structure
-
-struct {
- int inuse;
- int pid;
- HANDLE oshandle;
- FILE *pipe;
-} MyPopenRecord[MYPOPENSIZE];
-
-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);
-
- for( i = 0; szInternalCmds[i] ; i++){
- if(!strcmp(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 saved, reading;
- int pipemode;
- int pipes[2];
- int pid;
- int slot;
- static initialized = 0;
-
- //
- // if first time through, intialize our book keeping structure
- //
-
- if (!initialized++) {
- for (slot = 0; slot < MYPOPENSIZE; slot++)
- MyPopenRecord[slot].inuse = FALSE;
- }
-
- //printf("mypopen %s\n", cmd);
-
- //
- // find a free popen slot
- //
-
- for (slot = 0; slot < MYPOPENSIZE && MyPopenRecord[slot].inuse; slot++)
- ;
-
- if (slot > MYPOPENSIZE) {
- return NULL;
- }
-
- //
- // Figure out what we\'re doing...
- //
-
- reading = (*mode == 'r') ? TRUE : FALSE;
- pipemode = (*(mode+1) == 'b') ? O_BINARY : O_TEXT;
-
- //
- // Now get a pipe
- //
-
-#if 0
- if (_pipe(pipes, NtPipeSize, pipemode) == -1) {
- return NULL;
- }
-
- if (reading) {
-
- //
- // we\'re reading from the pipe, so we must hook up the
- // write end of the pipe to the new processes stdout.
- // To do this we must save our file handle from stdout
- // by _dup\'ing it, then setting our stdout to be the pipe\'s
- // write descriptor. We must also make the write handle
- // inheritable so the new process can use it.
-
- if ((saved = _dup(fileno(stdout))) == -1) {
- _close(pipes[NtPipeRead]);
- _close(pipes[NtPipeWrite]);
- return NULL;
- }
- if (_dup2 (pipes[NtPipeWrite], fileno(stdout)) == -1) {
- _close(pipes[NtPipeRead]);
- _close(pipes[NtPipeWrite]);
- return NULL;
- }
- }
- else {
- //
- // must be writing to the new process. Do the opposite of
- // the above, i.e. hook up the processes stdin to the read
- // end of the pipe.
- //
-
- if ((saved = _dup(fileno(stdin))) == -1) {
- _close(pipes[NtPipeRead]);
- _close(pipes[NtPipeWrite]);
- return NULL;
- }
- if (_dup2(pipes[NtPipeRead], fileno(stdin)) == -1) {
- _close(pipes[NtPipeRead]);
- _close(pipes[NtPipeWrite]);
- return NULL;
- }
- }
-
- //
- // Start the new process. Must set _fileinfo to non-zero value
- // for file descriptors to be inherited. Reset after the process
- // is started.
- //
-
- if (NtHasRedirection(cmd)) {
- docmd:
- pid = spawnlpe(_P_NOWAIT, "cmd.exe", "/c", cmd, 0, environ);
- if (pid == -1) {
- _close(pipes[NtPipeRead]);
- _close(pipes[NtPipeWrite]);
- return NULL;
- }
- }
- else {
- char **vec;
- int vecc = NtMakeCmdVector(cmd, &vec, FALSE);
-
- //pid = spawnvpe (_P_NOWAIT, vec[0], vec, environ);
- pid = spawnvpe (_P_WAIT, vec[0], vec, environ);
- if (pid == -1) {
- goto docmd;
- }
- Safefree (vec, vecc);
- }
-
- if (reading) {
-
- //
- // We need to close our instance of the inherited pipe write
- // handle now that it's been inherited so that it will actually close
- // when the child process ends.
- //
-
- if (_close(pipes[NtPipeWrite]) == -1) {
- _close(pipes[NtPipeRead]);
- return NULL;
- }
- if (_dup2 (saved, fileno(stdout)) == -1) {
- _close(pipes[NtPipeRead]);
- return NULL;
- }
- _close(saved);
-
- //
- // Now get a stream pointer to return to the calling program.
- //
-
- if ((fp = (FILE *) fdopen(pipes[NtPipeRead], mode)) == NULL) {
- return NULL;
- }
- }
- else {
-
- //
- // need to close our read end of the pipe so that it will go
- // away when the write end is closed.
- //
-
- if (_close(pipes[NtPipeRead]) == -1) {
- _close(pipes[NtPipeWrite]);
- return NULL;
- }
- if (_dup2 (saved, fileno(stdin)) == -1) {
- _close(pipes[NtPipeWrite]);
- return NULL;
- }
- _close(saved);
-
- //
- // Now get a stream pointer to return to the calling program.
- //
-
- if ((fp = (FILE *) fdopen(pipes[NtPipeWrite], mode)) == NULL) {
- _close(pipes[NtPipeWrite]);
- return NULL;
- }
- }
-
- //
- // do the book keeping
- //
-
- MyPopenRecord[slot].inuse = TRUE;
- MyPopenRecord[slot].pipe = fp;
- MyPopenRecord[slot].pid = pid;
-
- return fp;
-#else
- {
- int p[2];
-
- BOOL fRet;
- HANDLE hInFile, hOutFile, hStdin, hStdout;
- LPCSTR lpApplicationName = NULL;
- LPTSTR lpCommandLine;
- LPTSTR lpCmd2 = NULL;
- DWORD dwCreationFlags;
- STARTUPINFO aStartupInfo;
- PROCESS_INFORMATION aProcessInformation;
- SECURITY_ATTRIBUTES sa;
- int fd;
-
- sa.nLength = sizeof (SECURITY_ATTRIBUTES);
- sa.lpSecurityDescriptor = NULL;
- sa.bInheritHandle = TRUE;
-
- if (!reading) {
- FILE *fp;
-
- fp = (_popen)(cmd, mode);
-
- MyPopenRecord[slot].inuse = TRUE;
- MyPopenRecord[slot].pipe = fp;
- MyPopenRecord[slot].pid = -1;
-
- if (!fp)
- rb_fatal("cannot open pipe \"%s\" (%s)", cmd, strerror(errno));
- return fp;
- }
-
- fRet = CreatePipe(&hInFile, &hOutFile, &sa, 2048L);
- if (!fRet)
- rb_fatal("cannot open pipe \"%s\" (%s)", cmd, strerror(errno));
-
- memset(&aStartupInfo, 0, sizeof (STARTUPINFO));
- memset(&aProcessInformation, 0, sizeof (PROCESS_INFORMATION));
- aStartupInfo.cb = sizeof (STARTUPINFO);
- aStartupInfo.dwFlags = STARTF_USESTDHANDLES;
-
- if (reading) {
- aStartupInfo.hStdInput = GetStdHandle(STD_OUTPUT_HANDLE);//hStdin;
- aStartupInfo.hStdError = INVALID_HANDLE_VALUE;
- //for save
- DuplicateHandle(GetCurrentProcess(), GetStdHandle(STD_OUTPUT_HANDLE),
- GetCurrentProcess(), &hStdout,
- 0, FALSE, DUPLICATE_SAME_ACCESS
- );
- //for redirect
- DuplicateHandle(GetCurrentProcess(), GetStdHandle(STD_INPUT_HANDLE),
- GetCurrentProcess(), &hStdin,
- 0, TRUE, DUPLICATE_SAME_ACCESS
- );
- aStartupInfo.hStdOutput = hOutFile;
- }
- else {
- aStartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); //hStdout;
- aStartupInfo.hStdError = INVALID_HANDLE_VALUE;
- // for save
- DuplicateHandle(GetCurrentProcess(), GetStdHandle(STD_INPUT_HANDLE),
- GetCurrentProcess(), &hStdin,
- 0, FALSE, DUPLICATE_SAME_ACCESS
- );
- //for redirect
- DuplicateHandle(GetCurrentProcess(), GetStdHandle(STD_OUTPUT_HANDLE),
- GetCurrentProcess(), &hStdout,
- 0, TRUE, DUPLICATE_SAME_ACCESS
- );
- aStartupInfo.hStdInput = hInFile;
- }
-
- dwCreationFlags = (NORMAL_PRIORITY_CLASS);
-
- lpCommandLine = cmd;
- if (NtHasRedirection(cmd) || isInternalCmd(cmd)) {
- lpApplicationName = getenv("COMSPEC");
- lpCmd2 = malloc(strlen(lpApplicationName) + 1 + strlen(cmd) + sizeof (" /c "));
- if (lpCmd2 == NULL)
- rb_fatal("Mypopen: malloc failed");
- sprintf(lpCmd2, "%s %s%s", lpApplicationName, " /c ", cmd);
- lpCommandLine = lpCmd2;
- }
-
- fRet = CreateProcess(lpApplicationName, lpCommandLine, &sa, &sa,
- sa.bInheritHandle, dwCreationFlags, NULL, NULL, &aStartupInfo, &aProcessInformation);
-
- if (!fRet) {
- CloseHandle(hInFile);
- CloseHandle(hOutFile);
- rb_fatal("cannot fork for \"%s\" (%s)", cmd, strerror(errno));
- }
-
- CloseHandle(aProcessInformation.hThread);
-
- if (reading) {
- HANDLE hDummy;
-
- fd = _open_osfhandle((long)hInFile, (_O_RDONLY | pipemode));
- CloseHandle(hOutFile);
- DuplicateHandle(GetCurrentProcess(), hStdout,
- GetCurrentProcess(), &hDummy,
- 0, TRUE, (DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE)
- );
- }
- else {
- HANDLE hDummy;
-
- fd = _open_osfhandle((long)hOutFile, (_O_WRONLY | pipemode));
- CloseHandle(hInFile);
- DuplicateHandle(GetCurrentProcess(), hStdin,
- GetCurrentProcess(), &hDummy,
- 0, TRUE, (DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE)
- );
- }
-
- if (fd == -1)
- rb_fatal("cannot open pipe \"%s\" (%s)", cmd, strerror(errno));
-
-
- if ((fp = (FILE *) fdopen(fd, mode)) == NULL)
- return NULL;
-
- if (lpCmd2)
- free(lpCmd2);
-
- MyPopenRecord[slot].inuse = TRUE;
- MyPopenRecord[slot].pipe = fp;
- MyPopenRecord[slot].oshandle = (reading ? hInFile : hOutFile);
- MyPopenRecord[slot].pid = (int)aProcessInformation.hProcess;
- return fp;
- }
-#endif
-}
-
-int
-mypclose(FILE *fp)
-{
- int i;
- int exitcode;
-
- Sleep(100);
- for (i = 0; i < MYPOPENSIZE; i++) {
- if (MyPopenRecord[i].inuse && MyPopenRecord[i].pipe == fp)
- break;
- }
- if (i >= MYPOPENSIZE) {
- rb_fatal("Invalid file pointer passed to mypclose!\n");
- }
-
- //
- // get the return status of the process
- //
-
-#if 0
- if (_cwait(&exitcode, MyPopenRecord[i].pid, WAIT_CHILD) == -1) {
- if (errno == ECHILD) {
- fprintf(stderr, "mypclose: nosuch child as pid %x\n",
- MyPopenRecord[i].pid);
- }
- }
-#else
- for (;;) {
- if (GetExitCodeProcess((HANDLE)MyPopenRecord[i].pid, &exitcode)) {
- if (exitcode == STILL_ACTIVE) {
- //printf("Process is Active.\n");
- Sleep(100);
- TerminateProcess((HANDLE)MyPopenRecord[i].pid, 0); // ugly...
- continue;
- }
- else if (exitcode == 0) {
- //printf("done.\n");
- break;
- }
- else {
- //printf("never.\n");
- break;
- }
- }
- }
-#endif
-
-
- //
- // close the pipe
- //
- // Closehandle() is done by fclose().
- //CloseHandle(MyPopenRecord[i].oshandle);
- fflush(fp);
- fclose(fp);
-
- //
- // free this slot
- //
-
- MyPopenRecord[i].inuse = FALSE;
- MyPopenRecord[i].pipe = NULL;
- MyPopenRecord[i].pid = 0;
-
- return exitcode;
-}
-#endif
-
-#if 1
-
-
-typedef char* CHARP;
-/*
- * The following code is based on the do_exec and do_aexec functions
- * in file doio.c
- */
-
-int
-do_spawn(cmd)
-char *cmd;
-{
- register char **a;
- register char *s;
- char **argv;
- int status;
- char *shell, *cmd2;
- int mode = NtSyncProcess ? P_WAIT : P_NOWAIT;
-
- /* save an extra exec if possible */
- if ((shell = getenv("RUBYSHELL")) != 0) {
- if (NtHasRedirection(cmd)) {
- int i;
- char *p;
- char *argv[4];
- char *cmdline = ALLOC_N(char, (strlen(cmd) * 2 + 1));
-
- p=cmdline;
- *p++ = '"';
- for (s=cmd; *s;) {
- if (*s == '"')
- *p++ = '\\'; /* Escape d-quote */
- *p++ = *s++;
- }
- *p++ = '"';
- *p = '\0';
-
- /* fprintf(stderr, "do_spawn: %s %s\n", shell, cmdline); */
- argv[0] = shell;
- argv[1] = "-c";
- argv[2] = cmdline;
- argv[4] = NULL;
- status = spawnvpe(mode, argv[0], argv, environ);
- /* return spawnle(mode, shell, shell, "-c", cmd, (char*)0, environ); */
- free(cmdline);
- return status;
- }
- }
- else if ((shell = getenv("COMSPEC")) != 0) {
- if (NtHasRedirection(cmd) /* || isInternalCmd(cmd) */) {
- do_comspec_shell:
- return spawnle(mode, shell, shell, "/c", cmd, (char*)0, environ);
- }
- }
-
- 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 = spawnvpe(mode, argv[0], argv, environ)) == -1) {
- free(argv);
- free(cmd2);
- return -1;
- }
- }
- free(cmd2);
- free(argv);
- return status;
-}
-
-#endif
-
-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.
-//
-
-void
-NtCmdGlob (NtCmdLineElement *patt)
-{
- WIN32_FIND_DATA fd;
- HANDLE fh;
- char buffer[512];
- NtCmdLineElement *tmphead, *tmptail, *tmpcurr;
-
- strncpy(buffer, patt->str, patt->len);
- buffer[patt->len] = '\0';
- if ((fh = FindFirstFile (buffer, &fd)) == INVALID_HANDLE_VALUE) {
- return;
- }
- tmphead = tmptail = NULL;
- do {
- tmpcurr = ALLOC(NtCmdLineElement);
- if (tmpcurr == NULL) {
- fprintf(stderr, "Out of Memory in globbing!\n");
- while (tmphead) {
- tmpcurr = tmphead;
- tmphead = tmphead->next;
- free(tmpcurr->str);
- free(tmpcurr);
- }
- return;
- }
- memset (tmpcurr, 0, sizeof(*tmpcurr));
- tmpcurr->len = strlen(fd.cFileName);
- tmpcurr->str = ALLOC_N(char, tmpcurr->len+1);
- if (tmpcurr->str == NULL) {
- fprintf(stderr, "Out of Memory in globbing!\n");
- while (tmphead) {
- tmpcurr = tmphead;
- tmphead = tmphead->next;
- free(tmpcurr->str);
- free(tmpcurr);
- }
- return;
- }
- strcpy(tmpcurr->str, fd.cFileName);
- tmpcurr->flags |= NTMALLOC;
- if (tmptail) {
- tmptail->next = tmpcurr;
- tmpcurr->prev = tmptail;
- tmptail = tmpcurr;
- }
- else {
- tmptail = tmphead = tmpcurr;
- }
- } while(FindNextFile(fh, &fd));
-
- //
- // ok, now we\'ve got a list of files that matched the wildcard
- // specification. Put it in place of the pattern structure.
- //
-
- tmphead->prev = patt->prev;
- tmptail->next = patt->next;
-
- if (tmphead->prev)
- tmphead->prev->next = tmphead;
-
- if (tmptail->next)
- tmptail->next->prev = tmptail;
-
- //
- // Now get rid of the pattern structure
- //
-
- 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 '<':
-
- 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;
- }
-
- //
- // strip trailing white space
- //
-
- ptr = cmdline+(cmdlen - 1);
- while(ptr >= cmdline && isspace(*ptr))
- --ptr;
- *++ptr = '\0';
-
- //
- // check for newlines and formfeeds. If we find any, make a new
- // command string that replaces them with escaped sequences (\n or \f)
- //
-
- for (ptr = cmdline, newline = 0; *ptr; ptr++) {
- if (*ptr == '\n' || *ptr == '\f')
- newline++;
- }
-
- if (newline) {
- base = ALLOC_N(char, strlen(cmdline) + 1 + newline + slashes);
- if (base == NULL) {
- fprintf(stderr, "malloc failed!\n");
- return 0;
- }
- for (i = 0, ptr = base; (unsigned) i < strlen(cmdline); i++) {
- switch (cmdline[i]) {
- case '\n':
- *ptr++ = '\\';
- *ptr++ = 'n';
- break;
- default:
- *ptr++ = cmdline[i];
- }
- }
- *ptr = '\0';
- cmdline = base;
- need_free++;
- }
-
- //
- // 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 ' ':
- 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);
- if (curr == NULL) {
- NtFreeCmdLine();
- fprintf(stderr, "Out of memory!!\n");
- *vec = NULL;
- return 0;
- }
- 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] == '\"') ||
- (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);
- if (buffer == NULL) {
- fprintf(stderr, "Out of memory!!\n");
- NtFreeCmdLine();
- *vec = NULL;
- return 0;
- }
-
- 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;
- return elements;
-}
-
-
-#if 1
-//
-// 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(char *filename)
-{
- DIR *p;
- long len;
- long idx;
- char scannamespc[PATHLEN];
- char *scanname = scannamespc;
- struct stat sbuf;
- WIN32_FIND_DATA FindData;
- HANDLE fh;
- char root[PATHLEN];
- char volname[PATHLEN];
- DWORD serial, maxname, flags;
-
- //
- // check to see if we\'ve got a directory
- //
-
- if (stat (filename, &sbuf) < 0 ||
- sbuf.st_mode & _S_IFDIR == 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("/\\", *(scanname + strlen(scanname) - 1)) == 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);
-}
-#endif
-
-
-//
-// 98.2% of this code was lifted from the OS2 port. (JCW)
-//
-
-#if 0
-// add_suffix is in util.c too.
-/*
- * 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 char suffix1[] = ".$$$";
-static char suffix2[] = ".~~~";
-
-#define ext (&buf[1000])
-
-#define strEQ(s1,s2) (strcmp(s1,s2) == 0)
-
-void
-add_suffix(struct RString *str, char *suffix)
-{
- int baselen;
- int extlen = strlen(suffix);
- char *s, *t, *p;
- int slen;
- char buf[1024];
-
- if (str->len > 1000)
- rb_fatal("Cannot do inplace edit on long filename (%d characters)", str->len);
-
- /* Style 0 */
- slen = str->len;
- str_cat(str, suffix, extlen);
- if (valid_filename(str->ptr)) return;
-
- /* Fooey, style 0 failed. Fix str before continuing. */
- str->ptr[str->len = slen] = '\0';
-
- slen = extlen;
- t = buf; baselen = 0; s = 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);
- }
- str_grow(str, strlen(buf));
- memcpy(str->ptr, buf, str->len);
-}
-#endif
-
-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);
-
-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 */
-#if defined (_MT) && !defined (DLL_FOR_WIN32S)
- int lockinitflag;
- CRITICAL_SECTION lock;
-#endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
-} ioinfo;
-
-EXTERN_C 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 _osfile(i) (_pioinfo(i)->osfile)
-
-#define FOPEN 0x01 /* file handle open */
-#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 */
-
-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;
-
- /* attempt to allocate a C Runtime file handle */
- if ((fh = _alloc_osfhnd()) == -1) {
- errno = EMFILE; /* too many open files */
- _doserrno = 0L; /* not an OS error */
- return -1; /* return error to caller */
- }
-
- /* 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 */
-// _unlock_fhandle(fh);
-
- return fh; /* return handle */
-}
-
-FILE *
-myfdopen (int fd, const char *mode)
-{
- char sockbuf[80];
- int optlen;
- int retval;
- int fh;
- extern int errno;
-
- //fprintf(stderr, "myfdopen()\n");
-
- optlen = sizeof(sockbuf);
- retval = getsockopt((SOCKET)fd, SOL_SOCKET, SO_TYPE, sockbuf, &optlen);
- if (retval == SOCKET_ERROR) {
- int iRet;
-
- iRet = WSAGetLastError();
- if (iRet == WSAENOTSOCK || iRet == WSANOTINITIALISED)
- return (_fdopen(fd, mode));
- }
-
- //
- // If we get here, then fd is actually a socket.
- //
-
- fh = my_open_osfhandle((SOCKET)fd, O_RDWR|O_BINARY);
- return _fdopen(fh, mode); // return file pointer
-}
-
-
-void
-myfdclose(FILE *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];
- extern int sys_nerr;
- DWORD source = 0;
-
- if (e < 0 || e > sys_nerr) {
- if (e < 0)
- e = GetLastError();
- if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
- buffer, 512, NULL) == 0) {
- strcpy (buffer, "Unknown Error");
- }
- 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_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;
-
-long
-myselect (int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
- struct timeval *timeout)
-{
- long r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- if ((r = select (nfds, rd, wr, ex, timeout)) == SOCKET_ERROR) {
- errno = WSAGetLastError();
- switch (errno) {
- case WSAEINTR:
- errno = EINTR;
- break;
- case WSAENOTSOCK:
- // assume normal files are always readable/writable
- // fake read/write fd_set and return value
- r = 0;
- if (rd) r += rd->fd_count;
- if (wr) r += wr->fd_count;
- if (ex && ex->fd_count > 0) {
- // exceptional condition never happen for normal files
- if (r > 0)
- ex->fd_count = 0;
- else {
- errno = EBADF;
- r = SOCKET_ERROR;
- }
- }
- 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));
-}
-
-#undef accept
-
-SOCKET
-myaccept (SOCKET s, struct sockaddr *addr, int *addrlen)
-{
- SOCKET r;
-
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- if ((r = accept (TO_SOCKET(s), addr, addrlen)) == INVALID_SOCKET)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef bind
-
-int
-mybind (SOCKET s, struct sockaddr *addr, int addrlen)
-{
- int r;
-
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- if ((r = bind (s, addr, addrlen)) == SOCKET_ERROR)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef connect
-
-int
-myconnect (SOCKET s, struct sockaddr *addr, int addrlen)
-{
- int r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- if ((r = connect (s, addr, addrlen)) == SOCKET_ERROR)
- errno = WSAGetLastError();
- return r;
-}
-
-
-#undef getpeername
-
-int
-mygetpeername (SOCKET s, struct sockaddr *addr, int *addrlen)
-{
- int r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- if ((r = getpeername (TO_SOCKET(s), addr, addrlen)) == SOCKET_ERROR)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef getsockname
-
-int
-mygetsockname (SOCKET s, struct sockaddr *addr, int *addrlen)
-{
- int r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- if ((r = getsockname (TO_SOCKET(s), addr, addrlen)) == SOCKET_ERROR)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef getsockopt
-
-int
-mygetsockopt (SOCKET s, int level, int optname, char *optval, int *optlen)
-{
- int r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- if ((r = getsockopt (s, level, optname, optval, optlen)) == SOCKET_ERROR)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef ioctlsocket
-
-int
-myioctlsocket (SOCKET s, long cmd, u_long *argp)
-{
- int r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- if ((r = ioctlsocket (TO_SOCKET(s), cmd, argp)) == SOCKET_ERROR)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef listen
-
-int
-mylisten (SOCKET s, int backlog)
-{
- int r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- if ((r = listen (s, backlog)) == SOCKET_ERROR)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef recv
-
-int
-myrecv (SOCKET s, char *buf, int len, int flags)
-{
- int r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- if ((r = recv (TO_SOCKET(s), buf, len, flags)) == 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();
- }
- if ((r = recvfrom (TO_SOCKET(s), buf, len, flags, from, fromlen)) == SOCKET_ERROR)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef send
-
-int
-mysend (SOCKET s, char *buf, int len, int flags)
-{
- int r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- if ((r = send (TO_SOCKET(s), buf, len, flags)) == 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();
- }
- if ((r = sendto (TO_SOCKET(s), buf, len, flags, to, tolen)) == 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();
- }
- if ((r = setsockopt (s, level, optname, optval, optlen))
- == SOCKET_ERROR)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef shutdown
-
-int
-myshutdown (SOCKET s, int how)
-{
- int r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- if ((r = shutdown (TO_SOCKET(s), how)) == SOCKET_ERROR)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef socket
-
-SOCKET
-mysocket (int af, int type, int protocol)
-{
- SOCKET s;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- if ((s = socket (af, type, protocol)) == INVALID_SOCKET) {
- errno = WSAGetLastError();
- //fprintf(stderr, "socket fail (%d)", WSAGetLastError());
- }
- return s;
-}
-
-#undef gethostbyaddr
-
-struct hostent *
-mygethostbyaddr (char *addr, int len, int type)
-{
- struct hostent *r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- if ((r = gethostbyaddr (addr, len, type)) == NULL)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef gethostbyname
-
-struct hostent *
-mygethostbyname (char *name)
-{
- struct hostent *r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- if ((r = gethostbyname (name)) == NULL)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef gethostname
-
-int
-mygethostname (char *name, int len)
-{
- int r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- if ((r = gethostname (name, len)) == SOCKET_ERROR)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef getprotobyname
-
-struct protoent *
-mygetprotobyname (char *name)
-{
- struct protoent *r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- if ((r = getprotobyname (name)) == NULL)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef getprotobynumber
-
-struct protoent *
-mygetprotobynumber (int num)
-{
- struct protoent *r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- if ((r = getprotobynumber (num)) == NULL)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef getservbyname
-
-struct servent *
-mygetservbyname (char *name, char *proto)
-{
- struct servent *r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- if ((r = getservbyname (name, proto)) == NULL)
- errno = WSAGetLastError();
- return r;
-}
-
-#undef getservbyport
-
-struct servent *
-mygetservbyport (int port, char *proto)
-{
- struct servent *r;
- if (!NtSocketsInitialized++) {
- StartSockets();
- }
- if ((r = getservbyport (port, proto)) == 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
-
-pid_t
-waitpid (pid_t pid, int *stat_loc, int options)
-{
- DWORD timeout;
-
- if (options == WNOHANG) {
- timeout = 0;
- } else {
- timeout = INFINITE;
- }
- if (WaitForSingleObject((HANDLE) pid, timeout) == WAIT_OBJECT_0) {
- pid = _cwait(stat_loc, pid, 0);
- return pid;
- }
- return 0;
-}
-
-#include <sys/timeb.h>
-
-int _cdecl
-gettimeofday(struct timeval *tv, struct timezone *tz)
-{
- struct timeb tb;
-
- ftime(&tb);
- tv->tv_sec = tb.time;
- tv->tv_usec = tb.millitm * 1000;
-
- return 0;
-}
-
-char *
-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++) {
- 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>
-int
-kill(int pid, int sig)
-{
-#if 1
- if ((unsigned int)pid == GetCurrentProcessId())
- return raise(sig);
-
- if (sig == 2 && pid > 0)
- if (GenerateConsoleCtrlEvent(CTRL_C_EVENT, (DWORD)pid))
- return 0;
-
- return -1;
-#else
- return 0;
-#endif
-}
-
-int
-link(char *from, char *to)
-{
- return -1;
-}
-
-int
-wait()
-{
- return 0;
-}
-
-char *
-win32_getenv(const char *name)
-{
- static char *curitem = NULL; /* XXX threadead */
- static DWORD curlen = 0; /* XXX threadead */
- DWORD needlen;
- if (!curitem) {
- 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;
-}
diff --git a/win32/win32.h b/win32/win32.h
deleted file mode 100644
index 04cb192c43..0000000000
--- a/win32/win32.h
+++ /dev/null
@@ -1,395 +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.
- *
- */
-
-#if defined(IMPORT)
-#define EXTERN extern __declspec(dllimport)
-#elif defined(EXPORT)
-#define EXTERN extern __declspec(dllexport)
-#endif
-
-//
-// Definitions for NT port of Perl
-//
-
-//
-// GRRRR!!!! Windows Nonsense.
-// Define the following so we don't get tons of extra stuff
-// when we include windows.h
-//
-#if 0
-#define NOGDICAPMASKS
-#define NOVIRTUALKEYCODES
-#define NOWINMESSAGES
-#define NOWINSTYLES
-#define NOSYSMETRICS
-#define NOMENUS
-#define NOICONS
-#define NOKEYSTATES
-#define NOSYSCOMMANDS
-#define NORASTEROPS
-#define NOSHOWWINDOW
-#define OEMRESOURCE
-#define NOATOM
-#define NOCLIPBOARD
-#define NOCOLOR
-#define NOCTLMGR
-#define NODRAWTEXT
-#define NOGDI
-//#define NOKERNEL
-//#define NOUSER
-#define NONLS
-#define NOMB
-#define NOMEMMGR
-#define NOMETAFILE
-#define NOMINMAX
-#define NOMSG
-#define NOOPENFILE
-#define NOSCROLL
-#define NOSERVICE
-#define NOSOUND
-#define NOTEXTMETRIC
-#define NOWH
-#define NOWINOFFSETS
-#define NOCOMM
-#define NOKANJI
-#define NOHELP
-#define NOPROFILER
-#define NODEFERWINDOWPOS
-#endif
-
-//
-// 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)
-}
-#endif
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <direct.h>
-#include <process.h>
-#include <time.h>
-#include <math.h>
-#include <sys/types.h>
-#include <sys/utime.h>
-#include <io.h>
-#include <malloc.h>
-
-#if defined(__cplusplus)
-extern "C" {
-#endif
-
-#define UIDTYPE int
-#define GIDTYPE int
-#define pid_t int
-#define WNOHANG -1
-
-#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) 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
-/* these are defined in nt.c */
-
-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 FILE * myfdopen(int, const char *);
-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 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 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
-//
-extern int ioctl (int, unsigned int, long);
-extern UIDTYPE getuid (void);
-extern UIDTYPE geteuid (void);
-extern GIDTYPE getgid (void);
-extern GIDTYPE getegid (void);
-extern int setuid (int);
-extern int setgid (int);
-
-
-#if 0
-extern int sys_nerr;
-extern char *sys_errlist[];
-#endif
-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 fdopen
-#undef fdopen
-#endif
-#define fdopen myfdopen
-
-#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_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 getenv
-#undef getenv
-#endif
-#define getenv win32_getenv
-
-#endif
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 ();
- }
-}