git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@2 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
matz 1998-01-16 12:13:05 +00:00
Родитель 392296c12d
Коммит 3db12e8b23
225 изменённых файлов: 75935 добавлений и 0 удалений

4305
ChangeLog Normal file

Разница между файлами не показана из-за своего большого размера Загрузить разницу

186
MANIFEST Normal file
Просмотреть файл

@ -0,0 +1,186 @@
ChangeLog
MANIFEST
Makefile.in
README
README.jp
README.EXT
ToDo
array.c
bignum.c
class.c
compar.c
configure
configure.bat
configure.in
config.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
fnmatch.c
fnmatch.h
gc.c
glob.c
hash.c
inits.c
install-sh
io.c
io.h
main.c
math.c
node.h
numeric.c
object.c
pack.c
parse.y
process.c
random.c
range.c
re.c
re.h
regex.c
regex.h
ruby.1
ruby.c
ruby.h
sig.h
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
ext/Setup
ext/Setup.dj
ext/Setup.nt
ext/Setup.x68
ext/extmk.rb.in
ext/extmk.rb.nt
ext/aix_ld.rb
lib/English.rb
lib/base64.rb
lib/cgi-lib.rb
lib/complex.rb
lib/date.rb
lib/debug.rb
lib/e2mmap.rb
lib/e2mmap1_0.rb
lib/find.rb
lib/finalize.rb
lib/ftplib.rb
lib/getopts.rb
lib/jcode.rb
lib/mailread.rb
lib/mathn.rb
lib/matrix.rb
lib/mutex_m.rb
lib/observer.rb
lib/parsearg.rb
lib/parsedate.rb
lib/ping.rb
lib/rational.rb
lib/sync.rb
lib/thread.rb
lib/thwait.rb
lib/tk.rb
lib/tkcore.rb
lib/tkcanvas.rb
lib/tkclass.rb
lib/tkentry.rb
lib/tkscrollbox.rb
lib/tktext.rb
lib/tkthcore.rb
lib/tracer.rb
missing/alloca.c
missing/crypt.c
missing/dir.h
missing/dup2.c
missing/file.h
missing/flock.c
missing/memmove.c
missing/mkdir.c
missing/nt.c
missing/nt.h
missing/setenv.c
missing/strcasecmp.c
missing/strdup.c
missing/strerror.c
missing/strftime.c
missing/strstr.c
missing/strtol.c
missing/strtoul.c
missing/x68.c
sample/biorhythm.rb
sample/clnt.rb
sample/dbmtest.rb
sample/dir.rb
sample/eval.rb
sample/export.rb
sample/exyacc.rb
sample/fact.rb
sample/fib.awk
sample/fib.pl
sample/fib.rb
sample/fib.scm
sample/freq.rb
sample/from.rb
sample/fullpath.rb
sample/getopts.test
sample/io.rb
sample/less.rb
sample/list.rb
sample/list2.rb
sample/list3.rb
sample/mrshtest.rb
sample/mkproto.rb
sample/mpart.rb
sample/observ.rb
sample/occur.pl
sample/occur.rb
sample/occur2.rb
sample/philos.rb
sample/pi.rb
sample/rcs.awk
sample/rcs.dat
sample/rcs.rb
sample/regx.rb
sample/ruby-mode.el
sample/rubydb2x.el
sample/rubydb3x.el
sample/sieve.rb
sample/svr.rb
sample/test.rb
sample/time.rb
sample/tkbiff.rb
sample/tkbrowse.rb
sample/tkdialog.rb
sample/tkfrom.rb
sample/tkhello.rb
sample/tkline.rb
sample/tktimer.rb
sample/trojan.rb
sample/tsvr.rb
sample/uumerge.rb
win32/Makefile
win32/config.h
win32/ntsetup.bat
win32/ruby.def
x68/fconvert.c
x68/select.c
x68/_dtos18.c
x68/_round.c

219
Makefile.in Normal file
Просмотреть файл

@ -0,0 +1,219 @@
SHELL = /bin/sh
#### Start of system configuration section. ####
srcdir = @srcdir@
VPATH = @srcdir@:@srcdir@/missing
CC = @CC@
YACC = @YACC@
INSTALL = @INSTALL@
INSTALL_PROGRAM = @INSTALL_PROGRAM@
INSTALL_DATA = @INSTALL_DATA@
PURIFY =
@SET_MAKE@
CFLAGS = @CFLAGS@ -I@srcdir@
LDFLAGS = @STATIC@ $(CFLAGS) @LDFLAGS@
LIBS = @LIBS@ $(EXTLIBS)
MISSING = @LIBOBJS@ @ALLOCA@
program_transform_name = -e @program_transform_name@
RUBY_INSTALL_NAME = `t='$(program_transform_name)'; echo ruby | sed $$t`
prefix = @prefix@
exec_prefix = @exec_prefix@
bindir = @bindir@
libdir = @libdir@/$(RUBY_INSTALL_NAME)
binsuffix = @binsuffix@
#### End of system configuration section. ####
LIBRUBY = libruby.a
EXTOBJS = dmyext.o
MAINOBJ = main.o
OBJS = array.o \
bignum.o \
class.o \
compar.o \
dir.o \
dln.o \
enum.o \
error.o \
eval.o \
file.o \
fnmatch.o \
gc.o \
glob.o \
hash.o \
inits.o \
io.o \
math.o \
numeric.o \
object.o \
pack.o \
parse.o \
process.o \
random.o \
range.o \
re.o \
regex.o \
ruby.o \
signal.o \
sprintf.o \
st.o \
string.o \
struct.o \
time.o \
util.o \
variable.o \
version.o \
$(MISSING)
all: miniruby$(binsuffix) @srcdir@/ext/Setup
@if test -z "$$UNDER_EXTMAKE_RB"; \
then echo "Compiling ext modules"; \
UNDER_EXTMAKE_RB=yes; export UNDER_EXTMAKE_RB; \
cd ext; ../miniruby ./extmk.rb @EXTSTATIC@; fi
miniruby$(binsuffix): $(OBJS) $(MAINOBJ) $(EXTOBJS)
@rm -f $@
$(PURIFY) $(CC) $(LDFLAGS) $(MAINOBJ) $(OBJS) $(EXTOBJS) $(LIBS) -o miniruby
ruby$(binsuffix): $(LIBRUBY) $(MAINOBJ) $(EXTOBJS)
@rm -f $@
$(PURIFY) $(CC) $(LDFLAGS) $(MAINOBJ) $(EXTOBJS) $(LIBRUBY) $(LIBS) -o ruby
$(LIBRUBY): $(OBJS) dmyext.o
@AR@ rcu $(LIBRUBY) $(OBJS) dmyext.o
@-@RANLIB@ $(LIBRUBY) 2> /dev/null || true
install:; $(INSTALL_PROGRAM) ruby$(binsuffix) $(bindir)/$(RUBY_INSTALL_NAME)$(binsuffix)
@-@STRIP@ $(bindir)/$(RUBY_INSTALL_NAME)$(binsuffix)
@test -d $(libdir) || mkdir $(libdir)
cd ext; ../miniruby ./extmk.rb install
@for rb in `grep '^lib/' @srcdir@/MANIFEST`; do \
$(INSTALL_DATA) @srcdir@/$$rb $(libdir); \
done
clean:; @rm -f $(OBJS) $(LIBRUBY) $(MAINOBJ)
@rm -f ext/extinit.c ext/extinit.o dmyext.o
cd ext; ../miniruby ./extmk.rb clean
realclean: clean
@rm -f Makefile ext/extmk.rb ext/config.cache parse.c
@rm -f config.cache config.h config.log config.status
@rm -f core ruby$(binsuffix) miniruby$(binsuffix) parse.c *~ *.core gmon.out
test:; @-./ruby @srcdir@/sample/test.rb > ./ruby_test 2>&1; \
if grep '^end of test' ./ruby_test > /dev/null; then \
echo "test succeeded"; \
else \
grep '^sample/test.rb' ./ruby_test; \
grep '^not' ./ruby_test; \
echo "test failed";\
fi;\
rm -f ./ruby_test
.c.o:
$(CC) $(CFLAGS) $(CPPFLAGS) -c $<
parse.c: parse.y
$(YACC) $<
mv -f y.tab.c parse.c
alloca.o: @srcdir@/missing/alloca.c
$(CC) -I. $(CFLAGS) $(CPPFLAGS) -c @srcdir@/missing/alloca.c
crypt.o: @srcdir@/missing/crypt.c
$(CC) -I. $(CFLAGS) $(CPPFLAGS) -c @srcdir@/missing/crypt.c
dup2.o: @srcdir@/missing/dup2.c
$(CC) -I. $(CFLAGS) $(CPPFLAGS) -c @srcdir@/missing/dup2.c
flock.o: @srcdir@/missing/flock.c
$(CC) -I. $(CFLAGS) $(CPPFLAGS) -c @srcdir@/missing/flock.c
memmove.o: @srcdir@/missing/memmove.c
$(CC) $(CFLAGS) $(CPPFLAGS) -c @srcdir@/missing/memmove.c
mkdir.o: @srcdir@/missing/mkdir.c
$(CC) $(CFLAGS) $(CPPFLAGS) -c @srcdir@/missing/mkdir.c
setenv.o: @srcdir@/missing/setenv.c
$(CC) $(CFLAGS) $(CPPFLAGS) -c @srcdir@/missing/setenv.c
strcasecmp.o: @srcdir@/missing/strcasecmp.c
$(CC) $(CFLAGS) $(CPPFLAGS) -c @srcdir@/missing/strcasecmp.c
strerror.o: @srcdir@/missing/strerror.c
$(CC) $(CFLAGS) $(CPPFLAGS) -c @srcdir@/missing/strerror.c
strdup.o: @srcdir@/missing/strdup.c
$(CC) $(CFLAGS) $(CPPFLAGS) -c @srcdir@/missing/strdup.c
strftime.o: @srcdir@/missing/strftime.c
$(CC) -I. $(CFLAGS) $(CPPFLAGS) -c @srcdir@/missing/strftime.c
strstr.o: @srcdir@/missing/strstr.c
$(CC) $(CFLAGS) $(CPPFLAGS) -c @srcdir@/missing/strstr.c
strtol.o: @srcdir@/missing/strtol.c
$(CC) $(CFLAGS) $(CPPFLAGS) -c @srcdir@/missing/strtol.c
strtoul.o: @srcdir@/missing/strtoul.c
$(CC) $(CFLAGS) $(CPPFLAGS) -c @srcdir@/missing/strtoul.c
nt.o: @srcdir@/missing/nt.c
$(CC) $(CFLAGS) $(CPPFLAGS) -c @srcdir@/missing/nt.c
x68.o: @srcdir@/missing/x68.c
$(CC) $(CFLAGS) $(CPPFLAGS) -c @srcdir@/missing/x68.c
# Prevent GNU make v3 from overflowing arg limit on SysV.
.NOEXPORT:
###
parse.o : parse.y ruby.h defines.h config.h env.h node.h st.h regex.h
###
array.o: array.c ruby.h config.h defines.h
bignum.o: bignum.c ruby.h config.h defines.h
class.o: class.c ruby.h config.h defines.h node.h st.h
compar.o: compar.c ruby.h config.h defines.h
dir.o: dir.c ruby.h config.h defines.h
dln.o: dln.c config.h defines.h dln.h st.h
dmyext.o: dmyext.c
enum.o: enum.c ruby.h config.h defines.h
error.o: error.c ruby.h config.h defines.h env.h
eval.o: eval.c ruby.h config.h defines.h env.h node.h sig.h st.h dln.h
file.o: file.c ruby.h config.h defines.h io.h sig.h
fnmatch.o: fnmatch.c config.h fnmatch.h
gc.o: gc.c ruby.h config.h defines.h env.h sig.h st.h node.h re.h regex.h
glob.o: glob.c config.h fnmatch.h
hash.o: hash.c ruby.h config.h defines.h st.h
inits.o: inits.c ruby.h config.h defines.h
io.o: io.c ruby.h config.h defines.h io.h sig.h
main.o: main.c
math.o: math.c ruby.h config.h defines.h
numeric.o: numeric.c ruby.h config.h defines.h
object.o: object.c ruby.h config.h defines.h st.h
pack.o: pack.c ruby.h config.h defines.h
process.o: process.c ruby.h config.h defines.h sig.h st.h
random.o: random.c ruby.h config.h defines.h
range.o: range.c ruby.h config.h defines.h
re.o: re.c ruby.h config.h defines.h re.h regex.h
regex.o: regex.c config.h defines.h regex.h util.h
ruby.o: ruby.c ruby.h config.h defines.h re.h regex.h dln.h
signal.o: signal.c ruby.h config.h defines.h sig.h
sprintf.o: sprintf.c ruby.h config.h defines.h
st.o: st.c config.h st.h
string.o: string.c ruby.h config.h defines.h re.h regex.h
struct.o: struct.c ruby.h config.h defines.h
time.o: time.c ruby.h config.h defines.h
util.o: util.c defines.h config.h util.h
variable.o: variable.c ruby.h config.h defines.h env.h st.h
version.o: version.c ruby.h config.h defines.h version.h

108
README Normal file
Просмотреть файл

@ -0,0 +1,108 @@
* 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)
* How to get ruby
** by ftp
The ruby distribution can be found on
ftp://ftp.netlab.co.jp/pub/lang/ruby/
* 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, if
you want to link modules statically.
If you want to link all the extension modules, remove comment
mark from the line "#option nodynamic".
4. Run make.
5. Optionally, run 'make test' to check that the compiled ruby
interpreter works well. If you see the message "test succeeded",
your ruby works as it should.
6. Run 'make install'
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 by Yukihiro Matsumoto <matz@ruby.club.co.jp>.
This source is distributed under the conditions blow:
1. You may make and give away verbatim copies of the source form of
the software without restriction, provided that you do not modify
the original distribution files.
If you want to distribute the modified version in any way, contact
the author.
2. You may distribute the software in object code or executable
form, provided that you distribute it with instructions on where
to get the software.
3. You may modify the software in any way, provided that you do not
distribute the modified version.
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]¡¤fnmatch.[ch]¡¤
glob.c, st.[ch] and somme files under the ./missing directory. See
each files 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.netlab.co.jp/ruby/
* 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:

1064
README.EXT Normal file

Разница между файлами не показана из-за своего большого размера Загрузить разницу

150
README.jp Normal file
Просмотреть файл

@ -0,0 +1,150 @@
* Rubyとは
Rubyはシンプルかつ強力なオブジェクト指向スクリプト言語です
Rubyは最初から純粋なオブジェクト指向言語として設計されていま
すから,オブジェクト指向プログラミングを手軽に行う事が出来ま
す.もちろん通常の手続き型のプログラミングも可能です.
Rubyはテキスト処理関係の能力などに優れperlと同じくらい強力
です.さらにシンプルな文法と,例外処理やイテレータなどの機構
によって,より分かりやすいプログラミングが出来ます.
* Rubyの特長
+ シンプルな文法
+ 普通のオブジェクト指向機能(クラス,メソッドコールなど)
+ 特殊なオブジェクト指向機能(Mixin, 特異メソッドなど)
+ 演算子オーバーロード
+ 例外処理機能
+ イテレータとクロージャ
+ ガーベージコレクタ
+ ダイナミックローディング (アーキテクチャによる)
+ 移植性が高い多くのUNIX上で動く
* 入手法
** ftpで
以下の場所においてあります.
ftp://ftp.netlab.co.jp/pub/lang/ruby/
* ホームページ
RubyのホームページのURLは
http://www.netlab.co.jp/ruby/jp/
です.
* メイリングリスト
Rubyに関わる話題のためのメイリングリストを開設しました
ドレスは
ruby-list@netlab.co.jp
です.このアドレスにメイルを送れば,自動的に登録されます.
* コンパイル・インストール
以下の手順で行ってください.
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
もし,コンパイル時にエラーが発生した場合にはエラーのログとマ
シンOSの種類を含むできるだけ詳しいレポートを作者に送ってく
ださると他の方のためにもなります.
* 移植
UNIXであればconfigureがほとんどの差異を吸収してくれるはずで
すが,思わぬ見落としがあった場合(あるに違いない),作者にその
ことをレポートすれば,解決できるかも知れません.
アークテクチャにもっとも依存するのはGC部ですrubyのGCは対象
のアーキテクチャがsetjmp()によって全てのレジスタを jmp_bufに
格納することとjmp_bufとスタックが32bitアラインメントされて
いることを仮定しています.特に前者が成立しない場合の対応は非
常に困難でしょう後者の解決は比較的簡単でgc.cでスタックを
マークしている部分にアラインメントのバイト数だけずらしてマー
クするコードを追加するだけで済みます「defined(THINK_C)」で
括られている部分を参考にしてください
# 実際にはrubyはThink Cではコンパイルできません
レジスタウィンドウを持つCPUではレジスタウィンドウをスタッ
クにフラッシュするアセンブラコードを追加する必要があるかも知
れません.
* 配布条件
作者は以下の条件のもとにrubyを配布します
+ 再配布
配布した状態を維持する限り自由です.変更を行ったものを再
配布することを希望する時には作者に連絡してください.
変更を行なわないrubyをコンパイルしたバイナリの配布は禁止
しませんが,バイナリを受け取った人がソースを入手できるよ
うに,ソースの入手法を明示してください.
+ 変更
再配布を行わない限り,いかなる目的であれ自由です.ただし,
機能拡張やバグ修正は作者へのフィードバックを期待します
(もちろん強制ではありません)
+ 他のプログラムへの引用
いかなる目的であれ自由ですただしrubyに含まれる他の作
者によるコードは,それぞれの作者の意向による制限が加えら
れます具体的にはgc.c(一部)util.c(一部)regex.[ch]
fnmatch.[ch]glob.cst.[ch]と./missingディレクトリ下の
ファイル群が該当します.
+ Rubyスクリプトの権利
全てのrubyスクリプトの権利はそれぞれの著作者に属します
作者はこれらに関して一切の権利を主張しませんまたrubyに
組み込むための拡張モジュールに関しても同様です.
+ 無保証
Rubyは無保証です作者はrubyをサポートする意志はあります
ruby自身のバグあるいはrubyスクリプトのバグなどから発
生するいかなる損害に対しても責任を持ちません.
* 著者
コメント,バグレポートその他は matz@netlab.co.jp まで.
-------------------------------------------------------
created at: Thu Aug 3 11:57:36 JST 1995
Local variables:
mode: indented-text
end:

4
ToDo Normal file
Просмотреть файл

@ -0,0 +1,4 @@
* non-blocking open/write for thread
* パッケージまたは大域変数のアクセス制御
* format機能
* re-write regex code for speed and copyright

1242
array.c Normal file

Разница между файлами не показана из-за своего большого размера Загрузить разницу

1249
bignum.c Normal file

Разница между файлами не показана из-за своего большого размера Загрузить разницу

427
class.c Normal file
Просмотреть файл

@ -0,0 +1,427 @@
/************************************************
class.c -
$Author$
$Date$
created at: Tue Aug 10 15:05:44 JST 1993
Copyright (C) 1993-1995 Yukihiro Matsumoto
************************************************/
#include "ruby.h"
#include "node.h"
#include "st.h"
struct st_table *new_idhash();
extern st_table *rb_class_tbl;
extern VALUE cClass;
extern VALUE cModule;
VALUE
class_new(super)
struct RClass *super;
{
NEWOBJ(cls, struct RClass);
OBJSETUP(cls, cClass, T_CLASS);
cls->super = super;
cls->iv_tbl = 0;
cls->m_tbl = 0; /* safe GC */
cls->m_tbl = new_idhash();
return (VALUE)cls;
}
VALUE
singleton_class_new(super)
struct RClass *super;
{
struct RClass *cls = (struct RClass*)class_new(super);
FL_SET(cls, FL_SINGLETON);
return (VALUE)cls;
}
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
singleton_class_clone(class)
struct RClass *class;
{
if (!FL_TEST(class, FL_SINGLETON))
return (VALUE)class;
else {
/* copy singleton(unnamed) class */
NEWOBJ(clone, struct RClass);
CLONESETUP(clone, class);
clone->super = class->super;
clone->iv_tbl = 0;
clone->m_tbl = 0;
clone->m_tbl = new_idhash();
st_foreach(class->m_tbl, clone_method, clone->m_tbl);
FL_SET(clone, FL_SINGLETON);
return (VALUE)clone;
}
}
VALUE
rb_define_class_id(id, super)
ID id;
struct RBasic *super;
{
struct RClass *cls;
if (!super) super = (struct RBasic*)cClass;
cls = (struct RClass*)class_new(super);
rb_name_class(cls, id);
/* make metaclass */
RBASIC(cls)->class = singleton_class_new(super->class);
return (VALUE)cls;
}
VALUE
rb_define_class(name, super)
char *name;
VALUE super;
{
VALUE class;
ID id;
id = rb_intern(name);
class = rb_define_class_id(id, super);
st_add_direct(rb_class_tbl, id, class);
return class;
}
VALUE
rb_define_class_under(under, name, super)
VALUE under;
char *name;
VALUE super;
{
VALUE class;
ID id;
id = rb_intern(name);
class = rb_define_class_id(id, super);
rb_const_set(under, id, class);
rb_set_class_path(class, under, name);
return class;
}
VALUE
module_new()
{
NEWOBJ(mdl, struct RClass);
OBJSETUP(mdl, cModule, T_MODULE);
mdl->super = 0;
mdl->iv_tbl = 0;
mdl->m_tbl = 0;
mdl->m_tbl = new_idhash();
return (VALUE)mdl;
}
VALUE
rb_define_module_id(id)
ID id;
{
extern st_table *rb_class_tbl;
struct RClass *mdl = (struct RClass*)module_new();
rb_name_class(mdl, id);
return (VALUE)mdl;
}
VALUE
rb_define_module(name)
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(under, name)
VALUE under;
char *name;
{
VALUE module;
ID id;
id = rb_intern(name);
module = rb_define_module_id(id);
rb_const_set(under, id, module);
rb_set_class_path(module, under, name);
return module;
}
static struct RClass *
include_class_new(module, super)
struct RClass *module, *super;
{
NEWOBJ(cls, struct RClass);
OBJSETUP(cls, cClass, T_ICLASS);
cls->m_tbl = module->m_tbl;
cls->iv_tbl = module->iv_tbl;
cls->super = super;
if (TYPE(module) == T_ICLASS) {
RBASIC(cls)->class = RBASIC(module)->class;
}
else {
RBASIC(cls)->class = (VALUE)module;
}
return cls;
}
void
rb_include_module(class, module)
VALUE class, module;
{
struct RClass *p;
if (NIL_P(module)) return;
switch (TYPE(module)) {
case T_MODULE:
case T_CLASS:
break;
default:
Check_Type(module, T_MODULE);
}
if (class == module) return;
rb_clear_cache();
while (module) {
/* ignore if the module included already in superclasses */
for (p = RCLASS(class)->super; p; p = p->super) {
if (BUILTIN_TYPE(p) == T_ICLASS && p->m_tbl == RCLASS(module)->m_tbl)
return;
}
RCLASS(class)->super = include_class_new(module, RCLASS(class)->super);
class = (VALUE)RCLASS(class)->super;
module = (VALUE)RCLASS(module)->super;
}
}
void
rb_define_method_id(class, name, func, argc)
struct RClass *class;
ID name;
VALUE (*func)();
int argc;
{
rb_add_method(class, name, NEW_CFUNC(func, argc), NOEX_PUBLIC);
}
void
rb_define_method(class, name, func, argc)
VALUE class;
char *name;
VALUE (*func)();
int argc;
{
rb_add_method(class, rb_intern(name), NEW_CFUNC(func, argc), NOEX_PUBLIC);
}
void
rb_undef_method(class, name)
VALUE class;
char *name;
{
rb_add_method(class, rb_intern(name), 0, NOEX_PUBLIC);
}
void
rb_define_private_method(class, name, func, argc)
struct RClass *class;
char *name;
VALUE (*func)();
int argc;
{
rb_add_method(class, rb_intern(name), NEW_CFUNC(func, argc), NOEX_PRIVATE);
}
VALUE
rb_singleton_class(obj)
struct RBasic *obj;
{
if (rb_special_const_p((VALUE)obj)) {
TypeError("cannot define singleton");
}
if (FL_TEST(obj->class, FL_SINGLETON)) {
return (VALUE)obj->class;
}
return obj->class = singleton_class_new(obj->class);
}
void
rb_define_singleton_method(obj, name, func, argc)
VALUE obj;
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;
char *name;
VALUE (*func)();
int argc;
{
rb_define_private_method(module, name, func, argc);
rb_define_singleton_method(module, name, func, argc);
}
VALUE mKernel;
void
rb_define_global_function(name, func, argc)
char *name;
VALUE (*func)();
int argc;
{
rb_define_private_method(mKernel, name, func, argc);
}
void
rb_define_alias(class, name1, name2)
VALUE class;
char *name1, *name2;
{
rb_alias(class, rb_intern(name1), rb_intern(name2));
}
void
rb_define_attr(class, id, pub)
VALUE class;
ID id;
int pub;
{
char *name;
char *buf;
ID attr, attreq, attriv;
name = rb_id2name(id);
attr = rb_intern(name);
buf = ALLOCA_N(char,strlen(name)+2);
sprintf(buf, "%s=", name);
attreq = rb_intern(buf);
sprintf(buf, "@%s", name);
attriv = rb_intern(buf);
if (!rb_method_boundp(class, attr, NOEX_PRIVATE)) {
rb_add_method(class, attr, NEW_IVAR(attriv), 0);
}
if (pub && !rb_method_boundp(class, attreq, NOEX_PRIVATE)) {
rb_add_method(class, attreq, NEW_ATTRSET(attriv), 0);
}
}
#include <varargs.h>
#include <ctype.h>
int
rb_scan_args(argc, argv, fmt, va_alist)
int argc;
VALUE *argv;
char *fmt;
va_dcl
{
int n, i;
char *p = fmt;
VALUE *var;
va_list vargs;
va_start(vargs);
if (*p == '*') {
var = va_arg(vargs, VALUE*);
*var = ary_new4(argc, argv);
return argc;
}
if (isdigit(*p)) {
n = *p - '0';
if (n > argc)
ArgError("Wrong # of arguments (%d for %d)", argc, n);
for (i=0; i<n; i++) {
var = va_arg(vargs, VALUE*);
*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) {
*var = argv[i];
}
else {
*var = Qnil;
}
}
p++;
}
if(*p == '*') {
var = va_arg(vargs, VALUE*);
if (argc > i) {
*var = ary_new4(argc-i, argv+i);
}
else {
*var = ary_new();
}
}
else if (*p == '\0') {
if (argc > i) {
ArgError("Wrong # of arguments(%d for %d)", argc, i);
}
}
else {
goto error;
}
va_end(vargs);
return argc;
error:
Fatal("bad scan arg format: %s", fmt);
return 0;
}

100
compar.c Normal file
Просмотреть файл

@ -0,0 +1,100 @@
/************************************************
compar.c -
$Author$
$Date$
created at: Thu Aug 26 14:39:48 JST 1993
Copyright (C) 1993-1996 Yukihiro Matsumoto
************************************************/
#include "ruby.h"
VALUE mComparable;
static ID cmp;
static VALUE
cmp_eq(x, y)
VALUE x, y;
{
VALUE c = rb_funcall(x, cmp, 1, y);
int t = NUM2INT(c);
if (t == 0) return TRUE;
return FALSE;
}
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 TRUE;
return FALSE;
}
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 TRUE;
return FALSE;
}
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 TRUE;
return FALSE;
}
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 TRUE;
return FALSE;
}
static VALUE
cmp_between(x, min, max)
VALUE x, min, max;
{
VALUE c = rb_funcall(x, cmp, 1, min);
int t = NUM2INT(c);
if (t < 0) return FALSE;
c = rb_funcall(x, cmp, 1, max);
t = NUM2INT(c);
if (t > 0) return FALSE;
return TRUE;
}
void
Init_Comparable()
{
mComparable = rb_define_module("Comparable");
rb_define_method(mComparable, "==", cmp_eq, 1);
rb_define_method(mComparable, ">", cmp_gt, 1);
rb_define_method(mComparable, ">=", cmp_ge, 1);
rb_define_method(mComparable, "<", cmp_lt, 1);
rb_define_method(mComparable, "<=", cmp_le, 1);
rb_define_method(mComparable, "between?", cmp_between, 2);
cmp = rb_intern("<=>");
}

36
config.dj Normal file
Просмотреть файл

@ -0,0 +1,36 @@
#define THREAD 1
#define HAVE_DIRENT_H 1
#define HAVE_UNISTD_H 1
#define HAVE_LIMITS_H 1
#define HAVE_SYS_FILE_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 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 FILE_COUNT _cnt
#define DLEXT ".so"
#define RUBY_LIB ";/usr/local/lib/ruby;."
#define RUBY_ARCHLIB "/usr/local/lib/ruby/i386-djgpp"
#define RUBY_PLATFORM "i386-djgpp"

613
config.guess поставляемый Normal file
Просмотреть файл

@ -0,0 +1,613 @@
#! /bin/sh
# Attempt to guess a canonical system name.
# Copyright (C) 1992, 93, 94, 95, 1996 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
alpha:OSF1:*:*)
# 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.
echo alpha-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[VTX]//'`
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 ;;
arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*)
echo arm-acorn-riscix${UNAME_RELEASE}
exit 0;;
Pyramid*:OSx*:*:*)
if test "`(/bin/universe) 2>/dev/null`" = att ; then
echo pyramid-pyramid-sysv3
else
echo pyramid-pyramid-bsd
fi
exit 0 ;;
sun4*: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 ;;
atari*:NetBSD:*:*)
echo m68k-atari-netbsd${UNAME_RELEASE}
exit 0 ;;
sun3*:NetBSD:*:*)
echo m68k-sun-netbsd${UNAME_RELEASE}
exit 0 ;;
mac68k:NetBSD:*:*)
echo m68k-apple-netbsd${UNAME_RELEASE}
exit 0 ;;
RISC*:ULTRIX:*:*)
echo mips-dec-ultrix${UNAME_RELEASE}
exit 0 ;;
VAX*:ULTRIX*:*:*)
echo vax-dec-ultrix${UNAME_RELEASE}
exit 0 ;;
mips:*:4*:UMIPS)
echo mips-mips-riscos4sysv
exit 0 ;;
mips:*:5*:RISCos)
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[34]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)
if /usr/sbin/lsattr -EHl proc0 | 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/[3478]??:HP-UX:*:*)
case "${UNAME_MACHINE}" in
9000/31? ) HP_ARCH=m68000 ;;
9000/[34]?? ) HP_ARCH=m68k ;;
9000/7?? | 9000/8?[679] ) HP_ARCH=hppa1.1 ;;
9000/8?? ) HP_ARCH=hppa1.0 ;;
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 ;;
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*C90:*:*:*)
echo c90-cray-unicos${UNAME_RELEASE}
exit 0 ;;
CRAY-2:*:*:*)
echo cray2-cray-unicos
exit 0 ;;
hp3[0-9][05]:NetBSD:*:*)
echo m68k-hp-netbsd${UNAME_RELEASE}
exit 0 ;;
i[34]86:BSD/386:*:* | *:BSD/OS:*:*)
echo ${UNAME_MACHINE}-pc-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 i386-pc-cygwin32
exit 0 ;;
p*:CYGWIN*:*)
echo powerpcle-unknown-cygwin32
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:*:*)
echo ${UNAME_MACHINE}-pc-linux
exit 0 ;;
# ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. earlier versions
# are messed up and put the nodename in both sysname and nodename.
i[34]86:DYNIX/ptx:4*:*)
echo i386-sequent-sysv4
exit 0 ;;
i[34]86:*:4.*:* | i[34]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[34]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 ;;
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 ;;
M680[234]0:*:R3V[567]*:*)
test -r /sysV68 && echo 'm68k-motorola-sysv' && exit 0 ;;
3[34]??:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0)
uname -p 2>/dev/null | grep 86 >/dev/null \
&& echo i486-ncr-sysv4.3 && exit 0 ;;
3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*)
uname -p 2>/dev/null | grep 86 >/dev/null \
&& echo i486-ncr-sysv4 && exit 0 ;;
m680[234]0:LynxOS:2.[23]*:*)
echo m68k-lynx-lynxos${UNAME_RELEASE}
exit 0 ;;
mc68030:UNIX_System_V:4.*:*)
echo m68k-atari-sysv4
exit 0 ;;
i[34]86:LynxOS:2.[23]*:*)
echo i386-lynx-lynxos${UNAME_RELEASE}
exit 0 ;;
TSUNAMI:LynxOS:2.[23]*:*)
echo sparc-lynx-lynxos${UNAME_RELEASE}
exit 0 ;;
rs6000:LynxOS:2.[23]*:*)
echo rs6000-lynx-lynxos${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 ;;
mc68*:A/UX:*:*)
echo m68k-apple-aux${UNAME_RELEASE}
exit 0 ;;
X680[02346]0:Human68k:*:*)
echo m68k-sharp-human
exit 0 ;;
R[34]000:*System_V*:*:*)
if [ -d /usr/nec ]; then
echo mips-nec-sysv${UNAME_RELEASE}
else
echo mips-unknown-sysv${UNAME_RELEASE}
fi
exit 0 ;;
R[34]???:UNIX_SV:4.?MP:*)
if [ -x /sbin/uversion ]; then
UVERSION_RELEASE=`(/sbin/uversion -r) 2>/dev/null` \
|| UVERSION_RELEASE=unknown
UVERSION_SYSTEM=`(/sbin/uversion -s) 2>/dev/null` \
|| UVERSION_SYSTEM=unknown
case "${UVERSION_RELEASE}:${UVERSION_SYSTEM}" in
Release*:EWS4800/*)
suffix=`echo ${UNAME_RELEASE} | tr '[A-Z]' '[a-z]'`
suffix=${suffix}r`echo ${UVERSION_RELEASE} | \
sed -e 's/Release//' -e 's/ Rev.*$//'`
echo mips-nec-sysv${suffix}
exit 0 ;;
esac
fi;;
*:machten:*:*)
echo ${UNAME_MACHINE}-apple-machten
exit 0 ;;
powerpc:JCC_BSD+:*:*)
echo powerpc-jcc-bsd4.4
exit 0 ;;
DS/90*:*:*:V20*)
echo sparc-fujitsu-uxpds
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`;
printf ("%s-next-nextstep%s\n", __ARCHITECTURE__, version==2 ? "2" : "3");
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
#if defined (__human68k__) || defined (HUMAN68K)
printf ("m68k-sharp-human\n"); exit (0);
#endif
exit (1);
}
EOF
${CC-cc} dummy.c -o dummy 2>/dev/null && ./dummy && rm -f dummy.c dummy.x dummy && exit 0
rm -f dummy.c dummy.x 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

931
config.sub поставляемый Normal file
Просмотреть файл

@ -0,0 +1,931 @@
#! /bin/sh
# Configuration validation subroutine script, version 1.1.
# Copyright (C) 1991, 92, 93, 94, 95, 1996 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 | m68k | m68000 | m88k | ns32k | arm \
| arme[lb] | pyramid \
| tron | a29k | 580 | i960 | h8300 | hppa1.0 | hppa1.1 \
| alpha | we32k | ns16k | clipper | i370 | sh \
| powerpc | powerpcle | 1750a | dsp16xx | mips64 | mipsel \
| pdp11 | mips64el | mips64orion | mips64orionel \
| sparc | sparclet | sparclite | sparc64)
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[3456]86)
basic_machine=$basic_machine-pc
;;
# Object if more than one company name word.
*-*-*)
echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
exit 1
;;
# Recognize the basic CPU types with company name.
vax-* | tahoe-* | i[3456]86-* | i860-* | m68k-* | m68000-* | m88k-* \
| sparc-* | ns32k-* | fx80-* | arm-* | c[123]* \
| mips-* | pyramid-* | tron-* | a29k-* | romp-* | rs6000-* | power-* \
| none-* | 580-* | cray2-* | h8300-* | i960-* | xmp-* | ymp-* \
| hppa1.0-* | hppa1.1-* | alpha-* | we32k-* | cydra-* | ns16k-* \
| pn-* | np1-* | xps100-* | clipper-* | orion-* | sparclite-* \
| pdp11-* | sh-* | powerpc-* | powerpcle-* | sparc64-* | mips64-* | mipsel-* \
| mips64el-* | mips64orion-* | mips64orionel-*)
;;
# 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
;;
amigados)
basic_machine=m68k-cbm
os=-amigados
;;
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
;;
ews4800)
basic_machine=mips-nec
os=-sysv4
;;
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
;;
i370-ibm* | ibm*)
basic_machine=i370-ibm
os=-mvs
;;
# I'm not sure what "Sysv32" means. Should this be sysv3.2?
i[3456]86v32)
basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
os=-sysv32
;;
i[3456]86v4*)
basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
os=-sysv4
;;
i[3456]86v)
basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
os=-sysv
;;
i[3456]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
;;
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)
basic_machine=i586-intel
;;
pentiumpro | p6)
basic_machine=i686-intel
;;
pentium-* | p5-*)
basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'`
;;
pentiumpro-* | p6-*)
basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
;;
k5)
# We don't have specific support for AMD's K5 yet, so just call it a Pentium
basic_machine=i586-amd
;;
nexen)
# We don't have specific support for Nexgen yet, so just call it a Pentium
basic_machine=i586-nexgen
;;
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
;;
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
;;
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)
basic_machine=mips-mips
;;
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
;;
human)
basic_machine=m68k-sharp
os=-human
;;
*)
echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
exit 1
;;
esac
# Here we canonicalize certain aliases for manufacturers.
case $basic_machine in
*-digital*)
basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'`
;;
*-commodore*)
basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'`
;;
*)
;;
esac
# Decode manufacturer-specific aliases for certain operating systems.
if [ x"$os" != x"" ]
then
case $os in
# First match some system type aliases
# that might get confused with valid system types.
# -solaris* is a basic system type, with this one exception.
-solaris1 | -solaris1.*)
os=`echo $os | sed -e 's|solaris1|sunos4|'`
;;
-solaris)
os=-solaris2
;;
-unixware* | svr4*)
os=-sysv4
;;
-gnu/linux*)
os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'`
;;
# 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* \
| -amigados* | -msdos* | -newsos* | -unicos* | -aof* | -aos* \
| -nindy* | -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* \
| -cygwin32* | -pe* | -psos* | -moss* | -proelf* \
| -linux* | -bow*)
# 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)
;;
-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
;;
*-ibm)
os=-aix
;;
*-hp)
os=-hpux
;;
*-hitachi)
os=-hiux
;;
i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent)
os=-sysv
;;
*-cbm)
os=-amigados
;;
*-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
;;
*)
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
;;
-lynxos*)
vendor=lynx
;;
-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
;;
-vxworks*)
vendor=wrs
;;
-aux*)
vendor=apple
;;
esac
basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"`
;;
esac
echo $basic_machine$os

4038
configure поставляемый Normal file

Разница между файлами не показана из-за своего большого размера Загрузить разницу

5
configure.bat Normal file
Просмотреть файл

@ -0,0 +1,5 @@
@echo off
sed -f top.sed Makefile.in >Makefile
sed -f top.sed ext/extmk.rb.in > ext\extmk.rb
copy ext\Setup.dj ext\Setup
copy config.dj config.h

474
configure.in Normal file
Просмотреть файл

@ -0,0 +1,474 @@
dnl Process this file with autoconf to produce a configure script.
AC_INIT(ruby.h)
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
dnl checks for thread
rb_thread=yes
AC_ARG_ENABLE(thread, [--disable-thread never use user-level thread], [
rb_thread=$enableval
])
if test $rb_thread = yes; then
AC_DEFINE(THREAD)
fi
AC_CANONICAL_HOST
dnl checks for fat-binary
fat_binary=no
AC_ARG_ENABLE( fat-binary,
[--enable-fat-binary build a NeXT Multi Architecture Binary. ],
[ fat_binary=$enableval ] )
if test "$fat_binary" = yes ; then
AC_MSG_CHECKING( target architecture )
if test "$TARGET_ARCHS" = "" ; then
if test `/usr/bin/arch` = "m68k" ; then
TARGET_ARCHS="m68k i486"
else
TARGET_ARCHS="m68k `/usr/bin/arch`"
fi
fi
# /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_INSTALL
AC_PROG_MAKE_SET
# checks for UNIX variants that set C preprocessor variables
AC_MINIX
dnl Checks for libraries.
case "$host_os" in
nextstep*) ;;
human*) ;;
*) LIBS="-lm $LIBS";;
esac
AC_CHECK_LIB(crypt, crypt)
AC_CHECK_LIB(dl, dlopen) # Dynamic linking for SunOS/Solaris and SYSV
AC_CHECK_LIB(dld, shl_load) # Dynamic linking for HP-UX
dnl Checks for header files.
AC_HEADER_DIRENT
AC_HEADER_STDC
AC_CHECK_HEADERS(stdlib.h unistd.h limits.h sys/file.h sys/ioctl.h pwd.h \
sys/select.h sys/time.h sys/times.h sys/param.h sys/wait.h\
syscall.h a.out.h string.h utime.h memory.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
AC_CHECK_SIZEOF(short)
AC_CHECK_SIZEOF(int)
AC_CHECK_SIZEOF(long)
AC_CHECK_SIZEOF(void*)
dnl Checks for library functions.
AC_TYPE_GETGROUPS
AC_TYPE_SIGNAL
AC_FUNC_ALLOCA
AC_FUNC_VFORK
AC_REPLACE_FUNCS(dup2 setenv memmove mkdir strcasecmp strerror strftime\
strstr strtoul strdup crypt flock)
AC_CHECK_FUNCS(fmod killpg random wait4 waitpid syscall getcwd\
truncate chsize times utimes fcntl lockf setitimer\
setruid seteuid setreuid setrgid setegid setregid\
setpgrp2 getpgid getgroups getpriority\
dlopen sigprocmask sigaction _setjmp)
if test "$ac_cv_func_strftime" = no; then
AC_STRUCT_TIMEZONE
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_MSG_CHECKING(for BSD signal semantics)
AC_CACHE_VAL(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)])
AC_MSG_RESULT($rb_cv_bsd_signal)
if test "$rb_cv_bsd_signal" = yes; then
AC_DEFINE(BSD_SIGNAL)
fi
fi
if test "$ac_cv_func_setpgrp2" = yes; then
AC_DEFINE(BSD_GETPGRP, getpgrp2)
AC_DEFINE(BSD_SETPGRP, setpgrp2)
else
AC_MSG_CHECKING(whether getpgrp() has arg)
AC_CACHE_VAL(rb_cv_bsdgetpgrp,
[AC_TRY_COMPILE([#include <unistd.h>], [getpgrp(0);],
rb_cv_bsdgetpgrp=yes,
rb_cv_bsdgetpgrp=no)])
AC_MSG_RESULT($rb_cv_bsdgetpgrp)
if test "$rb_cv_bsdgetpgrp" = yes; then
AC_DEFINE(BSD_GETPGRP, getpgrp)
fi
AC_MSG_CHECKING(whether setpgrp() has args)
AC_CACHE_VAL(rb_cv_bsdsetpgrp,
[AC_TRY_COMPILE([#include <unistd.h>], [setpgrp(1, 1);],
rb_cv_bsdsetpgrp=yes,
rb_cv_bsdsetpgrp=no)])
AC_MSG_RESULT($rb_cv_bsdsetpgrp)
if test "$rb_cv_bsdsetpgrp" = yes; then
AC_DEFINE(BSD_SETPGRP, setpgrp)
fi
fi
AC_C_BIGENDIAN
AC_CHAR_UNSIGNED
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", 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
if test "$ac_cv_func_getpwent" = yes; then
AC_MSG_CHECKING(struct passwd)
AC_EGREP_HEADER(pw_change, pwd.h, AC_DEFINE(PW_CHANGE))
AC_EGREP_HEADER(pw_quota, pwd.h, AC_DEFINE(PW_QUOTA))
AC_EGREP_HEADER(pw_age, pwd.h, AC_DEFINE(PW_AGE))
AC_EGREP_HEADER(pw_class, pwd.h, AC_DEFINE(PW_CLASS))
AC_EGREP_HEADER(pw_comment, pwd.h, AC_DEFINE(PW_COMMENT))
AC_EGREP_HEADER(pw_expire, pwd.h, AC_DEFINE(PW_EXPIRE))
AC_MSG_RESULT(done)
fi
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])
case "$host_os" in
linux*)
AC_MSG_CHECKING(whether ELF binaries are produced)
AC_CACHE_VAL(rb_cv_linux_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_linux_elf=yes,
rb_cv_linux_elf=no,
[:])])
AC_MSG_RESULT($rb_cv_linux_elf)
if test "$rb_cv_linux_elf" = no; then
with_dln_a_out=yes
host_os=linux-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*) ;;
human*) ;;
*) 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*) LDSHARED='ld -G'
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 ;;
linux*) LDSHARED="gcc -shared"
rb_cv_dlopen=yes ;;
freebsd*) LDSHARED="ld -Bshareable"
rb_cv_dlopen=yes ;;
netbsd*) LDSHARED="ld -Bshareable"
rb_cv_dlopen=yes ;;
openbsd*) LDSHARED="ld -Bshareable"
rb_cv_dlopen=yes ;;
nextstep*) LDSHARED='cc -r'
LDFLAGS="-u libsys_s"
DLDFLAGS="$ARCH_FLAG"
rb_cv_dlopen=yes ;;
aix*) LDSHARED='../../miniruby ../aix_ld.rb $(TARGET)'
rb_cv_dlopen=yes ;;
human*) DLDFLAGS=''
LDSHARED=''
LDFLAGS='' ;;
*) 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
AC_MSG_CHECKING(whether matz's dln works)
cat confdefs.h > config.h
AC_CACHE_VAL(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)])
AC_MSG_RESULT($rb_cv_dln_a_out)
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=o
AC_DEFINE(DLEXT, ".o")
CCDLFLAGS=
else
case "$host_os" in
hpux*) DLEXT=sl
AC_DEFINE(DLEXT, ".sl");;
nextstep*) DLEXT=o
AC_DEFINE(DLEXT, ".o");;
*) 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';;
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_MSG_CHECKING(whether PD libc _dtos18 fail to convert big number)
AC_CACHE_VAL(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)])
AC_MSG_RESULT($rb_cv_missing__dtos18)
if test "$rb_cv_missing__dtos18" = yes; then
AC_DEFINE(MISSING__DTOS18)
fi
AC_MSG_CHECKING(whether PD libc fconvert fail to round)
AC_CACHE_VAL(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)])
AC_MSG_RESULT($rb_cv_missing_fconvert)
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"
binsuffix=.x
setup=Setup.x68
;;
*)
binsuffix=
setup=Setup
;;
esac
AC_SUBST(binsuffix)
AC_SUBST(setup)
if test "$prefix" = NONE; then
prefix=$ac_default_prefix
fi
if test "$fat_binary" = yes ; then
CFLAGS="$CFLAGS -pipe $ARCH_FLAG"
fi
AC_DEFINE_UNQUOTED(RUBY_LIB, "${prefix}/lib/ruby")
AC_SUBST(arch)dnl
if test "$fat_binary" = yes ; then
arch="fat-${host_os}"
AC_DEFINE_UNQUOTED(RUBY_THIN_ARCHLIB,
"${prefix}/lib/ruby/" __ARCHITECTURE__ "-${host_os}" )
AC_DEFINE_UNQUOTED(RUBY_ARCHLIB, "${prefix}/lib/ruby/${arch}")
AC_DEFINE_UNQUOTED(RUBY_PLATFORM, __ARCHITECTURE__ "-${host_os}" )
else
arch="${host_cpu}-${host_os}"
AC_DEFINE_UNQUOTED(RUBY_ARCHLIB, "${prefix}/lib/ruby/${arch}")
AC_DEFINE_UNQUOTED(RUBY_PLATFORM, "${arch}")
fi
echo "creating config.h"
cat confdefs.h > config.h
AC_OUTPUT(Makefile ext/extmk.rb)

50
defines.h Normal file
Просмотреть файл

@ -0,0 +1,50 @@
/************************************************
defines.h -
$Author$
$Date$
created at: Wed May 18 00:21:44 JST 1994
************************************************/
#ifndef DEFINES_H
#define DEFINES_H
#define RUBY
/* define EUC/SJIS for default kanji-code */
#if defined(MSDOS) || defined(__CYGWIN32__) || defined(__human68k__)
#undef EUC
#define SJIS
#else
#define EUC
#undef SJIS
#endif
#ifdef NeXT
#define DYNAMIC_ENDIAN /* determine endian at runtime */
#define S_IXUSR _S_IXUSR /* execute/search permission, owner */
#define S_IXGRP 0000010 /* execute/search permission, group */
#define S_IXOTH 0000001 /* execute/search permission, other */
#endif /* NeXT */
#ifdef NT
#include "missing/nt.h"
#endif
#ifdef sparc
#define FLUSH_REGISTER_WINDOWS asm("ta 3")
#else
#define FLUSH_REGISTER_WINDOWS /* empty */
#endif
#ifdef __human68k__
#undef HAVE_RANDOM
#undef HAVE_SETITIMER
#endif
#ifndef RUBY_PLATFORM
#define RUBY_PLATFORM "unknown-unknown"
#endif
#endif

427
dir.c Normal file
Просмотреть файл

@ -0,0 +1,427 @@
/************************************************
dir.c -
$Author$
$Date$
created at: Wed Jan 5 09:51:01 JST 1994
Copyright (C) 1993-1996 Yukihiro Matsumoto
************************************************/
#include "ruby.h"
#include <sys/types.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_SYS_PARAM_H
# include <sys/param.h>
#else
# define MAXPATHLEN 1024
#endif
#if HAVE_DIRENT_H
# include <dirent.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
# ifdef NT
# include "missing/dir.h"
# endif
#endif
#include <errno.h>
#ifndef NT
char *getenv();
#endif
static VALUE cDir;
static void
free_dir(dir)
DIR *dir;
{
if (dir) closedir(dir);
}
static VALUE
dir_s_open(dir_class, dirname)
VALUE dir_class;
struct RString *dirname;
{
VALUE obj;
DIR *dirp;
Check_SafeStr(dirname);
dirp = opendir(dirname->ptr);
if (dirp == NULL) {
if (errno == EMFILE || errno == ENFILE) {
gc();
dirp = opendir(dirname->ptr);
}
if (dirp == NULL) {
rb_sys_fail(dirname->ptr);
}
}
obj = Data_Wrap_Struct(dir_class, 0, free_dir, dirp);
return obj;
}
static void
dir_closed()
{
Fail("closed directory");
}
#define GetDIR(obj, dirp) {\
Data_Get_Struct(obj, DIR, dirp);\
if (dirp == NULL) dir_closed();\
}
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 = str_taint(str_new(dp->d_name, NAMLEN(dp)));
rb_yield(file);
}
return dir;
}
static VALUE
dir_tell(dir)
VALUE dir;
{
DIR *dirp;
int pos;
#if !defined(__CYGWIN32__)
GetDIR(dir, dirp);
pos = telldir(dirp);
return int2inum(pos);
#else
rb_notimplement();
#endif
}
static VALUE
dir_seek(dir, pos)
VALUE dir, pos;
{
DIR *dirp;
#if !defined(__CYGWIN32__)
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);
rb_scan_args(argc, argv, "01", &path);
if (path) {
Check_SafeStr(path);
dist = RSTRING(path)->ptr;
}
else {
dist = getenv("HOME");
if (!dist) {
dist = getenv("LOGDIR");
}
}
if (chdir(dist) < 0)
rb_sys_fail(0);
return INT2FIX(0);
}
static VALUE
dir_s_getwd(dir)
VALUE dir;
{
extern char *getwd();
char path[MAXPATHLEN];
#ifdef HAVE_GETCWD
if (getcwd(path, sizeof(path)) == 0) rb_sys_fail(path);
#else
if (getwd(path) == 0) rb_sys_fail(path);
#endif
return str_taint(str_new2(path));
}
static VALUE
dir_s_chroot(dir, path)
VALUE dir, path;
{
#if !defined(DJGPP) && !defined(__CYGWIN32__) && !defined(NT) && !defined(__human68k__)
rb_secure(2);
Check_SafeStr(path);
if (chroot(RSTRING(path)->ptr) == -1)
rb_sys_fail(0);
return INT2FIX(0);
#else
rb_notimplement();
#endif
}
static VALUE
dir_s_mkdir(argc, argv, obj)
int argc;
VALUE *argv;
VALUE obj;
{
VALUE path, vmode;
int mode;
rb_secure(2);
if (rb_scan_args(argc, argv, "11", &path, &vmode) == 2) {
mode = NUM2INT(vmode);
}
else {
mode = 0777;
}
Check_SafeStr(path);
#ifndef NT
if (mkdir(RSTRING(path)->ptr, mode) == -1)
rb_sys_fail(RSTRING(path)->ptr);
#else
if (mkdir(RSTRING(path)->ptr) == -1)
rb_sys_fail(RSTRING(path)->ptr);
#endif
return INT2FIX(0);
}
static VALUE
dir_s_rmdir(obj, dir)
VALUE obj;
struct RString *dir;
{
rb_secure(2);
Check_SafeStr(dir);
if (rmdir(dir->ptr) < 0)
rb_sys_fail(dir->ptr);
return TRUE;
}
#define isdelim(c) ((c)==' '||(c)=='\t'||(c)=='\n'||(c)=='\0')
char **glob_filename();
extern char *glob_error_return;
static void
push_globs(ary, s)
VALUE ary;
char *s;
{
char **fnames, **ff;
fnames = glob_filename(s);
if (fnames == (char**)-1) rb_sys_fail(s);
ff = fnames;
while (*ff) {
ary_push(ary, str_taint(str_new2(*ff)));
free(*ff);
ff++;
}
if (fnames != &glob_error_return) {
free(fnames);
}
}
static void
push_braces(ary, s)
VALUE ary;
char *s;
{
char buf[MAXPATHLEN];
char *p, *t, *b;
char *lbrace, *rbrace;
p = s;
lbrace = rbrace = 0;
while (*p) {
if (*p == '{') {
lbrace = p;
break;
}
p++;
}
while (*p) {
if (*p == '}' && lbrace) {
rbrace = p;
break;
}
p++;
}
if (lbrace) {
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);
}
}
else {
push_globs(ary, s);
}
}
static VALUE
dir_s_glob(dir, str)
VALUE dir;
struct RString *str;
{
char *p, *pend;
char buf[MAXPATHLEN];
char *t, *t0;
int nest;
VALUE ary;
Check_SafeStr(str);
ary = ary_new();
p = str->ptr;
pend = p + str->len;
while (p < pend) {
t = buf;
while (p < pend && isdelim(*p)) p++;
while (p < pend && !isdelim(*p)) {
*t++ = *p++;
}
*t = '\0';
t0 = buf;
nest = 0;
while (t0 < t) {
if (*t0 == '{') nest+=2;
if (*t0 == '}') nest+=3;
t0++;
}
if (nest == 0) {
push_globs(ary, buf);
}
else if (nest % 5 == 0) {
push_braces(ary, buf);
}
/* else unmatched braces */
}
return ary;
}
static VALUE
dir_foreach(io, dirname)
VALUE io;
struct RString *dirname;
{
VALUE dir;
dir = dir_s_open(cDir, dirname);
return rb_ensure(dir_each, dir, dir_close, dir);
}
void
Init_Dir()
{
extern VALUE mEnumerable;
cDir = rb_define_class("Dir", cObject);
rb_include_module(cDir, mEnumerable);
rb_define_singleton_method(cDir, "open", dir_s_open, 1);
rb_define_singleton_method(cDir, "foreach", dir_foreach, 1);
rb_define_method(cDir,"each", dir_each, 0);
rb_define_method(cDir,"rewind", dir_rewind, 0);
rb_define_method(cDir,"tell", dir_tell, 0);
rb_define_method(cDir,"seek", dir_seek, 1);
rb_define_method(cDir,"close", dir_close, 0);
rb_define_singleton_method(cDir,"chdir", dir_s_chdir, -1);
rb_define_singleton_method(cDir,"getwd", dir_s_getwd, 0);
rb_define_singleton_method(cDir,"pwd", dir_s_getwd, 0);
rb_define_singleton_method(cDir,"chroot", dir_s_chroot, 1);
rb_define_singleton_method(cDir,"mkdir", dir_s_mkdir, -1);
rb_define_singleton_method(cDir,"rmdir", dir_s_rmdir, 1);
rb_define_singleton_method(cDir,"delete", dir_s_rmdir, 1);
rb_define_singleton_method(cDir,"unlink", dir_s_rmdir, 1);
rb_define_singleton_method(cDir,"glob", dir_s_glob, 1);
rb_define_singleton_method(cDir,"[]", dir_s_glob, 1);
}

1445
dln.c Normal file

Разница между файлами не показана из-за своего большого размера Загрузить разницу

22
dln.h Normal file
Просмотреть файл

@ -0,0 +1,22 @@
/************************************************
dln.h -
$Author$
$Revision$
$Date$
created at: Wed Jan 19 16:53:09 JST 1994
************************************************/
#ifndef DLN_H
#define DLN_H
char *dln_find_exe();
char *dln_find_file();
#ifdef USE_DLN_A_OUT
extern char *dln_argv0;
#endif
void dln_load();
#endif

4
dmyext.c Normal file
Просмотреть файл

@ -0,0 +1,4 @@
void
Init_ext()
{
}

369
enum.c Normal file
Просмотреть файл

@ -0,0 +1,369 @@
/************************************************
enum.c -
$Author$
$Date$
created at: Fri Oct 1 15:15:19 JST 1993
Copyright (C) 1993-1996 Yukihiro Matsumoto
************************************************/
#include "ruby.h"
VALUE mEnumerable;
static ID id_each, id_eqq, id_cmp;
void
rb_each(obj)
VALUE obj;
{
rb_funcall(obj, id_each, 0, 0);
}
static void
grep_i(i, arg)
VALUE i, *arg;
{
if (RTEST(rb_funcall(arg[0], id_eqq, 1, i))) {
ary_push(arg[1], i);
}
}
static void
grep_iter_i(i, pat)
VALUE i, pat;
{
if (RTEST(rb_funcall(pat, id_eqq, 1, i))) {
rb_yield(i);
}
}
static VALUE
enum_grep(obj, pat)
VALUE obj, pat;
{
if (iterator_p()) {
rb_iterate(rb_each, obj, grep_iter_i, pat);
return obj;
}
else {
VALUE tmp, arg[2];
arg[0] = pat; arg[1] = tmp = ary_new();
rb_iterate(rb_each, obj, grep_i, arg);
return tmp;
}
}
struct find_arg {
int found;
VALUE val;
};
static void
find_i(i, arg)
VALUE i;
struct find_arg *arg;
{
if (RTEST(rb_yield(i))) {
arg->found = TRUE;
arg->val = i;
rb_break();
}
}
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 = FALSE;
rb_iterate(rb_each, obj, find_i, &arg);
if (arg.found) {
return arg.val;
}
if (!NIL_P(if_none)) {
rb_eval_cmd(if_none, Qnil);
}
return Qnil;
}
static void
find_all_i(i, tmp)
VALUE i, tmp;
{
if (RTEST(rb_yield(i))) {
ary_push(tmp, i);
}
}
static VALUE
enum_find_all(obj)
VALUE obj;
{
VALUE tmp;
tmp = ary_new();
rb_iterate(rb_each, obj, find_all_i, tmp);
return tmp;
}
static void
collect_i(i, tmp)
VALUE i, tmp;
{
VALUE retval;
retval = rb_yield(i);
if (RTEST(retval)) {
ary_push(tmp, retval);
}
}
static VALUE
enum_collect(obj)
VALUE obj;
{
VALUE tmp;
tmp = ary_new();
rb_iterate(rb_each, obj, collect_i, tmp);
return tmp;
}
static void
reverse_i(i, tmp)
VALUE i, tmp;
{
ary_unshift(tmp, i);
}
static VALUE
enum_reverse(obj)
VALUE obj;
{
VALUE tmp;
tmp = ary_new();
rb_iterate(rb_each, obj, reverse_i, tmp);
return tmp;
}
static void
enum_all(i, ary)
VALUE i, ary;
{
ary_push(ary, i);
}
static VALUE
enum_to_a(obj)
VALUE obj;
{
VALUE ary;
ary = ary_new();
rb_iterate(rb_each, obj, enum_all, ary);
return ary;
}
static VALUE
enum_sort(obj)
VALUE obj;
{
return ary_sort(enum_to_a(obj));
}
static void
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 (FIX2INT(cmp) < 0)
*min = i;
}
}
static void
min_ii(i, min)
VALUE i, *min;
{
VALUE cmp;
if (NIL_P(*min))
*min = i;
else {
cmp = rb_yield(assoc_new(i, *min));
if (FIX2INT(cmp) < 0)
*min = i;
}
}
static VALUE
enum_min(obj)
VALUE obj;
{
VALUE min = Qnil;
rb_iterate(rb_each, obj, iterator_p()?min_ii:min_i, &min);
return min;
}
static void
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 (FIX2INT(cmp) > 0)
*max = i;
}
}
static void
max_ii(i, max)
VALUE i, *max;
{
VALUE cmp;
if (NIL_P(*max))
*max = i;
else {
cmp = rb_yield(assoc_new(i, *max));
if (FIX2INT(cmp) > 0)
*max = i;
}
}
static VALUE
enum_max(obj)
VALUE obj;
{
VALUE max = Qnil;
rb_iterate(rb_each, obj, iterator_p()?max_ii:max_i, &max);
return max;
}
struct i_v_pair {
int i;
VALUE v;
int found;
};
static void
index_i(item, iv)
VALUE item;
struct i_v_pair *iv;
{
if (rb_equal(item, iv->v)) {
iv->found = 1;
rb_break();
}
else {
iv->i++;
}
}
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, &iv);
if (iv.found) return INT2FIX(iv.i);
return Qnil; /* not found */
}
static void
member_i(item, iv)
VALUE item;
struct i_v_pair *iv;
{
if (rb_equal(item, iv->v)) {
iv->i = 1;
rb_break();
}
}
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, &iv);
if (iv.i) return TRUE;
return FALSE;
}
static void
length_i(i, length)
VALUE i;
int *length;
{
(*length)++;
}
VALUE
enum_length(obj)
VALUE obj;
{
int length = 0;
rb_iterate(rb_each, obj, length_i, &length);
return INT2FIX(length);
}
void
Init_Enumerable()
{
mEnumerable = rb_define_module("Enumerable");
rb_define_method(mEnumerable,"to_a", enum_to_a, 0);
rb_define_method(mEnumerable,"sort", enum_sort, 0);
rb_define_method(mEnumerable,"grep", enum_grep, 1);
rb_define_method(mEnumerable,"find", enum_find, -1);
rb_define_method(mEnumerable,"find_all", enum_find_all, 0);
rb_define_method(mEnumerable,"collect", enum_collect, 0);
rb_define_method(mEnumerable,"reverse", enum_reverse, 0);
rb_define_method(mEnumerable,"min", enum_min, 0);
rb_define_method(mEnumerable,"max", enum_max, 0);
rb_define_method(mEnumerable,"index", enum_index, 1);
rb_define_method(mEnumerable,"member?", enum_member, 1);
rb_define_method(mEnumerable,"include?", enum_member, 1);
rb_define_method(mEnumerable,"length", enum_length, 0);
rb_define_method(mEnumerable,"size", enum_length, 0);
id_eqq = rb_intern("===");
id_each = rb_intern("each");
id_cmp = rb_intern("<=>");
}

49
env.h Normal file
Просмотреть файл

@ -0,0 +1,49 @@
/************************************************
env.h -
$Author$
$Revision$
$Date$
created at: Mon Jul 11 11:53:03 JST 1994
************************************************/
#ifndef ENV_H
#define ENV_H
extern struct FRAME {
int argc;
VALUE *argv;
ID last_func;
struct RClass *last_class;
VALUE cbase;
struct FRAME *prev;
char *file;
int line;
int iter;
} *the_frame;
extern struct SCOPE {
struct RBasic super;
ID *local_tbl;
VALUE *local_vars;
int flag;
} *the_scope;
#define SCOPE_ALLOCA 0
#define SCOPE_MALLOC 1
#define SCOPE_NOSTACK 2
extern int rb_in_eval;
extern struct RClass *the_class;
struct RVarmap {
struct RBasic super;
ID id;
VALUE val;
struct RVarmap *next;
};
extern struct RVarmap *the_dyna_vars;
#endif /* ENV_H */

832
error.c Normal file
Просмотреть файл

@ -0,0 +1,832 @@
/************************************************
error.c -
$Author$
$Date$
created at: Mon Aug 9 16:11:34 JST 1993
Copyright (C) 1993-1996 Yukihiro Matsumoto
************************************************/
#include "ruby.h"
#include "env.h"
#include <stdio.h>
#include <varargs.h>
extern char *sourcefile;
extern int sourceline;
int nerrs;
static void
err_sprintf(buf, fmt, args)
char *buf, *fmt;
va_list args;
{
if (!sourcefile) {
vsprintf(buf, fmt, args);
}
else {
sprintf(buf, "%s:%d: ", sourcefile, sourceline);
vsprintf((char*)buf+strlen(buf), fmt, args);
}
}
static void
err_append(s)
char *s;
{
extern VALUE errinfo;
if (rb_in_eval) {
if (NIL_P(errinfo)) {
errinfo = str_new2(s);
}
else {
str_cat(errinfo, "\n", 1);
str_cat(errinfo, s, strlen(s));
}
}
else {
fputs(s, stderr);
fputs("\n", stderr);
fflush(stderr);
}
}
static void
err_print(fmt, args)
char *fmt;
va_list args;
{
char buf[BUFSIZ];
err_sprintf(buf, fmt, args);
err_append(buf);
}
void
Error(fmt, va_alist)
char *fmt;
va_dcl
{
va_list args;
va_start(args);
err_print(fmt, args);
va_end(args);
nerrs++;
}
void
Error_Append(fmt, va_alist)
char *fmt;
va_dcl
{
va_list args;
char buf[BUFSIZ];
va_start(args);
vsprintf(buf, fmt, args);
va_end(args);
err_append(buf);
}
void
Warning(fmt, va_alist)
char *fmt;
va_dcl
{
char buf[BUFSIZ];
va_list args;
if (!verbose) return;
sprintf(buf, "warning: %s", fmt);
va_start(args);
err_print(buf, args);
va_end(args);
}
void
Bug(fmt, va_alist)
char *fmt;
va_dcl
{
char buf[BUFSIZ];
va_list args;
sprintf(buf, "[BUG] %s", fmt);
rb_in_eval = 0;
va_start(args);
err_print(buf, args);
va_end(args);
abort();
}
static struct types {
int type;
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,
};
extern void TypeError();
void
rb_check_type(x, t)
VALUE x;
int t;
{
struct types *type = builtin_types;
if (TYPE(x)!=(t)) {
while (type->type >= 0) {
if (type->type == t) {
TypeError("wrong argument type %s (expected %s)",
rb_class2name(CLASS_OF(x)), type->name);
}
type++;
}
Bug("unknown type 0x%x", t);
}
}
/* exception classes */
#include "errno.h"
extern VALUE cString;
VALUE eGlobalExit, eException;
VALUE eSystemExit, eInterrupt, eFatal;
VALUE eRuntimeError;
VALUE eSyntaxError;
VALUE eTypeError;
VALUE eArgError;
VALUE eNameError;
VALUE eIndexError;
VALUE eNotImpError;
VALUE eLoadError;
VALUE eSecurityError;
VALUE eSystemCallError;
VALUE mErrno;
VALUE
exc_new(etype, ptr, len)
VALUE etype;
char *ptr;
UINT len;
{
NEWOBJ(exc, struct RString);
OBJSETUP(exc, etype, T_STRING);
exc->len = len;
exc->orig = 0;
exc->ptr = ALLOC_N(char,len+1);
if (ptr) {
memcpy(exc->ptr, ptr, len);
}
exc->ptr[len] = '\0';
return (VALUE)exc;
}
VALUE
exc_new2(etype, s)
VALUE etype;
char *s;
{
return exc_new(etype, s, strlen(s));
}
VALUE
exc_new3(etype, str)
VALUE etype;
struct RString *str;
{
Check_Type(str, T_STRING);
return exc_new(etype, str->ptr, str->len);
}
static VALUE
exc_s_new(argc, argv, etype)
int argc;
VALUE *argv;
VALUE etype;
{
VALUE arg;
if (rb_scan_args(argc, argv, "01", &arg) == 0) {
return exc_new(etype, 0, 0);
}
Check_Type(arg, T_STRING);
return exc_new3(etype, arg);
}
static VALUE
exc_inspect(exc)
VALUE exc;
{
struct RString *classpath = RSTRING(rb_class_path(CLASS_OF(exc)));
VALUE str = str_new(classpath->ptr, classpath->len);
str_cat(str, ":", 1);
if (RSTRING(exc)->len == 0) {
str_cat(str, "\"\"", 2);
}
str_cat(str, RSTRING(exc)->ptr, RSTRING(exc)->len);
return str;
}
static VALUE
exception(argc, argv)
int argc;
VALUE *argv;
{
void ArgError();
VALUE v = Qnil;
int i;
ID id;
if (argc == 0) {
ArgError("wrong # of arguments");
}
for (i=0; i<argc; i++) { /* argument check */
id = rb_to_id(argv[i]);
if (!rb_id2name(id)) {
ArgError("argument needs to be symbol or string");
}
if (!rb_is_const_id(id)) {
ArgError("identifier %s needs to be constant", rb_id2name(id));
}
}
for (i=0; i<argc; i++) {
v = rb_define_class(rb_id2name(rb_to_id(argv[i])), eException);
}
return v;
}
static VALUE *syserr_list;
#ifndef NT
extern int sys_nerr;
#endif
static void
set_syserr(i, name)
int i;
char *name;
{
if (i <= sys_nerr) {
syserr_list[i] = rb_define_class_under(mErrno, name, eSystemCallError);
rb_global_variable(&syserr_list[i]);
}
}
static void init_syserr();
void
Init_Exception()
{
eGlobalExit = rb_define_class("GlobalExit", cString);
rb_define_singleton_method(eGlobalExit, "new", exc_s_new, -1);
rb_define_method(eGlobalExit, "inspect", exc_inspect, 0);
eSystemExit = rb_define_class("SystemExit", eGlobalExit);
eFatal = rb_define_class("fatal", eGlobalExit);
eInterrupt = rb_define_class("Interrupt", eGlobalExit);
eException = rb_define_class("Exception", eGlobalExit);
eSyntaxError = rb_define_class("SyntaxError", eException);
eTypeError = rb_define_class("TypeError", eException);
eArgError = rb_define_class("ArgumentError", eException);
eNameError = rb_define_class("NameError", eException);
eIndexError = rb_define_class("IndexError", eException);
eNotImpError = rb_define_class("NotImplementError", eException);
eLoadError = rb_define_class("LoadError", eException);
eRuntimeError = rb_define_class("RuntimeError", eException);
eSecurityError = rb_define_class("SecurityError", eException);
init_syserr();
rb_define_global_function("Exception", exception, -1);
}
#define RAISE_ERROR(class) {\
va_list args;\
char buf[BUFSIZ];\
\
va_start(args);\
vsprintf(buf, fmt, args);\
va_end(args);\
\
rb_raise(exc_new2(class, buf));\
}
void
Raise(exc, fmt, va_alist)
VALUE exc;
char *fmt;
va_dcl
{
RAISE_ERROR(exc);
}
void
TypeError(fmt, va_alist)
char *fmt;
va_dcl
{
RAISE_ERROR(eTypeError);
}
void
ArgError(fmt, va_alist)
char *fmt;
va_dcl
{
RAISE_ERROR(eArgError);
}
void
NameError(fmt, va_alist)
char *fmt;
va_dcl
{
RAISE_ERROR(eNameError);
}
void
IndexError(fmt, va_alist)
char *fmt;
va_dcl
{
RAISE_ERROR(eIndexError);
}
void
Fail(fmt, va_alist)
char *fmt;
va_dcl
{
RAISE_ERROR(eRuntimeError);
}
void
rb_notimplement()
{
Raise(eNotImpError,
"The %s() function is unimplemented on this machine",
rb_id2name(the_frame->last_func));
}
void
LoadError(fmt, va_alist)
char *fmt;
va_dcl
{
RAISE_ERROR(eLoadError);
}
void
Fatal(fmt, va_alist)
char *fmt;
va_dcl
{
va_list args;
char buf[BUFSIZ];
va_start(args);
vsprintf(buf, fmt, args);
va_end(args);
rb_in_eval = 0;
rb_fatal(exc_new2(eFatal, buf));
}
void
rb_sys_fail(mesg)
char *mesg;
{
#ifndef NT
char *strerror();
#endif
char buf[BUFSIZ];
extern int errno;
int n = errno;
if (RTEST(mesg))
sprintf(buf, "%s - %s", strerror(errno), mesg);
else
sprintf(buf, "%s", strerror(errno));
errno = 0;
if (n > sys_nerr || !syserr_list[n]) {
char name[6];
sprintf(name, "E%03d", n);
set_syserr(n, name);
}
rb_raise(exc_new2(syserr_list[n], buf));
}
static void
init_syserr()
{
eSystemCallError = rb_define_class("SystemCallError", eException);
mErrno = rb_define_module("Errno");
syserr_list = ALLOC_N(VALUE, sys_nerr+1);
MEMZERO(syserr_list, VALUE, sys_nerr+1);
#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
}

5402
eval.c Normal file

Разница между файлами не показана из-за своего большого размера Загрузить разницу

12
ext/Setup Normal file
Просмотреть файл

@ -0,0 +1,12 @@
#option nodynamic
#GD
#curses
#dbm
#etc
#fcntl
#kconv
#marshal
#md5
#socket
#tkutil

12
ext/Setup.dj Normal file
Просмотреть файл

@ -0,0 +1,12 @@
option nodynamic
#GD
#curses
dbm
#etc
fcntl
kconv
marshal
md5
#socket
#tkutil

12
ext/Setup.nt Normal file
Просмотреть файл

@ -0,0 +1,12 @@
option nodynamic
#GD
#curses
#dbm
#etc
fcntl
kconv
#marshal
md5
socket
#tkutil

12
ext/Setup.x68 Normal file
Просмотреть файл

@ -0,0 +1,12 @@
option nodynamic
#GD
#curses
dbm
#etc
fcntl
kconv
marshal
md5
#socket
#tkutil

73
ext/aix_ld.rb Normal file
Просмотреть файл

@ -0,0 +1,73 @@
#! /usr/local/bin/ruby
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
target = ARGV.shift
unless target =~ /\.so/
STDERR.printf "wrong suffix specified\n"
exit 1
end
base = File.basename(target, ".so")
entry="Init_#{base}"
ldargs = "-e#{entry} -bI:../ruby.imp -bM:SRE -T512 -H512 -lc"
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", "T"
line[2]
else
next
end
}.sort!
uniq(data)
exp = open(out, "w")
for line in data
exp.printf "%s\n", line
end
exp.close
nm.close
end
if older("../ruby.imp", "../../miniruby")
# nm = open("|/usr/ccs/bin/nm -Bex ../../*.o")
# nm = open("|/usr/ccs/bin/nm -Bex ../../*.o")
nm = open("|nm ../../*.o")
extract(nm, "../ruby.imp")
end
objs = Dir["*.o"].join(" ")
#nm = open("|/usr/ccs/bin/nm -Bex #{objs}")
nm = open("|nm #{objs}")
extract(nm, "#{base}.exp")
#system format("/usr/ccs/bin/ld %s %s ",ldargs,ARGV.join(' '))
#system "/bin/rm -f #{base}.exp"
#system "chmod o-rwx ${base}.so"
p format("/usr/ccs/bin/ld %s %s ",ldargs,ARGV.join(' '))
p "/bin/rm -f #{base}.exp"
p "chmod o-rwx ${base}.so"

6
ext/curses/MANIFEST Normal file
Просмотреть файл

@ -0,0 +1,6 @@
MANIFEST
curses.c
extconf.rb
hello.rb
rain.rb
view.rb

798
ext/curses/curses.c Normal file
Просмотреть файл

@ -0,0 +1,798 @@
/*
* ext/curses/curses.c
*
* by MAEDA Shugo (ender@pic-internet.or.jp)
* modified by Yukihiro Matsumoto (matz@ruby.club.or.jp)
*/
#ifdef HAVE_NCURSES_H
# include <ncurses.h>
#else
# ifdef HAVE_NCURSES_CURSES_H
# include <ncurses/curses.h>
# else
# include <curses.h>
# if defined(__NetBSD__) && !defined(_maxx)
# define _maxx maxx
# endif
# if defined(__NetBSD__) && !defined(_maxy)
# define _maxy maxy
# endif
# endif
#endif
#include "ruby.h"
static VALUE mCurses;
static VALUE cWindow;
VALUE rb_stdscr;
struct windata {
WINDOW *window;
};
#define NUM2CHAR(x) (char)NUM2INT(x)
#define CHAR2FIX(x) INT2FIX((int)x)
static void
no_window()
{
Fail("already closed window");
}
#define GetWINDOW(obj, winp) {\
Data_Get_Struct(obj, struct windata, winp);\
if (winp->window == 0) no_window();\
}
static void
curses_err()
{
Fail("curses error");
}
#define CHECK(c) if ((c)==ERR) {curses_err();}
static void
free_window(winp)
struct windata *winp;
{
if (winp->window && winp->window != stdscr) delwin(winp->window);
winp->window = 0;
}
static VALUE
prep_window(class, window)
VALUE class;
WINDOW *window;
{
VALUE obj;
struct windata *winp;
if (window == NULL) {
Fail("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) {
Fail("cannot initialize curses");
}
clear();
rb_stdscr = prep_window(cWindow, stdscr);
return Qnil;
}
/* def stdscr */
static VALUE
curses_stdscr()
{
if (!rb_stdscr) curses_init_screen();
return rb_stdscr;
}
/* def close_screen */
static VALUE
curses_close_screen()
{
CHECK(endwin());
return Qnil;
}
/* def closed? */
static VALUE
curses_closed()
{
#ifdef HAVE_ENDWIN
if (isendwin()) {
return TRUE;
}
return FALSE;
#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;
{
CHECK(refresh());
return Qnil;
}
/* def refresh */
static VALUE
curses_doupdate(obj)
VALUE obj;
{
CHECK(doupdate());
return Qnil;
}
/* def echo */
static VALUE
curses_echo(obj)
VALUE obj;
{
CHECK(echo());
return Qnil;
}
/* def noecho */
static VALUE
curses_noecho(obj)
VALUE obj;
{
CHECK(noecho());
return Qnil;
}
/* def raw */
static VALUE
curses_raw(obj)
VALUE obj;
{
CHECK(raw());
return Qnil;
}
/* def noraw */
static VALUE
curses_noraw(obj)
VALUE obj;
{
CHECK(noraw());
return Qnil;
}
/* def cbreak */
static VALUE
curses_cbreak(obj)
VALUE obj;
{
CHECK(cbreak());
return Qnil;
}
/* def nocbreak */
static VALUE
curses_nocbreak(obj)
VALUE obj;
{
CHECK(nocbreak());
return Qnil;
}
/* def nl */
static VALUE
curses_nl(obj)
VALUE obj;
{
CHECK(nl());
return Qnil;
}
/* def nonl */
static VALUE
curses_nonl(obj)
VALUE obj;
{
CHECK(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;
{
flash();
return Qnil;
}
/* def ungetch */
static VALUE
curses_ungetch(obj, ch)
VALUE obj;
VALUE ch;
{
#ifdef HAVE_UNGETCH
CHECK(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;
{
CHECK(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 CHAR2FIX(inch());
}
/* def addch(ch) */
static VALUE
curses_addch(obj, ch)
VALUE obj;
VALUE ch;
{
CHECK(addch(NUM2CHAR(ch)));
return Qnil;
}
/* def insch(ch) */
static VALUE
curses_insch(obj, ch)
VALUE obj;
VALUE ch;
{
CHECK(insch(NUM2CHAR(ch)));
return Qnil;
}
/* def addstr(str) */
static VALUE
curses_addstr(obj, str)
VALUE obj;
VALUE str;
{
addstr(RSTRING(str)->ptr);
return Qnil;
}
/* def getch */
static VALUE
curses_getch(obj)
VALUE obj;
{
return CHAR2FIX(getch());
}
/* def getstr */
static VALUE
curses_getstr(obj)
VALUE obj;
{
char rtn[1024]; /* This should be big enough.. I hope */
CHECK(getstr(rtn));
return str_taint(str_new2(rtn));
}
/* def delch */
static VALUE
curses_delch(obj)
VALUE obj;
{
CHECK(delch());
return Qnil;
}
/* def delelteln */
static VALUE
curses_deleteln(obj)
VALUE obj;
{
CHECK(deleteln());
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;
{
WINDOW *window;
window = newwin(NUM2INT(lines), NUM2INT(cols), NUM2INT(top), NUM2INT(left));
wclear(window);
return prep_window(class, window);
}
/* 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;
GetWINDOW(obj, winp);
window = subwin(winp->window, NUM2INT(lines), NUM2INT(cols),
NUM2INT(top), NUM2INT(left));
return prep_window(cWindow, window);
}
/* def close */
static VALUE
window_close(obj)
VALUE obj;
{
struct windata *winp;
GetWINDOW(obj, winp);
free_window(winp);
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);
CHECK(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, NUM2CHAR(vert), NUM2CHAR(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);
CHECK(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);
CHECK(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 CHAR2FIX(winch(winp->window));
}
/* def addch(ch) */
static VALUE
window_addch(obj, ch)
VALUE obj;
VALUE ch;
{
struct windata *winp;
GetWINDOW(obj, winp);
CHECK(waddch(winp->window, NUM2CHAR(ch)));
return Qnil;
}
/* def insch(ch) */
static VALUE
window_insch(obj, ch)
VALUE obj;
VALUE ch;
{
struct windata *winp;
GetWINDOW(obj, winp);
CHECK(winsch(winp->window, NUM2CHAR(ch)));
return Qnil;
}
/* def addstr(str) */
static VALUE
window_addstr(obj, str)
VALUE obj;
VALUE str;
{
struct windata *winp;
GetWINDOW(obj, winp);
CHECK(waddstr(winp->window, RSTRING(str)->ptr));
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;
GetWINDOW(obj, winp);
return CHAR2FIX(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);
CHECK(wgetstr(winp->window, rtn));
return str_taint(str_new2(rtn));
}
/* def delch */
static VALUE
window_delch(obj)
VALUE obj;
{
struct windata *winp;
GetWINDOW(obj, winp);
CHECK(wdelch(winp->window));
return Qnil;
}
/* def delelteln */
static VALUE
window_deleteln(obj)
VALUE obj;
{
struct windata *winp;
GetWINDOW(obj, winp);
CHECK(wdeleteln(winp->window));
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", 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);
}

21
ext/curses/extconf.rb Normal file
Просмотреть файл

@ -0,0 +1,21 @@
$CFLAGS="-I/usr/include/ncurses -I/usr/local/include/ncurses"
$LDFLAGS="-L/usr/local/lib"
make=FALSE
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
else
$CFLAGS=nil
have_library("termcap", "tgetent")
if have_library("curses", "initscr")
make=TRUE
end
end
if make then
for f in ["isendwin", "ungetch", "beep"]
have_func(f)
end
create_makefile("curses")
end

28
ext/curses/hello.rb Normal file
Просмотреть файл

@ -0,0 +1,28 @@
#!/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.getch
win.close
end
init_screen
begin
crmode
# show_message("Hit any key")
setpos (lines - 5) / 2, (cols - 10) / 2
addstr("Hit any key")
getch
show_message("Hello, World!")
refresh
ensure
close_screen
end

76
ext/curses/rain.rb Normal file
Просмотреть файл

@ -0,0 +1,76 @@
#!/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

90
ext/curses/view.rb Normal file
Просмотреть файл

@ -0,0 +1,90 @@
#!/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
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

4
ext/dbm/MANIFEST Normal file
Просмотреть файл

@ -0,0 +1,4 @@
MANIFEST
dbm.c
depend
extconf.rb

515
ext/dbm/dbm.c Normal file
Просмотреть файл

@ -0,0 +1,515 @@
/************************************************
dbm.c -
$Author$
$Date$
created at: Mon Jan 24 15:59:52 JST 1994
Copyright (C) 1995 Yukihiro Matsumoto
************************************************/
#include "ruby.h"
#include <ndbm.h>
#include <fcntl.h>
#include <errno.h>
VALUE cDBM;
extern VALUE mEnumerable;
struct dbmdata {
int di_size;
DBM *di_dbm;
};
static void
closed_dbm()
{
Fail("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);
}
static VALUE
fdbm_s_open(argc, argv, class)
int argc;
VALUE *argv;
VALUE class;
{
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)
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(class,struct dbmdata,0,free_dbm,dbmp);
dbmp->di_dbm = dbm;
dbmp->di_size = -1;
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 str_taint(str_new(value.dptr, value.dsize));
}
static VALUE
fdbm_indexes(obj, args)
VALUE obj;
struct RArray *args;
{
VALUE *p, *pend;
VALUE new;
int i = 0;
args = (struct RArray*)rb_to_a(args);
new = ary_new2(args->len);
p = args->ptr; pend = p + args->len;
while (p < pend) {
ary_push(new, fdbm_fetch(obj, *p++));
}
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 (iterator_p()) rb_yield(keystr);
return Qnil;
}
if (dbm_delete(dbm, key)) {
dbmp->di_size = -1;
Fail("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 = str_taint(str_new(key.dptr, key.dsize));
valstr = str_taint(str_new(val.dptr, val.dsize));
return 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 = str_taint(str_new(key.dptr, key.dsize));
valstr = str_taint(str_new(val.dptr, val.dsize));
if (RTEST(rb_yield(assoc_new(keystr, valstr)))) {
if (dbm_delete(dbm, key)) {
Fail("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)) {
Fail("dbm_delete failed");
}
}
return obj;
}
static VALUE
fdbm_store(obj, keystr, valstr)
VALUE obj, keystr, valstr;
{
datum key, val;
struct dbmdata *dbmp;
DBM *dbm;
if (valstr == Qnil) {
fdbm_delete(obj, keystr);
return Qnil;
}
rb_secure(4);
keystr = obj_as_string(keystr);
key.dptr = RSTRING(keystr)->ptr;
key.dsize = RSTRING(keystr)->len;
if (NIL_P(valstr)) return fdbm_delete(obj, keystr);
valstr = 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)) {
dbm_clearerr(dbm);
if (errno == EPERM) rb_sys_fail(Qnil);
Fail("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 TRUE;
return FALSE;
}
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(str_taint(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(str_taint(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 = str_taint(str_new(key.dptr, key.dsize));
valstr = str_taint(str_new(val.dptr, val.dsize));
rb_yield(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 = ary_new();
for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
ary_push(ary, str_taint(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 = ary_new();
for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
val = dbm_fetch(dbm, key);
ary_push(ary, str_taint(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 TRUE;
return FALSE;
}
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 TRUE;
}
return FALSE;
}
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 = ary_new();
for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
val = dbm_fetch(dbm, key);
ary_push(ary, assoc_new(str_taint(str_new(key.dptr, key.dsize)),
str_taint(str_new(val.dptr, val.dsize))));
}
return ary;
}
Init_dbm()
{
cDBM = rb_define_class("DBM", cObject);
rb_include_module(cDBM, mEnumerable);
rb_define_singleton_method(cDBM, "open", 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, -2);
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, "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);
}

1
ext/dbm/depend Normal file
Просмотреть файл

@ -0,0 +1 @@
dbm.o: dbm.c ../../ruby.h ../../config.h ../../defines.h

5
ext/dbm/extconf.rb Normal file
Просмотреть файл

@ -0,0 +1,5 @@
$LDFLAGS = "-L/usr/local/lib"
have_library("gdbm", "dbm_open") or have_library("dbm", "dbm_open")
if have_func("dbm_open")
create_makefile("dbm")
end

5
ext/etc/MANIFEST Normal file
Просмотреть файл

@ -0,0 +1,5 @@
MANIFEST
etc.c
etc.doc
depend
extconf.rb

1
ext/etc/depend Normal file
Просмотреть файл

@ -0,0 +1 @@
etc.o : etc.c ../../ruby.h ../../config.h ../../defines.h

266
ext/etc/etc.c Normal file
Просмотреть файл

@ -0,0 +1,266 @@
/************************************************
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 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 struct_new(sPasswd,
str_new2(pwd->pw_name),
str_new2(pwd->pw_passwd),
INT2FIX(pwd->pw_uid),
INT2FIX(pwd->pw_gid),
str_new2(pwd->pw_gecos),
str_new2(pwd->pw_dir),
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
str_new2(pwd->pw_class),
#endif
#ifdef PW_COMMENT
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) Fail("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) Fail("can't find user for %s", RSTRING(nam)->ptr);
return setup_passwd(pwd);
#else
return Qnil;
#endif
}
static VALUE
etc_passwd(obj)
VALUE obj;
{
#if defined(HAVE_GETPWENT) && !defined(__CYGWIN32__)
struct passwd *pw;
if (iterator_p()) {
setpwent();
while (pw = getpwent()) {
rb_yield(setup_passwd(pw));
}
endpwent();
return obj;
}
pw = getpwent();
if (pw == 0) Fail("can't fetch next -- /etc/passwd");
return setup_passwd(pw);
#else
return Qnil;
#endif
}
#ifdef HAVE_GETGRENT
static VALUE
setup_group(grp)
struct group *grp;
{
VALUE mem;
char **tbl;
mem = ary_new();
tbl = grp->gr_mem;
while (*tbl) {
ary_push(mem, str_new2(*tbl));
tbl++;
}
return struct_new(sGroup,
str_new2(grp->gr_name),
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) Fail("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) Fail("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 (iterator_p()) {
setgrent();
while (grp = getgrent()) {
rb_yield(setup_group(grp));
}
endgrent();
return obj;
}
return setup_group(getgrent());
#else
return Qnil;
#endif
}
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 = struct_define("Passwd",
"name", "passwd", "uid", "gid",
"gecos", "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 = struct_define("Group", "name", "passwd", "gid", "mem", 0);
rb_global_variable(&sGroup);
#endif
}

73
ext/etc/etc.doc Normal file
Просмотреть файл

@ -0,0 +1,73 @@
.\" etc.doc - -*- Indented-Text -*- created at: Fri Jul 14 00:47:15 JST 1995
** Etc(モジュール)
/etcディレクトリ以下の情報を得るためのモジュールクラスにインクルード
して使うこともできる.
Methods:
Single Methods:
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エントリを順にアクセスするためのイテレータ

7
ext/etc/extconf.rb Normal file
Просмотреть файл

@ -0,0 +1,7 @@
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
create_makefile("etc")
end

468
ext/extmk.rb.in Normal file
Просмотреть файл

@ -0,0 +1,468 @@
#! /usr/local/bin/ruby
if ARGV[0] == 'static'
$force_static = TRUE
ARGV.shift
elsif ARGV[0] == 'install'
$install = TRUE
ARGV.shift
elsif ARGV[0] == 'clean'
$clean = TRUE
ARGV.shift
end
$extlist = []
$cache_mod = FALSE;
$lib_cache = {}
$func_cache = {}
$hdr_cache = {}
$topdir = "@top_srcdir@"
if $topdir !~ "^/"
# get absolute path
save = Dir.pwd
Dir.chdir ".."
$topdir = Dir.pwd
Dir.chdir save
end
if File.exist?("config.cache") then
f = open("config.cache", "r")
while f.gets
case $_
when /^lib: ([\w_]+) (yes|no)/
$lib_cache[$1] = $2
when /^func: ([\w_]+) (yes|no)/
$func_cache[$1] = $2
when /^hdr: (.+) (yes|no)/
$hdr_cache[$1] = $2
end
end
f.close
end
def older(file1, file2)
if !File.exist?(file1) then
return TRUE
end
if !File.exist?(file2) then
return FALSE
end
if File.mtime(file1) < File.mtime(file2)
return TRUE
end
return FALSE
end
if PLATFORM == "m68k-human"
CFLAGS = "@CFLAGS@".gsub(/-c..-stack=[0-9]+ */, '')
LINK = "@CC@ -o conftest -I#{$topdir} " + CFLAGS + " %s @LDFLAGS@ %s conftest.c @LIBS@ %s > nul 2>&1"
CPP = "@CPP@ @CPPFLAGS@ -I#{$topdir} " + CFLAGS + " %s conftest.c > nul 2>&1"
else
CFLAGS = "@CFLAGS@"
LINK = "@CC@ -o conftest -I#{$topdir} " + CFLAGS + " %s @LDFLAGS@ %s conftest.c %s > /dev/null 2>&1"
CPP = "@CPP@ @CPPFLAGS@ -I#{$topdir} " + CFLAGS + " %s conftest.c > /dev/null 2>&1"
end
def try_link(libs)
system(format(LINK, $CFLAGS, $LDFLAGS, libs))
end
def try_cpp
system(format(CPP, $CFLAGS))
end
def have_library(lib, func)
if $lib_cache[lib]
if $lib_cache[lib] == "yes"
if $libs
$libs = "-l" + lib + " " + $libs
else
$libs = "-l" + lib
end
return TRUE
else
return FALSE
end
end
cfile = open("conftest.c", "w")
cfile.printf "\
int main() { return 0; }
int t() { %s(); return 0; }
", func
cfile.close
begin
if $libs
libs = "-l" + lib + " " + $libs
else
libs = "-l" + lib
end
unless try_link(libs)
$lib_cache[lib] = 'no'
$cache_mod = TRUE
return FALSE
end
ensure
system "rm -f conftest*"
end
$libs = libs
$lib_cache[lib] = 'yes'
$cache_mod = TRUE
return TRUE
end
def have_func(func)
if $func_cache[func]
if $func_cache[func] == "yes"
$defs.push(format("-DHAVE_%s", func.upcase))
return TRUE
else
return FALSE
end
end
cfile = open("conftest.c", "w")
cfile.printf "\
char %s();
int main() { return 0; }
int t() { %s(); return 0; }
", func, func
cfile.close
libs = $libs
libs = "" if libs == nil
begin
unless try_link(libs)
$func_cache[func] = 'no'
$cache_mod = TRUE
return FALSE
end
ensure
system "rm -f conftest*"
end
$defs.push(format("-DHAVE_%s", func.upcase))
$func_cache[func] = 'yes'
$cache_mod = TRUE
return TRUE
end
def have_header(header)
if $hdr_cache[header]
if $hdr_cache[header] == "yes"
header.tr!("a-z./\055", "A-Z___")
$defs.push(format("-DHAVE_%s", header))
return TRUE
else
return FALSE
end
end
cfile = open("conftest.c", "w")
cfile.printf "\
#include <%s>
", header
cfile.close
begin
unless try_cpp
$hdr_cache[header] = 'no'
$cache_mod = TRUE
return FALSE
end
ensure
system "rm -f conftest*"
end
$hdr_cache[header] = 'yes'
header.tr!("a-z./\055", "A-Z___")
$defs.push(format("-DHAVE_%s", header))
$cache_mod = TRUE
return TRUE
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 create_makefile(target)
if $libs and "@DLEXT@" == "o"
libs = $libs.split
for lib in libs
lib.sub!(/-l(.*)/, '"lib\1.a"')
end
$defs.push(format("-DEXTLIB='%s'", libs.join(",")))
end
$libs = "" unless $libs
$srcdir = $topdir + "/ext/" + target
mfile = open("Makefile", "w")
mfile.printf "\
SHELL = /bin/sh
#### Start of system configuration section. ####
srcdir = #{$srcdir}
VPATH = #{$srcdir}
CC = @CC@
CFLAGS = %s -I#{$topdir} %s #$CFLAGS %s
DLDFLAGS = @DLDFLAGS@ #$LDFLAGS
LDSHARED = @LDSHARED@
", if $static then "" else "@CCDLFLAGS@" end, CFLAGS, $defs.join(" ")
mfile.printf "\
program_transform_name = -e @program_transform_name@
RUBY_INSTALL_NAME = `t='$(program_transform_name)'; echo ruby | sed $$t`
prefix = @prefix@
exec_prefix = @exec_prefix@
libdir = @libdir@/$(RUBY_INSTALL_NAME)/@arch@
@SET_MAKE@
#### End of system configuration section. ####
"
mfile.printf "LOCAL_LIBS = %s\n", $local_libs if $local_libs
mfile.printf "LIBS = %s\n", $libs
mfile.printf "OBJS = "
if !$objs then
$objs = Dir["#{$topdir}/ext/#{target}/*.c"]
for f in $objs
f.sub!(/\.c$/, ".o")
end
end
mfile.printf $objs.join(" ")
mfile.printf "\n"
dots = if "@INSTALL@" =~ /^\// then "" else "#{$topdir}/ext/" end
mfile.printf "\
TARGET = %s.%s
INSTALL = %s@INSTALL@
binsuffix = @binsuffix@
all: $(TARGET)
clean:; @rm -f *.o *.so *.sl
@rm -f Makefile extconf.h conftest.*
@rm -f core ruby$(binsuffix) *~
realclean: clean
", target,
if $static then "o" else "@DLEXT@" end, dots
if !$static
mfile.printf "\
install:
@test -d $(libdir) || mkdir $(libdir)
$(INSTALL) $(TARGET) $(libdir)/$(TARGET)
"
else
mfile.printf "\
install:;
"
end
if !$static && "@DLEXT@" != "o"
mfile.printf "\
$(TARGET): $(OBJS)
$(LDSHARED) $(DLDFLAGS) -o $(TARGET) $(OBJS) $(LOCAL_LIBS) $(LIBS)
"
elsif not File.exist?(target + ".c")
if PLATFORM == "m68k-human"
mfile.printf "\
$(TARGET): $(OBJS)
ar cru $(TARGET) $(OBJS)
"
elsif PLATFORM =~ "-nextstep"
mfile.printf "\
$(TARGET): $(OBJS)
cc -r $(CFLAGS) -o $(TARGET) $(OBJS)
"
elsif $static
mfile.printf "\
$(TARGET): $(OBJS)
ld -r -o $(TARGET) $(OBJS)
"
else
mfile.printf "\
$(TARGET): $(OBJS)
ld $(DLDFLAGS) -r -o $(TARGET) $(OBJS)
"
end
end
if File.exist?("depend")
dfile = open("depend", "r")
mfile.printf "###\n"
while line = dfile.gets()
mfile.printf "%s", line
end
dfile.close
end
mfile.close
if $static
$extlist.push [$static,target]
end
end
def extmake(target)
if $force_static or $static_ext[target]
$static = target
else
$static = FALSE
end
return if $nodynamic and not $static
$local_libs = nil
$libs = nil
$objs = nil
$CFLAGS = nil
$LDFLAGS = nil
begin
system "mkdir " + target unless File.directory?(target)
Dir.chdir target
if $static_ext.size > 0 ||
!File.exist?("./Makefile") ||
older("./Makefile", "#{$topdir}/ext/@setup@") ||
older("./Makefile", "../extmk.rb") ||
older("./Makefile", "./extconf.rb")
then
$defs = []
if File.exist?("extconf.rb")
load "extconf.rb"
else
create_makefile(target);
end
end
if File.exist?("./Makefile")
if $install
system "make install"
elsif $clean
system "make clean"
else
system "make all"
end
end
if $static
$extlibs += " " + $LDFLAGS if $LDFLAGS
$extlibs += " " + $local_libs if $local_libs
$extlibs += " " + $libs if $libs
end
ensure
Dir.chdir ".."
end
end
# get static-link modules
$static_ext = {}
if File.file? "#{$topdir}/ext/@setup@"
f = open("#{$topdir}/ext/@setup@")
while f.gets()
$_.chop!
sub!(/#.*$/, '')
next if /^\s*$/
if /^option +nodynamic/
$nodynamic = TRUE
next
end
$static_ext[$_.split[0]] = TRUE
end
f.close
end
for d in Dir["#{$topdir}/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"
end
extmake(d)
end
if $cache_mod
f = open("config.cache", "w")
for k,v in $lib_cache
f.printf "lib: %s %s\n", k, v
end
for k,v in $func_cache
f.printf "func: %s %s\n", k, v
end
for k,v in $hdr_cache
f.printf "hdr: %s %s\n", k, v
end
f.close
end
exit if $install or $clean
if $extlist.size > 0
for s,t in $extlist
f = format("%s/%s.o", s, t)
if File.exist?(f)
$extinit += format("\
\tInit_%s();\n\
\trb_provide(\"%s.o\");\n\
", t, t)
$extobjs += "ext/"
$extobjs += f
$extobjs += " "
else
FALSE
end
end
if older("extinit.c", "#{$topdir}/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.o", "extinit.c")
cmd = "@CC@ " + CFLAGS + " -c extinit.c"
print cmd, "\n"
system cmd or exit 1
end
Dir.chdir ".."
if older("ruby@binsuffix@", "#{$topdir}/ext/@setup@") or older("ruby@binsuffix@", "miniruby@binsuffix@")
`rm -f ruby@binsuffix@`
end
$extobjs = "ext/extinit.o " + $extobjs
system format('make ruby@binsuffix@ EXTOBJS="%s" EXTLIBS="%s"', $extobjs, $extlibs)
else
Dir.chdir ".."
if older("ruby@binsuffix@", "miniruby@binsuffix@")
`rm -f ruby@binsuffix@`
`cp miniruby@binsuffix@ ruby@binsuffix@`
end
end
#Local variables:
# mode: ruby
#end:

480
ext/extmk.rb.nt Normal file
Просмотреть файл

@ -0,0 +1,480 @@
#! /usr/local/bin/ruby
if ARGV[0] == 'static'
$force_static = TRUE
ARGV.shift
elsif ARGV[0] == 'install'
$install = TRUE
ARGV.shift
elsif ARGV[0] == 'clean'
$clean = TRUE
ARGV.shift
end
$extlist = []
$cache_mod = FALSE;
$lib_cache = {}
$func_cache = {}
$hdr_cache = {}
$dllopt = '-MD'
if File.exist?("config.cache") then
f = open("config.cache", "r")
while f.gets
case $_
when /^lib: ([\w_]+) (yes|no)/
$lib_cache[$1] = $2
when /^func: ([\w_]+) (yes|no)/
$func_cache[$1] = $2
when /^hdr: (.+) (yes|no)/
$hdr_cache[$1] = $2
end
end
f.close
end
def older(file1, file2)
if !File.exist?(file1) then
return TRUE
end
if !File.exist?(file2) then
return FALSE
end
if File.mtime(file1) < File.mtime(file2)
return TRUE
end
return FALSE
end
LINK = "cl -o conftest -I../.. -Zi -O -I. %s %s conftest.c %s > nul"
CPP = "cl -E -I../.. -I../../missing -I. -Zi -O %s conftest.c > nul"
def try_link(libs)
system(format(LINK, $CFLAGS, $LDFLAGS, libs))
end
def try_cpp
system(format(CPP, $CFLAGS))
end
def have_library(lib, func)
if $lib_cache[lib]
if $lib_cache[lib] == "yes"
if $libs
$libs = "-l" + lib + " " + $libs
else
$libs = "-l" + lib
end
return TRUE
else
return FALSE
end
end
cfile = open("conftest.c", "w")
cfile.printf "\
int main() { return 0; }
int t() { %s(); return 0; }
", func
cfile.close
begin
if $libs
libs = lib + ".lib " + $libs
else
libs = lib + ".lib"
end
unless try_link(libs)
$lib_cache[lib] = 'no'
$cache_mod = TRUE
return FALSE
end
ensure
system "rm -f conftest*"
end
$libs = libs
$lib_cache[lib] = 'yes'
$cache_mod = TRUE
return TRUE
end
def have_func(func)
if $func_cache[func]
if $func_cache[func] == "yes"
$defs.push(format("-DHAVE_%s", func.upcase))
return TRUE
else
return FALSE
end
end
cfile = open("conftest.c", "w")
cfile.printf "\
char %s();
int main() { return 0; }
int t() { %s(); return 0; }
", func, func
cfile.close
libs = $libs
libs = "" if libs == nil
begin
unless try_link(libs)
$func_cache[func] = 'no'
$cache_mod = TRUE
return FALSE
end
ensure
system "rm -f conftest*"
end
$defs.push(format("-DHAVE_%s", func.upcase))
$func_cache[func] = 'yes'
$cache_mod = TRUE
return TRUE
end
def have_header(header)
if $hdr_cache[header]
if $hdr_cache[header] == "yes"
header.tr!("a-z./\055", "A-Z___")
$defs.push(format("-DHAVE_%s", header))
return TRUE
else
return FALSE
end
end
cfile = open("conftest.c", "w")
cfile.printf "\
#include <%s>
", header
cfile.close
begin
unless try_cpp
$hdr_cache[header] = 'no'
$cache_mod = TRUE
return FALSE
end
ensure
system "rm -f conftest*"
end
$hdr_cache[header] = 'yes'
header.tr!("a-z./\055", "A-Z___")
$defs.push(format("-DHAVE_%s", header))
$cache_mod = TRUE
return TRUE
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 create_makefile(target)
if $libs and "obj" == "obj"
libs = $libs.split
for lib in libs
lib.sub!(/(.*)/, '"lib\1.lib"')
end
$defs.push(format("-DEXTLIB='%s'", libs.join(",")))
end
$libs = "" unless $libs
mfile = open("Makefile", "w")
mfile.printf "\
SHELL = $(COMPSEC)
#### Start of system configuration section. ####
srcdir = .
VPATH = .
CC = cl
CFLAGS = %s -I../.. -I../../missing -I. -O -DNT %s #$CFLAGS %s
RUBYLIB = ../../ruby.lib
DLDFLAGS = /DLL
LDSHARED =
", if $static then "" else "-fpic" end, $dllopt, $defs.join(" ")
if $force_static
print "static\n"
else
print "non static\n"
end
mfile.printf "\
libdir = /usr/local/lib/ruby/i386-mswin32
#### End of system configuration section. ####
"
mfile.printf "LOCAL_LIBS = %s\n", $local_libs if $local_libs
mfile.printf "LIBS = %s\n", $libs
mfile.printf "OBJS = "
if !$objs then
$objs = Dir["*.c"]
for f in $objs
f.sub!(/\.c$/, ".obj")
end
end
mfile.printf $objs.join(" ")
mfile.printf "\n"
dots = if "ginstall -c" =~ /^\// then "" else "../" end
mfile.printf "\
TARGET = %s.%s
INSTALL = %sginstall -c
DEFFILE = %s.def
all: $(TARGET)
clean:; @rm -f *.obj *.lib *.exp *.pdb *.bak
@rm -f Makefile extconf.h conftest.*
realclean: clean
", target,
if $force_static then "lib" else "dll" end, dots, target
if !$static
mfile.printf "\
install: $(libdir)/$(TARGET)
$(libdir)/$(TARGET): $(TARGET)
@test -d $(libdir) || mkdir $(libdir)
$(INSTALL) $(TARGET) $(libdir)/$(TARGET)
"
else
mfile.printf "\
install:;
"
end
if $force_static
mfile.printf "\
$(TARGET): $(OBJS)
lib /OUT:$(TARGET) $(OBJS)
"
else
mfile.printf "\
$(DEFFILE):
echo $(DEFFILE)
$(TARGET): $(OBJS) $(DEFFILE)
cl -DLL -o$(TARGET) $(OBJS) $(RUBYLIB) -link /DEF:$(DEFFILE)
"
end
if File.exist?("depend")
dfile = open("depend", "r")
mfile.printf "###\n"
while line = dfile.gets()
mfile.printf "%s", line
end
dfile.close
end
mfile.close
if $static
printf format("push %s,%s\n", $static, target); ##debug print##
$extlist.push [$static,target]
end
end
def extmake(target)
if $force_static or $static_ext[target]
$static = target
else
$static = FALSE
end
return if $nodynamic and not $static
$local_libs = nil
$libs = nil
$objs = nil
$CFLAGS = nil
$LDFLAGS = nil
begin
Dir.chdir target
if $static_ext.size > 0 ||
!File.exist?("./Makefile") ||
older("./Makefile", "../Setup") ||
older("./Makefile", "../extmk.rb") ||
older("./Makefile", "./extconf.rb")
then
$defs = []
if File.exist?("extconf.rb")
load "extconf.rb"
else
create_makefile(target);
end
end
if File.exist?("./Makefile")
if $install
system "nmake install"
if File.directory? "./lib"
for i in Dir["./lib/*.rb"]
system "ginstall -c #{i} /usr/local/lib/ruby/i386-mswin32"
end
end
elsif $clean
system "nmake clean"
else
system "nmake all"
end
end
if $static
$extlibs += " " + $LDFLAGS if $LDFLAGS
$extlibs += " " + $local_libs if $local_libs
$extlibs += " " + $libs if $libs
end
ensure
Dir.chdir ".."
end
end
# get static-link modules
$static_ext = {}
if File.file? "./Setup"
f = open("./Setup")
while f.gets()
$_.chop!
sub!(/#.*$/, '')
next if /^\s*$/
print $_, "\n"
if /^option +nodynamic/
$nodynamic = TRUE
next
end
$static_ext[$_.split[0]] = TRUE
end
f.close
end
for d in Dir["*"]
File.directory?(d) || next
File.file?(d + "/MANIFEST") || next
d = $1 if d =~ /\/([\/]*)$/
if $install
print "installing ", d, "\n"
elsif $clean
print "cleaning ", d, "\n"
else
print "compiling ", d, "\n"
end
extmake(d)
end
if $cache_mod
f = open("config.cache", "w")
for k,v in $lib_cache
f.printf "lib: %s %s\n", k, v
end
for k,v in $func_cache
f.printf "func: %s %s\n", k, v
end
for k,v in $hdr_cache
f.printf "hdr: %s %s\n", k, v
end
f.close
end
exit if $install or $clean
if $extlist.size > 0
#for s,t in $extlist
for s,t in $static_ext
#f = format("%s/%s.obj", s, t)
#f = format("%s/%s.obj", s, s)
l = format("%s/%s.lib", s, s)
#print format("%s/%s.obj\n", s, s) ##debug print##
if File.exist?(l)
$extinit += format("\
\tInit_%s();\n\
\trb_provide(\"%s.o\");\n\
", s, s)
$extobjs += "ext/"
#$extobjs += f # *.obj
$extobjs += l # *.lib
$extobjs += " "
else
FALSE
end
end
if older("extinit.c", "Setup")
f = open("extinit.c", "w")
f.printf "void Init_ext() {\n"
f.printf $extinit
f.printf "}\n"
f.close
end
if older("extinit.obj", "extinit.c")
cmd = "cl -Zi -O -I. -c extinit.c"
print cmd, "\n"
system cmd or exit 1
end
Dir.chdir ".."
if older("ruby.exe", "ext/Setup") or older("ruby.exe", "miniruby.exe")
`rm -f ruby.exe`
end
$extobjs = "ext/extinit.obj " + $extobjs
$extlibs = ""
system format('nmake ruby.exe EXTOBJS="%s" EXTLIBS="%s"', $extobjs, $extlibs)
else
Dir.chdir ".."
if older("ruby.exe", "miniruby.exe")
`rm -f ruby.exe`
`cp miniruby.exe ruby.exe`
end
end
#template of .def file.
#LIBRARY kconv.dll
#CODE LOADONCALL
#DATA LOADONCALL
#DESCRIPTION 'win32 kconv.dll'
#EXPORTS
#
# Init_kconv
def makedef(basename)
defname = sprintf("%s.def", basename)
f = open(defname, "w")
f.printf "\
LIBRARY %s.dll
CODE LOADONCALL
DATA LOADONCALL
DESCRIPTION 'win32 %s.dll'
EXPORTS
Init_%s
", basename, basename
f.close
end
#Local variables:
# mode: ruby
#end:

3
ext/fcntl/MANIFEST Normal file
Просмотреть файл

@ -0,0 +1,3 @@
MANIFEST
depend
fcntl.c

1
ext/fcntl/depend Normal file
Просмотреть файл

@ -0,0 +1 @@
fcntl.o: fcntl.c ../../ruby.h ../../config.h ../../defines.h

106
ext/fcntl/fcntl.c Normal file
Просмотреть файл

@ -0,0 +1,106 @@
/************************************************
fcntl.c -
$Author$
created at: Mon Apr 7 18:53:05 JST 1997
Copyright (C) 1997 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>
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
}

3
ext/kconv/MANIFEST Normal file
Просмотреть файл

@ -0,0 +1,3 @@
MANIFEST
depend
kconv.c

1
ext/kconv/depend Normal file
Просмотреть файл

@ -0,0 +1 @@
kconv.o: kconv.c ../../ruby.h ../../config.h ../../defines.h

1881
ext/kconv/kconv.c Normal file

Разница между файлами не показана из-за своего большого размера Загрузить разницу

5
ext/marshal/MANIFEST Normal file
Просмотреть файл

@ -0,0 +1,5 @@
MANIFEST
depend
extconf.rb
marshal.c
marshal.doc

2
ext/marshal/depend Normal file
Просмотреть файл

@ -0,0 +1,2 @@
marshal.o: marshal.c ../../ruby.h ../../config.h ../../defines.h ../../io.h \
../../st.h

1
ext/marshal/extconf.rb Normal file
Просмотреть файл

@ -0,0 +1 @@
create_makefile("marshal")

850
ext/marshal/marshal.c Normal file
Просмотреть файл

@ -0,0 +1,850 @@
/************************************************
marshal.c -
$Author$
$Revision$
$Date$
created at: Thu Apr 27 16:30:01 JST 1995
************************************************/
#include "ruby.h"
#include "io.h"
#include "st.h"
#define MARSHAL_MAJOR 4
#define MARSHAL_MINOR 0
#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_STRUCT 'S'
#define TYPE_MODULE 'M'
#define TYPE_SYMBOL ':'
#define TYPE_SYMLINK ';'
#define TYPE_LINK '@'
extern VALUE cString;
extern VALUE cRegexp;
extern VALUE cArray;
extern VALUE cHash;
VALUE rb_path2class();
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 str_cat(arg->str, (UCHAR*)&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 {
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(USHORT); 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_insert(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));
extern VALUE cIO, cBignum, cStruct;
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, class, arg)
VALUE obj, class;
struct dump_arg *arg;
{
if (CLASS_OF(obj) != class) {
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;
{
int n;
struct dump_call_arg c_arg;
if (limit == 0) {
Fail("exceed depth limit");
}
limit--;
c_arg.limit = limit;
c_arg.arg = arg;
if (obj == Qnil) {
w_byte(TYPE_NIL, arg);
}
else if (obj == TRUE) {
w_byte(TYPE_TRUE, arg);
}
else if (obj == FALSE) {
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(obj, 32) == 0 || RSHIFT(obj, 32) == -1) {
w_byte(TYPE_FIXNUM, arg);
w_long(FIX2INT(obj), arg);
}
else {
obj = int2big(FIX2INT(obj));
goto write_bignum;
}
#endif
}
else {
int num;
if (st_lookup(arg->data, obj, &num)) {
w_byte(TYPE_LINK, arg);
w_long(num, arg);
return;
}
st_insert(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, limit);
if (TYPE(v) != T_STRING) {
TypeError("_dump_to must return String");
}
w_bytes(RSTRING(v)->ptr, RSTRING(v)->len, arg);
return;
}
switch (BUILTIN_TYPE(obj)) {
case T_MODULE:
case T_CLASS:
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:
write_bignum:
w_byte(TYPE_BIGNUM, arg);
{
char sign = RBIGNUM(obj)->sign?'+':'-';
int len = RBIGNUM(obj)->len;
USHORT *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, cString, arg);
w_byte(TYPE_STRING, arg);
w_bytes(RSTRING(obj)->ptr, RSTRING(obj)->len, arg);
return;
case T_REGEXP:
w_uclass(obj, cRegexp, arg);
w_byte(TYPE_REGEXP, arg);
w_bytes(RREGEXP(obj)->str, RREGEXP(obj)->len, arg);
w_byte(FL_TEST(obj, FL_USER1), arg);
return;
case T_ARRAY:
w_uclass(obj, 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, cHash, arg);
w_byte(TYPE_HASH, arg);
w_long(RHASH(obj)->tbl->num_entries, arg);
st_foreach(RHASH(obj)->tbl, hash_each, &c_arg);
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) {
Fatal("non-initialized struct");
}
for (i=0; i<len; i++) {
w_symbol(FIX2INT(RARRAY(mem)->ptr[i]), arg);
w_object(RSTRUCT(obj)->ptr[i], arg, limit);
}
}
break;
case T_OBJECT:
w_byte(TYPE_OBJECT, arg);
{
VALUE class = CLASS_OF(obj);
char *path;
if (FL_TEST(class, FL_SINGLETON)) {
TypeError("singleton can't be dumped");
}
path = rb_class2name(class);
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:
TypeError("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);
}
static VALUE
dump_ensure(arg)
struct dump_arg *arg;
{
st_free_table(arg->symbol);
st_free_table(arg->data);
}
static VALUE
marshal_dump(argc, argv)
int argc;
VALUE argv;
{
VALUE obj, port, a1, a2;
int limit = -1;
extern VALUE cIO;
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 (obj_is_kind_of(port, cIO)) {
OpenFile *fptr;
io_binmode(port);
GetOpenFile(port, fptr);
io_writable(fptr);
arg.fp = (fptr->f2) ? fptr->f2 : fptr->f;
}
else {
TypeError("instance of IO needed");
}
}
else {
arg.fp = 0;
port = 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, &c_arg, dump_ensure, &arg);
return port;
}
struct load_arg {
FILE *fp;
UCHAR *ptr, *end;
st_table *symbol;
st_table *data;
};
static int
r_byte(arg)
struct load_arg *arg;
{
if (arg->fp) return getc(arg->fp);
if (arg->ptr < arg->end) return *arg->ptr++;
return EOF;
}
static USHORT
r_short(arg)
struct load_arg *arg;
{
USHORT x;
int i;
x = 0;
for (i=0; i<sizeof(USHORT); i++) {
x |= r_byte(arg)<<(i*8);
}
return x;
}
static void
long_toobig(size)
int size;
{
TypeError("long too big for this architecture (size %d, given %d)",
sizeof(long), size);
}
static long
r_long(arg)
struct load_arg *arg;
{
int c = r_byte(arg), i;
register long x;
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 if (c < 0) {
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_bytes(s, arg) \
(s = (char*)r_long(arg), r_bytes0(&s,ALLOCA_N(char,(long)s),(long)s,arg))
static int
r_bytes0(sp, s, len, arg)
char **sp, *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';
*sp = s;
return len;
}
static ID
r_symbol(arg)
struct load_arg *arg;
{
char *buf;
ID id;
char type;
if (r_byte(arg) == TYPE_SYMLINK) {
int num = r_long(arg);
if (st_lookup(arg->symbol, num, &id)) {
return id;
}
TypeError("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_bytes(buf, arg);
return str_taint(str_new(buf, len));
}
static VALUE
r_regist(v, arg)
VALUE v;
struct load_arg *arg;
{
st_insert(arg->data, arg->data->num_entries, v);
return v;
}
static VALUE
r_object(arg)
struct load_arg *arg;
{
VALUE v;
int type = r_byte(arg);
switch (type) {
case EOF:
eof_error();
return Qnil;
case TYPE_LINK:
if (st_lookup(arg->data, r_long(arg), &v)) {
return v;
}
ArgError("dump format error (unlinked)");
break;
case TYPE_UCLASS:
{
VALUE c = rb_path2class(r_unique(arg));
v = r_object(arg);
if (rb_special_const_p(v)) {
ArgError("dump format error (user class)");
}
RBASIC(v)->class = c;
return v;
}
case TYPE_NIL:
return Qnil;
case TYPE_TRUE:
return TRUE;
case TYPE_FALSE:
return FALSE;
case TYPE_FIXNUM:
{
int i = r_long(arg);
return INT2FIX(i);
}
case TYPE_FLOAT:
{
#ifndef atof
double atof();
#endif
char *buf;
r_bytes(buf, arg);
v = float_new(atof(buf));
return r_regist(v, arg);
}
case TYPE_BIGNUM:
{
int len;
USHORT *digits;
NEWOBJ(big, struct RBignum);
OBJSETUP(big, cBignum, T_BIGNUM);
big->sign = (r_byte(arg) == '+');
big->len = len = r_long(arg);
big->digits = digits = ALLOC_N(USHORT, len);
while (len--) {
*digits++ = r_short(arg);
}
big = RBIGNUM(big_norm((VALUE)big));
if (TYPE(big) == T_BIGNUM) {
r_regist(big, arg);
}
return (VALUE)big;
}
case TYPE_STRING:
return r_regist(r_string(arg), arg);
case TYPE_REGEXP:
{
char *buf;
int len = r_bytes(buf, arg);
int ci = r_byte(arg);
return r_regist(reg_new(buf, len, ci), arg);
}
case TYPE_ARRAY:
{
volatile int len = r_long(arg);
v = ary_new2(len);
r_regist(v, arg);
while (len--) {
ary_push(v, r_object(arg));
}
return v;
}
case TYPE_HASH:
{
int len = r_long(arg);
v = hash_new();
r_regist(v, arg);
while (len--) {
VALUE key = r_object(arg);
VALUE value = r_object(arg);
hash_aset(v, key, value);
}
return v;
}
case TYPE_STRUCT:
{
VALUE class, mem, values;
int i, len;
int num = arg->data->num_entries;
class = rb_path2class(r_unique(arg));
mem = rb_ivar_get(class, rb_intern("__member__"));
if (mem == Qnil) {
Fatal("non-initialized struct");
}
len = r_long(arg);
values = ary_new2(len);
for (i=0; i<len; i++) {
ary_push(values, Qnil);
}
v = struct_alloc(class, values);
r_regist(v, arg);
for (i=0; i<len; i++) {
ID slot = r_symbol(arg);
if (RARRAY(mem)->ptr[i] != INT2FIX(slot))
TypeError("struct not compatible");
struct_aset(v, INT2FIX(i), r_object(arg));
}
return v;
}
break;
case TYPE_USERDEF:
{
VALUE class;
int len;
class = rb_path2class(r_unique(arg));
if (rb_respond_to(class, s_load)) {
v = rb_funcall(class, s_load, 1, r_string(arg));
return r_regist(v, arg);
}
TypeError("class %s needs to have method `_load_from'",
rb_class2name(class));
}
break;
case TYPE_OBJECT:
{
VALUE class;
int len;
class = rb_path2class(r_unique(arg));
len = r_long(arg);
v = obj_alloc(class);
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:
{
char *buf;
r_bytes(buf, arg);
return rb_path2class(buf);
}
default:
ArgError("dump format error(0x%x)", type);
break;
}
}
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);
st_free_table(arg->data);
}
static VALUE
marshal_load(self, port)
VALUE self, port;
{
FILE *fp;
int major;
VALUE v;
OpenFile *fptr;
struct load_arg arg;
if (TYPE(port) == T_STRING) {
arg.fp = 0;
arg.ptr = RSTRING(port)->ptr;
arg.end = arg.ptr + RSTRING(port)->len;
}
else {
if (obj_is_kind_of(port, cIO)) {
io_binmode(port);
GetOpenFile(port, fptr);
io_readable(fptr);
arg.fp = fptr->f;
}
else {
TypeError("instance of IO needed");
}
}
major = r_byte(&arg);
if (major == MARSHAL_MAJOR) {
if (r_byte(&arg) != MARSHAL_MINOR) {
Warning("Old marshal file format (can be read)");
}
arg.symbol = st_init_numtable();
arg.data = st_init_numtable();
v = rb_ensure(load, &arg, load_ensure, &arg);
}
else {
TypeError("Old marshal file format (can't read)");
}
return v;
}
Init_marshal()
{
VALUE mMarshal = rb_define_module("Marshal");
s_dump = rb_intern("_dump_to");
s_load = rb_intern("_load_from");
rb_define_module_function(mMarshal, "dump", marshal_dump, -1);
rb_define_module_function(mMarshal, "load", marshal_load, 1);
rb_define_module_function(mMarshal, "restore", marshal_load, 1);
}

48
ext/marshal/marshal.doc Normal file
Просмотреть файл

@ -0,0 +1,48 @@
.\" marshal.doc - -*- Indented-Text -*- created at: Tue May 16 12:18:08 JST 1995
** Marshal(モジュール)
rubyオブジェクトをファイルに書き出したり読みも度したりする機能を提供
するモジュール.大部分のクラスのインスタンスを書き出す事ができるが,ファ
イルへの不可能なクラスも存在し(例:IO),そのようなクラスを書き出そうと
すると例外を発生させる.
Methods:
Single Methods:
dump(obj, port[, limit])
objを再帰的にファイルに書き出すファイルに書き出せないクラスのイ
ンスタンスをファイルに書き出そうとすると例外を発生させる.ファイル
に書き出せないクラスは以下の通り.
Class, Module, Data
また,これらのクラスを間接的に指すクラス(例えばIOのサブクラス)など
も書き出せないportはIO(またはそのサブクラス)のインスタンスを指定
する.
出力するオブジェクトがメソッド`_dump_to'を定義している場合には,ファ
イル出力はそのメソッドを使って行われる.メソッド`_dump_to'は引数と
して出力先のファイルオブジェクトを受け取る.インスタンスがメソッド
`_dump_to'を持つクラスは必ず同じフォーマットを読み戻す特異メソッド
`_load_from'を定義する必要がある.
limitを指定した場合limit段以上深くリンクしたオブジェクトをダンプ
できない(デフォルトは100レベル)。負のlimitを指定すると深さチェック
を行わない。
dumps(obj)
dump()がファイルに書き出すのと同じ内容を含む文字列を返す.
load(port)
portからオブジェクトを読み込んで来て元のオブジェクトと同じ状態を
もつオブジェクトを生成するportは文字列かIO(またはそのサブクラス)
のインスタンスである.
-------------------------------------------------------
Local variables:
fill-column: 70
end:

6
ext/md5/MANIFEST Normal file
Просмотреть файл

@ -0,0 +1,6 @@
MANIFEST
depend
md5.doc
md5.h
md5c.c
md5init.c

2
ext/md5/depend Normal file
Просмотреть файл

@ -0,0 +1,2 @@
md5c.o: md5c.c md5.h
md5init.o: md5init.c ../../ruby.h ../../config.h ../../defines.h md5.h

36
ext/md5/md5.doc Normal file
Просмотреть файл

@ -0,0 +1,36 @@
.\" 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)
keyをキーとする値を返す
-------------------------------------------------------
Local variables:
fill-column: 70
end:

86
ext/md5/md5.h Normal file
Просмотреть файл

@ -0,0 +1,86 @@
/* 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 *));

337
ext/md5/md5c.c Normal file
Просмотреть файл

@ -0,0 +1,337 @@
/* 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;
}

90
ext/md5/md5init.c Normal file
Просмотреть файл

@ -0,0 +1,90 @@
/************************************************
md5init.c -
$Author$
created at: Fri Aug 2 09:24:12 JST 1996
Copyright (C) 1995 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 Qnil;
}
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 str_new(digest, 16);
}
static VALUE
md5_clone(obj)
VALUE obj;
{
VALUE clone;
MD5_CTX *md5, *md5_new;
Data_Get_Struct(obj, MD5_CTX, md5);
obj = Data_Make_Struct(CLASS_OF(obj), MD5_CTX, 0, 0, md5_new);
*md5_new = *md5;
return obj;
}
static VALUE
md5_new(argc, argv, class)
{
int i;
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, 0, md5);
MD5Init(md5);
if (!NIL_P(arg)) {
md5_update(obj, arg);
}
return obj;
}
Init_md5()
{
cMD5 = rb_define_class("MD5", 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, "clone", md5_clone, 0);
}

4
ext/socket/MANIFEST Normal file
Просмотреть файл

@ -0,0 +1,4 @@
MANIFEST
depend
extconf.rb
socket.c

1
ext/socket/depend Normal file
Просмотреть файл

@ -0,0 +1 @@
socket.o : socket.c ../../ruby.h ../../config.h ../../defines.h ../../io.h ../../sig.h

17
ext/socket/extconf.rb Normal file
Просмотреть файл

@ -0,0 +1,17 @@
$LDFLAGS = "-L/usr/local/lib"
have_library("wsock32", "cygwin32_socket") or have_library("socket", "socket")
have_library("inet", "gethostbyname")
have_library("nsl", "gethostbyname")
have_header("sys/un.h")
if have_func("socket") or have_func("cygwin32_socket")
have_func("hsterror")
unless have_func("gethostname")
have_func("uname")
end
if ENV["SOCKS_SERVER"] # test if SOCKSsocket needed
if have_library("socks", "Rconnect")
$CFLAGS="-DSOCKS"
end
end
create_makefile("socket")
end

1407
ext/socket/socket.c Normal file

Разница между файлами не показана из-за своего большого размера Загрузить разницу

3
ext/tkutil/MANIFEST Normal file
Просмотреть файл

@ -0,0 +1,3 @@
MANIFEST
tkutil.c
depend

1
ext/tkutil/depend Normal file
Просмотреть файл

@ -0,0 +1 @@
tkutil.o: tkutil.c ../../ruby.h ../../config.h ../../defines.h

46
ext/tkutil/tkutil.c Normal file
Просмотреть файл

@ -0,0 +1,46 @@
/************************************************
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);
rb_eval_cmd(cmd, rest);
return Qnil;
}
static VALUE
tk_s_new(argc, argv, class)
int argc;
VALUE *argv;
VALUE class;
{
VALUE obj = obj_alloc(class);
rb_funcall2(obj, rb_intern("initialize"), argc, argv);
if (iterator_p()) rb_yield_0(obj, obj);
return obj;
}
Init_tkutil()
{
VALUE mTK = rb_define_module("TkUtil");
VALUE cTK = rb_define_class("TkKernel", cObject);
rb_define_singleton_method(mTK, "eval_cmd", tk_eval_cmd, -1);
rb_define_singleton_method(cTK, "new", tk_s_new, -1);
}

1756
file.c Normal file

Разница между файлами не показана из-за своего большого размера Загрузить разницу

190
fnmatch.c Normal file
Просмотреть файл

@ -0,0 +1,190 @@
/* Copyright (C) 1991 Free Software Foundation, Inc.
This file is part of the GNU C Library.
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., 675 Mass Ave,
Cambridge, MA 02139, USA. */
#include "config.h"
#include <errno.h>
#include "fnmatch.h"
#if !defined (__GNU_LIBRARY__) && !defined (STDC_HEADERS)
# if !defined (errno)
extern int errno;
# endif /* !errno */
#endif
/* Match STRING against the filename pattern PATTERN, returning zero if
it matches, FNM_NOMATCH if not. */
int
fnmatch (pattern, string, flags)
char *pattern;
char *string;
int flags;
{
register char *p = pattern, *n = string;
register char c;
if ((flags & ~__FNM_FLAGS) != 0)
{
errno = EINVAL;
return (-1);
}
while ((c = *p++) != '\0')
{
switch (c)
{
case '?':
if (*n == '\0')
return (FNM_NOMATCH);
else if ((flags & FNM_PATHNAME) && *n == '/')
return (FNM_NOMATCH);
else if ((flags & FNM_PERIOD) && *n == '.' &&
(n == string || ((flags & FNM_PATHNAME) && n[-1] == '/')))
return (FNM_NOMATCH);
break;
case '\\':
if (!(flags & FNM_NOESCAPE))
c = *p++;
if (*n != c)
return (FNM_NOMATCH);
break;
case '*':
if ((flags & FNM_PERIOD) && *n == '.' &&
(n == string || ((flags & FNM_PATHNAME) && n[-1] == '/')))
return (FNM_NOMATCH);
for (c = *p++; c == '?' || c == '*'; c = *p++, ++n)
if (((flags & FNM_PATHNAME) && *n == '/') ||
(c == '?' && *n == '\0'))
return (FNM_NOMATCH);
if (c == '\0')
return (0);
{
char c1 = (!(flags & FNM_NOESCAPE) && c == '\\') ? *p : c;
for (--p; *n != '\0'; ++n)
if ((c == '[' || *n == c1) &&
fnmatch (p, n, flags & ~FNM_PERIOD) == 0)
return (0);
return (FNM_NOMATCH);
}
case '[':
{
/* Nonzero if the sense of the character class is inverted. */
register int not;
if (*n == '\0')
return (FNM_NOMATCH);
if ((flags & FNM_PERIOD) && *n == '.' &&
(n == string || ((flags & FNM_PATHNAME) && n[-1] == '/')))
return (FNM_NOMATCH);
/* Make sure there is a closing `]'. If there isn't, the `['
is just a character to be matched. */
{
register char *np;
for (np = p; np && *np && *np != ']'; np++);
if (np && !*np)
{
if (*n != '[')
return (FNM_NOMATCH);
goto next_char;
}
}
not = (*p == '!' || *p == '^');
if (not)
++p;
c = *p++;
for (;;)
{
register char cstart = c, cend = c;
if (!(flags & FNM_NOESCAPE) && c == '\\')
cstart = cend = *p++;
if (c == '\0')
/* [ (unterminated) loses. */
return (FNM_NOMATCH);
c = *p++;
if ((flags & FNM_PATHNAME) && c == '/')
/* [/] can never match. */
return (FNM_NOMATCH);
if (c == '-' && *p != ']')
{
cend = *p++;
if (!(flags & FNM_NOESCAPE) && cend == '\\')
cend = *p++;
if (cend == '\0')
return (FNM_NOMATCH);
c = *p++;
}
if (*n >= cstart && *n <= cend)
goto matched;
if (c == ']')
break;
}
if (!not)
return (FNM_NOMATCH);
next_char:
break;
matched:
/* Skip the rest of the [...] that already matched. */
while (c != ']')
{
if (c == '\0')
/* [... (unterminated) loses. */
return (FNM_NOMATCH);
c = *p++;
if (!(flags & FNM_NOESCAPE) && c == '\\')
/* 1003.2d11 is unclear if this is right. %%% */
++p;
}
if (not)
return (FNM_NOMATCH);
}
break;
default:
if (c != *n)
return (FNM_NOMATCH);
}
++n;
}
if (*n == '\0')
return (0);
return (FNM_NOMATCH);
}

36
fnmatch.h Normal file
Просмотреть файл

@ -0,0 +1,36 @@
/* Copyright (C) 1991 Free Software Foundation, Inc.
This file is part of the GNU C Library.
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., 675 Mass Ave,
Cambridge, MA 02139, USA. */
#ifndef _FNMATCH_H
#define _FNMATCH_H 1
/* Bits set in the FLAGS argument to `fnmatch'. */
#define FNM_PATHNAME (1 << 0)/* No wildcard can ever match `/'. */
#define FNM_NOESCAPE (1 << 1)/* Backslashes don't quote special chars. */
#define FNM_PERIOD (1 << 2)/* Leading `.' is matched only explicitly. */
#define __FNM_FLAGS (FNM_PATHNAME|FNM_NOESCAPE|FNM_PERIOD)
/* Value returned by `fnmatch' if STRING does not match PATTERN. */
#define FNM_NOMATCH 1
/* Match STRING against the filename pattern PATTERN,
returning zero if it matches, FNM_NOMATCH if not. */
extern int fnmatch();
#endif /* fnmatch.h */

989
gc.c Normal file
Просмотреть файл

@ -0,0 +1,989 @@
/************************************************
gc.c -
$Author$
$Date$
created at: Tue Oct 5 09:44:46 JST 1993
Copyright (C) 1993-1996 Yukihiro Matsumoto
************************************************/
#include "ruby.h"
#include "sig.h"
#include "st.h"
#include "node.h"
#include "env.h"
#include "re.h"
#include <stdio.h>
#include <setjmp.h>
#ifndef setjmp
#ifdef HAVE__SETJMP
#define setjmp(env) _setjmp(env)
#define longjmp(env,val) _longjmp(env,val)
#endif
#endif
#ifdef _AIX
#pragma alloca
#endif
#ifdef C_ALLOCA
void *alloca();
#endif
void gc();
void gc_mark();
static void run_final();
#ifndef GC_MALLOC_LIMIT
#if defined(MSDOS) || defined(__human68k__)
#define GC_MALLOC_LIMIT 200000
#else
#define GC_MALLOC_LIMIT 400000
#endif
#endif
static unsigned long malloc_memories = 0;
void *
xmalloc(size)
unsigned long size;
{
void *mem;
if (size == 0) size = 1;
malloc_memories += size;
if (malloc_memories > GC_MALLOC_LIMIT) {
gc();
}
mem = malloc(size);
if (!mem) {
gc();
mem = malloc(size);
if (!mem)
Fatal("failed to allocate memory");
}
return mem;
}
void *
xcalloc(n, size)
unsigned long n, size;
{
void *mem;
mem = xmalloc(n * size);
memset(mem, 0, n * size);
return mem;
}
void *
xrealloc(ptr, size)
void *ptr;
unsigned long size;
{
void *mem;
if (!ptr) return xmalloc(size);
mem = realloc(ptr, size);
if (!mem) {
gc();
mem = realloc(ptr, size);
if (!mem)
Fatal("failed to allocate memory(realloc)");
}
return mem;
}
/* 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 rb_in_compile;
static int dont_gc;
VALUE
gc_s_enable()
{
int old = dont_gc;
dont_gc = FALSE;
return old;
}
VALUE
gc_s_disable()
{
int old = dont_gc;
dont_gc = TRUE;
return old;
}
VALUE 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 {
UINT flag; /* always 0 for freed obj */
struct RVALUE *next;
} free;
struct RBasic basic;
struct RObject object;
struct RClass class;
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;
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) Fatal("can't alloc memory");
}
p = heaps[heaps_used++] = (RVALUE*)malloc(sizeof(RVALUE)*HEAP_SLOTS);
if (p == 0) Fatal("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++;
}
}
struct RBasic *
rb_newobj()
{
struct RBasic *obj;
if (freelist) {
retry:
obj = (struct RBasic*)freelist;
freelist = freelist->as.free.next;
return obj;
}
if (dont_gc) add_heap();
else gc();
goto retry;
}
VALUE
data_object_alloc(class, datap, dmark, dfree)
VALUE class;
void *datap;
void (*dfree)();
void (*dmark)();
{
struct RData *data = (struct RData*)rb_newobj();
OBJSETUP(data, class, T_DATA);
data->data = datap;
data->dfree = dfree;
data->dmark = dmark;
return (VALUE)data;
}
extern st_table *rb_class_tbl;
VALUE *gc_stack_start;
static int
looks_pointerp(p)
register RVALUE *p;
{
register RVALUE *heap_org;
register long i;
if (p < lomem || p > himem) return FALSE;
/* 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 TRUE;
}
return FALSE;
}
static void
mark_locations_array(x, n)
VALUE *x;
long n;
{
while (n--) {
if (looks_pointerp(*x)) {
gc_mark(*x);
}
x++;
}
}
void
gc_mark_locations(start, end)
VALUE *start, *end;
{
VALUE *tmp;
long n;
if (start > end) {
tmp = start;
start = end;
end = tmp;
}
n = end - start;
mark_locations_array(start,n);
}
static int
mark_entry(key, value)
ID key;
VALUE value;
{
gc_mark(value);
return ST_CONTINUE;
}
static void
mark_tbl(tbl)
st_table *tbl;
{
if (!tbl) return;
st_foreach(tbl, mark_entry, 0);
}
static int
mark_hashentry(key, value)
ID key;
VALUE value;
{
gc_mark(key);
gc_mark(value);
return ST_CONTINUE;
}
static void
mark_hash(tbl)
st_table *tbl;
{
if (!tbl) return;
st_foreach(tbl, mark_hashentry, 0);
}
void
gc_mark_maybe(obj)
void *obj;
{
if (looks_pointerp(obj)) {
gc_mark(obj);
}
}
void
gc_mark(obj)
register RVALUE *obj;
{
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; /* marked */
obj->as.basic.flags |= FL_MARK;
switch (obj->as.basic.flags & T_MASK) {
case T_NIL:
case T_FIXNUM:
Bug("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:
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_CALL:
gc_mark(obj->as.node.u1.node);
/* fall through */
case NODE_SUPER: /* 3 */
case NODE_FCALL:
case NODE_NEWLINE:
obj = (RVALUE*)obj->as.node.u3.node;
goto Top;
case NODE_WHILE: /* 1,2 */
case NODE_UNTIL:
gc_mark(obj->as.node.u1.node);
/* fall through */
case NODE_METHOD: /* 2 */
case NODE_NOT:
obj = (RVALUE*)obj->as.node.u2.node;
goto Top;
case NODE_HASH: /* 1 */
case NODE_LIT:
case NODE_STR:
case NODE_XSTR:
case NODE_DEFINED:
obj = (RVALUE*)obj->as.node.u1.node;
goto Top;
case NODE_SCOPE: /* 2,3 */
gc_mark(obj->as.node.u3.node);
obj = (RVALUE*)obj->as.node.u2.node;
goto Top;
case NODE_ZARRAY: /* - */
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_UNDEF:
case NODE_SELF:
case NODE_NIL:
break;
default:
if (looks_pointerp(obj->as.node.u1.node)) {
gc_mark(obj->as.node.u1.node);
}
if (looks_pointerp(obj->as.node.u2.node)) {
gc_mark(obj->as.node.u2.node);
}
if (looks_pointerp(obj->as.node.u3.node)) {
obj = (RVALUE*)obj->as.node.u3.node;
goto Top;
}
}
return; /* no need to mark class. */
}
gc_mark(obj->as.basic.class);
switch (obj->as.basic.flags & T_MASK) {
case T_ICLASS:
gc_mark(obj->as.class.super);
mark_tbl(obj->as.class.iv_tbl);
mark_tbl(obj->as.class.m_tbl);
break;
case T_CLASS:
case T_MODULE:
gc_mark(obj->as.class.super);
mark_tbl(obj->as.class.m_tbl);
mark_tbl(obj->as.class.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++)
gc_mark(*ptr++);
}
break;
case T_HASH:
mark_hash(obj->as.hash.tbl);
break;
case T_STRING:
if (obj->as.string.orig) {
obj = (RVALUE*)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:
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 = (RVALUE*)obj->as.match.str;
goto Top;
}
break;
case T_VARMAP:
gc_mark(obj->as.varmap.val);
obj = (RVALUE*)obj->as.varmap.next;
goto Top;
break;
case T_SCOPE:
if (obj->as.scope.local_vars) {
int n = obj->as.scope.local_tbl[0]+1;
VALUE *vars = &obj->as.scope.local_vars[-1];
while (n--) {
gc_mark_maybe(*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++)
gc_mark(*ptr++);
}
break;
default:
Bug("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();
static void
gc_sweep()
{
RVALUE *p, *pend;
int freed = 0;
int i;
if (rb_in_compile) {
for (i = 0; i < heaps_used; i++) {
p = heaps[i]; pend = p + HEAP_SLOTS;
while (p < pend) {
if (!(p->as.basic.flags&FL_MARK) && BUILTIN_TYPE(p) == T_NODE)
gc_mark(p);
p++;
}
}
}
freelist = 0;
for (i = 0; i < heaps_used; i++) {
RVALUE *nfreelist;
int n = 0;
nfreelist = freelist;
p = heaps[i]; pend = p + HEAP_SLOTS;
while (p < pend) {
if (!(p->as.basic.flags & FL_MARK)) {
if (p->as.basic.flags) obj_free(p);
p->as.free.flag = 0;
p->as.free.next = nfreelist;
nfreelist = p;
n++;
}
else
RBASIC(p)->flags &= ~FL_MARK;
p++;
}
freed += n;
freelist = nfreelist;
}
if (freed < FREE_MIN) {
add_heap();
}
}
void
gc_force_recycle(p)
RVALUE *p;
{
p->as.free.flag = 0;
p->as.free.next = freelist;
freelist = p;
}
static int need_call_final = 0;
static void
obj_free(obj)
RVALUE *obj;
{
switch (obj->as.basic.flags & T_MASK) {
case T_NIL:
case T_FIXNUM:
case T_TRUE:
case T_FALSE:
Bug("obj_free() called for broken object");
break;
}
if (need_call_final) {
run_final(obj);
}
switch (obj->as.basic.flags & T_MASK) {
case T_OBJECT:
if (obj->as.object.iv_tbl) st_free_table(obj->as.object.iv_tbl);
break;
case T_MODULE:
case T_CLASS:
rb_clear_cache();
st_free_table(obj->as.class.m_tbl);
if (obj->as.object.iv_tbl) st_free_table(obj->as.object.iv_tbl);
break;
case T_STRING:
if (!obj->as.string.orig) free(obj->as.string.ptr);
break;
case T_ARRAY:
if (obj->as.array.ptr) free(obj->as.array.ptr);
break;
case T_HASH:
st_free_table(obj->as.hash.tbl);
break;
case T_REGEXP:
reg_free(obj->as.regexp.ptr);
free(obj->as.regexp.str);
break;
case T_DATA:
if (obj->as.data.dfree && DATA_PTR(obj))
(*obj->as.data.dfree)(DATA_PTR(obj));
break;
case T_MATCH:
re_free_registers(obj->as.match.regs);
free(obj->as.match.regs);
break;
case T_FILE:
io_fptr_finalize(obj->as.file.fptr);
free(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 (obj->as.bignum.digits) free(obj->as.bignum.digits);
break;
case T_NODE:
if (nd_type(obj) == NODE_SCOPE && obj->as.node.u1.tbl) {
free(obj->as.node.u1.tbl);
}
return; /* no need to free iv_tbl */
case T_SCOPE:
if (obj->as.scope.local_vars) {
VALUE *vars = obj->as.scope.local_vars-1;
if (vars[0] == 0)
free(obj->as.scope.local_tbl);
if (obj->as.scope.flag&SCOPE_MALLOC)
free(vars);
}
break;
case T_STRUCT:
free(obj->as.rstruct.ptr);
break;
default:
Bug("gc_sweep(): unknown data type %d", obj->as.basic.flags & T_MASK);
}
}
void
gc_mark_frame(frame)
struct FRAME *frame;
{
int n = frame->argc;
VALUE *tbl = frame->argv;
while (n--) {
gc_mark_maybe(*tbl);
tbl++;
}
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
gc()
{
struct gc_list *list;
struct FRAME *frame;
jmp_buf save_regs_gc_mark;
VALUE stack_end;
if (dont_gc) return;
dont_gc++;
malloc_memories = 0;
#ifdef C_ALLOCA
alloca(0);
#endif
/* mark frame stack */
for (frame = the_frame; frame; frame = frame->prev) {
gc_mark_frame(frame);
}
gc_mark(the_scope);
gc_mark(the_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 *));
gc_mark_locations(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
gc_mark_locations((VALUE*)((char*)gc_stack_start + 2),
(VALUE*)((char*)&stack_end + 2));
#endif
#ifdef THREAD
gc_mark_threads();
#endif
/* mark protected global variables */
for (list = Global_List; list; list = list->next) {
gc_mark(*list->varptr);
}
gc_mark_global_tbl();
mark_tbl(rb_class_tbl);
gc_mark_trap_list();
gc_sweep();
dont_gc--;
}
static VALUE
gc_method()
{
gc();
return Qnil;
}
void
init_stack()
{
#ifdef __human68k__
extern void *_SEND;
gc_stack_start = _SEND;
#else
VALUE start;
gc_stack_start = &start;
#endif
}
void
init_heap()
{
init_stack();
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(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 (obj_is_kind_of(p, of)) {
rb_yield(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;
{
extern VALUE cProc;
if (!obj_is_kind_of(proc, cProc)) {
ArgError("wrong type argument %s (Proc required)",
rb_class2name(CLASS_OF(proc)));
}
ary_push(finalizers, proc);
return proc;
}
static VALUE
rm_final(os, proc)
VALUE os, proc;
{
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 void
run_final(obj)
VALUE obj;
{
int i;
if (!FL_TEST(obj, FL_FINALIZE)) return;
obj |= FIXNUM_FLAG; /* make obj into id */
for (i=0; i<RARRAY(finalizers)->len; i++) {
rb_eval_cmd(RARRAY(finalizers)->ptr[i], obj);
}
}
extern VALUE cModule;
void
Init_GC()
{
VALUE mObSpace;
mGC = rb_define_module("GC");
rb_define_singleton_method(mGC, "start", gc_method, 0);
rb_define_singleton_method(mGC, "enable", gc_s_enable, 0);
rb_define_singleton_method(mGC, "disable", gc_s_disable, 0);
rb_define_method(mGC, "garbage_collect", gc_method, 0);
mObSpace = rb_define_module("ObjectSpace");
rb_define_module_function(mObSpace, "each_object", os_each_obj, -1);
rb_define_module_function(mObSpace, "garbage_collect", gc, 0);
rb_define_module_function(mObSpace, "add_finalizer", add_final, 1);
rb_define_module_function(mObSpace, "remove_finalizer", rm_final, 1);
rb_define_module_function(mObSpace, "finalizers", finals, 0);
rb_define_module_function(mObSpace, "call_finalizer", call_final, 1);
rb_global_variable(&finalizers);
finalizers = ary_new();
}

574
glob.c Normal file
Просмотреть файл

@ -0,0 +1,574 @@
/* File-name wildcard pattern matching for GNU.
Copyright (C) 1985, 1988, 1989 Free Software Foundation, Inc.
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 1, 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., 675 Mass Ave, Cambridge, MA 02139, USA. */
/* To whomever it may concern: I have never seen the code which most
Unix programs use to perform this function. I wrote this from scratch
based on specifications for the pattern matching. --RMS. */
#include "config.h"
#include <sys/types.h>
#if !defined (SHELL) && (defined (_POSIX_VERSION) || defined (USGr3))
# if !defined (HAVE_DIRENT_H)
# define HAVE_DIRENT_H
# endif /* !HAVE_DIRENT_H */
#endif /* !SHELL && (_POSIX_VERSION || USGr3) */
#if defined (HAVE_DIRENT_H)
# include <dirent.h>
# if !defined (direct)
# define direct dirent
# endif /* !direct */
# define D_NAMLEN(d) strlen ((d)->d_name)
#else /* !HAVE_DIRENT_H */
# define D_NAMLEN(d) ((d)->d_namlen)
# if defined (USG)
# if defined (Xenix)
# include <sys/ndir.h>
# else /* !Xenix (but USG...) */
# include "ndir.h"
# endif /* !Xenix */
# else /* !USG */
# if defined(NT)
# include "missing/dir.h"
# else
# include <sys/dir.h>
# endif /* !NT */
# endif /* !USG */
#endif /* !HAVE_DIRENT_H */
#if defined (_POSIX_SOURCE) || defined(DJGPP)
/* Posix does not require that the d_ino field be present, and some
systems do not provide it. */
# define REAL_DIR_ENTRY(dp) 1
#else
# define REAL_DIR_ENTRY(dp) (dp->d_ino != 0)
#endif /* _POSIX_SOURCE */
#if defined (USG) || defined (NeXT)
# if !defined (HAVE_STRING_H)
# define HAVE_STRING_H
# endif /* !HAVE_STRING_H */
#endif /* USG || NeXT */
#if defined (HAVE_STRING_H)
# include <string.h>
#else /* !HAVE_STRING_H */
# include <strings.h>
#endif /* !HAVE_STRING_H */
#ifndef bcopy
# define bcopy(s, d, n) (memcpy ((d), (s), (n)))
#endif
#ifdef _AIX
#pragma alloca
#else
#if defined(HAVE_ALLOCA_H) && !defined(__GNUC__)
#include <alloca.h>
#else
char *alloca ();
#endif
#endif
#include "fnmatch.h"
/* If the opendir () on your system lets you open non-directory files,
then we consider that not robust. Define OPENDIR_NOT_ROBUST in the
SYSDEP_CFLAGS for your machines entry in machines.h. */
#if defined (OPENDIR_NOT_ROBUST)
# if defined (SHELL)
# include "posixstat.h"
# else /* !SHELL */
# include <sys/stat.h>
# endif /* !SHELL */
#endif /* OPENDIR_NOT_ROBUST */
extern void *xmalloc (), *xrealloc ();
#if !defined (HAVE_STDLIB_H)
extern void free ();
#endif /* !HAVE_STDLIB_H */
#if !defined (NULL)
# if defined (__STDC__)
# define NULL ((void *) 0)
# else
# define NULL 0x0
# endif /* __STDC__ */
#endif /* !NULL */
#if defined (SHELL)
extern int interrupt_state;
#endif /* SHELL */
/* Global variable which controls whether or not * matches .*.
Non-zero means don't match .*. */
int noglob_dot_filenames = 1;
/* Global variable to return to signify an error in globbing. */
char *glob_error_return;
/* Return nonzero if PATTERN has any special globbing chars in it. */
int
glob_pattern_p (pattern)
char *pattern;
{
register char *p = pattern;
register char c;
int open = 0;
while ((c = *p++) != '\0')
switch (c)
{
case '?':
case '*':
return (1);
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 (1);
continue;
case '\\':
if (*p++ == '\0')
return (0);
}
return (0);
}
/* Remove backslashes quoting characters in PATHNAME by modifying PATHNAME. */
static void
dequote_pathname (pathname)
char *pathname;
{
register int i, j;
for (i = j = 0; pathname && pathname[i]; )
{
if (pathname[i] == '\\')
i++;
pathname[j++] = pathname[i++];
if (!pathname[i - 1])
break;
}
pathname[j] = '\0';
}
/* Return a vector of names of files in directory DIR
whose names match glob pattern PAT.
The names are not in any particular order.
Wildcards at the beginning of PAT do not match an initial period.
The vector is terminated by an element that is a null pointer.
To free the space allocated, first free the vector's elements,
then free the vector.
Return 0 if cannot get enough memory to hold the pointer
and the names.
Return -1 if cannot access directory DIR.
Look in errno for more information. */
char **
glob_vector (pat, dir)
char *pat;
char *dir;
{
struct globval
{
struct globval *next;
char *name;
};
DIR *d;
register struct direct *dp;
struct globval *lastlink;
register struct globval *nextlink;
register char *nextname;
unsigned int count;
int lose, skip;
register char **name_vector;
register unsigned int i;
#if defined (OPENDIR_NOT_ROBUST)
struct stat finfo;
if (stat (dir, &finfo) < 0)
return ((char **) &glob_error_return);
if (!S_ISDIR (finfo.st_mode))
return ((char **) &glob_error_return);
#endif /* OPENDIR_NOT_ROBUST */
d = opendir (dir);
if (d == NULL)
return ((char **) &glob_error_return);
lastlink = 0;
count = 0;
lose = 0;
skip = 0;
/* If PAT is empty, skip the loop, but return one (empty) filename. */
if (!pat || !*pat)
{
nextlink = (struct globval *)alloca (sizeof (struct globval));
nextlink->next = lastlink;
nextname = (char *) xmalloc (1);
if (!nextname)
lose = 1;
else
{
lastlink = nextlink;
nextlink->name = nextname;
nextname[0] = '\0';
count++;
}
skip = 1;
}
/* Scan the directory, finding all names that match.
For each name that matches, allocate a struct globval
on the stack and store the name in it.
Chain those structs together; lastlink is the front of the chain. */
while (!skip)
{
int flags; /* Flags passed to fnmatch (). */
#if defined (SHELL)
/* Make globbing interruptible in the bash shell. */
if (interrupt_state)
{
closedir (d);
lose = 1;
goto lost;
}
#endif /* SHELL */
dp = readdir (d);
if (dp == NULL)
break;
/* If this directory entry is not to be used, try again. */
if (!REAL_DIR_ENTRY (dp))
continue;
/* If a dot must be explicity matched, check to see if they do. */
if (noglob_dot_filenames && dp->d_name[0] == '.' && pat[0] != '.')
continue;
flags = (noglob_dot_filenames ? FNM_PERIOD : 0) | FNM_PATHNAME;
if (fnmatch (pat, dp->d_name, flags) != FNM_NOMATCH)
{
nextlink = (struct globval *) alloca (sizeof (struct globval));
nextlink->next = lastlink;
nextname = (char *) xmalloc (D_NAMLEN (dp) + 1);
if (nextname == NULL)
{
lose = 1;
break;
}
lastlink = nextlink;
nextlink->name = nextname;
bcopy (dp->d_name, nextname, D_NAMLEN (dp) + 1);
++count;
}
}
(void) closedir (d);
if (!lose)
{
name_vector = (char **) xmalloc ((count + 1) * sizeof (char *));
lose |= name_vector == NULL;
}
/* Have we run out of memory? */
lost:
if (lose)
{
/* Here free the strings we have got. */
while (lastlink)
{
free (lastlink->name);
lastlink = lastlink->next;
}
#if defined (SHELL)
if (interrupt_state)
throw_to_top_level ();
#endif /* SHELL */
return (NULL);
}
/* Copy the name pointers from the linked list into the vector. */
for (i = 0; i < count; ++i)
{
name_vector[i] = lastlink->name;
lastlink = lastlink->next;
}
name_vector[count] = NULL;
return (name_vector);
}
/* Return a new array which is the concatenation of each string in ARRAY
to DIR. This function expects you to pass in an allocated ARRAY, and
it takes care of free()ing that array. Thus, you might think of this
function as side-effecting ARRAY. */
static char **
glob_dir_to_array (dir, array)
char *dir, **array;
{
register unsigned int i, l;
int add_slash;
char **result;
l = strlen (dir);
if (l == 0)
return (array);
add_slash = dir[l - 1] != '/';
i = 0;
while (array[i] != NULL)
++i;
result = (char **) xmalloc ((i + 1) * sizeof (char *));
if (result == NULL)
return (NULL);
for (i = 0; array[i] != NULL; i++)
{
result[i] = (char *) xmalloc (l + (add_slash ? 1 : 0)
+ strlen (array[i]) + 1);
if (result[i] == NULL)
return (NULL);
sprintf (result[i], "%s%s%s", dir, add_slash ? "/" : "", array[i]);
}
result[i] = NULL;
/* Free the input array. */
for (i = 0; array[i] != NULL; i++)
free (array[i]);
free ((char *) array);
return (result);
}
/* Do globbing on PATHNAME. Return an array of pathnames that match,
marking the end of the array with a null-pointer as an element.
If no pathnames match, then the array is empty (first element is null).
If there isn't enough memory, then return NULL.
If a file system error occurs, return -1; `errno' has the error code. */
char **
glob_filename (pathname)
char *pathname;
{
#ifndef strrchr
char *strrchr();
#endif
char **result;
unsigned int result_size;
char *directory_name, *filename;
unsigned int directory_len;
result = (char **) xmalloc (sizeof (char *));
result_size = 1;
if (result == NULL)
return (NULL);
result[0] = NULL;
/* Find the filename. */
filename = strrchr (pathname, '/');
if (filename == NULL)
{
filename = pathname;
directory_name = "";
directory_len = 0;
}
else
{
directory_len = (filename - pathname) + 1;
directory_name = (char *) alloca (directory_len + 1);
bcopy (pathname, directory_name, directory_len);
directory_name[directory_len] = '\0';
++filename;
}
/* If directory_name contains globbing characters, then we
have to expand the previous levels. Just recurse. */
if (glob_pattern_p (directory_name))
{
char **directories;
register unsigned int i;
if (directory_name[directory_len - 1] == '/')
directory_name[directory_len - 1] = '\0';
directories = glob_filename (directory_name);
if (directories == NULL)
goto memory_error;
else if (directories == (char **)&glob_error_return)
return ((char **) &glob_error_return);
else if (*directories == NULL)
{
free ((char *) directories);
return ((char **) &glob_error_return);
}
/* We have successfully globbed the preceding directory name.
For each name in DIRECTORIES, call glob_vector on it and
FILENAME. Concatenate the results together. */
for (i = 0; directories[i] != NULL; ++i)
{
char **temp_results;
/* Scan directory even on a NULL pathname. That way, `*h/'
returns only directories ending in `h', instead of all
files ending in `h' with a `/' appended. */
temp_results = glob_vector (filename, directories[i]);
/* Handle error cases. */
if (temp_results == NULL)
goto memory_error;
else if (temp_results == (char **)&glob_error_return)
/* This filename is probably not a directory. Ignore it. */
;
else
{
char **array;
register unsigned int l;
array = glob_dir_to_array (directories[i], temp_results);
l = 0;
while (array[l] != NULL)
++l;
result =
(char **)xrealloc(result, (result_size + l) * sizeof (char *));
if (result == NULL)
goto memory_error;
for (l = 0; array[l] != NULL; ++l)
result[result_size++ - 1] = array[l];
result[result_size - 1] = NULL;
/* Note that the elements of ARRAY are not freed. */
free ((char *) array);
}
}
/* Free the directories. */
for (i = 0; directories[i]; i++)
free (directories[i]);
free ((char *) directories);
return (result);
}
/* If there is only a directory name, return it. */
if (*filename == '\0')
{
result = (char **) xrealloc ((char *) result, 2 * sizeof (char *));
if (result == NULL)
return (NULL);
result[0] = (char *) xmalloc (directory_len + 1);
if (result[0] == NULL)
goto memory_error;
bcopy (directory_name, result[0], directory_len + 1);
result[1] = NULL;
return (result);
}
else
{
char **temp_results;
/* There are no unquoted globbing characters in DIRECTORY_NAME.
Dequote it before we try to open the directory since there may
be quoted globbing characters which should be treated verbatim. */
if (directory_len > 0)
dequote_pathname (directory_name);
/* We allocated a small array called RESULT, which we won't be using.
Free that memory now. */
free (result);
/* Just return what glob_vector () returns appended to the
directory name. */
temp_results =
glob_vector (filename, (directory_len == 0 ? "." : directory_name));
if (temp_results == NULL || temp_results == (char **)&glob_error_return)
return (temp_results);
return (glob_dir_to_array (directory_name, temp_results));
}
/* We get to memory_error if the program has run out of memory, or
if this is the shell, and we have been interrupted. */
memory_error:
if (result != NULL)
{
register unsigned int i;
for (i = 0; result[i] != NULL; ++i)
free (result[i]);
free ((char *) result);
}
#if defined (SHELL)
if (interrupt_state)
throw_to_top_level ();
#endif /* SHELL */
return (NULL);
}
#if defined (TEST)
main (argc, argv)
int argc;
char **argv;
{
unsigned int i;
for (i = 1; i < argc; ++i)
{
char **value = glob_filename (argv[i]);
if (value == NULL)
puts ("Out of memory.");
else if (value == &glob_error_return)
perror (argv[i]);
else
for (i = 0; value[i] != NULL; i++)
puts (value[i]);
}
exit (0);
}
#endif /* TEST. */

1005
hash.c Normal file

Разница между файлами не показана из-за своего большого размера Загрузить разницу

48
inits.c Normal file
Просмотреть файл

@ -0,0 +1,48 @@
/************************************************
inits.c -
$Author$
$Date$
created at: Tue Dec 28 16:01:58 JST 1993
Copyright (C) 1993-1996 Yukihiro Matsumoto
************************************************/
#include "ruby.h"
void
rb_call_inits()
{
Init_sym();
Init_var_tables();
Init_Object();
#ifdef THREAD
Init_Thread();
#endif
Init_eval();
Init_Comparable();
Init_Enumerable();
Init_String();
Init_Exception();
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_version();
}

238
install-sh Normal file
Просмотреть файл

@ -0,0 +1,238 @@
#! /bin/sh
#
# install - install a program, script, or datafile
# This comes from X11R5.
#
# Calling this script install-sh is preferred over install.sh, to prevent
# `make' implicit rules from creating a file called install from it
# when there is no Makefile.
#
# This script is compatible with the BSD install script, but was written
# from scratch.
#
# set DOITPROG to echo to test this script
# Don't use :- since 4.3BSD and earlier shells don't like it.
doit="${DOITPROG-}"
# put in absolute paths if you don't have them in your path; or use env. vars.
mvprog="${MVPROG-mv}"
cpprog="${CPPROG-cp}"
chmodprog="${CHMODPROG-chmod}"
chownprog="${CHOWNPROG-chown}"
chgrpprog="${CHGRPPROG-chgrp}"
stripprog="${STRIPPROG-strip}"
rmprog="${RMPROG-rm}"
mkdirprog="${MKDIRPROG-mkdir}"
tranformbasename=""
transform_arg=""
instcmd="$mvprog"
chmodcmd="$chmodprog 0755"
chowncmd=""
chgrpcmd=""
stripcmd=""
rmcmd="$rmprog -f"
mvcmd="$mvprog"
src=""
dst=""
dir_arg=""
while [ x"$1" != x ]; do
case $1 in
-c) instcmd="$cpprog"
shift
continue;;
-d) dir_arg=true
shift
continue;;
-m) chmodcmd="$chmodprog $2"
shift
shift
continue;;
-o) chowncmd="$chownprog $2"
shift
shift
continue;;
-g) chgrpcmd="$chgrpprog $2"
shift
shift
continue;;
-s) stripcmd="$stripprog"
shift
continue;;
-t=*) transformarg=`echo $1 | sed 's/-t=//'`
shift
continue;;
-b=*) transformbasename=`echo $1 | sed 's/-b=//'`
shift
continue;;
*) if [ x"$src" = x ]
then
src=$1
else
# this colon is to work around a 386BSD /bin/sh bug
:
dst=$1
fi
shift
continue;;
esac
done
if [ x"$src" = x ]
then
echo "install: no input file specified"
exit 1
else
true
fi
if [ x"$dir_arg" != x ]; then
dst=$src
src=""
if [ -d $dst ]; then
instcmd=:
else
instcmd=mkdir
fi
else
# Waiting for this to be detected by the "$instcmd $src $dsttmp" command
# might cause directories to be created, which would be especially bad
# if $src (and thus $dsttmp) contains '*'.
if [ -f $src -o -d $src ]
then
true
else
echo "install: $src does not exist"
exit 1
fi
if [ x"$dst" = x ]
then
echo "install: no destination specified"
exit 1
else
true
fi
# If destination is a directory, append the input filename; if your system
# does not like double slashes in filenames, you may need to add some logic
if [ -d $dst ]
then
dst="$dst"/`basename $src`
else
true
fi
fi
## this sed command emulates the dirname command
dstdir=`echo $dst | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'`
# Make sure that the destination directory exists.
# this part is taken from Noah Friedman's mkinstalldirs script
# Skip lots of stat calls in the usual case.
if [ ! -d "$dstdir" ]; then
defaultIFS='
'
IFS="${IFS-${defaultIFS}}"
oIFS="${IFS}"
# Some sh's can't handle IFS=/ for some reason.
IFS='%'
set - `echo ${dstdir} | sed -e 's@/@%@g' -e 's@^%@/@'`
IFS="${oIFS}"
pathcomp=''
while [ $# -ne 0 ] ; do
pathcomp="${pathcomp}${1}"
shift
if [ ! -d "${pathcomp}" ] ;
then
$mkdirprog "${pathcomp}"
else
true
fi
pathcomp="${pathcomp}/"
done
fi
if [ x"$dir_arg" != x ]
then
$doit $instcmd $dst &&
if [ x"$chowncmd" != x ]; then $doit $chowncmd $dst; else true ; fi &&
if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dst; else true ; fi &&
if [ x"$stripcmd" != x ]; then $doit $stripcmd $dst; else true ; fi &&
if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dst; else true ; fi
else
# If we're going to rename the final executable, determine the name now.
if [ x"$transformarg" = x ]
then
dstfile=`basename $dst`
else
dstfile=`basename $dst $transformbasename |
sed $transformarg`$transformbasename
fi
# don't allow the sed command to completely eliminate the filename
if [ x"$dstfile" = x ]
then
dstfile=`basename $dst`
else
true
fi
# Make a temp file name in the proper directory.
dsttmp=$dstdir/#inst.$$#
# Move or copy the file name to the temp name
$doit $instcmd $src $dsttmp &&
trap "rm -f ${dsttmp}" 0 &&
# and set any options; do chmod last to preserve setuid bits
# If any of these fail, we abort the whole thing. If we want to
# ignore errors from any of these, just make sure not to ignore
# errors from the above "$doit $instcmd $src $dsttmp" command.
if [ x"$chowncmd" != x ]; then $doit $chowncmd $dsttmp; else true;fi &&
if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dsttmp; else true;fi &&
if [ x"$stripcmd" != x ]; then $doit $stripcmd $dsttmp; else true;fi &&
if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dsttmp; else true;fi &&
# Now rename the file to the real destination.
$doit $rmcmd -f $dstdir/$dstfile &&
$doit $mvcmd $dsttmp $dstdir/$dstfile
fi &&
exit 0

2306
io.c Normal file

Разница между файлами не показана из-за своего большого размера Загрузить разницу

53
io.h Normal file
Просмотреть файл

@ -0,0 +1,53 @@
/************************************************
io.h -
$Author$
$Revision$
$Date$
created at: Fri Nov 12 16:47:09 JST 1993
Copyright (C) 1993-1996 Yukihiro Matsumoto
************************************************/
#ifndef IO_H
#define IO_H
#include "sig.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) ((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 GetWriteFile(fptr) (((fptr)->f2) ? (fptr)->f2 : (fptr)->f)
FILE *rb_fopen();
#endif

28
lib/English.rb Normal file
Просмотреть файл

@ -0,0 +1,28 @@
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 $+

54
lib/base64.rb Normal file
Просмотреть файл

@ -0,0 +1,54 @@
def decode64(str)
string = ''
for line in str.split("\n")
line.delete!('^A-Za-z0-9+/') # remove non-base64 chars
line.tr!('A-Za-z0-9+/', ' -_') # convert to uuencoded format
len = ["#{32 + line.length * 3 / 4}"].pack("c")
# compute length byte
string += "#{len}#{line}".unpack("u") # uudecode and concatenate
end
return string
end
def j2e(str)
while str =~ /\033\$B([^\033]*)\033\(B/
s = $1
pre, post = $`, $'
s.gsub!(/./) { |ch|
(ch[0]|0x80).chr
}
str = pre + s + post
end
# str.gsub!(/\033\$B([^\033]*)\033\(B/) {
# $1.gsub!(/./) { |ch|
# (ch[0]|0x80).chr
# }
# }
str
end
def decode_b(str)
str.gsub!(/=\?ISO-2022-JP\?B\?([!->@-~]+)\?=/i) {
decode64($1)
}
str.gsub!(/\n/, ' ')
str.gsub!(/\0/, '')
j2e(str)
end
def encode64(bin)
encode = ""
pad = 0
[bin].pack("u").each do |uu|
len = (2 + (uu[0] - 32)* 4) / 3
encode << uu[1, len].tr('` -_', 'AA-Za-z0-9+/')
pad += uu.length - 2 - len
end
encode + "=" * (pad % 3)
end
def b64encode(bin, len = 60)
encode64(bin).scan(/.{1,#{len}}/o) do
print $&, "\n"
end
end

56
lib/cgi-lib.rb Normal file
Просмотреть файл

@ -0,0 +1,56 @@
#!/usr/local/bin/ruby
#
# Get CGI String
#
# EXAMPLE:
# require "cgi-lib.rb"
# foo = CGI.new
# foo['field'] <== value of 'field'
# foo.keys <== array of fields
# foo.inputs <== hash of { <field> => <value> }
class CGI
attr("inputs")
def initialize
str = if ENV['REQUEST_METHOD'] == "GET"
ENV['QUERY_STRING']
elsif ENV['REQUEST_METHOD'] == "POST"
$stdin.read ENV['CONTENT_LENGTH'].to_i
else
""
end
arr = str.split(/&/)
@inputs = {}
arr.each do |x|
x.gsub!(/\+/, ' ')
key, val = x.split(/=/, 2)
val = "" unless val
key.gsub!(/%(..)/) { [$1.hex].pack("c") }
val.gsub!(/%(..)/) { [$1.hex].pack("c") }
@inputs[key] += "\0" if @inputs[key]
@inputs[key] += val
end
end
def keys
@inputs.keys
end
def [](key)
@inputs[key]
end
def CGI.message(msg, title = "")
print "Content-type: text/html\n\n"
print "<html><head><title>"
print title
print "</title></head><body>\n"
print msg
print "</body></html>\n"
TRUE
end
end

490
lib/complex.rb Normal file
Просмотреть файл

@ -0,0 +1,490 @@
#
# complex.rb -
# $Release Version: 0.5 $
# $Revision: 1.1 $
# $Date: 1996/11/11 04:25:19 $
# 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
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)
@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 = a.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 = a.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 = a.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 = a.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 = a.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 = a.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 = a.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 = a.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
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

227
lib/date.rb Normal file
Просмотреть файл

@ -0,0 +1,227 @@
#
# Date.rb -
# $Release Version: $
# $Revision: 1.2 $
# $Date: 1997/02/14 11:05:29 $
# 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
def initialize(y = 1, m = 1, d = 1)
if y.kind_of?(String) && y.size == 8
@year = y[0,4].to_i
@month = y[4,2].to_i
@day = y[6,2].to_i
else
if m.kind_of?(String)
ml = {"jan"=>1, "feb"=>2, "mar"=>3, "apr"=>4, "may"=>5, "jun"=>6, "jul"=>7, "aug"=>8, "sep"=>9, "oct"=>10, "nov"=>11, "dec"=>12}
m = ml[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 day_of_week
dl = Date.daylist(@year)
d = Date.jan1!(@year)
for m in 1..(@month - 1)
d += dl[m]
end
d += @day - 1
if @year == 1752 && @month == 9 && @day >= 14
d -= (14 - 3)
end
return (d % 7)
end
Weektag = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
def name_of_week
return Weektag[self.day_of_week]
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
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?
if Date.leapyear(@year) == 1
return FALSE
else
return TRUE
end
end
def _check_date
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(1900+d.year, d.mon+1, 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 - 1) > 1752
p -= ((y - 1 - 1752) / 100.0).to_i
p += ((y - 1 - 1752) / 400.0).to_i
p -= (14 - 3)
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

262
lib/debug.rb Normal file
Просмотреть файл

@ -0,0 +1,262 @@
class DEBUGGER__
trap("INT") { DEBUGGER__::CONTEXT.interrupt }
$DEBUG = TRUE
def initialize
@break_points = []
@stop_next = 1
@frames = [nil]
@frame_pos = nil
@last_file = nil
@scripts = {}
end
def interrupt
@stop_next = 1
end
def debug_eval(str, binding)
begin
val = eval(str, binding)
val
rescue
at = caller(0)
printf "%s:%s\n", at.shift, $!
for i in at
break if i =~ /`debug_(eval|command)'$/ #`
printf "\tfrom %s\n", i
end
end
end
def debug_command(file, line, id, binding)
if (ENV['EMACS'] == 't')
printf "\032\032%s:%d:\n", file, line
else
printf "%s:%d:%s", file, line, line_at(file, line)
end
@frames[-1] = binding
STDOUT.print "(rdb:-) "
STDOUT.flush
while input = STDIN.gets
input.chop!
case input
when /^b(reak)?\s+(([^:\n]+:)?.+)/
pos = $2
if pos.index ":"
file, pos = pos.split(":")
end
file = File.basename(file)
if pos =~ /^\d+$/
pname = pos
pos = Integer(pos)
else
pname = pos = pos.intern.id2name
end
printf "Set breakpoint %d at %s:%s\n", @break_points.size, file, pname
@break_points.push [file, pos]
when /^b(reak)?$/, /^info b(reak)?$/
n = 0
for f, p in @break_points
printf "%d %s:%s\n", n, f, p
n += 1
end
when /^del(ete)?(\s+(\d+))?$/
pos = $3
unless pos
STDOUT.print "clear all breakpoints? (y/n) "
STDOUT.flush
input = STDIN.gets.chop!
if input == "y"
for n in @break_points.indexes
@break_points[n] = nil
end
end
else
pos = Integer(pos)
if @break_points[pos]
bp = @break_points[pos]
printf "Clear breakpoint %d at %s:%s\n", pos, bp[0], bp[1]
@break_points[pos] = nil
else
printf "Breakpoint %d is not defined\n", pos
end
end
when /^c(ont)?$/
return
when /^s(tep)?\s*(\d+)?$/
if $1
lev = Integer($1)
else
lev = 1
end
@stop_next = lev
return
when /^n(ext)?\s*(\d+)?$/
if $1
lev = Integer($1)
else
lev = 1
end
@stop_next = lev
@no_step = @frames.size
return
when /^up\s*(\d+)?$/
if $1
lev = Integer($1)
else
lev = 1
end
unless @frame_pos
@frame_pos = @frames.size - 1
end
@frame_pos -= lev
if @frame_pos < 0
STDOUT.print "at toplevel\n"
@frame_pos = 0
else
binding = @frames[@frame_pos]
end
when /^down\s*(\d+)??$/
if $1
lev = Integer($1)
else
lev = 1
end
if lev >= @frames.size or @frame_pos and @frame_pos+lev >= @frames.size
STDOUT.print "at stack bottom\n"
@frame_pos = nil
else
@frame_pos += lev
binding = @frames[@frame_pos]
end
when /^fin(ish)?$/
@finish_pos = @frames.size
return
when /^q(uit)?$/
STDOUT.print "really quit? (y/n) "
STDOUT.flush
input = STDIN.gets.chop!
exit if input == "y"
when /^where$/
at = caller(4)
for i in at
printf " %s\n", i
end
when /^l(ist)?(\s+(.*))?$/
if $3
b, e = $3.split(/[-,]/)
b = Integer(b)-1
if e
e = Integer(e)-1
else
e = b + 10
end
end
unless b
b = line - 1
e = line + 9
end
p [b,e]
line_at(file, line)
if lines = @scripts[file] and lines != TRUE
n = b+1
for l in lines[b..e]
printf "%4d %s", n, l
n += 1
end
else
printf "no sourcefile available for %s\n", file
end
when /^p\s+/
p debug_eval($', binding)
else
v = debug_eval(input, binding)
p v unless v == nil
end
STDOUT.print "(rdb:-) "
STDOUT.flush
end
end
def line_at(file, line)
lines = @scripts[file]
if lines
return "\n" if lines == TRUE
line = lines[line-1]
return "\n" unless line
return line
end
begin
f = open(file)
lines = @scripts[file] = f.readlines
rescue
@scripts[file] = TRUE
return "\n"
end
line = lines[line-1]
return "\n" unless line
return line
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)
if @break_points.include? [file, pos]
index = @break_points.index([file, pos])
printf "Breakpoint %d, %s at %s:%s\n",
index, debug_funcname(id), file, pos
return TRUE
end
return FALSE
end
def trace_func(event, file, line, id, binding)
if event == 'line'
if @no_step == nil or @no_step >= @frames.size
@stop_next -= 1
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
end
if event == 'call'
@frames.push binding
if check_break_points(file, id.id2name, binding, id)
debug_command(file, line, id, binding)
end
end
if event == 'class'
@frames.push binding
end
if event == 'return' or event == 'end'
if @finish_pos == @frames.size
@stop_next = 1
end
@frames.pop
end
@last_file = file
end
CONTEXT = new
end
set_trace_func proc{|event, file, line, id, binding|
DEBUGGER__::CONTEXT.trace_func event, file, line, id, binding
}

94
lib/e2mmap.rb Normal file
Просмотреть файл

@ -0,0 +1,94 @@
#
# e2mmap.rb - for ruby 1.1
# $Release Version: 1.1$
# $Revision: 1.4 $
# $Date: 1997/08/18 07:12:12 $
# by Keiju ISHITSUKA
#
# --
#
#
if VERSION < "1.1"
require "e2mmap1_0.rb"
else
module Exception2MessageMapper
RCS_ID='-$Header: /home/keiju/var/src/var.lib/ruby/RCS/e2mmap.rb,v 1.4 1997/08/18 07:12:12 keiju Exp keiju $-'
E2MM = Exception2MessageMapper
def E2MM.extend_object(cl)
super
cl.bind(self)
end
# 以前との互換性のために残してある.
def E2MM.extend_to(b)
c = eval("self", b)
c.extend(self)
end
# public :fail
# alias e2mm_fail fail
def fail(err = nil, *rest)
Exception2MessageMapper.fail Exception2MessageMapper::ErrNotRegisteredException, err.to_s
end
def bind(cl)
self.module_eval %q^
E2MM_ErrorMSG = {}
# fail(err, *rest)
# err: 例外
# rest: メッセージに渡すパラメータ
#
def self.fail(err = nil, *rest)
$@ = caller(0) if $@.nil?
$@.shift
if form = E2MM_ErrorMSG[err]
$! = err.new(sprintf(form, *rest))
# e2mm_fail()
raise()
# elsif self == Exception2MessageMapper
# fail Exception2MessageMapper::ErrNotRegisteredException, err.to_s
else
# print "super\n"
super
end
end
class << self
public :fail
end
# def_exception(c, m)
# c: exception
# m: message_form
# 例外cのメッセージをmとする.
#
def self.def_e2message(c, m)
E2MM_ErrorMSG[c] = m
end
# def_exception(c, m)
# n: exception_name
# m: message_form
# s: 例外スーパークラス(デフォルト: Exception)
# 例外名``c''をもつ例外を定義し, そのメッセージをmとする.
#
#def def_exception(n, m)
def self.def_exception(n, m, s = Exception)
n = n.id2name if n.kind_of?(Fixnum)
e = Class.new(s)
const_set(n, e)
E2MM_ErrorMSG[e] = m
# const_get(:E2MM_ErrorMSG)[e] = m
end
^
end
extend E2MM
def_exception(:ErrNotClassOrModule, "Not Class or Module")
def_exception(:ErrNotRegisteredException, "not registerd exception(%s)")
end
end

71
lib/e2mmap1_0.rb Normal file
Просмотреть файл

@ -0,0 +1,71 @@
#
# e2mmap.rb -
# $Release Version: 1.0$
# $Revision$
# $Date$
# by Keiju ISHITSUKA
#
# --
#
#
module Exception2MessageMapper
RCS_ID='-$Header$-'
E2MM = Exception2MessageMapper
def E2MM.extend_to(b)
c = eval("self", b)
c.extend(self)
c.bind(b)
end
def bind(b)
eval "
@binding = binding
E2MM_ErrorMSG = Hash.new
# fail(err, *rest)
# err: 例外
# rest: メッセージに渡すパラメータ
#
def fail!(*rest)
super
end
def fail(err, *rest)
$! = err.new(sprintf(E2MM_ErrorMSG[err], *rest))
super()
end
public :fail
# def_exception(c, m)
# c: exception
# m: message_form
# 例外cのメッセージをmとする.
#
def def_e2message(c, m)
E2MM_ErrorMSG[c] = m
end
# def_exception(c, m)
# c: exception_name
# m: message_form
# s: 例外スーパークラス(デフォルト: Exception)
# 例外名``c''をもつ例外を定義し, そのメッセージをmとする.
#
def def_exception(c, m)
c = c.id2name if c.kind_of?(Fixnum)
eval \"class \#{c} < Exception
end
E2MM_ErrorMSG[\#{c}] = '\#{m}'
\", @binding
end
", b
end
E2MM.extend_to(binding)
def_exception("ErrNotClassOrModule", "Not Class or Module")
end

205
lib/finalize.rb Normal file
Просмотреть файл

@ -0,0 +1,205 @@
#
# finalize.rb -
# $Release Version: $
# $Revision: 1.2 $
# $Date: 1997/07/25 02:43:00 $
# by Keiju ISHITSUKA(SHL Japan Inc.)
#
# --
#
# Usage:
#
# add(obj, dependant, method = :finalize, *opt)
# add_dependency(obj, dependant, method = :finalize, *opt)
# 依存関係 R_method(obj, dependant) の追加
#
# delete(obj_or_id, dependant, method = :finalize)
# delete_dependency(obj_or_id, dependant, method = :finalize)
# 依存関係 R_method(obj, dependant) の削除
# delete_all_dependency(obj_or_id, dependant)
# 依存関係 R_*(obj, dependant) の削除
# delete_by_dependant(dependant, method = :finalize)
# 依存関係 R_method(*, dependant) の削除
# delete_all_by_dependant(dependant)
# 依存関係 R_*(*, dependant) の削除
# delete_all
# 全ての依存関係の削除.
#
# finalize(obj_or_id, dependant, method = :finalize)
# finalize_dependency(obj_or_id, dependant, method = :finalize)
# 依存関連 R_method(obj, dependtant) で結ばれるdependantを
# finalizeする.
# finalize_all_dependency(obj_or_id, dependant)
# 依存関連 R_*(obj, dependtant) で結ばれるdependantをfinalizeする.
# finalize_by_dependant(dependant, method = :finalize)
# 依存関連 R_method(*, dependtant) で結ばれるdependantをfinalizeする.
# fainalize_all_by_dependant(dependant)
# 依存関連 R_*(*, dependtant) で結ばれるdependantをfinalizeする.
# finalize_all
# Finalizerに登録される全てのdependantをfinalizeする
#
# safe{..}
# gc時にFinalizerが起動するのを止める.
#
#
module Finalizer
RCS_ID='-$Header: /home/keiju/var/src/var.lib/ruby/RCS/finalize.rb,v 1.2 1997/07/25 02:43:00 keiju Exp keiju $-'
# @dependency: {id => [[dependant, method, *opt], ...], ...}
# 依存関係 R_method(obj, dependant) の追加
def add_dependency(obj, dependant, method = :finalize, *opt)
ObjectSpace.call_finalizer(obj)
method = method.id unless method.kind_of?(Fixnum)
assoc = [dependant, method].concat(opt)
if dep = @dependency[obj.id]
dep.push assoc
else
@dependency[obj.id] = [assoc]
end
end
alias add add_dependency
# 依存関係 R_method(obj, dependant) の削除
def delete_dependency(id, dependant, method = :finalize)
id = id.id unless id.kind_of?(Fixnum)
method = method.id unless method.kind_of?(Fixnum)
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
# 依存関係 R_*(obj, dependant) の削除
def delete_all_dependency(id, dependant)
id = id.id unless id.kind_of?(Fixnum)
method = method.id unless method.kind_of?(Fixnum)
for assoc in @dependency[id]
assoc.delete_if do
|d, m, *o|
d == dependant
end
@dependency.delete(id) if assoc.empty?
end
end
# 依存関係 R_method(*, dependant) の削除
def delete_by_dependant(dependant, method = :finalize)
method = method.id unless method.kind_of?(Fixnum)
for id in @dependency.keys
delete(id, dependant, method)
end
end
# 依存関係 R_*(*, dependant) の削除
def delete_all_by_dependant(dependant)
for id in @dependency.keys
delete_all_dependency(id, dependant)
end
end
# 依存関連 R_method(obj, dependtant) で結ばれるdependantをfinalizeす
# る.
def finalize_dependency(id, dependant, method = :finalize)
id = id.id unless id.kind_of?(Fixnum)
method = method.id unless method.kind_of?(Fixnum)
for assocs in @dependency[id]
assocs.delete_if do
|d, m, *o|
d.send(m, *o) if ret = d == dependant && m == method
ret
end
@dependency.delete(id) if assoc.empty?
end
end
alias finalize finalize_dependency
# 依存関連 R_*(obj, dependtant) で結ばれるdependantをfinalizeする.
def finalize_all_dependency(id, dependant)
id = id.id unless id.kind_of?(Fixnum)
method = method.id unless method.kind_of?(Fixnum)
for assoc in @dependency[id]
assoc.delete_if do
|d, m, *o|
d.send(m, *o) if ret = d == dependant
end
@dependency.delete(id) if assoc.empty?
end
end
# 依存関連 R_method(*, dependtant) で結ばれるdependantをfinalizeする.
def finalize_by_dependant(dependant, method = :finalize)
method = method.id unless method.kind_of?(Fixnum)
for id in @dependency.keys
finalize(id, dependant, method)
end
end
# 依存関連 R_*(*, dependtant) で結ばれるdependantをfinalizeする.
def fainalize_all_by_dependant(dependant)
for id in @dependency.keys
finalize_all_dependency(id, dependant)
end
end
# Finalizerに登録されている全てのdependantをfinalizeする
def finalize_all
for id, assocs in @dependency
for dependant, method, *opt in assocs
dependant.send(method, id, *opt)
end
assocs.clear
end
end
# finalize_* を安全に呼び出すためのイテレータ
def safe
old_status = Thread.critical
Thread.critical = TRUE
ObjectSpace.remove_finalizer(@proc)
yield
ObjectSpace.add_finalizer(@proc)
Thread.critical = old_status
end
# 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

39
lib/find.rb Normal file
Просмотреть файл

@ -0,0 +1,39 @@
# Usage:
# require "find.rb"
#
# 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 and not File.symlink? 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

617
lib/ftplib.rb Normal file
Просмотреть файл

@ -0,0 +1,617 @@
### ftplib.rb -*- Mode: ruby; tab-width: 8; -*-
## $Revision: 1.5 $
## $Date: 1997/09/16 08:03:31 $
## by maeda shugo <shugo@po.aianet.ne.jp>
### Code:
require "socket"
require "sync" if defined? Thread
class FTPError < Exception; end
class FTPReplyError < FTPError; end
class FTPTempError < FTPError; end
class FTPPermError < FTPError; end
class FTPProtoError < FTPError; end
class FTP
RCS_ID = '$Id: ftplib.rb,v 1.5 1997/09/16 08:03:31 shugo Exp $'
FTP_PORT = 21
CRLF = "\r\n"
attr :passive, TRUE
attr :return_code, TRUE
attr :debug_mode, TRUE
attr :welcome
attr :lastresp
THREAD_SAFE = defined?(Thread) != FALSE
if THREAD_SAFE
def synchronize(mode = :EX)
if @sync
@sync.synchronize(mode) do
yield
end
end
end
def sock_synchronize(mode = :EX)
if @sock
@sock.synchronize(mode) do
yield
end
end
end
else
def synchronize(mode = :EX)
yield
end
def sock_synchronize(mode = :EX)
yield
end
end
private :sock_synchronize
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)
if THREAD_SAFE
@sync = Sync.new
end
@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
SOCKSsocket.open(host, port)
else
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)
if THREAD_SAFE
@sock.extend Sync_m
end
voidresp
end
end
def sanitize(s)
if s =~ /^PASS /i
s[0, 5] + "*" * (s.length - 5)
else
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
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
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
sock_synchronize do
putline(cmd)
getresp
end
end
end
def voidcmd(cmd)
synchronize do
sock_synchronize do
putline(cmd)
voidresp
end
end
nil
end
def sendport(host, port)
hbytes = host.split(".")
pbytes = [port / 256, port % 256]
bytes = hbytes + pbytes
cmd = "PORT " + bytes.join(",")
voidcmd(cmd)
end
private :sendport
def makeport
sock = TCPserver.open(0)
port = sock.addr[1]
host = TCPsocket.getaddress(@sock.addr[2])
resp = sendport(host, port)
sock
end
private :makeport
def transfercmd(cmd)
if @passive
host, port = parse227(sendcmd("PASV"))
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
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
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)
while TRUE
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)
while TRUE
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)
while TRUE
buf = file.read(blocksize)
break if buf == nil
conn.write(buf)
if use_callback
callback.call(buf)
end
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)
while TRUE
buf = file.gets
break if buf == nil
if buf[-2, 2] != CRLF
if buf[-1] == ?\r or
buf[-1] == ?\n
buf = buf[0 .. -2]
end
buf = buf + CRLF
end
conn.write(buf)
if use_callback
callback.call(buf)
end
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)
if use_callback
callback.call(data)
end
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)
if use_callback
callback.call(line)
end
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|
if use_callback
callback.call(data)
end
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|
if use_callback
callback.call(line)
end
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
files
end
def list(*args)
cmd = "LIST"
if iterator?
callback = Proc.new
elsif args[-1].is_a?(Proc)
callback = args.pop
else
callback = nil
end
args.each do |arg|
cmd = cmd + " " + arg
end
retrlines(cmd, callback)
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)
resp = sendcmd("SIZE " + filename)
if resp[0, 3] == "213"
return Integer(resp[3 .. -1].strip)
end
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
resp = ""
sock_synchronize do
print "put: ABOR\n" if @debug_mode
@sock.send(line, Socket::MSG_OOB)
resp = getmultiline
end
unless ["426", "226", "225"].include?(resp[0, 3])
raise FTPProtoError, resp
end
resp
end
def status
line = "STAT" + CRLF
resp = ""
sock_synchronize do
print "put: STAT\n" if @debug_mode
@sock.send(line, Socket::MSG_OOB)
resp = getresp
end
resp
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 = (Integer(numbers[4]) << 8) + Integer(numbers[5])
return host, port
end
private :parse227
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

142
lib/getopts.rb Normal file
Просмотреть файл

@ -0,0 +1,142 @@
#!/usr/local/bin/ruby
#
# getopts.rb -
# $Release Version: $
# $Revision$
# $Date$
# by Yasuo OHBA(SHL Japan Inc. Technology Dept.)
#
# --
#
#
#
$RCS_ID="$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

207
lib/jcode.rb Normal file
Просмотреть файл

@ -0,0 +1,207 @@
# 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
def jlength
self.split(//).length
end
alias original_succ succ
private :original_succ
def mbchar?(c)
if $KCODE =~ /^s/i
c =~ /[\x81-\x9f\xe0-\xef][\x40-\x7e\x80-\xfc]/n
elsif $KCODE =~ /^e/i
c =~ /[\xa1-\xfe][\xa1-\xfe]/n
else
FALSE
end
end
def succ
if self[-2] && self[-2] & 0x80 != 0
s = self.dup
s[-1] += 1
s[-1] += 1 if !mbchar?(s)
return s
else
original_succ
end
end
def upto(to)
return if self > to
curr = self
tail = self[-2..-1]
if tail.length == 2 and tail =~ /^.$/ then
if self[0..-2] == to[0..-2]
first = self[-2].chr
for c in self[-1] .. to[-1]
if mbchar?(first+c.chr)
yield self[0..-2]+c.chr
end
end
end
else
loop do
yield curr
return if curr == to
curr = curr.succ
return if curr.length > to.length
end
end
return nil
end
def _expand_ch
a = []
self.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 tr!(from, to)
return self.delete!(from) if to.length == 0
if from =~ /^\^/
comp=TRUE
from = $'
end
afrom = from._expand_ch
ato = to._expand_ch
i = 0
if comp
self.gsub!(/(.|\n)/) do |c|
unless afrom.include?(c)
ato[-1]
else
c
end
end
else
self.gsub!(/(.|\n)/) do |c|
if i = afrom.index(c)
if i < ato.size then ato[i] else ato[-1] end
else
c
end
end
end
end
def tr(from, to)
self.dup.tr!(from, to)
end
def delete!(del)
if del =~ /^\^/
comp=TRUE
del = $'
end
adel = del._expand_ch
if comp
self.gsub!(/(.|\n)/) do |c|
next unless adel.include?(c)
c
end
else
self.gsub!(/(.|\n)/) do |c|
next if adel.include?(c)
c
end
end
end
def delete(del)
self.dup.delete!(del)
end
def squeeze!(del=nil)
if del
if del =~ /^\^/
comp=TRUE
del = $'
end
adel = del._expand_ch
if comp
self.gsub!(/(.|\n)\1+/) do
next unless adel.include?($1)
$&
end
else
for c in adel
cq = Regexp.quote(c)
self.gsub!(/#{cq}(#{cq})+/, cq)
end
end
self
else
self.gsub!(/(.|\n)\1+/, '\1')
end
end
def squeeze(del=nil)
self.dup.squeeze!(del)
end
def tr_s!(from, to)
return self.delete!(from) if to.length == 0
if from =~ /^\^/
comp=TRUE
from = $'
end
afrom = from._expand_ch
ato = to._expand_ch
i = 0
c = nil
last = nil
self.gsub!(/(.|\n)/) do |c|
if comp
unless afrom.include?(c)
ato[-1]
else
c
end
elsif i = afrom.index(c)
c = if i < ato.size then ato[i] else ato[-1] end
next if c == last
last = c
else
last = nil
c
end
end
end
def tr_s(from, to)
self.dup.tr_s!(from,to)
end
alias original_chop! chop!
private :original_chop!
def chop!
if self =~ /(.)$/ and $1.size == 2
original_chop!
end
original_chop!
end
def chop
self.dup.chop!
end
end
$VERBOSE = $vsave

48
lib/mailread.rb Normal file
Просмотреть файл

@ -0,0 +1,48 @@
class Mail
def Mail.new(f)
unless 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 unless $_
while f.gets()
break if /^From /
@body.push($_)
end
end
def header
return @header
end
def body
return @body
end
def [](field)
@header[field]
end
end

308
lib/mathn.rb Normal file
Просмотреть файл

@ -0,0 +1,308 @@
#
# mathn.rb -
# $Release Version: 0.5 $
# $Revision: 1.1 $
# $Date: 1997/07/03 04:43:47 $
# 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
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

777
lib/matrix.rb Normal file
Просмотреть файл

@ -0,0 +1,777 @@
#!/usr/local/bin/ruby
#
# matrix.rb -
# $Release Version: 1.0$
# $Revision: 1.0 $
# $Date: 97/05/23 11:35:28 $
# 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: ¹Ô
#
require "e2mmap.rb"
module ExceptionForMatrix
Exception2MessageMapper.extend_to(binding)
def_e2message(TypeError, "wrong argument type %s (expected %s)")
def_e2message(ArgumentError, "Wrong # of arguments(%d for %d)")
def_exception("ErrDimensionMismatch", "\#{self.type} dimemsion mismatch")
def_exception("ErrNotRegular", "Not Regular Matrix")
def_exception("ErrOperationNotDefined", "This operation(%s) can\\'t defined")
end
class Matrix
RCS_ID='-$Header: ruby-mode,v 1.2 91/04/20 17:24:57 keiju Locked $-'
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.fail 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
# 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.fail 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.fail ErrOperationNotDefined, "+"
when Vector
m = Matrix.column_vector(m)
when Matrix
else
x, y = m.coerce(self)
return x + y
end
Matrix.fail 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.fail ErrOperationNotDefined, "-"
when Vector
m = Matrix.column_vector(m)
when Matrix
else
x, y = m.coerce(self)
return x - y
end
Matrix.fail 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 inverse
Matrix.fail 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
fail 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)
fail ErrOperationNotDefined, "**"
else
fail 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]
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 = -1
nothing = FALSE
begin
if (i += 1) > column_size - 1
nothing = TRUE
break
end
end while a[i][k] == 0
next if nothing
a[i], a[k] = a[k], a[i]
akk = a[k][k]
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
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.fail 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.fail 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.fail 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.fail 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.fail ErrDimensionMismatch if size != v.size
0.upto(size - 1) do
|i|
yield @elements[i], v[i]
end
end
def collect2(v)
Vector.fail ErrDimensionMismatch if size != v.size
(0 .. size - 1).collect do
|i|
yield @elements[i], v[i]
end
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.corece(self)
s * x
end
end
def +(v)
case v
when Vector
Vector.fail 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.corece(self)
s + x
end
end
def -(v)
case v
when Vector
Vector.fail 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.corece(self)
s - x
end
end
# VECTOR FUNCTIONS
def inner_product(v)
Vector.fail 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 v.sqrt
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
end
end
# PRINTING
def to_s
"Vector[" + @elements.join(", ") + "]"
end
def inspect
str = "Vector"+@elements.inspect
end
end

183
lib/mutex_m.rb Normal file
Просмотреть файл

@ -0,0 +1,183 @@
#
# mutex_m.rb -
# $Release Version: 2.0$
# $Revision: 1.2 $
# $Date: 1997/07/25 02:43:21 $
# Original from mutex.rb
# by Keiju ISHITSUKA(SHL Japan Inc.)
#
# --
# Usage:
# require "mutex_m.rb"
# obj = Object.new
# obj.extend Mutex_m
# ...
# 後はMutexと同じ使い方
#
require "finalize"
module Mutex_m
def Mutex_m.extend_object(obj)
if Fixnum === obj or TRUE === obj or FALSE === obj or nil == obj
raise TypeError, "Mutex_m can't extend to this class(#{obj.type})"
else
begin
eval "class << obj
@mu_locked
end"
obj.extend(For_primitive_object)
rescue TypeError
obj.extend(For_general_object)
end
end
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
end
def mu_synchronize
begin
mu_lock
yield
ensure
mu_unlock
end
end
module For_general_object
include Mutex_m
def For_general_object.extend_object(obj)
super
obj.mu_extended
end
def mu_extended
super
@mu_waiting = []
@mu_locked = FALSE;
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
end
module For_primitive_object
include Mutex_m
Mu_Locked = Hash.new
def For_primitive_object.extend_object(obj)
super
obj.mu_extended
Finalizer.add(obj, For_primitive_object, :mu_finalize)
end
def For_primitive_object.mu_finalize(id)
Thread.critical = TRUE
if wait = Mu_Locked.delete(id)
# wait == [] ときだけ GCされるので, for w in wait は意味なし.
Thread.critical = FALSE
for w in wait
w.run
end
else
Thread.critical = FALSE
end
self
end
def mu_locked?
Mu_Locked.key?(self.id)
end
def mu_try_lock
Thread.critical = TRUE
if Mu_Locked.key?(self.id)
ret = FALSE
else
Mu_Locked[self.id] = []
Finalizer.set(self, For_primitive_object, :mu_delete_Locked)
ret = TRUE
end
Thread.critical = FALSE
ret
end
def mu_lock
while (Thread.critical = TRUE; w = Mu_Locked[self.id])
w.push Thread.current
Thread.stop
end
Mu_Locked[self.id] = []
Finalizer.add(self, For_primitive_object, :mu_delete_Locked)
Thread.critical = FALSE
self
end
def mu_unlock
Thread.critical = TRUE
if wait = Mu_Locked.delete(self.id)
Finalizer.delete(self, For_primitive_object, :mu_finalize)
Thread.critical = FALSE
for w in wait
w.run
end
else
Thread.critical = FALSE
end
self
end
end
end

40
lib/observer.rb Normal file
Просмотреть файл

@ -0,0 +1,40 @@
# 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_peers and @observer_state
for i in @observer_peers
i.update(*arg)
end
@observer_state = FALSE
end
end
end

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше