summaryrefslogtreecommitdiffhomepage
path: root/mrbgems
diff options
context:
space:
mode:
Diffstat (limited to 'mrbgems')
-rw-r--r--mrbgems/default.gembox3
-rw-r--r--mrbgems/mruby-array-ext/mrbgem.rake1
-rw-r--r--mrbgems/mruby-array-ext/mrblib/array.rb39
-rw-r--r--mrbgems/mruby-array-ext/src/array.c4
-rw-r--r--mrbgems/mruby-array-ext/test/array.rb65
-rw-r--r--mrbgems/mruby-bin-config/mrbgem.rake23
-rw-r--r--mrbgems/mruby-bin-config/mruby-config (renamed from mrbgems/mruby-bin-mruby-config/mruby-config)0
-rw-r--r--mrbgems/mruby-bin-config/mruby-config.bat (renamed from mrbgems/mruby-bin-mruby-config/mruby-config.bat)0
-rw-r--r--mrbgems/mruby-bin-debugger/tools/mrdb/apibreak.c16
-rw-r--r--mrbgems/mruby-bin-debugger/tools/mrdb/apilist.c2
-rw-r--r--mrbgems/mruby-bin-debugger/tools/mrdb/apiprint.c9
-rw-r--r--mrbgems/mruby-bin-debugger/tools/mrdb/apiprint.h2
-rw-r--r--mrbgems/mruby-bin-debugger/tools/mrdb/cmdbreak.c6
-rw-r--r--mrbgems/mruby-bin-debugger/tools/mrdb/cmdmisc.c8
-rw-r--r--mrbgems/mruby-bin-debugger/tools/mrdb/cmdprint.c25
-rw-r--r--mrbgems/mruby-bin-debugger/tools/mrdb/cmdrun.c2
-rw-r--r--mrbgems/mruby-bin-debugger/tools/mrdb/mrdb.c9
-rw-r--r--mrbgems/mruby-bin-debugger/tools/mrdb/mrdb.h4
-rw-r--r--mrbgems/mruby-bin-debugger/tools/mrdb/mrdbconf.h4
-rw-r--r--mrbgems/mruby-bin-mirb/tools/mirb/mirb.c49
-rw-r--r--mrbgems/mruby-bin-mrbc/tools/mrbc/mrbc.c3
-rw-r--r--mrbgems/mruby-bin-mruby-config/mrbgem.rake31
-rw-r--r--mrbgems/mruby-bin-mruby/bintest/mruby.rb58
-rw-r--r--mrbgems/mruby-bin-mruby/tools/mruby/mruby.c41
-rw-r--r--mrbgems/mruby-class-ext/src/class.c3
-rw-r--r--mrbgems/mruby-compiler/core/codegen.c119
-rw-r--r--mrbgems/mruby-compiler/core/keywords3
-rw-r--r--mrbgems/mruby-compiler/core/lex.def110
-rw-r--r--mrbgems/mruby-compiler/core/parse.y503
-rw-r--r--mrbgems/mruby-complex/mrbgem.rake10
-rw-r--r--mrbgems/mruby-complex/mrblib/complex.rb122
-rw-r--r--mrbgems/mruby-complex/src/complex.c249
-rw-r--r--mrbgems/mruby-complex/test/complex.rb153
-rw-r--r--mrbgems/mruby-enum-chain/mrblib/chain.rb36
-rw-r--r--mrbgems/mruby-enum-chain/test/enum_chain.rb50
-rw-r--r--mrbgems/mruby-enum-ext/mrblib/enum.rb35
-rw-r--r--mrbgems/mruby-enum-ext/test/enum.rb15
-rw-r--r--mrbgems/mruby-enumerator/mrbgem.rake1
-rw-r--r--mrbgems/mruby-enumerator/mrblib/enumerator.rb71
-rw-r--r--mrbgems/mruby-enumerator/test/enumerator.rb75
-rw-r--r--mrbgems/mruby-eval/src/eval.c89
-rw-r--r--mrbgems/mruby-eval/test/eval.rb4
-rw-r--r--mrbgems/mruby-fiber/src/fiber.c19
-rw-r--r--mrbgems/mruby-fiber/test/fiber.rb2
-rw-r--r--mrbgems/mruby-hash-ext/mrblib/hash.rb3
-rw-r--r--mrbgems/mruby-io/.gitignore1
-rw-r--r--mrbgems/mruby-io/.travis.yml2
-rw-r--r--mrbgems/mruby-io/README.md4
-rw-r--r--mrbgems/mruby-io/mrbgem.rake2
-rw-r--r--mrbgems/mruby-io/mrblib/io.rb36
-rw-r--r--mrbgems/mruby-io/run_test.rb26
-rw-r--r--mrbgems/mruby-io/src/file.c33
-rw-r--r--mrbgems/mruby-io/src/file_test.c21
-rw-r--r--mrbgems/mruby-io/src/io.c63
-rw-r--r--mrbgems/mruby-io/test/file.rb48
-rw-r--r--mrbgems/mruby-io/test/file_test.rb21
-rw-r--r--mrbgems/mruby-io/test/io.rb99
-rw-r--r--mrbgems/mruby-io/test/mruby_io_test.c12
-rw-r--r--mrbgems/mruby-kernel-ext/mrbgem.rake2
-rw-r--r--mrbgems/mruby-kernel-ext/mrblib/kernel.rb15
-rw-r--r--mrbgems/mruby-kernel-ext/src/kernel.c32
-rw-r--r--mrbgems/mruby-kernel-ext/test/kernel.rb2
-rw-r--r--mrbgems/mruby-math/src/math.c20
-rw-r--r--mrbgems/mruby-math/test/math.rb82
-rw-r--r--mrbgems/mruby-metaprog/src/metaprog.c63
-rw-r--r--mrbgems/mruby-metaprog/test/metaprog.rb114
-rw-r--r--mrbgems/mruby-method/mrblib/kernel.rb2
-rw-r--r--mrbgems/mruby-method/mrblib/method.rb12
-rw-r--r--mrbgems/mruby-method/mrblib/unbound_method.rb9
-rw-r--r--mrbgems/mruby-method/src/method.c229
-rw-r--r--mrbgems/mruby-method/test/method.rb10
-rw-r--r--mrbgems/mruby-numeric-ext/mrblib/numeric_ext.rb6
-rw-r--r--mrbgems/mruby-numeric-ext/src/numeric_ext.c54
-rw-r--r--mrbgems/mruby-numeric-ext/test/numeric.rb8
-rw-r--r--mrbgems/mruby-object-ext/mrbgem.rake2
-rw-r--r--mrbgems/mruby-object-ext/mrblib/object.rb16
-rw-r--r--mrbgems/mruby-object-ext/src/object.c35
-rw-r--r--mrbgems/mruby-object-ext/test/nil.rb4
-rw-r--r--mrbgems/mruby-objectspace/test/objectspace.rb2
-rw-r--r--mrbgems/mruby-pack/.gitignore5
-rw-r--r--mrbgems/mruby-pack/.travis.yml2
-rw-r--r--mrbgems/mruby-pack/packtest.rb157
-rw-r--r--mrbgems/mruby-pack/run_test.rb26
-rw-r--r--mrbgems/mruby-pack/src/pack.c49
-rw-r--r--mrbgems/mruby-pack/test/pack.rb92
-rw-r--r--mrbgems/mruby-proc-ext/src/proc.c12
-rw-r--r--mrbgems/mruby-proc-ext/test/proc.rb26
-rw-r--r--mrbgems/mruby-random/src/mt19937ar.c224
-rw-r--r--mrbgems/mruby-random/src/mt19937ar.h80
-rw-r--r--mrbgems/mruby-random/src/random.c281
-rw-r--r--mrbgems/mruby-random/src/random.h12
-rw-r--r--mrbgems/mruby-random/test/random.rb98
-rw-r--r--mrbgems/mruby-range-ext/mrblib/range.rb38
-rw-r--r--mrbgems/mruby-range-ext/src/range.c37
-rw-r--r--mrbgems/mruby-range-ext/test/range.rb112
-rw-r--r--mrbgems/mruby-rational/mrbgem.rake5
-rw-r--r--mrbgems/mruby-rational/mrblib/rational.rb117
-rw-r--r--mrbgems/mruby-rational/src/rational.c209
-rw-r--r--mrbgems/mruby-rational/test/rational.rb308
-rw-r--r--mrbgems/mruby-sleep/.gitignore4
-rw-r--r--mrbgems/mruby-sleep/.travis.yml29
-rw-r--r--mrbgems/mruby-sleep/.travis_build_config.rb6
-rw-r--r--mrbgems/mruby-sleep/Rakefile29
-rw-r--r--mrbgems/mruby-socket/.travis.yml4
-rw-r--r--mrbgems/mruby-socket/README.md2
-rw-r--r--mrbgems/mruby-socket/run_test.rb28
-rw-r--r--mrbgems/mruby-socket/src/socket.c17
-rw-r--r--mrbgems/mruby-socket/test/socket.rb2
-rw-r--r--mrbgems/mruby-sprintf/src/sprintf.c36
-rw-r--r--mrbgems/mruby-string-ext/mrbgem.rake1
-rw-r--r--mrbgems/mruby-string-ext/mrblib/string.rb14
-rw-r--r--mrbgems/mruby-string-ext/src/string.c223
-rw-r--r--mrbgems/mruby-string-ext/test/numeric.rb29
-rw-r--r--mrbgems/mruby-string-ext/test/range.rb26
-rw-r--r--mrbgems/mruby-string-ext/test/string.rb153
-rw-r--r--mrbgems/mruby-struct/mrblib/struct.rb43
-rw-r--r--mrbgems/mruby-struct/src/struct.c98
-rw-r--r--mrbgems/mruby-struct/test/struct.rb31
-rw-r--r--mrbgems/mruby-symbol-ext/src/symbol.c19
-rw-r--r--mrbgems/mruby-symbol-ext/test/symbol.rb30
-rw-r--r--mrbgems/mruby-test/driver.c204
-rw-r--r--mrbgems/mruby-test/init_mrbtest.c39
-rw-r--r--mrbgems/mruby-test/mrbgem.rake14
-rw-r--r--mrbgems/mruby-test/vformat.c200
-rw-r--r--mrbgems/mruby-time/include/mruby/time.h3
-rw-r--r--mrbgems/mruby-time/src/time.c279
-rw-r--r--mrbgems/mruby-time/test/time.rb127
127 files changed, 4364 insertions, 2379 deletions
diff --git a/mrbgems/default.gembox b/mrbgems/default.gembox
index 23e65fcee..9859c7d52 100644
--- a/mrbgems/default.gembox
+++ b/mrbgems/default.gembox
@@ -86,6 +86,9 @@ MRuby::GemBox.new do |conf|
# Use class/module extension
conf.gem :core => "mruby-class-ext"
+ # Use Method/UnboundMethod class
+ conf.gem :core => "mruby-method"
+
# Use mruby-compiler to build other mrbgems
conf.gem :core => "mruby-compiler"
end
diff --git a/mrbgems/mruby-array-ext/mrbgem.rake b/mrbgems/mruby-array-ext/mrbgem.rake
index 58d4428d4..882caf1ab 100644
--- a/mrbgems/mruby-array-ext/mrbgem.rake
+++ b/mrbgems/mruby-array-ext/mrbgem.rake
@@ -2,5 +2,4 @@ MRuby::Gem::Specification.new('mruby-array-ext') do |spec|
spec.license = 'MIT'
spec.author = 'mruby developers'
spec.summary = 'Array class extension'
- spec.add_test_dependency 'mruby-enumerator', core: 'mruby-enumerator'
end
diff --git a/mrbgems/mruby-array-ext/mrblib/array.rb b/mrbgems/mruby-array-ext/mrblib/array.rb
index 6096696cb..5201cbe57 100644
--- a/mrbgems/mruby-array-ext/mrblib/array.rb
+++ b/mrbgems/mruby-array-ext/mrblib/array.rb
@@ -126,6 +126,22 @@ class Array
##
# call-seq:
+ # ary.difference(other_ary1, other_ary2, ...) -> new_ary
+ #
+ # Returns a new array that is a copy of the original array, removing all
+ # occurences of any item that also appear in +other_ary+. The order is
+ # preserved from the original array.
+ #
+ def difference(*args)
+ ary = self.dup
+ args.each do |x|
+ ary = self - x
+ end
+ ary
+ end
+
+ ##
+ # call-seq:
# ary & other_ary -> new_ary
#
# Set Intersection---Returns a new array
@@ -266,7 +282,6 @@ class Array
self
end
- NONE=Object.new
##
# call-seq:
# ary.fetch(index) -> obj
@@ -816,12 +831,11 @@ class Array
# a.permutation(0).to_a #=> [[]] # one permutation of length 0
# a.permutation(4).to_a #=> [] # no permutations of length 4
def permutation(n=self.size, &block)
- size = self.size
return to_enum(:permutation, n) unless block
- return if n > size
+ size = self.size
if n == 0
- yield []
- else
+ yield []
+ elsif 0 < n && n <= size
i = 0
while i<size
result = [self[i]]
@@ -836,6 +850,7 @@ class Array
i += 1
end
end
+ self
end
##
@@ -862,9 +877,8 @@ class Array
# a.combination(5).to_a #=> [] # no combinations of length 5
def combination(n, &block)
- size = self.size
return to_enum(:combination, n) unless block
- return if n > size
+ size = self.size
if n == 0
yield []
elsif n == 1
@@ -873,7 +887,7 @@ class Array
yield [self[i]]
i += 1
end
- else
+ elsif n <= size
i = 0
while i<size
result = [self[i]]
@@ -883,6 +897,7 @@ class Array
i += 1
end
end
+ self
end
##
@@ -904,8 +919,8 @@ class Array
column_count = nil
self.each do |row|
raise TypeError unless row.is_a?(Array)
- column_count ||= row.count
- raise IndexError, 'element size differs' unless column_count == row.count
+ column_count ||= row.size
+ raise IndexError, 'element size differs' unless column_count == row.size
end
Array.new(column_count) do |column_index|
@@ -937,4 +952,8 @@ class Array
end
h
end
+
+ alias append push
+ alias prepend unshift
+ alias filter! select!
end
diff --git a/mrbgems/mruby-array-ext/src/array.c b/mrbgems/mruby-array-ext/src/array.c
index b6d9c9c80..cb4798d49 100644
--- a/mrbgems/mruby-array-ext/src/array.c
+++ b/mrbgems/mruby-array-ext/src/array.c
@@ -145,7 +145,7 @@ mrb_ary_slice_bang(mrb_state *mrb, mrb_value self)
mrb_get_args(mrb, "o|i", &index, &len);
switch (mrb_type(index)) {
case MRB_TT_RANGE:
- if (mrb_range_beg_len(mrb, index, &i, &len, ARY_LEN(a), TRUE) == 1) {
+ if (mrb_range_beg_len(mrb, index, &i, &len, ARY_LEN(a), TRUE) == MRB_RANGE_OK) {
goto delete_pos_len;
}
else {
@@ -194,7 +194,7 @@ mrb_mruby_array_ext_gem_init(mrb_state* mrb)
mrb_define_method(mrb, a, "at", mrb_ary_at, MRB_ARGS_REQ(1));
mrb_define_method(mrb, a, "rassoc", mrb_ary_rassoc, MRB_ARGS_REQ(1));
mrb_define_method(mrb, a, "values_at", mrb_ary_values_at, MRB_ARGS_ANY());
- mrb_define_method(mrb, a, "slice!", mrb_ary_slice_bang, MRB_ARGS_ANY());
+ mrb_define_method(mrb, a, "slice!", mrb_ary_slice_bang, MRB_ARGS_ARG(1,1));
}
void
diff --git a/mrbgems/mruby-array-ext/test/array.rb b/mrbgems/mruby-array-ext/test/array.rb
index 853554bcc..029325aab 100644
--- a/mrbgems/mruby-array-ext/test/array.rb
+++ b/mrbgems/mruby-array-ext/test/array.rb
@@ -1,6 +1,23 @@
##
# Array(Ext) Test
+def assert_permutation_combination(exp, receiver, meth, *args)
+ act = []
+ ret = receiver.__send__(meth, *args) { |v| act << v }
+ assert "assert_#{meth}" do
+ assert_equal(exp, act.sort)
+ assert_same(receiver, ret)
+ end
+end
+
+def assert_permutation(exp, receiver, *args)
+ assert_permutation_combination(exp, receiver, :permutation, *args)
+end
+
+def assert_combination(exp, receiver, *args)
+ assert_permutation_combination(exp, receiver, :combination, *args)
+end
+
assert("Array#assoc") do
s1 = [ "colors", "red", "blue", "green" ]
s2 = [ "letters", "a", "b", "c" ]
@@ -76,6 +93,14 @@ assert("Array#union") do
assert_equal [1, 2, 3, 4, 5], a.union(b,c)
end
+assert("Array#difference") do
+ a = [1, 2, 3, 1]
+ b = [1, 4]
+ c = [1, 5]
+
+ assert_equal [2, 3], a.difference(b,c)
+end
+
assert("Array#&") do
a = [1, 2, 3, 1]
b = [1, 4]
@@ -268,9 +293,9 @@ assert("Array#bsearch") do
end
end
-assert("Array#bsearch_index") do
- # tested through Array#bsearch
-end
+# tested through Array#bsearch
+#assert("Array#bsearch_index") do
+#end
assert("Array#delete_if") do
a = [1, 2, 3, 4, 5]
@@ -369,30 +394,24 @@ end
assert("Array#permutation") do
a = [1, 2, 3]
- assert_equal([[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]],
- a.permutation.to_a)
- assert_equal([[1],[2],[3]],
- a.permutation(1).to_a)
- assert_equal([[1,2],[1,3],[2,1],[2,3],[3,1],[3,2]],
- a.permutation(2).to_a)
- assert_equal([[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]],
- a.permutation(3).to_a)
- assert_equal([[]], a.permutation(0).to_a)
- assert_equal([], a.permutation(4).to_a)
+ assert_permutation([[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]], a)
+ assert_permutation([[1],[2],[3]], a, 1)
+ assert_permutation([[1,2],[1,3],[2,1],[2,3],[3,1],[3,2]], a, 2)
+ assert_permutation([[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]], a, 3)
+ assert_permutation([[]], a, 0)
+ assert_permutation([], a, 4)
+ assert_permutation([], a, -1)
end
assert("Array#combination") do
a = [1, 2, 3, 4]
- assert_equal([[1],[2],[3],[4]],
- a.combination(1).to_a)
- assert_equal([[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]],
- a.combination(2).to_a)
- assert_equal([[1,2,3],[1,2,4],[1,3,4],[2,3,4]],
- a.combination(3).to_a)
- assert_equal([[1,2,3,4]],
- a.combination(4).to_a)
- assert_equal([[]], a.combination(0).to_a)
- assert_equal([], a.combination(5).to_a)
+ assert_combination([[1],[2],[3],[4]], a, 1)
+ assert_combination([[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]], a, 2)
+ assert_combination([[1,2,3],[1,2,4],[1,3,4],[2,3,4]], a, 3)
+ assert_combination([[1,2,3,4]], a, 4)
+ assert_combination([[]], a, 0)
+ assert_combination([], a, 5)
+ assert_combination([], a, -1)
end
assert('Array#transpose') do
diff --git a/mrbgems/mruby-bin-config/mrbgem.rake b/mrbgems/mruby-bin-config/mrbgem.rake
new file mode 100644
index 000000000..3a0a1b897
--- /dev/null
+++ b/mrbgems/mruby-bin-config/mrbgem.rake
@@ -0,0 +1,23 @@
+unless MRuby::Build.current.kind_of?(MRuby::CrossBuild)
+ MRuby::Gem::Specification.new('mruby-bin-config') do |spec|
+ name = 'mruby-config'
+ spec.license = 'MIT'
+ spec.author = 'mruby developers'
+ spec.summary = "#{name} command"
+
+ mruby_config = name + (ENV['OS'] == 'Windows_NT' ? '.bat' : '')
+ mruby_config_path = "#{build.build_dir}/bin/#{mruby_config}"
+ make_cfg = "#{build.build_dir}/lib/libmruby.flags.mak"
+ tmplt_path = "#{__dir__}/#{mruby_config}"
+ build.bins << mruby_config
+
+ file mruby_config_path => [make_cfg, tmplt_path] do |t|
+ config = Hash[File.readlines(make_cfg).map!(&:chomp).map! {|l|
+ l.gsub('\\"', '"').split(' = ', 2).map! {|s| s.sub(/^(?=.)/, 'echo ')}
+ }]
+ tmplt = File.read(tmplt_path)
+ File.write(t.name, tmplt.gsub(/(#{Regexp.union(*config.keys)})\b/, config))
+ FileUtils.chmod(0755, t.name)
+ end
+ end
+end
diff --git a/mrbgems/mruby-bin-mruby-config/mruby-config b/mrbgems/mruby-bin-config/mruby-config
index 57346c03f..57346c03f 100644
--- a/mrbgems/mruby-bin-mruby-config/mruby-config
+++ b/mrbgems/mruby-bin-config/mruby-config
diff --git a/mrbgems/mruby-bin-mruby-config/mruby-config.bat b/mrbgems/mruby-bin-config/mruby-config.bat
index a1f7bfdd1..a1f7bfdd1 100644
--- a/mrbgems/mruby-bin-mruby-config/mruby-config.bat
+++ b/mrbgems/mruby-bin-config/mruby-config.bat
diff --git a/mrbgems/mruby-bin-debugger/tools/mrdb/apibreak.c b/mrbgems/mruby-bin-debugger/tools/mrdb/apibreak.c
index d3ccf08ae..530d824eb 100644
--- a/mrbgems/mruby-bin-debugger/tools/mrdb/apibreak.c
+++ b/mrbgems/mruby-bin-debugger/tools/mrdb/apibreak.c
@@ -84,7 +84,7 @@ free_breakpoint(mrb_state *mrb, mrb_debug_breakpoint *bp)
}
static uint16_t
-check_file_lineno(struct mrb_irep *irep, const char *file, uint16_t lineno)
+check_file_lineno(mrb_state *mrb, struct mrb_irep *irep, const char *file, uint16_t lineno)
{
mrb_irep_debug_info_file *info_file;
uint16_t result = 0;
@@ -93,8 +93,10 @@ check_file_lineno(struct mrb_irep *irep, const char *file, uint16_t lineno)
uint16_t i;
for (f_idx = 0; f_idx < irep->debug_info->flen; ++f_idx) {
+ const char *filename;
info_file = irep->debug_info->files[f_idx];
- if (!strcmp(info_file->filename, file)) {
+ filename = mrb_sym2name_len(mrb, info_file->filename_sym, NULL);
+ if (!strcmp(filename, file)) {
result = MRB_DEBUG_BP_FILE_OK;
fix_lineno = check_lineno(info_file, lineno);
@@ -103,7 +105,7 @@ check_file_lineno(struct mrb_irep *irep, const char *file, uint16_t lineno)
}
}
for (i=0; i < irep->rlen; ++i) {
- result |= check_file_lineno(irep->reps[i], file, lineno);
+ result |= check_file_lineno(mrb, irep->reps[i], file, lineno);
if (result == (MRB_DEBUG_BP_FILE_OK | MRB_DEBUG_BP_LINENO_OK)) {
return result;
}
@@ -185,7 +187,7 @@ mrb_debug_set_break_line(mrb_state *mrb, mrb_debug_context *dbg, const char *fil
}
/* file and lineno check (line type mrb_debug_line_ary only.) */
- result = check_file_lineno(dbg->root_irep, file, lineno);
+ result = check_file_lineno(mrb, dbg->root_irep, file, lineno);
if (result == 0) {
return MRB_DEBUG_BREAK_INVALID_FILE;
}
@@ -426,10 +428,10 @@ mrb_debug_disable_break_all(mrb_state *mrb, mrb_debug_context *dbg)
}
static mrb_bool
-check_start_pc_for_line(mrb_irep *irep, mrb_code *pc, uint16_t line)
+check_start_pc_for_line(mrb_state *mrb, mrb_irep *irep, const mrb_code *pc, uint16_t line)
{
if (pc > irep->iseq) {
- if (line == mrb_debug_get_line(irep, pc - irep->iseq - 1)) {
+ if (line == mrb_debug_get_line(mrb, irep, pc - irep->iseq - 1)) {
return FALSE;
}
}
@@ -447,7 +449,7 @@ mrb_debug_check_breakpoint_line(mrb_state *mrb, mrb_debug_context *dbg, const ch
return MRB_DEBUG_INVALID_ARGUMENT;
}
- if (!check_start_pc_for_line(dbg->irep, dbg->pc, line)) {
+ if (!check_start_pc_for_line(mrb, dbg->irep, dbg->pc, line)) {
return MRB_DEBUG_OK;
}
diff --git a/mrbgems/mruby-bin-debugger/tools/mrdb/apilist.c b/mrbgems/mruby-bin-debugger/tools/mrdb/apilist.c
index 21fe64127..66ddfa783 100644
--- a/mrbgems/mruby-bin-debugger/tools/mrdb/apilist.c
+++ b/mrbgems/mruby-bin-debugger/tools/mrdb/apilist.c
@@ -181,7 +181,7 @@ mrb_debug_get_source(mrb_state *mrb, mrdb_state *mrdb, const char *srcpath, cons
else srcname = filename;
search_path[0] = srcpath;
- search_path[1] = dirname(mrb, mrb_debug_get_filename(mrdb->dbg->irep, 0));
+ search_path[1] = dirname(mrb, mrb_debug_get_filename(mrb, mrdb->dbg->irep, 0));
search_path[2] = ".";
for (i = 0; i < 3; i++) {
diff --git a/mrbgems/mruby-bin-debugger/tools/mrdb/apiprint.c b/mrbgems/mruby-bin-debugger/tools/mrdb/apiprint.c
index c8700530f..cdd7b6fa6 100644
--- a/mrbgems/mruby-bin-debugger/tools/mrdb/apiprint.c
+++ b/mrbgems/mruby-bin-debugger/tools/mrdb/apiprint.c
@@ -31,9 +31,9 @@ mrdb_check_syntax(mrb_state *mrb, mrb_debug_context *dbg, const char *expr, size
}
mrb_value
-mrb_debug_eval(mrb_state *mrb, mrb_debug_context *dbg, const char *expr, size_t len, mrb_bool *exc)
+mrb_debug_eval(mrb_state *mrb, mrb_debug_context *dbg, const char *expr, size_t len, mrb_bool *exc, int direct_eval)
{
- void (*tmp)(struct mrb_state *, struct mrb_irep *, mrb_code *, mrb_value *);
+ void (*tmp)(struct mrb_state *, struct mrb_irep *, const mrb_code *, mrb_value *);
mrb_value ruby_code;
mrb_value s;
mrb_value v;
@@ -48,6 +48,11 @@ mrb_debug_eval(mrb_state *mrb, mrb_debug_context *dbg, const char *expr, size_t
v = mrb_obj_value(mrb->exc);
mrb->exc = 0;
}
+ else if (direct_eval) {
+ recv = dbg->regs[0];
+
+ v = mrb_funcall(mrb, recv, expr, 0);
+ }
else {
/*
* begin
diff --git a/mrbgems/mruby-bin-debugger/tools/mrdb/apiprint.h b/mrbgems/mruby-bin-debugger/tools/mrdb/apiprint.h
index e256f6262..ab8c08869 100644
--- a/mrbgems/mruby-bin-debugger/tools/mrdb/apiprint.h
+++ b/mrbgems/mruby-bin-debugger/tools/mrdb/apiprint.h
@@ -8,6 +8,6 @@
#include <mruby.h>
#include "mrdb.h"
-mrb_value mrb_debug_eval(mrb_state*, mrb_debug_context*, const char*, size_t, mrb_bool*);
+mrb_value mrb_debug_eval(mrb_state*, mrb_debug_context*, const char*, size_t, mrb_bool*, int);
#endif /* APIPRINT_H_ */
diff --git a/mrbgems/mruby-bin-debugger/tools/mrdb/cmdbreak.c b/mrbgems/mruby-bin-debugger/tools/mrdb/cmdbreak.c
index 8e5901754..bc9937e94 100644
--- a/mrbgems/mruby-bin-debugger/tools/mrdb/cmdbreak.c
+++ b/mrbgems/mruby-bin-debugger/tools/mrdb/cmdbreak.c
@@ -242,7 +242,7 @@ info_break_select(mrb_state *mrb, mrdb_state *mrdb)
}
mrb_debug_bptype
-parse_breakcommand(mrdb_state *mrdb, const char **file, uint32_t *line, char **cname, char **method)
+parse_breakcommand(mrb_state *mrb, mrdb_state *mrdb, const char **file, uint32_t *line, char **cname, char **method)
{
mrb_debug_context *dbg = mrdb->dbg;
char *args;
@@ -274,7 +274,7 @@ parse_breakcommand(mrdb_state *mrdb, const char **file, uint32_t *line, char **c
STRTOUL(l, body);
if (l <= 65535) {
*line = l;
- *file = (body == args)? mrb_debug_get_filename(dbg->irep, dbg->pc - dbg->irep->iseq): args;
+ *file = (body == args)? mrb_debug_get_filename(mrb, dbg->irep, dbg->pc - dbg->irep->iseq): args;
}
else {
puts(BREAK_ERR_MSG_RANGEOVER);
@@ -332,7 +332,7 @@ dbgcmd_break(mrb_state *mrb, mrdb_state *mrdb)
char *method = NULL;
int32_t ret;
- type = parse_breakcommand(mrdb, &file, &line, &cname, &method);
+ type = parse_breakcommand(mrb, mrdb, &file, &line, &cname, &method);
switch (type) {
case MRB_DEBUG_BPTYPE_LINE:
ret = mrb_debug_set_break_line(mrb, dbg, file, line);
diff --git a/mrbgems/mruby-bin-debugger/tools/mrdb/cmdmisc.c b/mrbgems/mruby-bin-debugger/tools/mrdb/cmdmisc.c
index 0a864567d..db28e4229 100644
--- a/mrbgems/mruby-bin-debugger/tools/mrdb/cmdmisc.c
+++ b/mrbgems/mruby-bin-debugger/tools/mrdb/cmdmisc.c
@@ -82,6 +82,12 @@ static help_msg help_msg_list[] = {
"Arguments are breakpoint numbers with spaces in between.\n"
},
{
+ "i[nfo]", "l[ocals]", "Print name of local variables",
+ "Usage: info locals\n"
+ "\n"
+ "Print name of local variables.\n"
+ },
+ {
"l[ist]", NULL, "List specified line",
"Usage: list\n"
" list first[,last]\n"
@@ -495,7 +501,7 @@ dbgcmd_quit(mrb_state *mrb, mrdb_state *mrdb)
if (mrdb->dbg->xm == DBG_QUIT) {
struct RClass *exc;
- exc = mrb_define_class(mrb, "DebuggerExit", mrb_class_get(mrb, "Exception"));
+ exc = mrb_define_class(mrb, "DebuggerExit", mrb->eException_class);
mrb_raise(mrb, exc, "Exit mrdb.");
}
return DBGST_PROMPT;
diff --git a/mrbgems/mruby-bin-debugger/tools/mrdb/cmdprint.c b/mrbgems/mruby-bin-debugger/tools/mrdb/cmdprint.c
index cca636711..25f071589 100644
--- a/mrbgems/mruby-bin-debugger/tools/mrdb/cmdprint.c
+++ b/mrbgems/mruby-bin-debugger/tools/mrdb/cmdprint.c
@@ -36,7 +36,7 @@ dbgcmd_print(mrb_state *mrb, mrdb_state *mrdb)
expr = mrb_str_cat_cstr(mrb, expr, mrdb->words[wcnt]);
}
- result = mrb_debug_eval(mrb, mrdb->dbg, RSTRING_PTR(expr), RSTRING_LEN(expr), NULL);
+ result = mrb_debug_eval(mrb, mrdb->dbg, RSTRING_PTR(expr), RSTRING_LEN(expr), NULL, 0);
/* $print_no = result */
s = mrb_str_cat_lit(mrb, result, "\0");
@@ -56,3 +56,26 @@ dbgcmd_eval(mrb_state *mrb, mrdb_state *mrdb)
{
return dbgcmd_print(mrb, mrdb);
}
+
+dbgcmd_state
+dbgcmd_info_local(mrb_state *mrb, mrdb_state *mrdb)
+{
+ mrb_value result;
+ mrb_value s;
+ int ai;
+
+ ai = mrb_gc_arena_save(mrb);
+
+ result = mrb_debug_eval(mrb, mrdb->dbg, "local_variables", 0, NULL, 1);
+
+ s = mrb_str_cat_lit(mrb, result, "\0");
+ printf("$%lu = %s\n", (unsigned long)mrdb->print_no++, RSTRING_PTR(s));
+
+ if (mrdb->print_no == 0) {
+ mrdb->print_no = 1;
+ }
+
+ mrb_gc_arena_restore(mrb, ai);
+
+ return DBGST_PROMPT;
+}
diff --git a/mrbgems/mruby-bin-debugger/tools/mrdb/cmdrun.c b/mrbgems/mruby-bin-debugger/tools/mrdb/cmdrun.c
index cb4c738fc..233c86cef 100644
--- a/mrbgems/mruby-bin-debugger/tools/mrdb/cmdrun.c
+++ b/mrbgems/mruby-bin-debugger/tools/mrdb/cmdrun.c
@@ -19,7 +19,7 @@ dbgcmd_run(mrb_state *mrb, mrdb_state *mrdb)
if (dbg->xphase == DBG_PHASE_RUNNING){
struct RClass *exc;
puts("Start it from the beginning.");
- exc = mrb_define_class(mrb, "DebuggerRestart", mrb_class_get(mrb, "Exception"));
+ exc = mrb_define_class(mrb, "DebuggerRestart", mrb->eException_class);
mrb_raise(mrb, exc, "Restart mrdb.");
}
}
diff --git a/mrbgems/mruby-bin-debugger/tools/mrdb/mrdb.c b/mrbgems/mruby-bin-debugger/tools/mrdb/mrdb.c
index 05a6f3622..d2fa4c856 100644
--- a/mrbgems/mruby-bin-debugger/tools/mrdb/mrdb.c
+++ b/mrbgems/mruby-bin-debugger/tools/mrdb/mrdb.c
@@ -52,6 +52,7 @@ static const debug_command debug_command_list[] = {
{"eval", NULL, 2, 0, 0, DBGCMD_EVAL, dbgcmd_eval}, /* ev[al] */
{"help", NULL, 1, 0, 1, DBGCMD_HELP, dbgcmd_help}, /* h[elp] */
{"info", "breakpoints", 1, 1, 1, DBGCMD_INFO_BREAK, dbgcmd_info_break}, /* i[nfo] b[reakpoints] */
+ {"info", "locals", 1, 1, 0, DBGCMD_INFO_LOCAL, dbgcmd_info_local}, /* i[nfo] l[ocals] */
{"list", NULL, 1, 0, 1, DBGCMD_LIST, dbgcmd_list}, /* l[ist] */
{"print", NULL, 1, 0, 0, DBGCMD_PRINT, dbgcmd_print}, /* p[rint] */
{"quit", NULL, 1, 0, 0, DBGCMD_QUIT, dbgcmd_quit}, /* q[uit] */
@@ -504,7 +505,7 @@ get_and_parse_command(mrb_state *mrb, mrdb_state *mrdb)
}
static int32_t
-check_method_breakpoint(mrb_state *mrb, mrb_irep *irep, mrb_code *pc, mrb_value *regs)
+check_method_breakpoint(mrb_state *mrb, mrb_irep *irep, const mrb_code *pc, mrb_value *regs)
{
struct RClass* c;
mrb_sym sym;
@@ -545,7 +546,7 @@ check_method_breakpoint(mrb_state *mrb, mrb_irep *irep, mrb_code *pc, mrb_value
}
static void
-mrb_code_fetch_hook(mrb_state *mrb, mrb_irep *irep, mrb_code *pc, mrb_value *regs)
+mrb_code_fetch_hook(mrb_state *mrb, mrb_irep *irep, const mrb_code *pc, mrb_value *regs)
{
const char *file;
int32_t line;
@@ -568,8 +569,8 @@ mrb_code_fetch_hook(mrb_state *mrb, mrb_irep *irep, mrb_code *pc, mrb_value *reg
dbg->xphase = DBG_PHASE_RUNNING;
}
- file = mrb_debug_get_filename(irep, pc - irep->iseq);
- line = mrb_debug_get_line(irep, pc - irep->iseq);
+ file = mrb_debug_get_filename(mrb, irep, pc - irep->iseq);
+ line = mrb_debug_get_line(mrb, irep, pc - irep->iseq);
switch (dbg->xm) {
case DBG_STEP:
diff --git a/mrbgems/mruby-bin-debugger/tools/mrdb/mrdb.h b/mrbgems/mruby-bin-debugger/tools/mrdb/mrdb.h
index 5ac12c1cd..7c21de317 100644
--- a/mrbgems/mruby-bin-debugger/tools/mrdb/mrdb.h
+++ b/mrbgems/mruby-bin-debugger/tools/mrdb/mrdb.h
@@ -23,6 +23,7 @@ typedef enum debug_command_id {
DBGCMD_STEP,
DBGCMD_BREAK,
DBGCMD_INFO_BREAK,
+ DBGCMD_INFO_LOCAL,
DBGCMD_WATCH,
DBGCMD_INFO_WATCH,
DBGCMD_ENABLE,
@@ -104,7 +105,7 @@ typedef struct mrb_debug_breakpoint {
typedef struct mrb_debug_context {
struct mrb_irep *root_irep;
struct mrb_irep *irep;
- mrb_code *pc;
+ const mrb_code *pc;
mrb_value *regs;
const char *prvfile;
@@ -151,6 +152,7 @@ dbgcmd_state dbgcmd_next(mrb_state*, mrdb_state*);
/* cmdbreak.c */
dbgcmd_state dbgcmd_break(mrb_state*, mrdb_state*);
dbgcmd_state dbgcmd_info_break(mrb_state*, mrdb_state*);
+dbgcmd_state dbgcmd_info_local(mrb_state*, mrdb_state*);
dbgcmd_state dbgcmd_delete(mrb_state*, mrdb_state*);
dbgcmd_state dbgcmd_enable(mrb_state*, mrdb_state*);
dbgcmd_state dbgcmd_disable(mrb_state*, mrdb_state*);
diff --git a/mrbgems/mruby-bin-debugger/tools/mrdb/mrdbconf.h b/mrbgems/mruby-bin-debugger/tools/mrdb/mrdbconf.h
index f17f9c57d..de2f90144 100644
--- a/mrbgems/mruby-bin-debugger/tools/mrdb/mrdbconf.h
+++ b/mrbgems/mruby-bin-debugger/tools/mrdb/mrdbconf.h
@@ -6,6 +6,10 @@
#ifndef MRDBCONF_H
#define MRDBCONF_H
+#ifndef MRB_ENABLE_DEBUG_HOOK
+# error Need 'MRB_ENABLE_DEBUG_HOOK' configuration in your 'build_config.rb'
+#endif
+
/* configuration options: */
/* maximum size for command buffer */
#define MAX_COMMAND_LINE 1024
diff --git a/mrbgems/mruby-bin-mirb/tools/mirb/mirb.c b/mrbgems/mruby-bin-mirb/tools/mirb/mirb.c
index 9519d88bb..45ead75f1 100644
--- a/mrbgems/mruby-bin-mirb/tools/mirb/mirb.c
+++ b/mrbgems/mruby-bin-mirb/tools/mirb/mirb.c
@@ -6,6 +6,15 @@
** immediately. It's a REPL...
*/
+#include <mruby.h>
+#include <mruby/array.h>
+#include <mruby/proc.h>
+#include <mruby/compile.h>
+#include <mruby/dump.h>
+#include <mruby/string.h>
+#include <mruby/variable.h>
+#include <mruby/throw.h>
+
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
@@ -49,15 +58,6 @@
#define SIGJMP_BUF jmp_buf
#endif
-#include <mruby.h>
-#include <mruby/array.h>
-#include <mruby/proc.h>
-#include <mruby/compile.h>
-#include <mruby/dump.h>
-#include <mruby/string.h>
-#include <mruby/variable.h>
-#include <mruby/throw.h>
-
#ifdef ENABLE_READLINE
static const char history_file_name[] = ".mirb_history";
@@ -373,7 +373,7 @@ check_keyword(const char *buf, const char *word)
size_t len = strlen(word);
/* skip preceding spaces */
- while (*p && isspace((unsigned char)*p)) {
+ while (*p && ISSPACE(*p)) {
p++;
}
/* check keyword */
@@ -383,7 +383,7 @@ check_keyword(const char *buf, const char *word)
p += len;
/* skip trailing spaces */
while (*p) {
- if (!isspace((unsigned char)*p)) return 0;
+ if (!ISSPACE(*p)) return 0;
p++;
}
return 1;
@@ -406,6 +406,26 @@ ctrl_c_handler(int signo)
}
#endif
+#ifndef DISABLE_MIRB_UNDERSCORE
+void decl_lv_underscore(mrb_state *mrb, mrbc_context *cxt)
+{
+ struct RProc *proc;
+ struct mrb_parser_state *parser;
+
+ parser = mrb_parse_string(mrb, "_=nil", cxt);
+ if (parser == NULL) {
+ fputs("create parser state error\n", stderr);
+ mrb_close(mrb);
+ exit(EXIT_FAILURE);
+ }
+
+ proc = mrb_generate_code(mrb, parser);
+ mrb_vm_run(mrb, proc, mrb_top_self(mrb), 0);
+
+ mrb_parser_free(parser);
+}
+#endif
+
int
main(int argc, char **argv)
{
@@ -471,6 +491,10 @@ main(int argc, char **argv)
cxt = mrbc_context_new(mrb);
+#ifndef DISABLE_MIRB_UNDERSCORE
+ decl_lv_underscore(mrb, cxt);
+#endif
+
/* Load libraries */
for (i = 0; i < args.libc; i++) {
FILE *lfp = fopen(args.libv[i], "r");
@@ -643,6 +667,9 @@ main(int argc, char **argv)
result = mrb_any_to_s(mrb, result);
}
p(mrb, result, 1);
+#ifndef DISABLE_MIRB_UNDERSCORE
+ *(mrb->c->stack + 1) = result;
+#endif
}
}
ruby_code[0] = '\0';
diff --git a/mrbgems/mruby-bin-mrbc/tools/mrbc/mrbc.c b/mrbgems/mruby-bin-mrbc/tools/mrbc/mrbc.c
index 2fd9da77d..4c8c680cb 100644
--- a/mrbgems/mruby-bin-mrbc/tools/mrbc/mrbc.c
+++ b/mrbgems/mruby-bin-mrbc/tools/mrbc/mrbc.c
@@ -71,7 +71,6 @@ get_outfilename(mrb_state *mrb, char *infile, const char *ext)
static int
parse_args(mrb_state *mrb, int argc, char **argv, struct mrbc_args *args)
{
- char *outfile = NULL;
static const struct mrbc_args args_zero = { 0 };
int i;
@@ -86,7 +85,7 @@ parse_args(mrb_state *mrb, int argc, char **argv, struct mrbc_args *args)
case 'o':
if (args->outfile) {
fprintf(stderr, "%s: an output file is already specified. (%s)\n",
- args->prog, outfile);
+ args->prog, args->outfile);
return -1;
}
if (argv[i][2] == '\0' && argv[i+1]) {
diff --git a/mrbgems/mruby-bin-mruby-config/mrbgem.rake b/mrbgems/mruby-bin-mruby-config/mrbgem.rake
deleted file mode 100644
index cca7423ac..000000000
--- a/mrbgems/mruby-bin-mruby-config/mrbgem.rake
+++ /dev/null
@@ -1,31 +0,0 @@
-module MRuby
- class Build
- def exefile(name)
- if name.is_a?(Array)
- name.flatten.map { |n| exefile(n) }
- elsif name !~ /\./
- "#{name}#{exts.executable}"
- else
- name
- end
- end
- end
-end
-
-MRuby.each_target do
- next if kind_of? MRuby::CrossBuild
-
- mruby_config = 'mruby-config' + (ENV['OS'] == 'Windows_NT' ? '.bat' : '')
- mruby_config_path = "#{build_dir}/bin/#{mruby_config}"
- @bins << mruby_config
-
- make_cfg = "#{build_dir}/lib/libmruby.flags.mak"
- file mruby_config_path => [libmruby_static, make_cfg] do |t|
- FileUtils.copy "#{File.dirname(__FILE__)}/#{mruby_config}", t.name
- config = Hash[open(make_cfg).read.split("\n").map {|x| a = x.split(/\s*=\s*/, 2); [a[0], a[1].gsub('\\"', '"') ]}]
- IO.write(t.name, File.open(t.name) {|f|
- f.read.gsub (/echo (MRUBY_CFLAGS|MRUBY_LIBS|MRUBY_LDFLAGS_BEFORE_LIBS|MRUBY_LDFLAGS|MRUBY_LIBMRUBY_PATH)/) {|x| config[$1].empty? ? '' : "echo #{config[$1]}"}
- })
- FileUtils.chmod(0755, t.name)
- end
-end
diff --git a/mrbgems/mruby-bin-mruby/bintest/mruby.rb b/mrbgems/mruby-bin-mruby/bintest/mruby.rb
index e8d1510f7..e032ff79a 100644
--- a/mrbgems/mruby-bin-mruby/bintest/mruby.rb
+++ b/mrbgems/mruby-bin-mruby/bintest/mruby.rb
@@ -1,10 +1,18 @@
require 'tempfile'
+require 'open3'
+
+def assert_mruby(exp_out, exp_err, exp_success, args)
+ out, err, stat = Open3.capture3(cmd("mruby"), *args)
+ assert "assert_mruby" do
+ assert_operator(exp_out, :===, out, "standard output")
+ assert_operator(exp_err, :===, err, "standard error")
+ assert_equal(exp_success, stat.success?, "exit success?")
+ end
+end
assert('regression for #1564') do
- o = `#{cmd('mruby')} -e #{shellquote('<<')} 2>&1`
- assert_include o, "-e:1:2: syntax error"
- o = `#{cmd('mruby')} -e #{shellquote('<<-')} 2>&1`
- assert_include o, "-e:1:3: syntax error"
+ assert_mruby("", /\A-e:1:2: syntax error, .*\n\z/, false, %w[-e <<])
+ assert_mruby("", /\A-e:1:3: syntax error, .*\n\z/, false, %w[-e <<-])
end
assert('regression for #1572') do
@@ -66,6 +74,11 @@ RUBY
assert_equal 0, $?.exitstatus
end
+assert('mruby -c option') do
+ assert_mruby("Syntax OK\n", "", true, ["-c", "-e", "p 1"])
+ assert_mruby("", /\A-e:1:7: syntax error, .*\n\z/, false, ["-c", "-e", "p 1; 1."])
+end
+
assert('mruby -d option') do
o = `#{cmd('mruby')} -e #{shellquote('p $DEBUG')}`
assert_equal "false\n", o
@@ -73,6 +86,14 @@ assert('mruby -d option') do
assert_equal "true\n", o
end
+assert('mruby -e option (no code specified)') do
+ assert_mruby("", /\A.*: No code specified for -e\n\z/, false, %w[-e])
+end
+
+assert('mruby -h option') do
+ assert_mruby(/\AUsage: #{Regexp.escape cmd("mruby")} .*/m, "", true, %w[-h])
+end
+
assert('mruby -r option') do
lib = Tempfile.new('lib.rb')
lib.write <<EOS
@@ -95,3 +116,32 @@ EOS
assert_equal 'hogeClass', `#{cmd('mruby')} -r #{lib.path} -r #{script.path} -e #{shellquote('print Hoge.class')}`
assert_equal 0, $?.exitstatus
end
+
+assert('mruby -r option (no library specified)') do
+ assert_mruby("", /\A.*: No library specified for -r\n\z/, false, %w[-r])
+end
+
+assert('mruby -r option (file not found)') do
+ assert_mruby("", /\A.*: Cannot open library file: .*\n\z/, false, %w[-r _no_exists_])
+end
+
+assert('mruby invalid short option') do
+ assert_mruby("", /\A.*: invalid option -1 .*\n\z/, false, %w[-1])
+end
+
+assert('mruby invalid long option') do
+ assert_mruby("", /\A.*: invalid option --longopt .*\n\z/, false, %w[--longopt])
+end
+
+assert('unhandled exception') do
+ assert_mruby("", /\bEXCEPTION\b.*\n\z/, false, %w[-e raise("EXCEPTION")])
+end
+
+assert('program file not found') do
+ assert_mruby("", /\A.*: Cannot open program file: .*\n\z/, false, %w[_no_exists_])
+end
+
+assert('codegen error') do
+ code = "def f(#{(1..100).map{|n| "a#{n}"} * ","}); end"
+ assert_mruby("", /\Acodegen error:.*\n\z/, false, ["-e", code])
+end
diff --git a/mrbgems/mruby-bin-mruby/tools/mruby/mruby.c b/mrbgems/mruby-bin-mruby/tools/mruby/mruby.c
index 498bedef2..29ab4c17c 100644
--- a/mrbgems/mruby-bin-mruby/tools/mruby/mruby.c
+++ b/mrbgems/mruby-bin-mruby/tools/mruby/mruby.c
@@ -7,19 +7,6 @@
#include <mruby/dump.h>
#include <mruby/variable.h>
-#ifdef MRB_DISABLE_STDIO
-static void
-p(mrb_state *mrb, mrb_value obj)
-{
- mrb_value val = mrb_inspect(mrb, obj);
-
- fwrite(RSTRING_PTR(val), RSTRING_LEN(val), 1, stdout);
- putc('\n', stdout);
-}
-#else
-#define p(mrb,obj) mrb_p(mrb,obj)
-#endif
-
struct _args {
FILE *rfp;
char* cmdline;
@@ -119,14 +106,17 @@ append_cmdline:
}
}
else {
- printf("%s: No code specified for -e\n", *origargv);
- return EXIT_SUCCESS;
+ fprintf(stderr, "%s: No code specified for -e\n", *origargv);
+ return EXIT_FAILURE;
}
break;
+ case 'h':
+ usage(*origargv);
+ exit(EXIT_SUCCESS);
case 'r':
if (!item[0]) {
if (argc <= 1) {
- printf("%s: No library specified for -r\n", *origargv);
+ fprintf(stderr, "%s: No library specified for -r\n", *origargv);
return EXIT_FAILURE;
}
argc--; argv++;
@@ -158,6 +148,7 @@ append_cmdline:
exit(EXIT_SUCCESS);
}
default:
+ fprintf(stderr, "%s: invalid option %s (-h will show valid options)\n", *origargv, *argv);
return EXIT_FAILURE;
}
}
@@ -167,7 +158,7 @@ append_cmdline:
else {
args->rfp = fopen(argv[0], args->mrbfile ? "rb" : "r");
if (args->rfp == NULL) {
- printf("%s: Cannot open program file. (%s)\n", *origargv, *argv);
+ fprintf(stderr, "%s: Cannot open program file: %s\n", *origargv, *argv);
return EXIT_FAILURE;
}
args->fname = TRUE;
@@ -212,14 +203,13 @@ main(int argc, char **argv)
mrb_sym zero_sym;
if (mrb == NULL) {
- fputs("Invalid mrb_state, exiting mruby\n", stderr);
+ fprintf(stderr, "%s: Invalid mrb_state, exiting mruby\n", *argv);
return EXIT_FAILURE;
}
n = parse_args(mrb, argc, argv, &args);
if (n == EXIT_FAILURE || (args.cmdline == NULL && args.rfp == NULL)) {
cleanup(mrb, &args);
- usage(argv[0]);
return n;
}
else {
@@ -258,7 +248,7 @@ main(int argc, char **argv)
for (i = 0; i < args.libc; i++) {
FILE *lfp = fopen(args.libv[i], args.mrbfile ? "rb" : "r");
if (lfp == NULL) {
- printf("Cannot open library file: %s\n", args.libv[i]);
+ fprintf(stderr, "%s: Cannot open library file: %s\n", *argv, args.libv[i]);
mrbc_context_free(mrb, c);
cleanup(mrb, &args);
return EXIT_FAILURE;
@@ -289,19 +279,16 @@ main(int argc, char **argv)
mrb_gc_arena_restore(mrb, ai);
mrbc_context_free(mrb, c);
if (mrb->exc) {
- if (mrb_undef_p(v)) {
- mrb_p(mrb, mrb_obj_value(mrb->exc));
- }
- else {
+ if (!mrb_undef_p(v)) {
mrb_print_error(mrb);
}
- n = -1;
+ n = EXIT_FAILURE;
}
else if (args.check_syntax) {
- printf("Syntax OK\n");
+ puts("Syntax OK");
}
}
cleanup(mrb, &args);
- return n == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
+ return n;
}
diff --git a/mrbgems/mruby-class-ext/src/class.c b/mrbgems/mruby-class-ext/src/class.c
index 705db9949..fdd56bcc3 100644
--- a/mrbgems/mruby-class-ext/src/class.c
+++ b/mrbgems/mruby-class-ext/src/class.c
@@ -5,8 +5,7 @@
static mrb_value
mrb_mod_name(mrb_state *mrb, mrb_value self)
{
- mrb_value name = mrb_class_path(mrb, mrb_class_ptr(self));
- return mrb_nil_p(name)? name : mrb_str_dup(mrb, name);
+ return mrb_class_path(mrb, mrb_class_ptr(self));
}
static mrb_value
diff --git a/mrbgems/mruby-compiler/core/codegen.c b/mrbgems/mruby-compiler/core/codegen.c
index cc46f835f..c0986893c 100644
--- a/mrbgems/mruby-compiler/core/codegen.c
+++ b/mrbgems/mruby-compiler/core/codegen.c
@@ -62,7 +62,7 @@ typedef struct scope {
struct loopinfo *loop;
int ensure_level;
- char const *filename;
+ mrb_sym filename_sym;
uint16_t lineno;
mrb_code *iseq;
@@ -102,12 +102,14 @@ codegen_error(codegen_scope *s, const char *message)
while (s->prev) {
codegen_scope *tmp = s->prev;
mrb_free(s->mrb, s->iseq);
+ mrb_free(s->mrb, s->lines);
mrb_pool_close(s->mpool);
s = tmp;
}
#ifndef MRB_DISABLE_STDIO
- if (s->filename && s->lineno) {
- fprintf(stderr, "codegen error:%s:%d: %s\n", s->filename, s->lineno, message);
+ if (s->filename_sym && s->lineno) {
+ const char *filename = mrb_sym2name_len(s->mrb, s->filename_sym, NULL);
+ fprintf(stderr, "codegen error:%s:%d: %s\n", filename, s->lineno, message);
}
else {
fprintf(stderr, "codegen error: %s\n", message);
@@ -271,8 +273,7 @@ genop_W(codegen_scope *s, mrb_code i, uint32_t a)
#define NOVAL 0
#define VAL 1
-//static
-mrb_bool
+static mrb_bool
no_optimize(codegen_scope *s)
{
if (s && s->parser && s->parser->no_optimize)
@@ -290,7 +291,7 @@ on_eval(codegen_scope *s)
}
struct mrb_insn_data
-mrb_decode_insn(mrb_code *pc)
+mrb_decode_insn(const mrb_code *pc)
{
struct mrb_insn_data data = { 0 };
mrb_code insn = READ_B();
@@ -734,7 +735,10 @@ lambda_body(codegen_scope *s, node *tree, int blk)
lp->pc0 = new_label(s);
}
tree = tree->cdr;
- if (tree->car) {
+ if (tree->car == NULL) {
+ genop_W(s, OP_ENTER, 0);
+ }
+ else {
mrb_aspec a;
int ma, oa, ra, pa, ka, kd, ba;
int pos, i;
@@ -820,8 +824,8 @@ lambda_body(codegen_scope *s, node *tree, int blk)
mrb_assert(nint(kwd->car) == NODE_KW_ARG);
if (def_arg) {
- genop_2(s, OP_KEY_P, cursp(), new_sym(s, kwd_sym));
- jmpif_key_p = genjmp2(s, OP_JMPIF, cursp(), 0, 0);
+ genop_2(s, OP_KEY_P, lv_idx(s, kwd_sym), new_sym(s, kwd_sym));
+ jmpif_key_p = genjmp2(s, OP_JMPIF, lv_idx(s, kwd_sym), 0, 0);
codegen(s, def_arg, VAL);
pop();
gen_move(s, lv_idx(s, kwd_sym), cursp(), 0);
@@ -952,7 +956,12 @@ gen_values(codegen_scope *s, node *t, int val, int extra)
}
else {
pop_n(n);
- genop_2(s, OP_ARRAY, cursp(), n);
+ if (n == 0 && is_splat) {
+ genop_1(s, OP_LOADNIL, cursp());
+ }
+ else {
+ genop_2(s, OP_ARRAY, cursp(), n);
+ }
push();
codegen(s, t->car, VAL);
pop(); pop();
@@ -1396,13 +1405,14 @@ codegen(codegen_scope *s, node *tree, int val)
codegen_error(s, "too complex expression");
}
if (s->irep && s->filename_index != tree->filename_index) {
- const char *filename = mrb_parser_get_filename(s->parser, s->filename_index);
+ mrb_sym fname = mrb_parser_get_filename(s->parser, s->filename_index);
+ const char *filename = mrb_sym2name_len(s->mrb, fname, NULL);
mrb_debug_info_append_file(s->mrb, s->irep->debug_info,
filename, s->lines, s->debug_start_pos, s->pc);
s->debug_start_pos = s->pc;
s->filename_index = tree->filename_index;
- s->filename = mrb_parser_get_filename(s->parser, tree->filename_index);
+ s->filename_sym = mrb_parser_get_filename(s->parser, tree->filename_index);
}
nt = nint(tree->car);
@@ -1548,7 +1558,7 @@ codegen(codegen_scope *s, node *tree, int val)
case NODE_IF:
{
- int pos1, pos2;
+ int pos1, pos2, nil_p = FALSE;
node *elsepart = tree->cdr->cdr->car;
if (!tree->car) {
@@ -1565,32 +1575,59 @@ codegen(codegen_scope *s, node *tree, int val)
case NODE_NIL:
codegen(s, elsepart, val);
goto exit;
+ case NODE_CALL:
+ {
+ node *n = tree->car->cdr;
+ mrb_sym mid = nsym(n->cdr->car);
+ mrb_sym mnil = mrb_intern_lit(s->mrb, "nil?");
+ if (mid == mnil && n->cdr->cdr->car == NULL) {
+ nil_p = TRUE;
+ codegen(s, n->car, VAL);
+ }
+ }
+ break;
+ }
+ if (!nil_p) {
+ codegen(s, tree->car, VAL);
}
- codegen(s, tree->car, VAL);
pop();
- pos1 = genjmp2(s, OP_JMPNOT, cursp(), 0, val);
-
- codegen(s, tree->cdr->car, val);
- if (elsepart) {
+ if (val || tree->cdr->car) {
+ if (nil_p) {
+ pos2 = genjmp2(s, OP_JMPNIL, cursp(), 0, val);
+ pos1 = genjmp(s, OP_JMP, 0);
+ dispatch(s, pos2);
+ }
+ else {
+ pos1 = genjmp2(s, OP_JMPNOT, cursp(), 0, val);
+ }
+ codegen(s, tree->cdr->car, val);
if (val) pop();
- pos2 = genjmp(s, OP_JMP, 0);
- dispatch(s, pos1);
- codegen(s, elsepart, val);
- dispatch(s, pos2);
- }
- else {
- if (val) {
- pop();
+ if (elsepart || val) {
pos2 = genjmp(s, OP_JMP, 0);
dispatch(s, pos1);
- genop_1(s, OP_LOADNIL, cursp());
+ codegen(s, elsepart, val);
dispatch(s, pos2);
- push();
}
else {
dispatch(s, pos1);
}
}
+ else { /* empty then-part */
+ if (elsepart) {
+ if (nil_p) {
+ pos1 = genjmp2(s, OP_JMPNIL, cursp(), 0, val);
+ }
+ else {
+ pos1 = genjmp2(s, OP_JMPIF, cursp(), 0, val);
+ }
+ codegen(s, elsepart, val);
+ dispatch(s, pos1);
+ }
+ else if (val && !nil_p) {
+ genop_1(s, OP_LOADNIL, cursp());
+ push();
+ }
+ }
}
break;
@@ -2354,13 +2391,9 @@ codegen(codegen_scope *s, node *tree, int val)
case NODE_BACK_REF:
if (val) {
- char buf[3];
- int sym;
+ char buf[] = {'$', nchar(tree)};
+ int sym = new_sym(s, mrb_intern(s->mrb, buf, sizeof(buf)));
- buf[0] = '$';
- buf[1] = nchar(tree);
- buf[2] = 0;
- sym = new_sym(s, mrb_intern_cstr(s->mrb, buf));
genop_2(s, OP_GETGV, cursp(), sym);
push();
}
@@ -2372,7 +2405,7 @@ codegen(codegen_scope *s, node *tree, int val)
mrb_value str;
int sym;
- str = mrb_format(mrb, "$%S", mrb_fixnum_value(nint(tree)));
+ str = mrb_format(mrb, "$%d", nint(tree));
sym = new_sym(s, mrb_intern_str(mrb, str));
genop_2(s, OP_GETGV, cursp(), sym);
push();
@@ -2991,15 +3024,15 @@ scope_new(mrb_state *mrb, codegen_scope *prev, node *lv)
}
p->ai = mrb_gc_arena_save(mrb);
- p->filename = prev->filename;
- if (p->filename) {
+ p->filename_sym = prev->filename_sym;
+ if (p->filename_sym) {
p->lines = (uint16_t*)mrb_malloc(mrb, sizeof(short)*p->icapa);
}
p->lineno = prev->lineno;
/* debug setting */
p->debug_start_pos = 0;
- if (p->filename) {
+ if (p->filename_sym) {
mrb_debug_info_alloc(mrb, p->irep);
}
else {
@@ -3019,6 +3052,9 @@ scope_finish(codegen_scope *s)
mrb_state *mrb = s->mrb;
mrb_irep *irep = s->irep;
+ if (s->nlocals >= 0x3ff) {
+ codegen_error(s, "too many local variables");
+ }
irep->flags = 0;
if (s->iseq) {
irep->iseq = (mrb_code *)codegen_realloc(s, s->iseq, sizeof(mrb_code)*s->pc);
@@ -3027,8 +3063,9 @@ scope_finish(codegen_scope *s)
irep->pool = (mrb_value*)codegen_realloc(s, irep->pool, sizeof(mrb_value)*irep->plen);
irep->syms = (mrb_sym*)codegen_realloc(s, irep->syms, sizeof(mrb_sym)*irep->slen);
irep->reps = (mrb_irep**)codegen_realloc(s, irep->reps, sizeof(mrb_irep*)*irep->rlen);
- if (s->filename) {
- const char *filename = mrb_parser_get_filename(s->parser, s->filename_index);
+ if (s->filename_sym) {
+ mrb_sym fname = mrb_parser_get_filename(s->parser, s->filename_index);
+ const char *filename = mrb_sym2name_len(s->mrb, fname, NULL);
mrb_debug_info_append_file(s->mrb, s->irep->debug_info,
filename, s->lines, s->debug_start_pos, s->pc);
@@ -3137,7 +3174,7 @@ generate_code(mrb_state *mrb, parser_state *p, int val)
}
scope->mrb = mrb;
scope->parser = p;
- scope->filename = p->filename;
+ scope->filename_sym = p->filename_sym;
scope->filename_index = p->current_filename_index;
MRB_TRY(&scope->jmp) {
diff --git a/mrbgems/mruby-compiler/core/keywords b/mrbgems/mruby-compiler/core/keywords
index 9cb86608c..a60ecd10a 100644
--- a/mrbgems/mruby-compiler/core/keywords
+++ b/mrbgems/mruby-compiler/core/keywords
@@ -1,8 +1,5 @@
%{
struct kwtable {const char *name; int id[2]; enum mrb_lex_state_enum state;};
-const struct kwtable *mrb_reserved_word(const char *, unsigned int);
-static const struct kwtable *reserved_word(const char *, unsigned int);
-#define mrb_reserved_word(str, len) reserved_word(str, len)
%}
struct kwtable;
diff --git a/mrbgems/mruby-compiler/core/lex.def b/mrbgems/mruby-compiler/core/lex.def
index 2ff266481..872bf40c1 100644
--- a/mrbgems/mruby-compiler/core/lex.def
+++ b/mrbgems/mruby-compiler/core/lex.def
@@ -1,4 +1,4 @@
-/* ANSI-C code produced by gperf version 3.0.4 */
+/* ANSI-C code produced by gperf version 3.1 */
/* Command-line: gperf -L ANSI-C -C -p -j1 -i 1 -g -o -t -N mrb_reserved_word -k'1,3,$' /home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords */
#if !((' ' == 32) && ('!' == 33) && ('"' == 34) && ('#' == 35) \
@@ -25,16 +25,13 @@
&& ('w' == 119) && ('x' == 120) && ('y' == 121) && ('z' == 122) \
&& ('{' == 123) && ('|' == 124) && ('}' == 125) && ('~' == 126))
/* The character set is not based on ISO-646. */
-#error "gperf generated tables don't work with this execution character set. Please report a bug to <[email protected]>."
+#error "gperf generated tables don't work with this execution character set. Please report a bug to <[email protected]>."
#endif
#line 1 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
struct kwtable {const char *name; int id[2]; enum mrb_lex_state_enum state;};
-const struct kwtable *mrb_reserved_word(const char *, unsigned int);
-static const struct kwtable *reserved_word(const char *, unsigned int);
-#define mrb_reserved_word(str, len) reserved_word(str, len)
-#line 8 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 5 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
struct kwtable;
#define TOTAL_KEYWORDS 40
@@ -52,7 +49,7 @@ inline
#endif
#endif
static unsigned int
-hash (const char *str, unsigned int len)
+hash (register const char *str, register size_t len)
{
static const unsigned char asso_values[] =
{
@@ -83,7 +80,7 @@ hash (const char *str, unsigned int len)
51, 51, 51, 51, 51, 51, 51, 51, 51, 51,
51, 51, 51, 51, 51, 51
};
- int hval = len;
+ register unsigned int hval = len;
switch (hval)
{
@@ -98,109 +95,103 @@ hash (const char *str, unsigned int len)
return hval + asso_values[(unsigned char)str[len - 1]];
}
-#ifdef __GNUC__
-__inline
-#if defined __GNUC_STDC_INLINE__ || defined __GNUC_GNU_INLINE__
-__attribute__ ((__gnu_inline__))
-#endif
-#endif
const struct kwtable *
-mrb_reserved_word (const char *str, unsigned int len)
+mrb_reserved_word (register const char *str, register size_t len)
{
static const struct kwtable wordlist[] =
{
{""}, {""}, {""}, {""}, {""}, {""}, {""}, {""},
-#line 18 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 15 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"break", {keyword_break, keyword_break}, EXPR_MID},
-#line 23 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 20 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"else", {keyword_else, keyword_else}, EXPR_BEG},
-#line 33 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 30 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"nil", {keyword_nil, keyword_nil}, EXPR_END},
-#line 26 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 23 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"ensure", {keyword_ensure, keyword_ensure}, EXPR_BEG},
-#line 25 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 22 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"end", {keyword_end, keyword_end}, EXPR_END},
-#line 42 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 39 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"then", {keyword_then, keyword_then}, EXPR_BEG},
-#line 34 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 31 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"not", {keyword_not, keyword_not}, EXPR_ARG},
-#line 27 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 24 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"false", {keyword_false, keyword_false}, EXPR_END},
-#line 40 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 37 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"self", {keyword_self, keyword_self}, EXPR_END},
-#line 24 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 21 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"elsif", {keyword_elsif, keyword_elsif}, EXPR_VALUE},
-#line 37 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 34 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"rescue", {keyword_rescue, modifier_rescue}, EXPR_MID},
-#line 43 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 40 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"true", {keyword_true, keyword_true}, EXPR_END},
-#line 46 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 43 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"until", {keyword_until, modifier_until}, EXPR_VALUE},
-#line 45 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 42 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"unless", {keyword_unless, modifier_unless}, EXPR_VALUE},
-#line 39 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 36 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"return", {keyword_return, keyword_return}, EXPR_MID},
-#line 21 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 18 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"def", {keyword_def, keyword_def}, EXPR_FNAME},
-#line 16 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 13 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"and", {keyword_and, keyword_and}, EXPR_VALUE},
-#line 22 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 19 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"do", {keyword_do, keyword_do}, EXPR_BEG},
-#line 49 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 46 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"yield", {keyword_yield, keyword_yield}, EXPR_ARG},
-#line 28 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 25 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"for", {keyword_for, keyword_for}, EXPR_VALUE},
-#line 44 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 41 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"undef", {keyword_undef, keyword_undef}, EXPR_FNAME},
-#line 35 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 32 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"or", {keyword_or, keyword_or}, EXPR_VALUE},
-#line 30 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 27 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"in", {keyword_in, keyword_in}, EXPR_VALUE},
-#line 47 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 44 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"when", {keyword_when, keyword_when}, EXPR_VALUE},
-#line 38 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 35 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"retry", {keyword_retry, keyword_retry}, EXPR_END},
-#line 29 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 26 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"if", {keyword_if, modifier_if}, EXPR_VALUE},
-#line 19 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 16 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"case", {keyword_case, keyword_case}, EXPR_VALUE},
-#line 36 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 33 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"redo", {keyword_redo, keyword_redo}, EXPR_END},
-#line 32 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 29 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"next", {keyword_next, keyword_next}, EXPR_MID},
-#line 41 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 38 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"super", {keyword_super, keyword_super}, EXPR_ARG},
-#line 31 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 28 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"module", {keyword_module, keyword_module}, EXPR_VALUE},
-#line 17 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 14 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"begin", {keyword_begin, keyword_begin}, EXPR_BEG},
-#line 12 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 9 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"__LINE__", {keyword__LINE__, keyword__LINE__}, EXPR_END},
-#line 11 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 8 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"__FILE__", {keyword__FILE__, keyword__FILE__}, EXPR_END},
-#line 10 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 7 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"__ENCODING__", {keyword__ENCODING__, keyword__ENCODING__}, EXPR_END},
-#line 14 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 11 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"END", {keyword_END, keyword_END}, EXPR_END},
-#line 15 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 12 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"alias", {keyword_alias, keyword_alias}, EXPR_FNAME},
-#line 13 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 10 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"BEGIN", {keyword_BEGIN, keyword_BEGIN}, EXPR_END},
{""},
-#line 20 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 17 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"class", {keyword_class, keyword_class}, EXPR_CLASS},
{""}, {""},
-#line 48 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 45 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
{"while", {keyword_while, modifier_while}, EXPR_VALUE}
};
if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)
{
- int key = hash (str, len);
+ register unsigned int key = hash (str, len);
- if (key <= MAX_HASH_VALUE && key >= 0)
+ if (key <= MAX_HASH_VALUE)
{
- const char *s = wordlist[key].name;
+ register const char *s = wordlist[key].name;
if (*str == *s && !strcmp (str + 1, s + 1))
return &wordlist[key];
@@ -208,4 +199,5 @@ mrb_reserved_word (const char *str, unsigned int len)
}
return 0;
}
-#line 50 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+#line 47 "/home/matz/work/mruby/mrbgems/mruby-compiler/core/keywords"
+
diff --git a/mrbgems/mruby-compiler/core/parse.y b/mrbgems/mruby-compiler/core/parse.y
index 6a2defa8f..6576ab702 100644
--- a/mrbgems/mruby-compiler/core/parse.y
+++ b/mrbgems/mruby-compiler/core/parse.y
@@ -10,13 +10,7 @@
# define YYDEBUG 1
#endif
#define YYERROR_VERBOSE 1
-/*
- * Force yacc to use our memory management. This is a little evil because
- * the macros assume that "parser_state *p" is in scope
- */
-#define YYMALLOC(n) mrb_malloc(p->mrb, (n))
-#define YYFREE(o) mrb_free(p->mrb, (o))
-#define YYSTACK_USE_ALLOCA 0
+#define YYSTACK_USE_ALLOCA 1
#include <ctype.h>
#include <errno.h>
@@ -76,6 +70,24 @@ typedef unsigned int stack_type;
#define nint(x) ((node*)(intptr_t)(x))
#define intn(x) ((int)(intptr_t)(x))
+#if defined(MRB_COMPLEX_NUMBERS) || defined(MRB_RATIONAL_NUMBERS)
+ #define MRB_SUFFIX_SUPPORT
+
+ #ifdef MRB_RATIONAL_NUMBERS
+ #define NUM_SUFFIX_R (1<<0)
+ #else
+ #define NUM_SUFFIX_R 0
+ #endif
+
+ #ifdef MRB_COMPLEX_NUMBERS
+ #define NUM_SUFFIX_I (1<<1)
+ #else
+ #define NUM_SUFFIX_I 0
+ #endif
+
+ #define NUM_SUFFIX_ALL (NUM_SUFFIX_R | NUM_SUFFIX_I)
+#endif
+
static inline mrb_sym
intern_cstr_gen(parser_state *p, const char *s)
{
@@ -220,6 +232,26 @@ parser_strdup(parser_state *p, const char *s)
#undef strdup
#define strdup(s) parser_strdup(p, s)
+static void
+dump_int(uint16_t i, char *s)
+{
+ char *p = s;
+ char *t = s;
+
+ while (i > 0) {
+ *p++ = (i % 10)+'0';
+ i /= 10;
+ }
+ if (p == s) *p++ = '0';
+ *p = 0;
+ p--; /* point the last char */
+ while (t < p) {
+ char c = *t;
+ *t++ = *p;
+ *p-- = c;
+ }
+}
+
/* xxx ----------------------------- */
static node*
@@ -283,6 +315,20 @@ local_add(parser_state *p, mrb_sym sym)
}
}
+static void
+local_add_blk(parser_state *p, mrb_sym blk)
+{
+ /* allocate register for block */
+ local_add_f(p, blk ? blk : mrb_intern_lit(p->mrb, "&"));
+}
+
+static void
+local_add_kw(parser_state *p, mrb_sym kwd)
+{
+ /* allocate register for keywords hash */
+ local_add_f(p, kwd ? kwd : mrb_intern_lit(p->mrb, "**"));
+}
+
static node*
locals_node(parser_state *p)
{
@@ -726,13 +772,11 @@ new_args_tail(parser_state *p, node *kws, node *kwrest, mrb_sym blk)
{
node *k;
- /* allocate register for keywords hash */
if (kws || kwrest) {
- local_add_f(p, (kwrest && kwrest->cdr)? sym(kwrest->cdr) : mrb_intern_lit(p->mrb, "**"));
+ local_add_kw(p, (kwrest && kwrest->cdr)? sym(kwrest->cdr) : 0);
}
- /* allocate register for block */
- local_add_f(p, blk? blk : mrb_intern_lit(p->mrb, "&"));
+ local_add_blk(p, blk);
// allocate register for keywords arguments
// order is for Proc#parameters
@@ -810,19 +854,57 @@ new_op_asgn(parser_state *p, node *a, mrb_sym op, node *b)
return list4((node*)NODE_OP_ASGN, a, nsym(op), b);
}
+#ifdef MRB_COMPLEX_NUMBERS
+static node*
+new_imaginary(parser_state *p, node *imaginary)
+{
+ return new_call(p, new_const(p, intern_cstr("Kernel")), intern_cstr("Complex"), list1(list2(list3((node*)NODE_INT, (node*)strdup("0"), nint(10)), imaginary)), 1);
+}
+#endif
+
+#ifdef MRB_RATIONAL_NUMBERS
+static node*
+new_rational(parser_state *p, node *rational)
+{
+ return new_call(p, new_const(p, intern_cstr("Kernel")), intern_cstr("Rational"), list1(list1(rational)), 1);
+}
+#endif
+
/* (:int . i) */
static node*
-new_int(parser_state *p, const char *s, int base)
+new_int(parser_state *p, const char *s, int base, int suffix)
{
- return list3((node*)NODE_INT, (node*)strdup(s), nint(base));
+ node* result = list3((node*)NODE_INT, (node*)strdup(s), nint(base));
+#ifdef MRB_RATIONAL_NUMBERS
+ if (suffix & NUM_SUFFIX_R) {
+ result = new_rational(p, result);
+ }
+#endif
+#ifdef MRB_COMPLEX_NUMBERS
+ if (suffix & NUM_SUFFIX_I) {
+ result = new_imaginary(p, result);
+ }
+#endif
+ return result;
}
#ifndef MRB_WITHOUT_FLOAT
/* (:float . i) */
static node*
-new_float(parser_state *p, const char *s)
+new_float(parser_state *p, const char *s, int suffix)
{
- return cons((node*)NODE_FLOAT, (node*)strdup(s));
+ node* result = cons((node*)NODE_FLOAT, (node*)strdup(s));
+#ifdef MRB_RATIONAL_NUMBERS
+ if (suffix & NUM_SUFFIX_R) {
+ result = new_rational(p, result);
+ }
+#endif
+#ifdef MRB_COMPLEX_NUMBERS
+ if (suffix & NUM_SUFFIX_I) {
+ result = new_imaginary(p, result);
+ }
+#endif
+ return result;
}
#endif
@@ -840,6 +922,86 @@ new_dstr(parser_state *p, node *a)
return cons((node*)NODE_DSTR, a);
}
+static int
+string_node_p(node *n)
+{
+ return (int)((enum node_type)(intptr_t)n->car == NODE_STR);
+}
+
+static node*
+composite_string_node(parser_state *p, node *a, node *b)
+{
+ size_t newlen = (size_t)a->cdr + (size_t)b->cdr;
+ char *str = (char*)mrb_pool_realloc(p->pool, a->car, (size_t)a->cdr + 1, newlen + 1);
+ memcpy(str + (size_t)a->cdr, b->car, (size_t)b->cdr);
+ str[newlen] = '\0';
+ a->car = (node*)str;
+ a->cdr = (node*)newlen;
+ cons_free(b);
+ return a;
+}
+
+static node*
+concat_string(parser_state *p, node *a, node *b)
+{
+ if (string_node_p(a)) {
+ if (string_node_p(b)) {
+ /* a == NODE_STR && b == NODE_STR */
+ composite_string_node(p, a->cdr, b->cdr);
+ cons_free(b);
+ return a;
+ }
+ else {
+ /* a == NODE_STR && b == NODE_DSTR */
+
+ if (string_node_p(b->cdr->car)) {
+ /* a == NODE_STR && b->[NODE_STR, ...] */
+ composite_string_node(p, a->cdr, b->cdr->car->cdr);
+ cons_free(b->cdr->car);
+ b->cdr->car = a;
+ return b;
+ }
+ }
+ }
+ else {
+ node *c; /* last node of a */
+ for (c = a; c->cdr != NULL; c = c->cdr) ;
+
+ if (string_node_p(b)) {
+ /* a == NODE_DSTR && b == NODE_STR */
+ if (string_node_p(c->car)) {
+ /* a->[..., NODE_STR] && b == NODE_STR */
+ composite_string_node(p, c->car->cdr, b->cdr);
+ cons_free(b);
+ return a;
+ }
+
+ push(a, b);
+ return a;
+ }
+ else {
+ /* a == NODE_DSTR && b == NODE_DSTR */
+ if (string_node_p(c->car) && string_node_p(b->cdr->car)) {
+ /* a->[..., NODE_STR] && b->[NODE_STR, ...] */
+ node *d = b->cdr;
+ cons_free(b);
+ composite_string_node(p, c->car->cdr, d->car->cdr);
+ cons_free(d->car);
+ c->cdr = d->cdr;
+ cons_free(d);
+ return a;
+ }
+ else {
+ c->cdr = b->cdr;
+ cons_free(b);
+ return a;
+ }
+ }
+ }
+
+ return new_dstr(p, list2(a, b));
+}
+
/* (:str . (s . len)) */
static node*
new_xstr(parser_state *p, const char *s, int len)
@@ -1188,7 +1350,7 @@ heredoc_end(parser_state *p)
%token <nd> tNTH_REF tBACK_REF
%token <num> tREGEXP_END
-%type <nd> singleton string string_rep string_interp xstring regexp
+%type <nd> singleton string string_fragment string_rep string_interp xstring regexp
%type <nd> literal numeric cpath symbol
%type <nd> top_compstmt top_stmts top_stmt
%type <nd> bodystmt compstmt stmts stmt expr arg primary command command_call method_call
@@ -2567,9 +2729,9 @@ block_param : f_arg ',' f_block_optarg ',' f_rest_arg opt_block_args_tail
{
$$ = new_args(p, $1, 0, $3, 0, $4);
}
- | f_arg ','
+ | f_arg ',' opt_block_args_tail
{
- $$ = new_args(p, $1, 0, 0, 0, 0);
+ $$ = new_args(p, $1, 0, 0, 0, $3);
}
| f_arg ',' f_rest_arg ',' f_arg opt_block_args_tail
{
@@ -2610,19 +2772,24 @@ block_param : f_arg ',' f_block_optarg ',' f_rest_arg opt_block_args_tail
;
opt_block_param : none
- | block_param_def
{
+ local_add_blk(p, 0);
+ $$ = 0;
+ }
+ | block_param_def
+ {
p->cmd_start = TRUE;
$$ = $1;
}
;
-block_param_def : '|' opt_bv_decl '|'
+block_param_def : '|' {local_add_blk(p, 0);} opt_bv_decl '|'
{
$$ = 0;
}
| tOROP
{
+ local_add_blk(p, 0);
$$ = 0;
}
| '|' block_param opt_bv_decl '|'
@@ -2835,7 +3002,14 @@ literal : numeric
| symbols
;
-string : tCHAR
+string : string_fragment
+ | string string_fragment
+ {
+ $$ = concat_string(p, $1, $2);
+ }
+ ;
+
+string_fragment : tCHAR
| tSTRING
| tSTRING_BEG tSTRING
{
@@ -3057,7 +3231,7 @@ var_ref : variable
}
| keyword__FILE__
{
- const char *fn = p->filename;
+ const char *fn = mrb_sym2name_len(p->mrb, p->filename_sym, NULL);
if (!fn) {
fn = "(null)";
}
@@ -3067,8 +3241,8 @@ var_ref : variable
{
char buf[16];
- snprintf(buf, sizeof(buf), "%d", p->lineno);
- $$ = new_int(p, buf, 10);
+ dump_int(p->lineno, buf);
+ $$ = new_int(p, buf, 10, 0);
}
| keyword__ENCODING__
{
@@ -3461,7 +3635,7 @@ assoc : arg tASSOC arg
void_expr_error(p, $3);
$$ = cons(new_sym(p, $1), $3);
}
- | string tLABEL_TAG arg
+ | string_fragment tLABEL_TAG arg
{
void_expr_error(p, $3);
if ($1->car == (node*)NODE_DSTR) {
@@ -3566,8 +3740,9 @@ yyerror(parser_state *p, const char *s)
if (! p->capture_errors) {
#ifndef MRB_DISABLE_STDIO
- if (p->filename) {
- fprintf(stderr, "%s:%d:%d: %s\n", p->filename, p->lineno, p->column, s);
+ if (p->filename_sym) {
+ const char *filename = mrb_sym2name_len(p->mrb, p->filename_sym, NULL);
+ fprintf(stderr, "%s:%d:%d: %s\n", filename, p->lineno, p->column, s);
}
else {
fprintf(stderr, "line %d:%d: %s\n", p->lineno, p->column, s);
@@ -3586,11 +3761,13 @@ yyerror(parser_state *p, const char *s)
}
static void
-yyerror_i(parser_state *p, const char *fmt, int i)
+yyerror_c(parser_state *p, const char *msg, char c)
{
char buf[256];
- snprintf(buf, sizeof(buf), fmt, i);
+ strncpy(buf, msg, sizeof(buf) - 2);
+ buf[sizeof(buf) - 2] = '\0';
+ strncat(buf, &c, 1);
yyerror(p, buf);
}
@@ -3602,11 +3779,12 @@ yywarn(parser_state *p, const char *s)
if (! p->capture_errors) {
#ifndef MRB_DISABLE_STDIO
- if (p->filename) {
- fprintf(stderr, "%s:%d:%d: %s\n", p->filename, p->lineno, p->column, s);
+ if (p->filename_sym) {
+ const char *filename = mrb_sym2name_len(p->mrb, p->filename_sym, NULL);
+ fprintf(stderr, "%s:%d:%d: warning: %s\n", filename, p->lineno, p->column, s);
}
else {
- fprintf(stderr, "line %d:%d: %s\n", p->lineno, p->column, s);
+ fprintf(stderr, "line %d:%d: warning: %s\n", p->lineno, p->column, s);
}
#endif
}
@@ -3628,11 +3806,14 @@ yywarning(parser_state *p, const char *s)
}
static void
-yywarning_s(parser_state *p, const char *fmt, const char *s)
+yywarning_s(parser_state *p, const char *msg, const char *s)
{
char buf[256];
- snprintf(buf, sizeof(buf), fmt, s);
+ strncpy(buf, msg, sizeof(buf) - 1);
+ buf[sizeof(buf) - 1] = '\0';
+ strncat(buf, ": ", sizeof(buf) - strlen(buf) - 1);
+ strncat(buf, s, sizeof(buf) - strlen(buf) - 1);
yywarning(p, buf);
}
@@ -3644,13 +3825,13 @@ backref_error(parser_state *p, node *n)
c = intn(n->car);
if (c == NODE_NTH_REF) {
- yyerror_i(p, "can't set variable $%" MRB_PRId, intn(n->cdr));
+ yyerror_c(p, "can't set variable $", (char)intn(n->cdr)+'0');
}
else if (c == NODE_BACK_REF) {
- yyerror_i(p, "can't set variable $%c", intn(n->cdr));
+ yyerror_c(p, "can't set variable $", (char)intn(n->cdr));
}
else {
- mrb_bug(p->mrb, "Internal error in backref_error() : n=>car == %S", mrb_fixnum_value(c));
+ mrb_bug(p->mrb, "Internal error in backref_error() : n=>car == %d", c);
}
}
@@ -4191,8 +4372,17 @@ parse_string(parser_state *p)
}
if (c < 0) {
char buf[256];
- snprintf(buf, sizeof(buf), "can't find heredoc delimiter \"%s\" anywhere before EOF", hinf->term);
- yyerror(p, buf);
+ const char s1[] = "can't find heredoc delimiter \"";
+ const char s2[] = "\" anywhere before EOF";
+
+ if (sizeof(s1)+sizeof(s2)+strlen(hinf->term)+1 >= sizeof(buf)) {
+ yyerror(p, "can't find heredoc delimiter anywhere before EOF");
+ } else {
+ strcpy(buf, s1);
+ strcat(buf, hinf->term);
+ strcat(buf, s2);
+ yyerror(p, buf);
+ }
return 0;
}
pylval.nd = new_str(p, tok(p), toklen(p));
@@ -4336,15 +4526,21 @@ parse_string(parser_state *p)
case 'm': f |= 4; break;
case 'u': f |= 16; break;
case 'n': f |= 32; break;
+ case 'o': break;
default: tokadd(p, re_opt); break;
}
}
pushback(p, re_opt);
if (toklen(p)) {
char msg[128];
+
+ strcpy(msg, "unknown regexp option");
tokfix(p);
- snprintf(msg, sizeof(msg), "unknown regexp option%s - %s",
- toklen(p) > 1 ? "s" : "", tok(p));
+ if (toklen(p) > 1) {
+ strcat(msg, "s");
+ }
+ strcat(msg, " - ");
+ strncat(msg, tok(p), sizeof(msg) - strlen(msg) - 1);
yyerror(p, msg);
}
if (f != 0) {
@@ -4375,6 +4571,45 @@ parse_string(parser_state *p)
return tSTRING;
}
+#ifdef MRB_SUFFIX_SUPPORT
+static int
+number_literal_suffix(parser_state *p, int mask)
+{
+ int c, result = 0;
+ node *list = 0;
+ int column = p->column;
+
+ while ((c = nextc(p)) != -1) {
+ list = push(list, (node*)(intptr_t)c);
+
+ if ((mask & NUM_SUFFIX_I) && c == 'i') {
+ result |= (mask & NUM_SUFFIX_I);
+ mask &= ~NUM_SUFFIX_I;
+ /* r after i, rational of complex is disallowed */
+ mask &= ~NUM_SUFFIX_R;
+ continue;
+ }
+ if ((mask & NUM_SUFFIX_R) && c == 'r') {
+ result |= (mask & NUM_SUFFIX_R);
+ mask &= ~NUM_SUFFIX_R;
+ continue;
+ }
+ if (!ISASCII(c) || ISALPHA(c) || c == '_') {
+ p->column = column;
+ if (p->pb) {
+ p->pb = append((node*)list, p->pb);
+ }
+ else {
+ p->pb = list;
+ }
+ return 0;
+ }
+ pushback(p, c);
+ break;
+ }
+ return result;
+}
+#endif
static int
heredoc_identifier(parser_state *p)
@@ -4495,52 +4730,66 @@ parser_yylex(parser_state *p)
/* fall through */
case -2: /* end of a file */
case '\n':
- maybe_heredoc:
+ maybe_heredoc:
heredoc_treat_nextline(p);
- switch (p->lstate) {
- case EXPR_BEG:
- case EXPR_FNAME:
- case EXPR_DOT:
- case EXPR_CLASS:
- case EXPR_VALUE:
- p->lineno++;
p->column = 0;
- if (p->parsing_heredoc != NULL) {
- if (p->lex_strterm) {
- return parse_string(p);
+ switch (p->lstate) {
+ case EXPR_BEG:
+ case EXPR_FNAME:
+ case EXPR_DOT:
+ case EXPR_CLASS:
+ case EXPR_VALUE:
+ p->lineno++;
+ if (p->parsing_heredoc != NULL) {
+ if (p->lex_strterm) {
+ return parse_string(p);
+ }
}
- }
- goto retry;
- default:
- break;
- }
- if (p->parsing_heredoc != NULL) {
- return '\n';
- }
- while ((c = nextc(p))) {
- switch (c) {
- case ' ': case '\t': case '\f': case '\r':
- case '\13': /* '\v' */
- space_seen = 1;
+ goto retry;
+ default:
break;
- case '.':
- if ((c = nextc(p)) != '.') {
- pushback(p, c);
- pushback(p, '.');
+ }
+ if (p->parsing_heredoc != NULL) {
+ return '\n';
+ }
+ while ((c = nextc(p))) {
+ switch (c) {
+ case ' ': case '\t': case '\f': case '\r':
+ case '\13': /* '\v' */
+ space_seen = 1;
+ break;
+ case '#': /* comment as a whitespace */
+ pushback(p, '#');
+ p->lineno++;
goto retry;
+ case '.':
+ if (!peek(p, '.')) {
+ pushback(p, '.');
+ p->lineno++;
+ goto retry;
+ }
+ pushback(p, c);
+ goto normal_newline;
+ case '&':
+ if (peek(p, '.')) {
+ pushback(p, '&');
+ p->lineno++;
+ goto retry;
+ }
+ pushback(p, c);
+ goto normal_newline;
+ case -1: /* EOF */
+ case -2: /* end of a file */
+ goto normal_newline;
+ default:
+ pushback(p, c);
+ goto normal_newline;
}
- case -1: /* EOF */
- case -2: /* end of a file */
- goto normal_newline;
- default:
- pushback(p, c);
- goto normal_newline;
}
- }
normal_newline:
- p->cmd_start = TRUE;
- p->lstate = EXPR_BEG;
- return '\n';
+ p->cmd_start = TRUE;
+ p->lstate = EXPR_BEG;
+ return '\n';
case '*':
if ((c = nextc(p)) == '*') {
@@ -4551,7 +4800,7 @@ parser_yylex(parser_state *p)
}
pushback(p, c);
if (IS_SPCARG(c)) {
- yywarning(p, "`**' interpreted as argument prefix");
+ yywarning(p, "'**' interpreted as argument prefix");
c = tDSTAR;
}
else if (IS_BEG()) {
@@ -4772,7 +5021,10 @@ parser_yylex(parser_state *p)
}
if (c2) {
char buf[256];
- snprintf(buf, sizeof(buf), "invalid character syntax; use ?\\%c", c2);
+ char cc[] = { (char)c2, '\0' };
+
+ strcpy(buf, "invalid character syntax; use ?\\");
+ strncat(buf, cc, 2);
yyerror(p, buf);
}
}
@@ -4783,10 +5035,10 @@ parser_yylex(parser_state *p)
}
newtok(p);
/* need support UTF-8 if configured */
- if ((isalnum(c) || c == '_')) {
+ if ((ISALNUM(c) || c == '_')) {
int c2 = nextc(p);
pushback(p, c2);
- if ((isalnum(c2) || c2 == '_')) {
+ if ((ISALNUM(c2) || c2 == '_')) {
goto ternary;
}
}
@@ -4946,6 +5198,7 @@ parser_yylex(parser_state *p)
case '5': case '6': case '7': case '8': case '9':
{
int is_float, seen_point, seen_e, nondigit;
+ int suffix = 0;
is_float = seen_point = seen_e = nondigit = 0;
p->lstate = EXPR_ENDARG;
@@ -4979,7 +5232,10 @@ parser_yylex(parser_state *p)
no_digits();
}
else if (nondigit) goto trailing_uc;
- pylval.nd = new_int(p, tok(p), 16);
+ #ifdef MRB_SUFFIX_SUPPORT
+ suffix = number_literal_suffix(p, NUM_SUFFIX_ALL);
+ #endif
+ pylval.nd = new_int(p, tok(p), 16, suffix);
return tINTEGER;
}
if (c == 'b' || c == 'B') {
@@ -5003,7 +5259,10 @@ parser_yylex(parser_state *p)
no_digits();
}
else if (nondigit) goto trailing_uc;
- pylval.nd = new_int(p, tok(p), 2);
+ #ifdef MRB_SUFFIX_SUPPORT
+ suffix = number_literal_suffix(p, NUM_SUFFIX_ALL);
+ #endif
+ pylval.nd = new_int(p, tok(p), 2, suffix);
return tINTEGER;
}
if (c == 'd' || c == 'D') {
@@ -5027,7 +5286,10 @@ parser_yylex(parser_state *p)
no_digits();
}
else if (nondigit) goto trailing_uc;
- pylval.nd = new_int(p, tok(p), 10);
+ #ifdef MRB_SUFFIX_SUPPORT
+ suffix = number_literal_suffix(p, NUM_SUFFIX_ALL);
+ #endif
+ pylval.nd = new_int(p, tok(p), 10, suffix);
return tINTEGER;
}
if (c == '_') {
@@ -5060,7 +5322,10 @@ parser_yylex(parser_state *p)
pushback(p, c);
tokfix(p);
if (nondigit) goto trailing_uc;
- pylval.nd = new_int(p, tok(p), 8);
+ #ifdef MRB_SUFFIX_SUPPORT
+ suffix = number_literal_suffix(p, NUM_SUFFIX_ALL);
+ #endif
+ pylval.nd = new_int(p, tok(p), 8, suffix);
return tINTEGER;
}
if (nondigit) {
@@ -5077,7 +5342,10 @@ parser_yylex(parser_state *p)
}
else {
pushback(p, c);
- pylval.nd = new_int(p, "0", 10);
+ #ifdef MRB_SUFFIX_SUPPORT
+ suffix = number_literal_suffix(p, NUM_SUFFIX_ALL);
+ #endif
+ pylval.nd = new_int(p, "0", 10, suffix);
return tINTEGER;
}
}
@@ -5145,13 +5413,13 @@ parser_yylex(parser_state *p)
pushback(p, c);
if (nondigit) {
trailing_uc:
- yyerror_i(p, "trailing '%c' in number", nondigit);
+ yyerror_c(p, "trailing non digit in number: ", (char)nondigit);
}
tokfix(p);
if (is_float) {
#ifdef MRB_WITHOUT_FLOAT
yywarning_s(p, "floating point numbers are not supported", tok(p));
- pylval.nd = new_int(p, "0", 10);
+ pylval.nd = new_int(p, "0", 10, 0);
return tINTEGER;
#else
double d;
@@ -5160,17 +5428,23 @@ parser_yylex(parser_state *p)
errno = 0;
d = mrb_float_read(tok(p), &endp);
if (d == 0 && endp == tok(p)) {
- yywarning_s(p, "corrupted float value %s", tok(p));
+ yywarning_s(p, "corrupted float value", tok(p));
}
else if (errno == ERANGE) {
- yywarning_s(p, "float %s out of range", tok(p));
+ yywarning_s(p, "float out of range", tok(p));
errno = 0;
}
- pylval.nd = new_float(p, tok(p));
+ #ifdef MRB_SUFFIX_SUPPORT
+ suffix = number_literal_suffix(p, NUM_SUFFIX_ALL);
+ #endif
+ pylval.nd = new_float(p, tok(p), suffix);
return tFLOAT;
#endif
}
- pylval.nd = new_int(p, tok(p), 10);
+ #ifdef MRB_SUFFIX_SUPPORT
+ suffix = number_literal_suffix(p, NUM_SUFFIX_ALL);
+ #endif
+ pylval.nd = new_int(p, tok(p), 10, suffix);
return tINTEGER;
}
@@ -5354,7 +5628,7 @@ parser_yylex(parser_state *p)
}
else {
term = nextc(p);
- if (isalnum(term)) {
+ if (ISALNUM(term)) {
yyerror(p, "unknown type of %string");
return 0;
}
@@ -5498,14 +5772,14 @@ parser_yylex(parser_state *p)
do {
tokadd(p, c);
c = nextc(p);
- } while (c >= 0 && isdigit(c));
+ } while (c >= 0 && ISDIGIT(c));
pushback(p, c);
if (last_state == EXPR_FNAME) goto gvar;
tokfix(p);
{
unsigned long n = strtoul(tok(p), NULL, 10);
if (n > INT_MAX) {
- yyerror_i(p, "capture group index must be <= %d", INT_MAX);
+ yyerror(p, "capture group index must be <= " MRB_STRINGIZE(INT_MAX));
return 0;
}
pylval.nd = new_nth_ref(p, (int)n);
@@ -5540,12 +5814,12 @@ parser_yylex(parser_state *p)
}
return 0;
}
- else if (isdigit(c)) {
+ else if (ISDIGIT(c)) {
if (p->tidx == 1) {
- yyerror_i(p, "'@%c' is not allowed as an instance variable name", c);
+ yyerror_c(p, "wrong instance variable name: @", c);
}
else {
- yyerror_i(p, "'@@%c' is not allowed as a class variable name", c);
+ yyerror_c(p, "wrong class variable name: @@", c);
}
return 0;
}
@@ -5561,7 +5835,15 @@ parser_yylex(parser_state *p)
default:
if (!identchar(c)) {
- yyerror_i(p, "Invalid char '\\x%02X' in expression", c);
+ char buf[36];
+ const char s[] = "Invalid char in expression: 0x";
+ const char hexdigits[] = "0123456789ABCDEF";
+
+ strcpy(buf, s);
+ buf[sizeof(s)-1] = hexdigits[(c & 0xf0) >> 4];
+ buf[sizeof(s)] = hexdigits[(c & 0x0f)];
+ buf[sizeof(s)+1] = 0;
+ yyerror(p, buf);
goto retry;
}
@@ -5697,7 +5979,7 @@ parser_yylex(parser_state *p)
mrb_sym ident = intern_cstr(tok(p));
pylval.id = ident;
- if (last_state != EXPR_DOT && islower(tok(p)[0]) && local_var_p(p, ident)) {
+ if (last_state != EXPR_DOT && ISLOWER(tok(p)[0]) && local_var_p(p, ident)) {
p->lstate = EXPR_END;
}
}
@@ -5907,7 +6189,7 @@ mrb_parser_set_filename(struct mrb_parser_state *p, const char *f)
mrb_sym* new_table;
sym = mrb_intern_cstr(p->mrb, f);
- p->filename = mrb_sym2name_len(p->mrb, sym, NULL);
+ p->filename_sym = sym;
p->lineno = (p->filename_table_length > 0)? 0 : 1;
for (i = 0; i < p->filename_table_length; ++i) {
@@ -5931,11 +6213,11 @@ mrb_parser_set_filename(struct mrb_parser_state *p, const char *f)
p->filename_table[p->filename_table_length - 1] = sym;
}
-MRB_API char const*
+MRB_API mrb_sym
mrb_parser_get_filename(struct mrb_parser_state* p, uint16_t idx) {
- if (idx >= p->filename_table_length) return NULL;
+ if (idx >= p->filename_table_length) return 0;
else {
- return mrb_sym2name_len(p->mrb, p->filename_table[idx], NULL);
+ return p->filename_table[idx];
}
}
@@ -5990,11 +6272,12 @@ mrb_load_exec(mrb_state *mrb, struct mrb_parser_state *p, mrbc_context *c)
if (c) c->parser_nerr = p->nerr;
if (p->capture_errors) {
char buf[256];
- int n;
- n = snprintf(buf, sizeof(buf), "line %d: %s\n",
- p->error_buffer[0].lineno, p->error_buffer[0].message);
- mrb->exc = mrb_obj_ptr(mrb_exc_new(mrb, E_SYNTAX_ERROR, buf, n));
+ strcpy(buf, "line ");
+ dump_int(p->error_buffer[0].lineno, buf+5);
+ strcat(buf, ": ");
+ strncat(buf, p->error_buffer[0].message, sizeof(buf) - strlen(buf) - 1);
+ mrb->exc = mrb_obj_ptr(mrb_exc_new(mrb, E_SYNTAX_ERROR, buf, strlen(buf)));
mrb_parser_free(p);
return mrb_undef_value();
}
diff --git a/mrbgems/mruby-complex/mrbgem.rake b/mrbgems/mruby-complex/mrbgem.rake
new file mode 100644
index 000000000..19612e74d
--- /dev/null
+++ b/mrbgems/mruby-complex/mrbgem.rake
@@ -0,0 +1,10 @@
+MRuby::Gem::Specification.new('mruby-complex') do |spec|
+ spec.license = 'MIT'
+ spec.author = 'mruby developers'
+ spec.summary = 'Complex class'
+
+ spec.add_dependency 'mruby-metaprog', core: 'mruby-metaprog'
+ spec.add_dependency 'mruby-object-ext', core: 'mruby-object-ext'
+ spec.add_dependency 'mruby-numeric-ext', core: 'mruby-numeric-ext'
+ spec.add_dependency 'mruby-math', core: 'mruby-math'
+end
diff --git a/mrbgems/mruby-complex/mrblib/complex.rb b/mrbgems/mruby-complex/mrblib/complex.rb
new file mode 100644
index 000000000..f32b84c8b
--- /dev/null
+++ b/mrbgems/mruby-complex/mrblib/complex.rb
@@ -0,0 +1,122 @@
+class Complex < Numeric
+ def self.polar(abs, arg = 0)
+ Complex(abs * Math.cos(arg), abs * Math.sin(arg))
+ end
+
+ def inspect
+ "(#{to_s})"
+ end
+
+ def to_s
+ "#{real}#{'+' unless imaginary.negative?}#{imaginary}i"
+ end
+
+ def +@
+ Complex(real, imaginary)
+ end
+
+ def -@
+ Complex(-real, -imaginary)
+ end
+
+ def +(rhs)
+ if rhs.is_a? Complex
+ Complex(real + rhs.real, imaginary + rhs.imaginary)
+ elsif rhs.is_a? Numeric
+ Complex(real + rhs, imaginary)
+ end
+ end
+
+ def -(rhs)
+ if rhs.is_a? Complex
+ Complex(real - rhs.real, imaginary - rhs.imaginary)
+ elsif rhs.is_a? Numeric
+ Complex(real - rhs, imaginary)
+ end
+ end
+
+ def *(rhs)
+ if rhs.is_a? Complex
+ Complex(real * rhs.real - imaginary * rhs.imaginary, real * rhs.imaginary + rhs.real * imaginary)
+ elsif rhs.is_a? Numeric
+ Complex(real * rhs, imaginary * rhs)
+ end
+ end
+
+ def /(rhs)
+ if rhs.is_a? Complex
+ __div__(rhs)
+ elsif rhs.is_a? Numeric
+ Complex(real / rhs, imaginary / rhs)
+ end
+ end
+ alias_method :quo, :/
+
+ def ==(rhs)
+ if rhs.is_a? Complex
+ real == rhs.real && imaginary == rhs.imaginary
+ elsif rhs.is_a? Numeric
+ imaginary.zero? && real == rhs
+ end
+ end
+
+ def abs
+ Math.hypot imaginary, real
+ end
+ alias_method :magnitude, :abs
+
+ def abs2
+ real * real + imaginary * imaginary
+ end
+
+ def arg
+ Math.atan2 imaginary, real
+ end
+ alias_method :angle, :arg
+ alias_method :phase, :arg
+
+ def conjugate
+ Complex(real, -imaginary)
+ end
+ alias_method :conj, :conjugate
+
+ def fdiv(numeric)
+ Complex(real.to_f / numeric, imaginary.to_f / numeric)
+ end
+
+ def polar
+ [abs, arg]
+ end
+
+ def real?
+ false
+ end
+
+ def rectangular
+ [real, imaginary]
+ end
+ alias_method :rect, :rectangular
+
+ def to_r
+ raise RangeError.new "can't convert #{to_s} into Rational" unless imaginary.zero?
+ Rational(real, 1)
+ end
+
+ alias_method :imag, :imaginary
+
+ [Fixnum, Float].each do |cls|
+ [:+, :-, :*, :/, :==].each do |op|
+ cls.instance_exec do
+ original_operator_name = "__original_operator_#{op}_complex"
+ alias_method original_operator_name, op
+ define_method op do |rhs|
+ if rhs.is_a? Complex
+ Complex(self).send(op, rhs)
+ else
+ send(original_operator_name, rhs)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/mrbgems/mruby-complex/src/complex.c b/mrbgems/mruby-complex/src/complex.c
new file mode 100644
index 000000000..10fa42a2c
--- /dev/null
+++ b/mrbgems/mruby-complex/src/complex.c
@@ -0,0 +1,249 @@
+#include <mruby.h>
+#include <mruby/class.h>
+#include <mruby/numeric.h>
+#include <math.h>
+
+#ifdef MRB_WITHOUT_FLOAT
+# error Complex conflicts 'MRB_WITHOUT_FLOAT' configuration in your 'build_config.rb'
+#endif
+
+struct mrb_complex {
+ mrb_float real;
+ mrb_float imaginary;
+};
+
+#ifdef MRB_USE_FLOAT
+#define F(x) x##f
+#else
+#define F(x) x
+#endif
+
+#if defined(MRB_64BIT) || defined(MRB_USE_FLOAT)
+
+#define COMPLEX_USE_ISTRUCT
+/* use TT_ISTRUCT */
+#include <mruby/istruct.h>
+
+#define complex_ptr(mrb, v) (struct mrb_complex*)mrb_istruct_ptr(v)
+
+static struct RBasic*
+complex_alloc(mrb_state *mrb, struct RClass *c, struct mrb_complex **p)
+{
+ struct RIStruct *s;
+
+ s = (struct RIStruct*)mrb_obj_alloc(mrb, MRB_TT_ISTRUCT, c);
+ *p = (struct mrb_complex*)s->inline_data;
+
+ return (struct RBasic*)s;
+}
+
+#else
+/* use TT_DATA */
+#include <mruby/data.h>
+
+static const struct mrb_data_type mrb_complex_type = {"Complex", mrb_free};
+
+static struct RBasic*
+complex_alloc(mrb_state *mrb, struct RClass *c, struct mrb_complex **p)
+{
+ struct RData *d;
+
+ Data_Make_Struct(mrb, c, struct mrb_complex, &mrb_complex_type, *p, d);
+
+ return (struct RBasic*)d;
+}
+
+static struct mrb_complex*
+complex_ptr(mrb_state *mrb, mrb_value v)
+{
+ struct mrb_complex *p;
+
+ p = DATA_GET_PTR(mrb, v, &mrb_complex_type, struct mrb_complex);
+ if (!p) {
+ mrb_raise(mrb, E_ARGUMENT_ERROR, "uninitialized complex");
+ }
+ return p;
+}
+#endif
+
+static mrb_value
+complex_new(mrb_state *mrb, mrb_float real, mrb_float imaginary)
+{
+ struct RClass *c = mrb_class_get(mrb, "Complex");
+ struct mrb_complex *p;
+ struct RBasic *comp = complex_alloc(mrb, c, &p);
+ p->real = real;
+ p->imaginary = imaginary;
+ MRB_SET_FROZEN_FLAG(comp);
+
+ return mrb_obj_value(comp);
+}
+
+static mrb_value
+complex_real(mrb_state *mrb, mrb_value self)
+{
+ struct mrb_complex *p = complex_ptr(mrb, self);
+ return mrb_float_value(mrb, p->real);
+}
+
+static mrb_value
+complex_imaginary(mrb_state *mrb, mrb_value self)
+{
+ struct mrb_complex *p = complex_ptr(mrb, self);
+ return mrb_float_value(mrb, p->imaginary);
+}
+
+static mrb_value
+complex_s_rect(mrb_state *mrb, mrb_value self)
+{
+ mrb_float real, imaginary = 0.0;
+
+ mrb_get_args(mrb, "f|f", &real, &imaginary);
+ return complex_new(mrb, real, imaginary);
+}
+
+static mrb_value
+complex_to_f(mrb_state *mrb, mrb_value self)
+{
+ struct mrb_complex *p = complex_ptr(mrb, self);
+
+ if (p->imaginary != 0) {
+ mrb_raisef(mrb, E_RANGE_ERROR, "can't convert %v into Float", self);
+ }
+
+ return mrb_float_value(mrb, p->real);
+}
+
+static mrb_value
+complex_to_i(mrb_state *mrb, mrb_value self)
+{
+ struct mrb_complex *p = complex_ptr(mrb, self);
+
+ if (p->imaginary != 0) {
+ mrb_raisef(mrb, E_RANGE_ERROR, "can't convert %v into Float", self);
+ }
+ return mrb_int_value(mrb, p->real);
+}
+
+static mrb_value
+complex_to_c(mrb_state *mrb, mrb_value self)
+{
+ return self;
+}
+
+/* Arithmetic on (significand, exponent) pairs avoids premature overflow in
+ complex division */
+struct float_pair {
+ mrb_float s;
+ int x;
+};
+
+static void
+add_pair(struct float_pair *s, struct float_pair const *a,
+ struct float_pair const *b)
+{
+ if (b->s == 0.0F) {
+ *s = *a;
+ } else if (a->s == 0.0F) {
+ *s = *b;
+ } else if (a->x >= b->x) {
+ s->s = a->s + F(ldexp)(b->s, b->x - a->x);
+ s->x = a->x;
+ } else {
+ s->s = F(ldexp)(a->s, a->x - b->x) + b->s;
+ s->x = b->x;
+ }
+}
+
+static void
+mul_pair(struct float_pair *p, struct float_pair const *a,
+ struct float_pair const *b)
+{
+ p->s = a->s * b->s;
+ p->x = a->x + b->x;
+}
+
+static void
+div_pair(struct float_pair *q, struct float_pair const *a,
+ struct float_pair const *b)
+{
+ q->s = a->s / b->s;
+ q->x = a->x - b->x;
+}
+
+static mrb_value
+complex_div(mrb_state *mrb, mrb_value self)
+{
+ mrb_value rhs;
+ struct mrb_complex *a, *b;
+ struct float_pair ar, ai, br, bi;
+ struct float_pair br2, bi2;
+ struct float_pair div;
+ struct float_pair ar_br, ai_bi;
+ struct float_pair ai_br, ar_bi;
+ struct float_pair zr, zi;
+
+ mrb_get_args(mrb, "o", &rhs);
+ a = complex_ptr(mrb, self);
+ b = complex_ptr(mrb, rhs);
+
+ /* Split floating point components into significand and exponent */
+ ar.s = F(frexp)(a->real, &ar.x);
+ ai.s = F(frexp)(a->imaginary, &ai.x);
+ br.s = F(frexp)(b->real, &br.x);
+ bi.s = F(frexp)(b->imaginary, &bi.x);
+
+ /* Perform arithmetic on (significand, exponent) pairs to produce
+ the result: */
+
+ /* the divisor */
+ mul_pair(&br2, &br, &br);
+ mul_pair(&bi2, &bi, &bi);
+ add_pair(&div, &br2, &bi2);
+
+ /* real component */
+ mul_pair(&ar_br, &ar, &br);
+ mul_pair(&ai_bi, &ai, &bi);
+ add_pair(&zr, &ar_br, &ai_bi);
+ div_pair(&zr, &zr, &div);
+
+ /* imaginary component */
+ mul_pair(&ai_br, &ai, &br);
+ mul_pair(&ar_bi, &ar, &bi);
+ ar_bi.s = -ar_bi.s;
+ add_pair(&zi, &ai_br, &ar_bi);
+ div_pair(&zi, &zi, &div);
+
+ /* assemble the result */
+ return complex_new(mrb, F(ldexp)(zr.s, zr.x), F(ldexp)(zi.s, zi.x));
+}
+
+void mrb_mruby_complex_gem_init(mrb_state *mrb)
+{
+ struct RClass *comp;
+
+#ifdef COMPLEX_USE_ISTRUCT
+ mrb_assert(sizeof(struct mrb_complex) < ISTRUCT_DATA_SIZE);
+#endif
+ comp = mrb_define_class(mrb, "Complex", mrb_class_get(mrb, "Numeric"));
+#ifdef COMPLEX_USE_ISTRUCT
+ MRB_SET_INSTANCE_TT(comp, MRB_TT_ISTRUCT);
+#else
+ MRB_SET_INSTANCE_TT(comp, MRB_TT_DATA);
+#endif
+ mrb_undef_class_method(mrb, comp, "new");
+ mrb_define_class_method(mrb, comp, "rectangular", complex_s_rect, MRB_ARGS_REQ(1)|MRB_ARGS_OPT(1));
+ mrb_define_class_method(mrb, comp, "rect", complex_s_rect, MRB_ARGS_REQ(1)|MRB_ARGS_OPT(1));
+ mrb_define_method(mrb, mrb->kernel_module, "Complex", complex_s_rect, MRB_ARGS_REQ(1)|MRB_ARGS_OPT(1));
+ mrb_define_method(mrb, comp, "real", complex_real, MRB_ARGS_NONE());
+ mrb_define_method(mrb, comp, "imaginary", complex_imaginary, MRB_ARGS_NONE());
+ mrb_define_method(mrb, comp, "to_f", complex_to_f, MRB_ARGS_NONE());
+ mrb_define_method(mrb, comp, "to_i", complex_to_i, MRB_ARGS_NONE());
+ mrb_define_method(mrb, comp, "to_c", complex_to_c, MRB_ARGS_NONE());
+ mrb_define_method(mrb, comp, "__div__", complex_div, MRB_ARGS_REQ(1));
+}
+
+void
+mrb_mruby_complex_gem_final(mrb_state* mrb)
+{
+}
diff --git a/mrbgems/mruby-complex/test/complex.rb b/mrbgems/mruby-complex/test/complex.rb
new file mode 100644
index 000000000..d996e8277
--- /dev/null
+++ b/mrbgems/mruby-complex/test/complex.rb
@@ -0,0 +1,153 @@
+def assert_complex(real, exp)
+ assert "assert_complex" do
+ assert_float real.real, exp.real
+ assert_float real.imaginary, exp.imaginary
+ end
+end
+
+assert 'Complex' do
+ c = 123i
+ assert_equal Complex, c.class
+ assert_equal [c.real, c.imaginary], [0, 123]
+ c = 123 + -1.23i
+ assert_equal Complex, c.class
+ assert_equal [c.real, c.imaginary], [123, -1.23]
+end
+
+assert 'Complex::polar' do
+ assert_complex Complex.polar(3, 0), (3 + 0i)
+ assert_complex Complex.polar(3, Math::PI/2), (0 + 3i)
+ assert_complex Complex.polar(3, Math::PI), (-3 + 0i)
+ assert_complex Complex.polar(3, -Math::PI/2), (0 + -3i)
+end
+
+assert 'Complex::rectangular' do
+ assert_complex Complex.rectangular(1, 2), (1 + 2i)
+end
+
+assert 'Complex#*' do
+ assert_complex Complex(2, 3) * Complex(2, 3), (-5 + 12i)
+ assert_complex Complex(900) * Complex(1), (900 + 0i)
+ assert_complex Complex(-2, 9) * Complex(-9, 2), (0 - 85i)
+ assert_complex Complex(9, 8) * 4, (36 + 32i)
+ assert_complex Complex(20, 9) * 9.8, (196.0 + 88.2i)
+end
+
+assert 'Complex#+' do
+ assert_complex Complex(2, 3) + Complex(2, 3) , (4 + 6i)
+ assert_complex Complex(900) + Complex(1) , (901 + 0i)
+ assert_complex Complex(-2, 9) + Complex(-9, 2), (-11 + 11i)
+ assert_complex Complex(9, 8) + 4 , (13 + 8i)
+ assert_complex Complex(20, 9) + 9.8 , (29.8 + 9i)
+end
+
+assert 'Complex#-' do
+ assert_complex Complex(2, 3) - Complex(2, 3) , (0 + 0i)
+ assert_complex Complex(900) - Complex(1) , (899 + 0i)
+ assert_complex Complex(-2, 9) - Complex(-9, 2), (7 + 7i)
+ assert_complex Complex(9, 8) - 4 , (5 + 8i)
+ assert_complex Complex(20, 9) - 9.8 , (10.2 + 9i)
+end
+
+assert 'Complex#-@' do
+ assert_complex(-Complex(1, 2), (-1 - 2i))
+end
+
+assert 'Complex#/' do
+ assert_complex Complex(2, 3) / Complex(2, 3) , (1 + 0i)
+ assert_complex Complex(900) / Complex(1) , (900 + 0i)
+ assert_complex Complex(-2, 9) / Complex(-9, 2), ((36 / 85) - (77i / 85))
+ assert_complex Complex(9, 8) / 4 , ((9 / 4) + 2i)
+ assert_complex Complex(20, 9) / 9.8 , (2.0408163265306123 + 0.9183673469387754i)
+ if 1e39.infinite? then
+ # MRB_USE_FLOAT in effect
+ ten = 1e21
+ one = 1e20
+ else
+ ten = 1e201
+ one = 1e200
+ end
+ assert_complex Complex(ten, ten) / Complex(one, one), Complex(10.0, 0.0)
+end
+
+assert 'Complex#==' do
+ assert_true Complex(2, 3) == Complex(2, 3)
+ assert_true Complex(5) == 5
+ assert_true Complex(0) == 0.0
+end
+
+assert 'Complex#abs' do
+ assert_float Complex(-1).abs, 1
+ assert_float Complex(3.0, -4.0).abs, 5.0
+ if 1e39.infinite? then
+ # MRB_USE_FLOAT in effect
+ exp = 125
+ else
+ exp = 1021
+ end
+ assert_true Complex(3.0*2.0**exp, 4.0*2.0**exp).abs.finite?
+ assert_float Complex(3.0*2.0**exp, 4.0*2.0**exp).abs, 5.0*2.0**exp
+end
+
+assert 'Complex#abs2' do
+ assert_float Complex(-1).abs2, 1
+ assert_float Complex(3.0, -4.0).abs2, 25.0
+end
+
+assert 'Complex#arg' do
+ assert_float Complex.polar(3, Math::PI/2).arg, 1.5707963267948966
+end
+
+assert 'Complex#conjugate' do
+ assert_complex Complex(1, 2).conjugate, (1 - 2i)
+end
+
+assert 'Complex#fdiv' do
+ assert_complex Complex(11, 22).fdiv(3), (3.6666666666666665 + 7.333333333333333i)
+end
+
+assert 'Complex#imaginary' do
+ assert_float Complex(7).imaginary , 0
+ assert_float Complex(9, -4).imaginary, -4
+end
+
+assert 'Complex#polar' do
+ assert_equal Complex(1, 2).polar, [2.23606797749979, 1.1071487177940904]
+end
+
+assert 'Complex#real' do
+ assert_float Complex(7).real, 7
+ assert_float Complex(9, -4).real, 9
+end
+
+assert 'Complex#real?' do
+ assert_false Complex(1).real?
+end
+
+assert 'Complex::rectangular' do
+ assert_equal Complex(1, 2).rectangular, [1, 2]
+end
+
+assert 'Complex::to_c' do
+ assert_equal Complex(1, 2).to_c, Complex(1, 2)
+end
+
+assert 'Complex::to_f' do
+ assert_float Complex(1, 0).to_f, 1.0
+ assert_raise(RangeError) do
+ Complex(1, 2).to_f
+ end
+end
+
+assert 'Complex::to_i' do
+ assert_equal Complex(1, 0).to_i, 1
+ assert_raise(RangeError) do
+ Complex(1, 2).to_i
+ end
+end
+
+assert 'Complex#frozen?' do
+ assert_predicate(1i, :frozen?)
+ assert_predicate(Complex(2,3), :frozen?)
+ assert_predicate(4+5i, :frozen?)
+end
diff --git a/mrbgems/mruby-enum-chain/mrblib/chain.rb b/mrbgems/mruby-enum-chain/mrblib/chain.rb
index 98515ea14..43d0926c8 100644
--- a/mrbgems/mruby-enum-chain/mrblib/chain.rb
+++ b/mrbgems/mruby-enum-chain/mrblib/chain.rb
@@ -6,28 +6,30 @@ module Enumerable
def chain(*args)
Enumerator::Chain.new(self, *args)
end
+end
+class Enumerator
def +(other)
- Enumerator::Chain.new(self, other)
+ Chain.new(self, other)
end
-end
-class Enumerator
class Chain
include Enumerable
def initialize(*args)
- @enums = args
- end
-
- def initialize_copy(orig)
- @enums = orig.__copy_enums
+ @enums = args.freeze
+ @pos = -1
end
def each(&block)
- return to_enum unless block_given?
+ return to_enum unless block
- @enums.each { |e| e.each(&block) }
+ i = 0
+ while i < @enums.size
+ @pos = i
+ @enums[i].each(&block)
+ i += 1
+ end
self
end
@@ -40,21 +42,21 @@ class Enumerator
end
def rewind
- @enums.reverse_each do |e|
+ while 0 <= @pos && @pos < @enums.size
+ e = @enums[@pos]
e.rewind if e.respond_to?(:rewind)
+ @pos -= 1
end
self
end
- def inspect
- "#<#{self.class}: #{@enums.inspect}>"
+ def +(other)
+ self.class.new(self, other)
end
- def __copy_enums
- @enums.each_with_object([]) do |e, a|
- a << e.clone
- end
+ def inspect
+ "#<#{self.class}: #{@enums.inspect}>"
end
end
end
diff --git a/mrbgems/mruby-enum-chain/test/enum_chain.rb b/mrbgems/mruby-enum-chain/test/enum_chain.rb
index 4dd59bd37..45bbc9a77 100644
--- a/mrbgems/mruby-enum-chain/test/enum_chain.rb
+++ b/mrbgems/mruby-enum-chain/test/enum_chain.rb
@@ -12,9 +12,9 @@ assert("Enumerable#chain") do
assert_raise(NoMethodError) { c.chain }
end
-assert("Enumerable#+") do
+assert("Enumerator#+") do
a = [].each
- b = {}.reverse_each
+ b = {}.each
c = Object.new # not has #each method
assert_kind_of Enumerator::Chain, a + b
@@ -24,7 +24,7 @@ assert("Enumerable#+") do
assert_raise(NoMethodError) { c + a }
end
-assert("Enumerator.new") do
+assert("Enumerator::Chain.new") do
a = []
b = {}
c = Object.new # not has #each method
@@ -46,13 +46,13 @@ assert("Enumerator::Chain#each") do
assert_kind_of Enumerator, aa.each
assert_equal [1, 2, 3, 1, 2, 3], aa.each.to_a
- aa = a.chain(a.reverse_each)
+ aa = a.chain(6..9)
assert_kind_of Enumerator, aa.each
- assert_equal [1, 2, 3, 3, 2, 1], aa.each.to_a
+ assert_equal [1, 2, 3, 6, 7, 8, 9], aa.each.to_a
- aa = a.chain(a.reverse_each, a)
+ aa = a.chain((-3..-2).each_with_index, a)
assert_kind_of Enumerator, aa.each
- assert_equal [1, 2, 3, 3, 2, 1, 1, 2, 3], aa.each.to_a
+ assert_equal [1, 2, 3, [-3, 0], [-2, 1], 1, 2, 3], aa.each.to_a
aa = a.chain(Object.new)
assert_kind_of Enumerator, aa.each
@@ -65,12 +65,44 @@ assert("Enumerator::Chain#size") do
aa = a.chain(a)
assert_equal 6, aa.size
- aa = a.chain(a.reverse_each)
+ aa = a.chain(3..4)
assert_nil aa.size
- aa = a.chain(a.reverse_each, a)
+ aa = a.chain(3..4, a)
assert_nil aa.size
aa = a.chain(Object.new)
assert_nil aa.size
end
+
+assert("Enumerator::Chain#rewind") do
+ rewound = nil
+ e1 = [1, 2]
+ e2 = (4..6)
+ (class << e1; self end).define_method(:rewind) { rewound << self }
+ (class << e2; self end).define_method(:rewind) { rewound << self }
+ c = e1.chain(e2)
+
+ rewound = []
+ c.rewind
+ assert_equal [], rewound
+
+ rewound = []
+ c.each{break c}.rewind
+ assert_equal [e1], rewound
+
+ rewound = []
+ c.each{}.rewind
+ assert_equal [e2, e1], rewound
+end
+
+assert("Enumerator::Chain#+") do
+ a = [].chain
+ b = {}.chain
+ c = Object.new # not has #each method
+
+ assert_kind_of Enumerator::Chain, a + b
+ assert_kind_of Enumerator::Chain, a + c
+ assert_kind_of Enumerator::Chain, b + a
+ assert_kind_of Enumerator::Chain, b + c
+end
diff --git a/mrbgems/mruby-enum-ext/mrblib/enum.rb b/mrbgems/mruby-enum-ext/mrblib/enum.rb
index fedf8b1ae..178496e7e 100644
--- a/mrbgems/mruby-enum-ext/mrblib/enum.rb
+++ b/mrbgems/mruby-enum-ext/mrblib/enum.rb
@@ -205,7 +205,6 @@ module Enumerable
ary.collect{|e,i| orig[i]}
end
- NONE = Object.new
##
# call-seq:
# enum.first -> obj or nil
@@ -812,10 +811,6 @@ module Enumerable
h
end
- def nil.to_h
- {}
- end
-
def uniq(&block)
hash = {}
if block
@@ -831,4 +826,34 @@ module Enumerable
end
hash.values
end
+
+ def filter_map(&blk)
+ return to_enum(:find_index, val) unless blk
+
+ ary = []
+ self.each do |x|
+ x = blk.call(x)
+ ary.push x if x
+ end
+ ary
+ end
+
+ alias filter select
+
+ ##
+ # call-seq:
+ # enum.tally -> a_hash
+ #
+ # Tallys the collection. Returns a hash where the keys are the
+ # elements and the values are numbers of elements in the collection
+ # that correspond to the key.
+ #
+ # ["a", "b", "c", "b"].tally #=> {"a"=>1, "b"=>2, "c"=>1}
+ def tally
+ hash = {}
+ self.each do |x|
+ hash[x] = (hash[x]||0)+1
+ end
+ hash
+ end
end
diff --git a/mrbgems/mruby-enum-ext/test/enum.rb b/mrbgems/mruby-enum-ext/test/enum.rb
index b2d7297a4..f0301a2d9 100644
--- a/mrbgems/mruby-enum-ext/test/enum.rb
+++ b/mrbgems/mruby-enum-ext/test/enum.rb
@@ -128,14 +128,14 @@ assert("Enumerable#any? (enhancement)") do
end
assert("Enumerable#each_with_object") do
- assert_true [2, 4, 6, 8, 10, 12, 14, 16, 18, 20], (1..10).each_with_object([]) { |i, a| a << i*2 }
+ assert_equal [2, 4, 6, 8, 10, 12, 14, 16, 18, 20], (1..10).each_with_object([]) { |i, a| a << i*2 }
assert_raise(ArgumentError) { (1..10).each_with_object() { |i, a| a << i*2 } }
end
assert("Enumerable#reverse_each") do
r = (1..3)
a = []
- assert_equal (1..3), r.reverse_each { |v| a << v }
+ assert_same r, r.reverse_each { |v| a << v }
assert_equal [3, 2, 1], a
end
@@ -186,8 +186,13 @@ assert("Enumerable#to_h") do
h = c.new.to_h
assert_equal Hash, h.class
assert_equal h0, h
- # mruby-enum-ext also provides nil.to_h
- assert_equal Hash.new, nil.to_h
-
assert_equal({1=>4,3=>8}, c.new.to_h{|k,v|[k,v*2]})
end
+
+assert("Enumerable#filter_map") do
+ assert_equal [4, 8, 12, 16, 20], (1..10).filter_map{|i| i * 2 if i%2==0}
+end
+
+assert("Enumerable#tally") do
+ assert_equal({"a"=>1, "b"=>2, "c"=>1}, ["a", "b", "c", "b"].tally)
+end
diff --git a/mrbgems/mruby-enumerator/mrbgem.rake b/mrbgems/mruby-enumerator/mrbgem.rake
index 8757a15ea..abcc54e7a 100644
--- a/mrbgems/mruby-enumerator/mrbgem.rake
+++ b/mrbgems/mruby-enumerator/mrbgem.rake
@@ -2,6 +2,5 @@ MRuby::Gem::Specification.new('mruby-enumerator') do |spec|
spec.license = 'MIT'
spec.author = 'mruby developers'
spec.add_dependency('mruby-fiber', :core => 'mruby-fiber')
- spec.add_dependency 'mruby-enum-ext', :core => 'mruby-enum-ext'
spec.summary = 'Enumerator class'
end
diff --git a/mrbgems/mruby-enumerator/mrblib/enumerator.rb b/mrbgems/mruby-enumerator/mrblib/enumerator.rb
index 76b4add72..5a98dc964 100644
--- a/mrbgems/mruby-enumerator/mrblib/enumerator.rb
+++ b/mrbgems/mruby-enumerator/mrblib/enumerator.rb
@@ -108,14 +108,17 @@ class Enumerator
#
# p fib.take(10) # => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
#
- def initialize(obj=nil, meth=:each, *args, &block)
+ # In the second, deprecated, form, a generated Enumerator iterates over the
+ # given object using the given method with the given arguments passed. This
+ # form is left only for internal use.
+ #
+ # Use of this form is discouraged. Use Kernel#enum_for or Kernel#to_enum
+ # instead.
+ def initialize(obj=NONE, meth=:each, *args, &block)
if block
obj = Generator.new(&block)
- else
- raise ArgumentError unless obj
- end
- if @obj and !self.respond_to?(meth)
- raise NoMethodError, "undefined method #{meth}"
+ elsif obj == NONE
+ raise ArgumentError, "wrong number of arguments (given 0, expected 1+)"
end
@obj = obj
@@ -220,13 +223,11 @@ class Enumerator
end
def inspect
- return "#<#{self.class}: uninitialized>" unless @obj
-
if @args && @args.size > 0
args = @args.join(", ")
- "#<#{self.class}: #{@obj}:#{@meth}(#{args})>"
+ "#<#{self.class}: #{@obj.inspect}:#{@meth}(#{args})>"
else
- "#<#{self.class}: #{@obj}:#{@meth}>"
+ "#<#{self.class}: #{@obj.inspect}:#{@meth}>"
end
end
@@ -242,9 +243,10 @@ class Enumerator
#
# === Examples
#
- # "Hello, world!".scan(/\w+/) #=> ["Hello", "world"]
- # "Hello, world!".to_enum(:scan, /\w+/).to_a #=> ["Hello", "world"]
- # "Hello, world!".to_enum(:scan).each(/\w+/).to_a #=> ["Hello", "world"]
+ # Array.new(3) #=> [nil, nil, nil]
+ # Array.new(3) { |i| i } #=> [0, 1, 2]
+ # Array.to_enum(:new, 3).to_a #=> [0, 1, 2]
+ # Array.to_enum(:new).each(3).to_a #=> [0, 1, 2]
#
# obj = Object.new
#
@@ -553,6 +555,46 @@ class Enumerator
self
end
end
+
+ ##
+ # call-seq:
+ # Enumerator.produce(initial = nil) { |val| } -> enumerator
+ #
+ # Creates an infinite enumerator from any block, just called over and
+ # over. Result of the previous iteration is passed to the next one.
+ # If +initial+ is provided, it is passed to the first iteration, and
+ # becomes the first element of the enumerator; if it is not provided,
+ # first iteration receives +nil+, and its result becomes first
+ # element of the iterator.
+ #
+ # Raising StopIteration from the block stops an iteration.
+ #
+ # Examples of usage:
+ #
+ # Enumerator.produce(1, &:succ) # => enumerator of 1, 2, 3, 4, ....
+ #
+ # Enumerator.produce { rand(10) } # => infinite random number sequence
+ #
+ # ancestors = Enumerator.produce(node) { |prev| node = prev.parent or raise StopIteration }
+ # enclosing_section = ancestors.find { |n| n.type == :section }
+ def Enumerator.produce(init=NONE, &block)
+ raise ArgumentError, "no block given" if block.nil?
+ Enumerator.new do |y|
+ if init == NONE
+ val = nil
+ else
+ val = init
+ y.yield(val)
+ end
+ begin
+ while true
+ y.yield(val = block.call(val))
+ end
+ rescue StopIteration
+ # do nothing
+ end
+ end
+ end
end
module Kernel
@@ -603,9 +645,6 @@ module Kernel
# enum.first(4) # => [1, 1, 1, 2]
#
def to_enum(meth=:each, *args)
- unless self.respond_to?(meth)
- raise ArgumentError, "undefined method #{meth}"
- end
Enumerator.new self, meth, *args
end
alias enum_for to_enum
diff --git a/mrbgems/mruby-enumerator/test/enumerator.rb b/mrbgems/mruby-enumerator/test/enumerator.rb
index f3bd1bdba..ecd6c4d65 100644
--- a/mrbgems/mruby-enumerator/test/enumerator.rb
+++ b/mrbgems/mruby-enumerator/test/enumerator.rb
@@ -6,11 +6,22 @@ class << @obj
end
end
-assert 'Enumerator' do
+def assert_take(exp, enumerator)
+ result = []
+ n = exp.size
+ enumerator.each do |v|
+ result << v
+ n -= 1
+ break if n == 0
+ end if n > 0
+ assert_equal exp, result
+end
+
+assert 'Enumerator.class' do
assert_equal Class, Enumerator.class
end
-assert 'Enumerator' do
+assert 'Enumerator.superclass' do
assert_equal Object, Enumerator.superclass
end
@@ -19,10 +30,8 @@ assert 'Enumerator.new' do
assert_equal [:x,:y,:z], [:x,:y,:z].each.map{|i| i}.sort
assert_equal [[:x,1],[:y,2]], {x:1, y:2}.each.map{|i| i}.sort
assert_equal [1,2,3], @obj.to_enum(:foo, 1,2,3).to_a
- assert_equal [1,2,3], Enumerator.new(@obj, :foo, 1,2,3).to_a
- assert_equal [1,2,3], Enumerator.new { |y| i = 0; loop { y << (i += 1) } }.take(3)
+ assert_take [1,2,3], Enumerator.new { |y| i = 0; loop { y << (i += 1) } }
assert_raise(ArgumentError) { Enumerator.new }
- assert_raise(ArgumentError) { @obj.to_enum }
# examples
fib = Enumerator.new do |y|
@@ -32,7 +41,7 @@ assert 'Enumerator.new' do
a, b = b, a + b
end
end
- assert_equal [1,1,2,3,5,8,13,21,34,55], fib.take(10)
+ assert_take [1,1,2,3,5,8,13,21,34,55], fib
end
assert 'Enumerator#initialize_copy' do
@@ -92,11 +101,13 @@ end
assert 'Enumerator#inspect' do
e = (0..10).each
- assert_equal("#<Enumerator: 0..10:each>", e.inspect)
- e = Enumerator.new("FooObject", :foo, 1)
- assert_equal("#<Enumerator: FooObject:foo(1)>", e.inspect)
- e = Enumerator.new("FooObject", :foo, 1, 2, 3)
- assert_equal("#<Enumerator: FooObject:foo(1, 2, 3)>", e.inspect)
+ assert_equal('#<Enumerator: 0..10:each>', e.inspect)
+ e = 'FooObject'.enum_for(:foo, 1)
+ assert_equal('#<Enumerator: "FooObject":foo(1)>', e.inspect)
+ e = 'FooObject'.enum_for(:foo, 1, 2, 3)
+ assert_equal('#<Enumerator: "FooObject":foo(1, 2, 3)>', e.inspect)
+ e = nil.enum_for(:to_s)
+ assert_equal('#<Enumerator: nil:to_s>', e.inspect)
end
assert 'Enumerator#each' do
@@ -418,8 +429,10 @@ assert 'nested iteration' do
end
assert 'Kernel#to_enum' do
+ e = nil
assert_equal Enumerator, [].to_enum.class
- assert_raise(ArgumentError){ nil.to_enum }
+ assert_nothing_raised { e = [].to_enum(:_not_implemented_) }
+ assert_raise(NoMethodError) { e.first }
end
assert 'modifying existing methods' do
@@ -547,3 +560,41 @@ assert 'Enumerable#zip' do
assert_raise(TypeError) { [1].zip(1) }
end
+
+assert 'Enumerator.produce' do
+ assert_raise(ArgumentError) { Enumerator.produce }
+
+ # Without initial object
+ passed_args = []
+ enum = Enumerator.produce {|obj| passed_args << obj; (obj || 0).succ }
+ assert_equal Enumerator, enum.class
+ assert_take [1, 2, 3], enum
+ assert_equal [nil, 1, 2], passed_args
+
+ # With initial object
+ passed_args = []
+ enum = Enumerator.produce(1) {|obj| passed_args << obj; obj.succ }
+ assert_take [1, 2, 3], enum
+ assert_equal [1, 2], passed_args
+
+ # Raising StopIteration
+ words = %w[The quick brown fox jumps over the lazy dog]
+ enum = Enumerator.produce { words.shift or raise StopIteration }
+ assert_equal %w[The quick brown fox jumps over the lazy dog], enum.to_a
+
+ # Raising StopIteration
+ object = [[[["abc", "def"], "ghi", "jkl"], "mno", "pqr"], "stuv", "wxyz"]
+ enum = Enumerator.produce(object) {|obj|
+ obj.respond_to?(:first) or raise StopIteration
+ obj.first
+ }
+ assert_nothing_raised {
+ assert_equal [
+ [[[["abc", "def"], "ghi", "jkl"], "mno", "pqr"], "stuv", "wxyz"],
+ [[["abc", "def"], "ghi", "jkl"], "mno", "pqr"],
+ [["abc", "def"], "ghi", "jkl"],
+ ["abc", "def"],
+ "abc",
+ ], enum.to_a
+ }
+end
diff --git a/mrbgems/mruby-eval/src/eval.c b/mrbgems/mruby-eval/src/eval.c
index fa687d624..e2388f026 100644
--- a/mrbgems/mruby-eval/src/eval.c
+++ b/mrbgems/mruby-eval/src/eval.c
@@ -102,25 +102,28 @@ patch_irep(mrb_state *mrb, mrb_irep *irep, int bnest, mrb_irep *top)
uint8_t c;
mrb_code insn;
int argc = irep_argc(irep);
+ mrb_code *iseq = (mrb_code *)irep->iseq;
+
+ mrb_assert((irep->flags & MRB_ISEQ_NO_FREE) == 0);
for (i = 0; i < irep->ilen; ) {
- insn = irep->iseq[i];
+ insn = iseq[i];
switch(insn){
case OP_EPUSH:
- b = PEEK_S(irep->iseq+i+1);
+ b = PEEK_S(iseq+i+1);
patch_irep(mrb, irep->reps[b], bnest + 1, top);
break;
case OP_LAMBDA:
case OP_BLOCK:
- a = PEEK_B(irep->iseq+i+1);
- b = PEEK_B(irep->iseq+i+2);
+ a = PEEK_B(iseq+i+1);
+ b = PEEK_B(iseq+i+2);
patch_irep(mrb, irep->reps[b], bnest + 1, top);
break;
case OP_SEND:
- b = PEEK_B(irep->iseq+i+2);
- c = PEEK_B(irep->iseq+i+3);
+ b = PEEK_B(iseq+i+2);
+ c = PEEK_B(iseq+i+3);
if (c != 0) {
break;
}
@@ -128,24 +131,24 @@ patch_irep(mrb_state *mrb, mrb_irep *irep, int bnest, mrb_irep *top)
uint16_t arg = search_variable(mrb, irep->syms[b], bnest);
if (arg != 0) {
/* must replace */
- irep->iseq[i] = OP_GETUPVAR;
- irep->iseq[i+2] = arg >> 8;
- irep->iseq[i+3] = arg & 0xff;
+ iseq[i] = OP_GETUPVAR;
+ iseq[i+2] = arg >> 8;
+ iseq[i+3] = arg & 0xff;
}
}
break;
case OP_MOVE:
- a = PEEK_B(irep->iseq+i+1);
- b = PEEK_B(irep->iseq+i+2);
+ a = PEEK_B(iseq+i+1);
+ b = PEEK_B(iseq+i+2);
/* src part */
if (potential_upvar_p(irep->lv, b, argc, irep->nlocals)) {
uint16_t arg = search_variable(mrb, irep->lv[b - 1].name, bnest);
if (arg != 0) {
/* must replace */
- irep->iseq[i] = insn = OP_GETUPVAR;
- irep->iseq[i+2] = arg >> 8;
- irep->iseq[i+3] = arg & 0xff;
+ iseq[i] = insn = OP_GETUPVAR;
+ iseq[i+2] = arg >> 8;
+ iseq[i+3] = arg & 0xff;
}
}
/* dst part */
@@ -153,18 +156,18 @@ patch_irep(mrb_state *mrb, mrb_irep *irep, int bnest, mrb_irep *top)
uint16_t arg = search_variable(mrb, irep->lv[a - 1].name, bnest);
if (arg != 0) {
/* must replace */
- irep->iseq[i] = insn = OP_SETUPVAR;
- irep->iseq[i+1] = (mrb_code)b;
- irep->iseq[i+2] = arg >> 8;
- irep->iseq[i+3] = arg & 0xff;
+ iseq[i] = insn = OP_SETUPVAR;
+ iseq[i+1] = (mrb_code)b;
+ iseq[i+2] = arg >> 8;
+ iseq[i+3] = arg & 0xff;
}
}
break;
case OP_GETUPVAR:
- a = PEEK_B(irep->iseq+i+1);
- b = PEEK_B(irep->iseq+i+2);
- c = PEEK_B(irep->iseq+i+3);
+ a = PEEK_B(iseq+i+1);
+ b = PEEK_B(iseq+i+2);
+ c = PEEK_B(iseq+i+3);
{
int lev = c+1;
mrb_irep *tmp = search_irep(top, bnest, lev, irep);
@@ -172,18 +175,18 @@ patch_irep(mrb_state *mrb, mrb_irep *irep, int bnest, mrb_irep *top)
uint16_t arg = search_variable(mrb, tmp->lv[b-1].name, bnest);
if (arg != 0) {
/* must replace */
- irep->iseq[i] = OP_GETUPVAR;
- irep->iseq[i+2] = arg >> 8;
- irep->iseq[i+3] = arg & 0xff;
+ iseq[i] = OP_GETUPVAR;
+ iseq[i+2] = arg >> 8;
+ iseq[i+3] = arg & 0xff;
}
}
}
break;
case OP_SETUPVAR:
- a = PEEK_B(irep->iseq+i+1);
- b = PEEK_B(irep->iseq+i+2);
- c = PEEK_B(irep->iseq+i+3);
+ a = PEEK_B(iseq+i+1);
+ b = PEEK_B(iseq+i+2);
+ c = PEEK_B(iseq+i+3);
{
int lev = c+1;
mrb_irep *tmp = search_irep(top, bnest, lev, irep);
@@ -191,25 +194,25 @@ patch_irep(mrb_state *mrb, mrb_irep *irep, int bnest, mrb_irep *top)
uint16_t arg = search_variable(mrb, tmp->lv[b-1].name, bnest);
if (arg != 0) {
/* must replace */
- irep->iseq[i] = OP_SETUPVAR;
- irep->iseq[i+1] = a;
- irep->iseq[i+2] = arg >> 8;
- irep->iseq[i+3] = arg & 0xff;
+ iseq[i] = OP_SETUPVAR;
+ iseq[i+1] = a;
+ iseq[i+2] = arg >> 8;
+ iseq[i+3] = arg & 0xff;
}
}
}
break;
case OP_EXT1:
- insn = PEEK_B(irep->iseq+i+1);
+ insn = PEEK_B(iseq+i+1);
i += mrb_insn_size1[insn]+1;
continue;
case OP_EXT2:
- insn = PEEK_B(irep->iseq+i+1);
+ insn = PEEK_B(iseq+i+1);
i += mrb_insn_size2[insn]+1;
continue;
case OP_EXT3:
- insn = PEEK_B(irep->iseq+i+1);
+ insn = PEEK_B(iseq+i+1);
i += mrb_insn_size3[insn]+1;
continue;
}
@@ -235,7 +238,7 @@ create_proc_from_string(mrb_state *mrb, char *s, mrb_int len, mrb_value binding,
}
cxt = mrbc_context_new(mrb);
- cxt->lineno = (short)line;
+ cxt->lineno = (uint16_t)line;
mrbc_filename(mrb, cxt, file ? file : "(eval)");
cxt->capture_errors = TRUE;
@@ -254,15 +257,15 @@ create_proc_from_string(mrb_state *mrb, char *s, mrb_int len, mrb_value binding,
mrb_value str;
if (file) {
- str = mrb_format(mrb, " file %S line %S: %S",
- mrb_str_new_cstr(mrb, file),
- mrb_fixnum_value(p->error_buffer[0].lineno),
- mrb_str_new_cstr(mrb, p->error_buffer[0].message));
+ str = mrb_format(mrb, "file %s line %d: %s",
+ file,
+ p->error_buffer[0].lineno,
+ p->error_buffer[0].message);
}
else {
- str = mrb_format(mrb, " line %S: %S",
- mrb_fixnum_value(p->error_buffer[0].lineno),
- mrb_str_new_cstr(mrb, p->error_buffer[0].message));
+ str = mrb_format(mrb, "line %d: %s",
+ p->error_buffer[0].lineno,
+ p->error_buffer[0].message);
}
mrb_parser_free(p);
mrbc_context_free(mrb, cxt);
@@ -387,7 +390,7 @@ void
mrb_mruby_eval_gem_init(mrb_state* mrb)
{
mrb_define_module_function(mrb, mrb->kernel_module, "eval", f_eval, MRB_ARGS_ARG(1, 3));
- mrb_define_method(mrb, mrb->kernel_module, "instance_eval", f_instance_eval, MRB_ARGS_ARG(1, 2));
+ mrb_define_method(mrb, mrb_class_get(mrb, "BasicObject"), "instance_eval", f_instance_eval, MRB_ARGS_ARG(1, 2));
}
void
diff --git a/mrbgems/mruby-eval/test/eval.rb b/mrbgems/mruby-eval/test/eval.rb
index 4d7dd4606..4930259c1 100644
--- a/mrbgems/mruby-eval/test/eval.rb
+++ b/mrbgems/mruby-eval/test/eval.rb
@@ -80,7 +80,7 @@ assert('Kernel.#eval(string) context') do
assert_equal('class') { obj.const_string }
end
-assert('Object#instance_eval with begin-rescue-ensure execution order') do
+assert('BasicObject#instance_eval with begin-rescue-ensure execution order') do
class HellRaiser
def raise_hell
order = [:enter_raise_hell]
@@ -100,7 +100,7 @@ assert('Object#instance_eval with begin-rescue-ensure execution order') do
assert_equal([:enter_raise_hell, :begin, :rescue, :ensure], hell_raiser.raise_hell)
end
-assert('Kernel#instance_eval() to define singleton methods Issue #3141') do
+assert('BasicObject#instance_eval to define singleton methods Issue #3141') do
foo_class = Class.new do
def bar(x)
instance_eval "def baz; #{x}; end"
diff --git a/mrbgems/mruby-fiber/src/fiber.c b/mrbgems/mruby-fiber/src/fiber.c
index 17ce77c5d..b702a3811 100644
--- a/mrbgems/mruby-fiber/src/fiber.c
+++ b/mrbgems/mruby-fiber/src/fiber.c
@@ -191,14 +191,21 @@ fiber_switch(mrb_state *mrb, mrb_value self, mrb_int len, const mrb_value *a, mr
fiber_check_cfunc(mrb, c);
status = c->status;
- if (resume && status == MRB_FIBER_TRANSFERRED) {
- mrb_raise(mrb, E_FIBER_ERROR, "resuming transferred fiber");
- }
- if (status == MRB_FIBER_RUNNING || status == MRB_FIBER_RESUMED) {
+ switch (status) {
+ case MRB_FIBER_TRANSFERRED:
+ if (resume) {
+ mrb_raise(mrb, E_FIBER_ERROR, "resuming transferred fiber");
+ }
+ break;
+ case MRB_FIBER_RUNNING:
+ case MRB_FIBER_RESUMED:
mrb_raise(mrb, E_FIBER_ERROR, "double resume");
- }
- if (status == MRB_FIBER_TERMINATED) {
+ break;
+ case MRB_FIBER_TERMINATED:
mrb_raise(mrb, E_FIBER_ERROR, "resuming dead fiber");
+ break;
+ default:
+ break;
}
old_c->status = resume ? MRB_FIBER_RESUMED : MRB_FIBER_TRANSFERRED;
c->prev = resume ? mrb->c : (c->prev ? c->prev : mrb->root_c);
diff --git a/mrbgems/mruby-fiber/test/fiber.rb b/mrbgems/mruby-fiber/test/fiber.rb
index d063a0a62..b6ecb798c 100644
--- a/mrbgems/mruby-fiber/test/fiber.rb
+++ b/mrbgems/mruby-fiber/test/fiber.rb
@@ -76,7 +76,7 @@ assert('Fiber iteration') do
end
assert('Fiber with splat in the block argument list') {
- Fiber.new{|*x|x}.resume(1) == [1]
+ assert_equal([1], Fiber.new{|*x|x}.resume(1))
}
assert('Fiber raises on resume when dead') do
diff --git a/mrbgems/mruby-hash-ext/mrblib/hash.rb b/mrbgems/mruby-hash-ext/mrblib/hash.rb
index 547f3404a..33e2dcb9f 100644
--- a/mrbgems/mruby-hash-ext/mrblib/hash.rb
+++ b/mrbgems/mruby-hash-ext/mrblib/hash.rb
@@ -494,4 +494,7 @@ class Hash
self.fetch(k, &block)
end
end
+
+ alias filter select
+ alias filter! select!
end
diff --git a/mrbgems/mruby-io/.gitignore b/mrbgems/mruby-io/.gitignore
deleted file mode 100644
index ceeb05b41..000000000
--- a/mrbgems/mruby-io/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-/tmp
diff --git a/mrbgems/mruby-io/.travis.yml b/mrbgems/mruby-io/.travis.yml
deleted file mode 100644
index ffe227284..000000000
--- a/mrbgems/mruby-io/.travis.yml
+++ /dev/null
@@ -1,2 +0,0 @@
-script:
- - "ruby run_test.rb all test"
diff --git a/mrbgems/mruby-io/README.md b/mrbgems/mruby-io/README.md
index 256fb8195..ccf56f970 100644
--- a/mrbgems/mruby-io/README.md
+++ b/mrbgems/mruby-io/README.md
@@ -1,7 +1,5 @@
mruby-io
========
-[![Build Status](https://travis-ci.org/iij/mruby-io.svg?branch=master)](https://travis-ci.org/iij/mruby-io)
-
`IO` and `File` classes for mruby
@@ -9,7 +7,7 @@ mruby-io
Add the line below to your `build_config.rb`:
```
- conf.gem :github => 'iij/mruby-io'
+ conf.gem core: 'mruby-io'
```
## Implemented methods
diff --git a/mrbgems/mruby-io/mrbgem.rake b/mrbgems/mruby-io/mrbgem.rake
index d79964590..e4f0b7bb6 100644
--- a/mrbgems/mruby-io/mrbgem.rake
+++ b/mrbgems/mruby-io/mrbgem.rake
@@ -6,7 +6,7 @@ MRuby::Gem::Specification.new('mruby-io') do |spec|
spec.cc.include_paths << "#{build.root}/src"
case RUBY_PLATFORM
- when /mingw|mswin/
+ when /mingw|mswin|msys/
spec.linker.libraries += ['Ws2_32']
#spec.cc.include_paths += ["C:/Windows/system/include"]
spec.linker.library_paths += ["C:/Windows/system"]
diff --git a/mrbgems/mruby-io/mrblib/io.rb b/mrbgems/mruby-io/mrblib/io.rb
index 6211bf15f..8297cb1b5 100644
--- a/mrbgems/mruby-io/mrblib/io.rb
+++ b/mrbgems/mruby-io/mrblib/io.rb
@@ -123,8 +123,8 @@ class IO
def write(string)
str = string.is_a?(String) ? string : string.to_s
- return str.size unless str.size > 0
- if 0 < @buf.length
+ return 0 if str.empty?
+ unless @buf.empty?
# reset real pos ignore buf
seek(pos, SEEK_SET)
end
@@ -140,8 +140,8 @@ class IO
def eof?
_check_readable
begin
- buf = _read_buf
- return buf.size == 0
+ _read_buf
+ return @buf.empty?
rescue EOFError
return true
end
@@ -150,7 +150,7 @@ class IO
def pos
raise IOError if closed?
- sysseek(0, SEEK_CUR) - @buf.length
+ sysseek(0, SEEK_CUR) - @buf.bytesize
end
alias_method :tell, :pos
@@ -170,8 +170,13 @@ class IO
end
def _read_buf
- return @buf if @buf && @buf.size > 0
- @buf = sysread(BUF_SIZE)
+ return @buf if @buf && @buf.bytesize >= 4 # maximum UTF-8 character is 4 bytes
+ @buf ||= ""
+ begin
+ @buf += sysread(BUF_SIZE)
+ rescue EOFError => e
+ raise e if @buf.empty?
+ end
end
def ungetc(substr)
@@ -207,9 +212,8 @@ class IO
end
if length
- consume = (length <= @buf.size) ? length : @buf.size
- array.push @buf[0, consume]
- @buf = @buf[consume, @buf.size - consume]
+ consume = (length <= @buf.bytesize) ? length : @buf.bytesize
+ array.push IO._bufread(@buf, consume)
length -= consume
break if length == 0
else
@@ -226,12 +230,12 @@ class IO
end
end
- def readline(arg = $/, limit = nil)
+ def readline(arg = "\n", limit = nil)
case arg
when String
rs = arg
when Fixnum
- rs = $/
+ rs = "\n"
limit = arg
else
raise ArgumentError
@@ -242,7 +246,7 @@ class IO
end
if rs == ""
- rs = $/ + $/
+ rs = "\n\n"
end
array = []
@@ -256,12 +260,12 @@ class IO
if limit && limit <= @buf.size
array.push @buf[0, limit]
- @buf = @buf[limit, @buf.size - limit]
+ @buf[0, limit] = ""
break
elsif idx = @buf.index(rs)
len = idx + rs.size
array.push @buf[0, len]
- @buf = @buf[len, @buf.size - len]
+ @buf[0, len] = ""
break
else
array.push @buf
@@ -285,7 +289,7 @@ class IO
def readchar
_read_buf
c = @buf[0]
- @buf = @buf[1, @buf.size]
+ @buf[0] = ""
c
end
diff --git a/mrbgems/mruby-io/run_test.rb b/mrbgems/mruby-io/run_test.rb
deleted file mode 100644
index 83d80294a..000000000
--- a/mrbgems/mruby-io/run_test.rb
+++ /dev/null
@@ -1,26 +0,0 @@
-#!/usr/bin/env ruby
-#
-# mrbgems test runner
-#
-
-if __FILE__ == $0
- repository, dir = 'https://github.com/mruby/mruby.git', 'tmp/mruby'
- build_args = ARGV
-
- Dir.mkdir 'tmp' unless File.exist?('tmp')
- unless File.exist?(dir)
- system "git clone #{repository} #{dir}"
- end
-
- exit system(%Q[cd #{dir}; MRUBY_CONFIG=#{File.expand_path __FILE__} ruby minirake #{build_args.join(' ')}])
-end
-
-MRuby::Build.new do |conf|
- toolchain :gcc
- conf.gembox 'default'
-
- conf.gem :git => 'https://github.com/iij/mruby-env.git'
- conf.enable_test
-
- conf.gem File.expand_path(File.dirname(__FILE__))
-end
diff --git a/mrbgems/mruby-io/src/file.c b/mrbgems/mruby-io/src/file.c
index c00663481..2fbda90af 100644
--- a/mrbgems/mruby-io/src/file.c
+++ b/mrbgems/mruby-io/src/file.c
@@ -116,7 +116,7 @@ mrb_file_s_unlink(mrb_state *mrb, mrb_value obj)
for (i = 0; i < argc; i++) {
const char *utf8_path;
pathv = mrb_ensure_string_type(mrb, argv[i]);
- utf8_path = mrb_string_value_cstr(mrb, &pathv);
+ utf8_path = RSTRING_CSTR(mrb, pathv);
path = mrb_locale_from_utf8(utf8_path, -1);
if (UNLINK(path) < 0) {
mrb_locale_free(path);
@@ -134,8 +134,8 @@ mrb_file_s_rename(mrb_state *mrb, mrb_value obj)
char *src, *dst;
mrb_get_args(mrb, "SS", &from, &to);
- src = mrb_locale_from_utf8(mrb_string_value_cstr(mrb, &from), -1);
- dst = mrb_locale_from_utf8(mrb_string_value_cstr(mrb, &to), -1);
+ src = mrb_locale_from_utf8(RSTRING_CSTR(mrb, from), -1);
+ dst = mrb_locale_from_utf8(RSTRING_CSTR(mrb, to), -1);
if (rename(src, dst) < 0) {
#if defined(_WIN32) || defined(_WIN64)
if (CHMOD(dst, 0666) == 0 && UNLINK(dst) == 0 && rename(src, dst) == 0) {
@@ -146,7 +146,7 @@ mrb_file_s_rename(mrb_state *mrb, mrb_value obj)
#endif
mrb_locale_free(src);
mrb_locale_free(dst);
- mrb_sys_fail(mrb, mrb_str_to_cstr(mrb, mrb_format(mrb, "(%S, %S)", from, to)));
+ mrb_sys_fail(mrb, RSTRING_CSTR(mrb, mrb_format(mrb, "(%v, %v)", from, to)));
}
mrb_locale_free(src);
mrb_locale_free(dst);
@@ -159,12 +159,12 @@ mrb_file_dirname(mrb_state *mrb, mrb_value klass)
#if defined(_WIN32) || defined(_WIN64)
char dname[_MAX_DIR], vname[_MAX_DRIVE];
char buffer[_MAX_DRIVE + _MAX_DIR];
+ const char *utf8_path;
char *path;
size_t ridx;
- mrb_value s;
- mrb_get_args(mrb, "S", &s);
- path = mrb_locale_from_utf8(mrb_str_to_cstr(mrb, s), -1);
- _splitpath((const char*)path, vname, dname, NULL, NULL);
+ mrb_get_args(mrb, "z", &utf8_path);
+ path = mrb_locale_from_utf8(utf8_path, -1);
+ _splitpath(path, vname, dname, NULL, NULL);
snprintf(buffer, _MAX_DRIVE + _MAX_DIR, "%s%s", vname, dname);
mrb_locale_free(path);
ridx = strlen(buffer);
@@ -248,7 +248,7 @@ mrb_file_realpath(mrb_state *mrb, mrb_value klass)
s = mrb_str_append(mrb, s, pathname);
pathname = s;
}
- cpath = mrb_locale_from_utf8(mrb_str_to_cstr(mrb, pathname), -1);
+ cpath = mrb_locale_from_utf8(RSTRING_CSTR(mrb, pathname), -1);
result = mrb_str_buf_new(mrb, PATH_MAX);
if (realpath(cpath, RSTRING_PTR(result)) == NULL) {
mrb_locale_free(cpath);
@@ -300,14 +300,14 @@ mrb_file__gethome(mrb_state *mrb, mrb_value klass)
mrb_raise(mrb, E_ARGUMENT_ERROR, "non-absolute home");
}
} else {
- const char *cuser = mrb_str_to_cstr(mrb, username);
+ const char *cuser = RSTRING_CSTR(mrb, username);
struct passwd *pwd = getpwnam(cuser);
if (pwd == NULL) {
return mrb_nil_value();
}
home = pwd->pw_dir;
if (!mrb_file_is_absolute_path(home)) {
- mrb_raisef(mrb, E_ARGUMENT_ERROR, "non-absolute home of ~%S", username);
+ mrb_raisef(mrb, E_ARGUMENT_ERROR, "non-absolute home of ~%v", username);
}
}
home = mrb_locale_from_utf8(home, -1);
@@ -393,13 +393,12 @@ mrb_file_s_symlink(mrb_state *mrb, mrb_value klass)
int ai = mrb_gc_arena_save(mrb);
mrb_get_args(mrb, "SS", &from, &to);
- src = mrb_locale_from_utf8(mrb_str_to_cstr(mrb, from), -1);
- dst = mrb_locale_from_utf8(mrb_str_to_cstr(mrb, to), -1);
-
+ src = mrb_locale_from_utf8(RSTRING_CSTR(mrb, from), -1);
+ dst = mrb_locale_from_utf8(RSTRING_CSTR(mrb, to), -1);
if (symlink(src, dst) == -1) {
mrb_locale_free(src);
mrb_locale_free(dst);
- mrb_sys_fail(mrb, mrb_str_to_cstr(mrb, mrb_format(mrb, "(%S, %S)", from, to)));
+ mrb_sys_fail(mrb, RSTRING_CSTR(mrb, mrb_format(mrb, "(%v, %v)", from, to)));
}
mrb_locale_free(src);
mrb_locale_free(dst);
@@ -417,16 +416,16 @@ mrb_file_s_chmod(mrb_state *mrb, mrb_value klass) {
mrb_get_args(mrb, "i*", &mode, &filenames, &argc);
for (i = 0; i < argc; i++) {
- const char *utf8_path = mrb_str_to_cstr(mrb, filenames[i]);
+ const char *utf8_path = RSTRING_CSTR(mrb, filenames[i]);
char *path = mrb_locale_from_utf8(utf8_path, -1);
if (CHMOD(path, mode) == -1) {
mrb_locale_free(path);
mrb_sys_fail(mrb, utf8_path);
}
mrb_locale_free(path);
+ mrb_gc_arena_restore(mrb, ai);
}
- mrb_gc_arena_restore(mrb, ai);
return mrb_fixnum_value(argc);
}
diff --git a/mrbgems/mruby-io/src/file_test.c b/mrbgems/mruby-io/src/file_test.c
index e429b06b3..445bafde9 100644
--- a/mrbgems/mruby-io/src/file_test.c
+++ b/mrbgems/mruby-io/src/file_test.c
@@ -1,5 +1,5 @@
/*
-** file.c - File class
+** file_test.c - FileTest class
*/
#include "mruby.h"
@@ -42,16 +42,9 @@ extern struct mrb_data_type mrb_io_type;
static int
mrb_stat0(mrb_state *mrb, mrb_value obj, struct stat *st, int do_lstat)
{
- mrb_value tmp;
- mrb_value io_klass, str_klass;
-
- io_klass = mrb_obj_value(mrb_class_get(mrb, "IO"));
- str_klass = mrb_obj_value(mrb_class_get(mrb, "String"));
-
- tmp = mrb_funcall(mrb, obj, "is_a?", 1, io_klass);
- if (mrb_test(tmp)) {
+ if (mrb_obj_is_kind_of(mrb, obj, mrb_class_get(mrb, "IO"))) {
struct mrb_io *fptr;
- fptr = (struct mrb_io *)mrb_get_datatype(mrb, obj, &mrb_io_type);
+ fptr = (struct mrb_io *)mrb_data_get_ptr(mrb, obj, &mrb_io_type);
if (fptr && fptr->fd >= 0) {
return fstat(fptr->fd, st);
@@ -60,10 +53,8 @@ mrb_stat0(mrb_state *mrb, mrb_value obj, struct stat *st, int do_lstat)
mrb_raise(mrb, E_IO_ERROR, "closed stream");
return -1;
}
-
- tmp = mrb_funcall(mrb, obj, "is_a?", 1, str_klass);
- if (mrb_test(tmp)) {
- char *path = mrb_locale_from_utf8(mrb_str_to_cstr(mrb, obj), -1);
+ else {
+ char *path = mrb_locale_from_utf8(RSTRING_CSTR(mrb, obj), -1);
int ret;
if (do_lstat) {
ret = LSTAT(path, st);
@@ -73,8 +64,6 @@ mrb_stat0(mrb_state *mrb, mrb_value obj, struct stat *st, int do_lstat)
mrb_locale_free(path);
return ret;
}
-
- return -1;
}
static int
diff --git a/mrbgems/mruby-io/src/io.c b/mrbgems/mruby-io/src/io.c
index e5b83e923..8228097cb 100644
--- a/mrbgems/mruby-io/src/io.c
+++ b/mrbgems/mruby-io/src/io.c
@@ -79,7 +79,7 @@ io_get_open_fptr(mrb_state *mrb, mrb_value self)
{
struct mrb_io *fptr;
- fptr = (struct mrb_io *)mrb_get_datatype(mrb, self, &mrb_io_type);
+ fptr = (struct mrb_io *)mrb_data_get_ptr(mrb, self, &mrb_io_type);
if (fptr == NULL) {
mrb_raise(mrb, E_IO_ERROR, "uninitialized stream.");
}
@@ -127,7 +127,7 @@ mrb_io_modestr_to_flags(mrb_state *mrb, const char *mode)
flags |= FMODE_WRITABLE | FMODE_APPEND | FMODE_CREATE;
break;
default:
- mrb_raisef(mrb, E_ARGUMENT_ERROR, "illegal access mode %S", mrb_str_new_cstr(mrb, mode));
+ mrb_raisef(mrb, E_ARGUMENT_ERROR, "illegal access mode %s", mode);
}
while (*m) {
@@ -141,7 +141,7 @@ mrb_io_modestr_to_flags(mrb_state *mrb, const char *mode)
case ':':
/* XXX: PASSTHROUGH*/
default:
- mrb_raisef(mrb, E_ARGUMENT_ERROR, "illegal access mode %S", mrb_str_new_cstr(mrb, mode));
+ mrb_raisef(mrb, E_ARGUMENT_ERROR, "illegal access mode %s", mode);
}
}
@@ -191,8 +191,7 @@ mrb_fd_cloexec(mrb_state *mrb, int fd)
flags = fcntl(fd, F_GETFD);
if (flags == -1) {
- mrb_bug(mrb, "mrb_fd_cloexec: fcntl(%S, F_GETFD) failed: %S",
- mrb_fixnum_value(fd), mrb_fixnum_value(errno));
+ mrb_bug(mrb, "mrb_fd_cloexec: fcntl(%d, F_GETFD) failed: %d", fd, errno);
}
if (fd <= 2) {
flags2 = flags & ~FD_CLOEXEC; /* Clear CLOEXEC for standard file descriptors: 0, 1, 2. */
@@ -202,8 +201,7 @@ mrb_fd_cloexec(mrb_state *mrb, int fd)
}
if (flags != flags2) {
if (fcntl(fd, F_SETFD, flags2) == -1) {
- mrb_bug(mrb, "mrb_fd_cloexec: fcntl(%S, F_SETFD, %S) failed: %S",
- mrb_fixnum_value(fd), mrb_fixnum_value(flags2), mrb_fixnum_value(errno));
+ mrb_bug(mrb, "mrb_fd_cloexec: fcntl(%d, F_SETFD, %d) failed: %d", fd, flags2, errno);
}
}
#endif
@@ -334,8 +332,8 @@ mrb_io_s_popen(mrb_state *mrb, mrb_value klass)
mrb_get_args(mrb, "S|SH", &cmd, &mode, &opt);
io = mrb_obj_value(mrb_data_object_alloc(mrb, mrb_class_ptr(klass), NULL, &mrb_io_type));
- pname = mrb_string_value_cstr(mrb, &cmd);
- flags = mrb_io_modestr_to_flags(mrb, mrb_string_value_cstr(mrb, &mode));
+ pname = RSTRING_CSTR(mrb, cmd);
+ flags = mrb_io_modestr_to_flags(mrb, RSTRING_CSTR(mrb, mode));
doexec = (strcmp("-", pname) != 0);
opt_in = option_to_fd(mrb, opt, "in");
@@ -381,7 +379,7 @@ mrb_io_s_popen(mrb_state *mrb, mrb_value klass)
CloseHandle(ifd[1]);
CloseHandle(ofd[0]);
CloseHandle(ofd[1]);
- mrb_raisef(mrb, E_IO_ERROR, "command not found: %S", cmd);
+ mrb_raisef(mrb, E_IO_ERROR, "command not found: %v", cmd);
}
CloseHandle(pi.hThread);
CloseHandle(ifd[0]);
@@ -430,8 +428,8 @@ mrb_io_s_popen(mrb_state *mrb, mrb_value klass)
mrb_get_args(mrb, "S|SH", &cmd, &mode, &opt);
io = mrb_obj_value(mrb_data_object_alloc(mrb, mrb_class_ptr(klass), NULL, &mrb_io_type));
- pname = mrb_string_value_cstr(mrb, &cmd);
- flags = mrb_io_modestr_to_flags(mrb, mrb_string_value_cstr(mrb, &mode));
+ pname = RSTRING_CSTR(mrb, cmd);
+ flags = mrb_io_modestr_to_flags(mrb, RSTRING_CSTR(mrb, mode));
doexec = (strcmp("-", pname) != 0);
opt_in = option_to_fd(mrb, opt, "in");
@@ -494,7 +492,7 @@ mrb_io_s_popen(mrb_state *mrb, mrb_value klass)
close(fd);
}
mrb_proc_exec(pname);
- mrb_raisef(mrb, E_IO_ERROR, "command not found: %S", cmd);
+ mrb_raisef(mrb, E_IO_ERROR, "command not found: %v", cmd);
_exit(127);
}
result = mrb_nil_value();
@@ -628,7 +626,7 @@ mrb_io_initialize(mrb_state *mrb, mrb_value io)
opt = mrb_hash_new(mrb);
}
- flags = mrb_io_modestr_to_flags(mrb, mrb_string_value_cstr(mrb, &mode));
+ flags = mrb_io_modestr_to_flags(mrb, RSTRING_CSTR(mrb, mode));
mrb_iv_set(mrb, io, mrb_intern_cstr(mrb, "@buf"), mrb_str_new_cstr(mrb, ""));
@@ -760,7 +758,6 @@ mrb_io_s_sysclose(mrb_state *mrb, mrb_value klass)
int
mrb_cloexec_open(mrb_state *mrb, const char *pathname, mrb_int flags, mrb_int mode)
{
- mrb_value emsg;
int fd, retry = FALSE;
char* fname = mrb_locale_from_utf8(pathname, -1);
@@ -783,9 +780,7 @@ reopen:
}
}
- emsg = mrb_format(mrb, "open %S", mrb_str_new_cstr(mrb, pathname));
- mrb_str_modify(mrb, mrb_str_ptr(emsg));
- mrb_sys_fail(mrb, RSTRING_PTR(emsg));
+ mrb_sys_fail(mrb, RSTRING_CSTR(mrb, mrb_format(mrb, "open %s", pathname)));
}
mrb_locale_free(fname);
@@ -812,8 +807,8 @@ mrb_io_s_sysopen(mrb_state *mrb, mrb_value klass)
perm = 0666;
}
- pat = mrb_string_value_cstr(mrb, &path);
- flags = mrb_io_modestr_to_flags(mrb, mrb_string_value_cstr(mrb, &mode));
+ pat = RSTRING_CSTR(mrb, path);
+ flags = mrb_io_modestr_to_flags(mrb, RSTRING_CSTR(mrb, mode));
modenum = mrb_io_flags_to_modenum(mrb, flags);
fd = mrb_cloexec_open(mrb, pat, modenum, perm);
return mrb_fixnum_value(fd);
@@ -955,7 +950,7 @@ mrb_value
mrb_io_closed(mrb_state *mrb, mrb_value io)
{
struct mrb_io *fptr;
- fptr = (struct mrb_io *)mrb_get_datatype(mrb, io, &mrb_io_type);
+ fptr = (struct mrb_io *)mrb_data_get_ptr(mrb, io, &mrb_io_type);
if (fptr == NULL || fptr->fd >= 0) {
return mrb_false_value();
}
@@ -1068,7 +1063,7 @@ mrb_io_s_select(mrb_state *mrb, mrb_value klass)
mrb_get_args(mrb, "*", &argv, &argc);
if (argc < 1 || argc > 4) {
- mrb_raisef(mrb, E_ARGUMENT_ERROR, "wrong number of arguments (%S for 1..4)", mrb_fixnum_value(argc));
+ mrb_raisef(mrb, E_ARGUMENT_ERROR, "wrong number of arguments (%i for 1..4)", argc);
}
timeout = mrb_nil_value();
@@ -1299,6 +1294,27 @@ mrb_io_sync(mrb_state *mrb, mrb_value self)
return mrb_bool_value(fptr->sync);
}
+static mrb_value
+io_bufread(mrb_state *mrb, mrb_value self)
+{
+ mrb_value str, str2;
+ mrb_int len, newlen;
+ struct RString *s;
+ char *p;
+
+ mrb_get_args(mrb, "Si", &str, &len);
+ s = RSTRING(str);
+ mrb_str_modify(mrb, s);
+ p = RSTR_PTR(s);
+ str2 = mrb_str_new(mrb, p, len);
+ newlen = RSTR_LEN(s)-len;
+ memmove(p, p+len, newlen);
+ p[newlen] = '\0';
+ RSTR_SET_LEN(s, newlen);
+
+ return str2;
+}
+
void
mrb_init_io(mrb_state *mrb)
{
@@ -1334,6 +1350,5 @@ mrb_init_io(mrb_state *mrb)
mrb_define_method(mrb, io, "pid", mrb_io_pid, MRB_ARGS_NONE()); /* 15.2.20.5.2 */
mrb_define_method(mrb, io, "fileno", mrb_io_fileno, MRB_ARGS_NONE());
-
- mrb_gv_set(mrb, mrb_intern_cstr(mrb, "$/"), mrb_str_new_cstr(mrb, "\n"));
+ mrb_define_class_method(mrb, io, "_bufread", io_bufread, MRB_ARGS_REQ(2));
}
diff --git a/mrbgems/mruby-io/test/file.rb b/mrbgems/mruby-io/test/file.rb
index 7b67ded26..143096759 100644
--- a/mrbgems/mruby-io/test/file.rb
+++ b/mrbgems/mruby-io/test/file.rb
@@ -1,15 +1,13 @@
##
# File Test
-assert('File TEST SETUP') do
- MRubyIOTestUtil.io_test_setup
-end
+MRubyIOTestUtil.io_test_setup
-assert('File', '15.2.21') do
+assert('File.class', '15.2.21') do
assert_equal Class, File.class
end
-assert('File', '15.2.21.2') do
+assert('File.superclass', '15.2.21.2') do
assert_equal IO, File.superclass
end
@@ -35,6 +33,7 @@ assert('File.basename') do
assert_equal 'a', File.basename('/a/')
assert_equal 'b', File.basename('/a/b')
assert_equal 'b', File.basename('../a/b')
+ assert_raise(ArgumentError) { File.basename("/a/b\0") }
end
assert('File.dirname') do
@@ -69,9 +68,6 @@ assert('File#flock') do
end
assert('File#mtime') do
- unless Object.const_defined?(:Time)
- skip "File#mtime require Time"
- end
begin
File.open("#{$mrbtest_io_wfname}.mtime", 'w') do |f|
assert_equal Time, f.mtime.class
@@ -111,6 +107,8 @@ assert('File.realpath') do
MRubyIOTestUtil.rmdir dir
end
end
+
+ assert_raise(ArgumentError) { File.realpath("TO\0DO") }
end
assert("File.readlink") do
@@ -177,25 +175,29 @@ assert('File.path') do
assert_equal "a/../b/./c", File.path("a/../b/./c")
assert_raise(TypeError) { File.path(nil) }
assert_raise(TypeError) { File.path(123) }
-
end
assert('File.symlink') do
target_name = "/usr/bin"
- symlink_name = "test-bin-dummy"
if !File.exist?(target_name)
skip("target directory of File.symlink is not found")
- else
- begin
- assert_equal 0, File.symlink(target_name, symlink_name)
- begin
- assert_equal true, File.symlink?(symlink_name)
- ensure
- File.delete symlink_name
- end
- rescue NotImplementedError => e
- skip e.message
- end
+ end
+
+ begin
+ tmpdir = MRubyIOTestUtil.mkdtemp("mruby-io-test.XXXXXX")
+ rescue => e
+ skip e.message
+ end
+
+ symlink_name = "#{tmpdir}/test-bin-dummy"
+ begin
+ assert_equal 0, File.symlink(target_name, symlink_name)
+ assert_equal true, File.symlink?(symlink_name)
+ rescue NotImplementedError => e
+ skip e.message
+ ensure
+ File.delete symlink_name rescue nil
+ MRubyIOTestUtil.rmdir tmpdir rescue nil
end
end
@@ -208,6 +210,4 @@ assert('File.chmod') do
end
end
-assert('File TEST CLEANUP') do
- assert_nil MRubyIOTestUtil.io_test_cleanup
-end
+MRubyIOTestUtil.io_test_cleanup
diff --git a/mrbgems/mruby-io/test/file_test.rb b/mrbgems/mruby-io/test/file_test.rb
index 2c831f0d5..2134c6a75 100644
--- a/mrbgems/mruby-io/test/file_test.rb
+++ b/mrbgems/mruby-io/test/file_test.rb
@@ -1,9 +1,7 @@
##
# FileTest
-assert('FileTest TEST SETUP') do
- MRubyIOTestUtil.io_test_setup
-end
+MRubyIOTestUtil.io_test_setup
assert("FileTest.directory?") do
dir = MRubyIOTestUtil.mkdtemp("mruby-io-test.XXXXXX")
@@ -22,9 +20,8 @@ assert("FileTest.exist?") do
assert_equal true, FileTest.exist?(io), "io obj - exist"
io.close
assert_equal true, io.closed?
- assert_raise IOError do
- FileTest.exist?(io)
- end
+ assert_raise(IOError) { FileTest.exist?(io) }
+ assert_raise(TypeError) { File.exist?($mrbtest_io_rfname.to_sym) }
end
assert("FileTest.file?") do
@@ -67,11 +64,11 @@ assert("FileTest.size?") do
assert_raise IOError do
FileTest.size?(fp1)
end
+ assert_true fp1.closed?
assert_raise IOError do
FileTest.size?(fp2)
end
-
- fp1.closed? && fp2.closed?
+ assert_true fp2.closed?
end
assert("FileTest.socket?") do
@@ -105,13 +102,11 @@ assert("FileTest.zero?") do
assert_raise IOError do
FileTest.zero?(fp1)
end
+ assert_true fp1.closed?
assert_raise IOError do
FileTest.zero?(fp2)
end
-
- fp1.closed? && fp2.closed?
+ assert_true fp2.closed?
end
-assert('FileTest TEST CLEANUP') do
- assert_nil MRubyIOTestUtil.io_test_cleanup
-end
+MRubyIOTestUtil.io_test_cleanup
diff --git a/mrbgems/mruby-io/test/io.rb b/mrbgems/mruby-io/test/io.rb
index 881e94185..e3024cf9a 100644
--- a/mrbgems/mruby-io/test/io.rb
+++ b/mrbgems/mruby-io/test/io.rb
@@ -1,37 +1,46 @@
##
# IO Test
-assert('IO TEST SETUP') do
- MRubyIOTestUtil.io_test_setup
- $cr = MRubyIOTestUtil.win? ? 1 : 0 # "\n" include CR or not
+MRubyIOTestUtil.io_test_setup
+$cr, $crlf, $cmd = MRubyIOTestUtil.win? ? [1, "\r\n", "cmd /c "] : [0, "\n", ""]
+
+def assert_io_open(meth)
+ assert "assert_io_open" do
+ fd = IO.sysopen($mrbtest_io_rfname)
+ assert_equal Fixnum, fd.class
+ io1 = IO.__send__(meth, fd)
+ begin
+ assert_equal IO, io1.class
+ assert_equal $mrbtest_io_msg, io1.read
+ ensure
+ io1.close
+ end
+
+ io2 = IO.__send__(meth, IO.sysopen($mrbtest_io_rfname))do |io|
+ if meth == :open
+ assert_equal $mrbtest_io_msg, io.read
+ else
+ flunk "IO.#{meth} does not take block"
+ end
+ end
+ io2.close unless meth == :open
+ end
end
-assert('IO', '15.2.20') do
+assert('IO.class', '15.2.20') do
assert_equal(Class, IO.class)
end
-assert('IO', '15.2.20.2') do
+assert('IO.superclass', '15.2.20.2') do
assert_equal(Object, IO.superclass)
end
-assert('IO', '15.2.20.3') do
+assert('IO.ancestors', '15.2.20.3') do
assert_include(IO.ancestors, Enumerable)
end
assert('IO.open', '15.2.20.4.1') do
- fd = IO.sysopen $mrbtest_io_rfname
- assert_equal Fixnum, fd.class
- io = IO.open fd
- assert_equal IO, io.class
- assert_equal $mrbtest_io_msg, io.read
- io.close
-
- fd = IO.sysopen $mrbtest_io_rfname
- IO.open(fd) do |io|
- assert_equal $mrbtest_io_msg, io.read
- end
-
- true
+ assert_io_open(:open)
end
assert('IO#close', '15.2.20.5.1') do
@@ -72,8 +81,6 @@ assert('IO#eof?', '15.2.20.5.6') do
io.read
assert_true io.eof?
io.close
-
- true
end
assert('IO#flush', '15.2.20.5.7') do
@@ -88,12 +95,11 @@ end
assert('IO#getc', '15.2.20.5.8') do
io = IO.new(IO.sysopen($mrbtest_io_rfname))
- $mrbtest_io_msg.each_char { |ch|
+ $mrbtest_io_msg.split("").each { |ch|
assert_equal ch, io.getc
}
assert_equal nil, io.getc
io.close
- true
end
#assert('IO#gets', '15.2.20.5.9') do
@@ -123,16 +129,17 @@ end
assert "IO#read(n) with n > IO::BUF_SIZE" do
skip "pipe is not supported on this platform" if MRubyIOTestUtil.win?
- r,w = IO.pipe
- n = IO::BUF_SIZE+1
- w.write 'a'*n
- assert_equal r.read(n), 'a'*n
+ IO.pipe do |r,w|
+ n = IO::BUF_SIZE+1
+ w.write 'a'*n
+ assert_equal 'a'*n, r.read(n)
+ end
end
assert('IO#readchar', '15.2.20.5.15') do
# almost same as IO#getc
IO.open(IO.sysopen($mrbtest_io_rfname)) do |io|
- $mrbtest_io_msg.each_char { |ch|
+ $mrbtest_io_msg.split("").each { |ch|
assert_equal ch, io.readchar
}
assert_raise(EOFError) do
@@ -179,8 +186,6 @@ assert('IO#write', '15.2.20.5.20') do
io.rewind
assert_equal "ab123fg", io.read
io.close
-
- true
end
assert('IO#<<') do
@@ -188,7 +193,6 @@ assert('IO#<<') do
io << "" << ""
assert_equal 0, io.pos
io.close
- true
end
assert('IO#dup for readable') do
@@ -208,7 +212,6 @@ assert('IO#dup for readable') do
dup.close
assert_false io.closed?
io.close
- true
end
assert('IO#dup for writable') do
@@ -221,25 +224,18 @@ assert('IO#dup for writable') do
assert_equal "mruby", dup.sysread(5)
dup.close
io.close
- true
end
assert('IO.for_fd') do
- fd = IO.sysopen($mrbtest_io_rfname)
- io = IO.for_fd(fd)
- assert_equal $mrbtest_io_msg, io.read
- io.close
- true
+ assert_io_open(:for_fd)
end
assert('IO.new') do
- io = IO.new(0)
- io.close
- true
+ assert_io_open(:new)
end
assert('IO gc check') do
- 100.times { IO.new(0) }
+ assert_nothing_raised { 100.times { IO.new(0) } }
end
assert('IO.sysopen("./nonexistent")') do
@@ -280,7 +276,6 @@ assert('IO.sysopen, IO#sysread') do
io = IO.new fd, "w"
assert_raise(IOError) { io.sysread(1) }
io.close
- true
end
assert('IO.sysopen, IO#syswrite') do
@@ -294,8 +289,6 @@ assert('IO.sysopen, IO#syswrite') do
io = IO.new(IO.sysopen($mrbtest_io_rfname), "r")
assert_raise(IOError) { io.syswrite("a") }
io.close
-
- true
end
assert('IO#_read_buf') do
@@ -319,7 +312,6 @@ assert('IO#_read_buf') do
assert_equal true, io.eof
assert_equal true, io.eof?
io.close
- io.closed?
end
assert('IO#isatty') do
@@ -352,7 +344,6 @@ assert('IO#pos=, IO#seek') do
assert_equal 0, io.seek(0)
assert_equal 0, io.pos
io.close
- io.closed?
end
assert('IO#rewind') do
@@ -363,7 +354,6 @@ assert('IO#rewind') do
assert_equal 0, io.rewind
assert_equal 0, io.pos
io.close
- io.closed?
end
assert('IO#gets') do
@@ -412,7 +402,6 @@ assert('IO#gets') do
assert_equal nil, io.gets, "gets third line; returns nil"
io.close
- io.closed?
end
assert('IO#gets - paragraph mode') do
@@ -423,7 +412,6 @@ assert('IO#gets - paragraph mode') do
io.write "2" * 10 + "\n"
assert_equal 34 + $cr * 4, io.pos
io.close
- assert_equal true, io.closed?
fd = IO.sysopen $mrbtest_io_wfname
io = IO.new fd
@@ -434,13 +422,12 @@ assert('IO#gets - paragraph mode') do
text2 = io.gets("")
assert_equal para2, text2
io.close
- io.closed?
end
assert('IO.popen') do
begin
$? = nil
- io = IO.popen("echo mruby-io")
+ io = IO.popen("#{$cmd}echo mruby-io")
assert_true io.close_on_exec?
assert_equal Fixnum, io.pid.class
@@ -528,7 +515,6 @@ assert('IO#fileno') do
assert_equal io.fileno, fd
assert_equal io.to_i, fd
io.close
- io.closed?
end
assert('IO#close_on_exec') do
@@ -550,7 +536,6 @@ assert('IO#close_on_exec') do
assert_equal(false, io.close_on_exec?)
io.close
- io.closed?
begin
r, w = IO.pipe
@@ -621,12 +606,10 @@ end
assert('`cmd`') do
begin
- assert_equal `echo foo`, "foo\n"
+ assert_equal `#{$cmd}echo foo`, "foo#{$crlf}"
rescue NotImplementedError => e
skip e.message
end
end
-assert('IO TEST CLEANUP') do
- assert_nil MRubyIOTestUtil.io_test_cleanup
-end
+MRubyIOTestUtil.io_test_cleanup
diff --git a/mrbgems/mruby-io/test/mruby_io_test.c b/mrbgems/mruby-io/test/mruby_io_test.c
index 71239a827..2c8a75fc9 100644
--- a/mrbgems/mruby-io/test/mruby_io_test.c
+++ b/mrbgems/mruby-io/test/mruby_io_test.c
@@ -136,9 +136,9 @@ mrb_io_test_io_setup(mrb_state *mrb, mrb_value self)
sun0.sun_family = AF_UNIX;
snprintf(sun0.sun_path, sizeof(sun0.sun_path), "%s", socketname);
if (bind(fd3, (struct sockaddr *)&sun0, sizeof(sun0)) == -1) {
- mrb_raisef(mrb, E_RUNTIME_ERROR, "can't bind AF_UNIX socket to %S: %S",
- mrb_str_new_cstr(mrb, sun0.sun_path),
- mrb_fixnum_value(errno));
+ mrb_raisef(mrb, E_RUNTIME_ERROR, "can't bind AF_UNIX socket to %s: %d",
+ sun0.sun_path,
+ errno);
}
close(fd3);
#endif
@@ -215,11 +215,9 @@ mrb_io_test_mkdtemp(mrb_state *mrb, mrb_value klass)
static mrb_value
mrb_io_test_rmdir(mrb_state *mrb, mrb_value klass)
{
- mrb_value str;
- char *cp;
+ const char *cp;
- mrb_get_args(mrb, "S", &str);
- cp = mrb_str_to_cstr(mrb, str);
+ mrb_get_args(mrb, "z", &cp);
if (rmdir(cp) == -1) {
mrb_sys_fail(mrb, "rmdir");
}
diff --git a/mrbgems/mruby-kernel-ext/mrbgem.rake b/mrbgems/mruby-kernel-ext/mrbgem.rake
index fcb3a83b0..e52c63a55 100644
--- a/mrbgems/mruby-kernel-ext/mrbgem.rake
+++ b/mrbgems/mruby-kernel-ext/mrbgem.rake
@@ -1,5 +1,5 @@
MRuby::Gem::Specification.new('mruby-kernel-ext') do |spec|
spec.license = 'MIT'
spec.author = 'mruby developers'
- spec.summary = 'Kernel module extension'
+ spec.summary = 'extensional function-like methods'
end
diff --git a/mrbgems/mruby-kernel-ext/mrblib/kernel.rb b/mrbgems/mruby-kernel-ext/mrblib/kernel.rb
deleted file mode 100644
index bf739ed1a..000000000
--- a/mrbgems/mruby-kernel-ext/mrblib/kernel.rb
+++ /dev/null
@@ -1,15 +0,0 @@
-module Kernel
- # call-seq:
- # obj.yield_self {|_obj|...} -> an_object
- # obj.then {|_obj|...} -> an_object
- #
- # Yields <i>obj</i> and returns the result.
- #
- # 'my string'.yield_self {|s|s.upcase} #=> "MY STRING"
- #
- def yield_self(&block)
- return to_enum :yield_self unless block
- block.call(self)
- end
- alias then yield_self
-end
diff --git a/mrbgems/mruby-kernel-ext/src/kernel.c b/mrbgems/mruby-kernel-ext/src/kernel.c
index 99affbfa4..376751e10 100644
--- a/mrbgems/mruby-kernel-ext/src/kernel.c
+++ b/mrbgems/mruby-kernel-ext/src/kernel.c
@@ -22,7 +22,7 @@ mrb_f_caller(mrb_state *mrb, mrb_value self)
case 1:
if (mrb_type(v) == MRB_TT_RANGE) {
mrb_int beg, len;
- if (mrb_range_beg_len(mrb, v, &beg, &len, bt_len, TRUE) == 1) {
+ if (mrb_range_beg_len(mrb, v, &beg, &len, bt_len, TRUE) == MRB_RANGE_OK) {
lev = beg;
n = len;
}
@@ -31,22 +31,21 @@ mrb_f_caller(mrb_state *mrb, mrb_value self)
}
}
else {
- v = mrb_to_int(mrb, v);
- lev = mrb_fixnum(v);
+ lev = mrb_int(mrb, v);
if (lev < 0) {
- mrb_raisef(mrb, E_ARGUMENT_ERROR, "negative level (%S)", v);
+ mrb_raisef(mrb, E_ARGUMENT_ERROR, "negative level (%v)", v);
}
n = bt_len - lev;
}
break;
case 2:
- lev = mrb_fixnum(mrb_to_int(mrb, v));
- n = mrb_fixnum(mrb_to_int(mrb, length));
+ lev = mrb_int(mrb, v);
+ n = mrb_int(mrb, length);
if (lev < 0) {
- mrb_raisef(mrb, E_ARGUMENT_ERROR, "negative level (%S)", v);
+ mrb_raisef(mrb, E_ARGUMENT_ERROR, "negative level (%v)", v);
}
if (n < 0) {
- mrb_raisef(mrb, E_ARGUMENT_ERROR, "negative size (%S)", length);
+ mrb_raisef(mrb, E_ARGUMENT_ERROR, "negative size (%v)", length);
}
break;
default:
@@ -206,22 +205,6 @@ mrb_f_hash(mrb_state *mrb, mrb_value self)
return mrb_ensure_hash_type(mrb, arg);
}
-/*
- * call-seq:
- * obj.itself -> an_object
- *
- * Returns <i>obj</i>.
- *
- * string = 'my string' #=> "my string"
- * string.itself.object_id == string.object_id #=> true
- *
- */
-static mrb_value
-mrb_f_itself(mrb_state *mrb, mrb_value self)
-{
- return self;
-}
-
void
mrb_mruby_kernel_ext_gem_init(mrb_state *mrb)
{
@@ -237,7 +220,6 @@ mrb_mruby_kernel_ext_gem_init(mrb_state *mrb)
mrb_define_module_function(mrb, krn, "String", mrb_f_string, MRB_ARGS_REQ(1));
mrb_define_module_function(mrb, krn, "Array", mrb_f_array, MRB_ARGS_REQ(1));
mrb_define_module_function(mrb, krn, "Hash", mrb_f_hash, MRB_ARGS_REQ(1));
- mrb_define_module_function(mrb, krn, "itself", mrb_f_itself, MRB_ARGS_NONE());
}
void
diff --git a/mrbgems/mruby-kernel-ext/test/kernel.rb b/mrbgems/mruby-kernel-ext/test/kernel.rb
index 28f089007..ad9177165 100644
--- a/mrbgems/mruby-kernel-ext/test/kernel.rb
+++ b/mrbgems/mruby-kernel-ext/test/kernel.rb
@@ -65,6 +65,8 @@ assert('Kernel#Float') do
assert_equal(123.456, Float(123.456))
assert_equal(123.456, Float("123.456"))
assert_raise(TypeError) { Float(nil) }
+ assert_raise(ArgumentError) { Float("1.5a") }
+ assert_raise(ArgumentError) { Float("1.5\0") }
end
assert('Kernel#String') do
diff --git a/mrbgems/mruby-math/src/math.c b/mrbgems/mruby-math/src/math.c
index c29ba6808..88b33771b 100644
--- a/mrbgems/mruby-math/src/math.c
+++ b/mrbgems/mruby-math/src/math.c
@@ -4,6 +4,10 @@
** See Copyright Notice in mruby.h
*/
+#ifdef MRB_WITHOUT_FLOAT
+# error Math conflicts 'MRB_WITHOUT_FLOAT' configuration in your 'build_config.rb'
+#endif
+
#include <mruby.h>
#include <mruby/array.h>
@@ -14,8 +18,7 @@ domain_error(mrb_state *mrb, const char *func)
{
struct RClass *math = mrb_module_get(mrb, "Math");
struct RClass *domainerror = mrb_class_get_under(mrb, math, "DomainError");
- mrb_value str = mrb_str_new_cstr(mrb, func);
- mrb_raisef(mrb, domainerror, "Numerical argument is out of domain - %S", str);
+ mrb_raisef(mrb, domainerror, "Numerical argument is out of domain - %s", func);
}
/* math functions not provided by Microsoft Visual C++ 2012 or older */
@@ -23,8 +26,6 @@ domain_error(mrb_state *mrb, const char *func)
#include <float.h>
-#define MATH_TOLERANCE 1E-12
-
double
asinh(double x)
{
@@ -122,7 +123,8 @@ erf(double x)
term *= xsqr/j;
sum += term/(2*j+1);
++j;
- } while (fabs(term/sum) > MATH_TOLERANCE);
+ if (sum == 0) break;
+ } while (fabs(term/sum) > DBL_EPSILON);
return two_sqrtpi*sum;
}
@@ -155,7 +157,7 @@ erfc(double x)
n += 0.5;
q1 = q2;
q2 = b/d;
- } while (fabs(q1-q2)/q2 > MATH_TOLERANCE);
+ } while (fabs(q1-q2)/q2 > DBL_EPSILON);
return one_sqrtpi*exp(-x*x)*q2;
}
@@ -742,12 +744,6 @@ mrb_mruby_math_gem_init(mrb_state* mrb)
mrb_define_const(mrb, mrb_math, "E", mrb_float_value(mrb, exp(1.0)));
#endif
-#ifdef MRB_USE_FLOAT
- mrb_define_const(mrb, mrb_math, "TOLERANCE", mrb_float_value(mrb, 1e-5));
-#else
- mrb_define_const(mrb, mrb_math, "TOLERANCE", mrb_float_value(mrb, 1e-12));
-#endif
-
mrb_define_module_function(mrb, mrb_math, "sin", math_sin, MRB_ARGS_REQ(1));
mrb_define_module_function(mrb, mrb_math, "cos", math_cos, MRB_ARGS_REQ(1));
mrb_define_module_function(mrb, mrb_math, "tan", math_tan, MRB_ARGS_REQ(1));
diff --git a/mrbgems/mruby-math/test/math.rb b/mrbgems/mruby-math/test/math.rb
index e9ea07cc1..86a4fc12c 100644
--- a/mrbgems/mruby-math/test/math.rb
+++ b/mrbgems/mruby-math/test/math.rb
@@ -1,46 +1,31 @@
##
# Math Test
-##
-# Performs fuzzy check for equality on methods returning floats
-# on the basis of the Math::TOLERANCE constant.
-def check_float(a, b)
- tolerance = Math::TOLERANCE
- a = a.to_f
- b = b.to_f
- if a.finite? and b.finite?
- (a-b).abs < tolerance
- else
- true
- end
-end
-
assert('Math.sin 0') do
- check_float(Math.sin(0), 0)
+ assert_float(0, Math.sin(0))
end
assert('Math.sin PI/2') do
- check_float(Math.sin(Math::PI / 2), 1)
+ assert_float(1, Math.sin(Math::PI / 2))
end
assert('Math.cos 0') do
- check_float(Math.cos(0), 1)
+ assert_float(1, Math.cos(0))
end
assert('Math.cos PI/2') do
- check_float(Math.cos(Math::PI / 2), 0)
+ assert_float(0, Math.cos(Math::PI / 2))
end
assert('Math.tan 0') do
- check_float(Math.tan(0), 0)
+ assert_float(0, Math.tan(0))
end
assert('Math.tan PI/4') do
- check_float(Math.tan(Math::PI / 4), 1)
+ assert_float(1, Math.tan(Math::PI / 4))
end
assert('Fundamental trig identities') do
- result = true
N = 13
N.times do |i|
a = Math::PI / N * i
@@ -48,105 +33,100 @@ assert('Fundamental trig identities') do
s = Math.sin(a)
c = Math.cos(a)
t = Math.tan(a)
- result &= check_float(s, Math.cos(ca))
- result &= check_float(t, 1 / Math.tan(ca))
- result &= check_float(s ** 2 + c ** 2, 1)
- result &= check_float(t ** 2 + 1, (1/c) ** 2)
- result &= check_float((1/t) ** 2 + 1, (1/s) ** 2)
+ assert_float(Math.cos(ca), s)
+ assert_float(1 / Math.tan(ca), t)
+ assert_float(1, s ** 2 + c ** 2)
+ assert_float((1/c) ** 2, t ** 2 + 1)
+ assert_float((1/s) ** 2, (1/t) ** 2 + 1)
end
- result
end
assert('Math.erf 0') do
- check_float(Math.erf(0), 0)
+ assert_float(0, Math.erf(0))
end
assert('Math.exp 0') do
- check_float(Math.exp(0), 1.0)
+ assert_float(1.0, Math.exp(0))
end
assert('Math.exp 1') do
- check_float(Math.exp(1), 2.718281828459045)
+ assert_float(2.718281828459045, Math.exp(1))
end
assert('Math.exp 1.5') do
- check_float(Math.exp(1.5), 4.4816890703380645)
+ assert_float(4.4816890703380645, Math.exp(1.5))
end
assert('Math.log 1') do
- check_float(Math.log(1), 0)
+ assert_float(0, Math.log(1))
end
assert('Math.log E') do
- check_float(Math.log(Math::E), 1.0)
+ assert_float(1.0, Math.log(Math::E))
end
assert('Math.log E**3') do
- check_float(Math.log(Math::E**3), 3.0)
+ assert_float(3.0, Math.log(Math::E**3))
end
assert('Math.log2 1') do
- check_float(Math.log2(1), 0.0)
+ assert_float(0.0, Math.log2(1))
end
assert('Math.log2 2') do
- check_float(Math.log2(2), 1.0)
+ assert_float(1.0, Math.log2(2))
end
assert('Math.log10 1') do
- check_float(Math.log10(1), 0.0)
+ assert_float(0.0, Math.log10(1))
end
assert('Math.log10 10') do
- check_float(Math.log10(10), 1.0)
+ assert_float(1.0, Math.log10(10))
end
assert('Math.log10 10**100') do
- check_float(Math.log10(10**100), 100.0)
+ assert_float(100.0, Math.log10(10**100))
end
assert('Math.sqrt') do
num = [0.0, 1.0, 2.0, 3.0, 4.0]
sqr = [0, 1, 4, 9, 16]
- result = true
sqr.each_with_index do |v,i|
- result &= check_float(Math.sqrt(v), num[i])
+ assert_float(num[i], Math.sqrt(v))
end
- result
end
assert('Math.cbrt') do
num = [-2.0, -1.0, 0.0, 1.0, 2.0]
cub = [-8, -1, 0, 1, 8]
- result = true
cub.each_with_index do |v,i|
- result &= check_float(Math.cbrt(v), num[i])
+ assert_float(num[i], Math.cbrt(v))
end
- result
end
assert('Math.hypot') do
- check_float(Math.hypot(3, 4), 5.0)
+ assert_float(5.0, Math.hypot(3, 4))
end
assert('Math.frexp 1234') do
n = 1234
fraction, exponent = Math.frexp(n)
- check_float(Math.ldexp(fraction, exponent), n)
+ assert_float(n, Math.ldexp(fraction, exponent))
end
assert('Math.erf 1') do
- check_float(Math.erf(1), 0.842700792949715)
+ assert_float(0.842700792949715, Math.erf(1))
end
assert('Math.erfc 1') do
- check_float(Math.erfc(1), 0.157299207050285)
+ assert_float(0.157299207050285, Math.erfc(1))
end
assert('Math.erf -1') do
- check_float(Math.erf(-1), -0.8427007929497148)
+ assert_float(-0.8427007929497148, Math.erf(-1))
end
assert('Math.erfc -1') do
- check_float(Math.erfc(-1), 1.8427007929497148)
+ assert_float(1.8427007929497148, Math.erfc(-1))
end
diff --git a/mrbgems/mruby-metaprog/src/metaprog.c b/mrbgems/mruby-metaprog/src/metaprog.c
index 25c153cee..97f53051f 100644
--- a/mrbgems/mruby-metaprog/src/metaprog.c
+++ b/mrbgems/mruby-metaprog/src/metaprog.c
@@ -117,6 +117,7 @@ mrb_obj_ivar_set(mrb_state *mrb, mrb_value self)
}
/* 15.3.1.2.7 */
+/* 15.3.1.3.28 */
/*
* call-seq:
* local_variables -> array
@@ -186,7 +187,7 @@ method_entry_loop(mrb_state *mrb, struct RClass* klass, khash_t(st)* set)
}
}
-mrb_value
+static mrb_value
mrb_class_instance_method_list(mrb_state *mrb, mrb_bool recur, struct RClass* klass, int obj)
{
khint_t i;
@@ -400,21 +401,21 @@ mod_define_singleton_method(mrb_state *mrb, mrb_value self)
return mrb_symbol_value(mid);
}
-static void
-check_cv_name_str(mrb_state *mrb, mrb_value str)
+static mrb_bool
+cv_name_p(mrb_state *mrb, const char *name, mrb_int len)
{
- const char *s = RSTRING_PTR(str);
- mrb_int len = RSTRING_LEN(str);
-
- if (len < 3 || !(s[0] == '@' && s[1] == '@')) {
- mrb_name_error(mrb, mrb_intern_str(mrb, str), "'%S' is not allowed as a class variable name", str);
- }
+ return len > 2 && name[0] == '@' && name[1] == '@' &&
+ !ISDIGIT(name[2]) && mrb_ident_p(name+2, len-2);
}
static void
check_cv_name_sym(mrb_state *mrb, mrb_sym id)
{
- check_cv_name_str(mrb, mrb_sym2str(mrb, id));
+ mrb_int len;
+ const char *name = mrb_sym2name_len(mrb, id, &len);
+ if (!cv_name_p(mrb, name, len)) {
+ mrb_name_error(mrb, id, "'%n' is not allowed as a class variable name", id);
+ }
}
/* 15.2.2.4.39 */
@@ -453,12 +454,10 @@ mrb_mod_remove_cvar(mrb_state *mrb, mrb_value mod)
if (!mrb_undef_p(val)) return val;
if (mrb_cv_defined(mrb, mod, id)) {
- mrb_name_error(mrb, id, "cannot remove %S for %S",
- mrb_sym2str(mrb, id), mod);
+ mrb_name_error(mrb, id, "cannot remove %n for %v", id, mod);
}
- mrb_name_error(mrb, id, "class variable %S not defined for %S",
- mrb_sym2str(mrb, id), mod);
+ mrb_name_error(mrb, id, "class variable %n not defined for %v", id, mod);
/* not reached */
return mrb_nil_value();
@@ -565,8 +564,6 @@ mrb_mod_included_modules(mrb_state *mrb, mrb_value self)
return result;
}
-mrb_value mrb_class_instance_method_list(mrb_state*, mrb_bool, struct RClass*, int);
-
/* 15.2.2.4.33 */
/*
* call-seq:
@@ -623,8 +620,7 @@ remove_method(mrb_state *mrb, mrb_value mod, mrb_sym mid)
}
}
- mrb_name_error(mrb, mid, "method '%S' not defined in %S",
- mrb_sym2str(mrb, mid), mod);
+ mrb_name_error(mrb, mid, "method '%n' not defined in %v", mid, mod);
}
/* 15.2.2.4.41 */
@@ -643,6 +639,7 @@ mrb_mod_remove_method(mrb_state *mrb, mrb_value mod)
mrb_value *argv;
mrb_get_args(mrb, "*", &argv, &argc);
+ mrb_check_frozen(mrb, mrb_obj_ptr(mod));
while (argc--) {
remove_method(mrb, mod, mrb_obj_to_sym(mrb, *argv));
argv++;
@@ -657,8 +654,30 @@ mrb_mod_s_constants(mrb_state *mrb, mrb_value mod)
return mrb_nil_value(); /* not reached */
}
-/* implementation of Module.nesting */
-mrb_value mrb_mod_s_nesting(mrb_state*, mrb_value);
+static mrb_value
+mrb_mod_s_nesting(mrb_state *mrb, mrb_value mod)
+{
+ struct RProc *proc;
+ mrb_value ary;
+ struct RClass *c = NULL;
+
+ mrb_get_args(mrb, "");
+ ary = mrb_ary_new(mrb);
+ proc = mrb->c->ci[-1].proc; /* callee proc */
+ mrb_assert(!MRB_PROC_CFUNC_P(proc));
+ while (proc) {
+ if (MRB_PROC_SCOPE_P(proc)) {
+ struct RClass *c2 = MRB_PROC_TARGET_CLASS(proc);
+
+ if (c2 != c) {
+ c = c2;
+ mrb_ary_push(mrb, ary, mrb_obj_value(c));
+ }
+ }
+ proc = proc->upper;
+ }
+ return ary;
+}
void
mrb_mruby_metaprog_gem_init(mrb_state* mrb)
@@ -666,8 +685,8 @@ mrb_mruby_metaprog_gem_init(mrb_state* mrb)
struct RClass *krn = mrb->kernel_module;
struct RClass *mod = mrb->module_class;
- mrb_define_method(mrb, krn, "global_variables", mrb_f_global_variables, MRB_ARGS_NONE()); /* 15.3.1.2.4 */
- mrb_define_method(mrb, krn, "local_variables", mrb_local_variables, MRB_ARGS_NONE()); /* 15.3.1.3.28 */
+ mrb_define_method(mrb, krn, "global_variables", mrb_f_global_variables, MRB_ARGS_NONE()); /* 15.3.1.3.14 (15.3.1.2.4) */
+ mrb_define_method(mrb, krn, "local_variables", mrb_local_variables, MRB_ARGS_NONE()); /* 15.3.1.3.28 (15.3.1.2.7) */
mrb_define_method(mrb, krn, "singleton_class", mrb_singleton_class, MRB_ARGS_NONE());
mrb_define_method(mrb, krn, "instance_variable_defined?", mrb_obj_ivar_defined, MRB_ARGS_REQ(1)); /* 15.3.1.3.20 */
diff --git a/mrbgems/mruby-metaprog/test/metaprog.rb b/mrbgems/mruby-metaprog/test/metaprog.rb
index 748fe9c6c..30b75bd60 100644
--- a/mrbgems/mruby-metaprog/test/metaprog.rb
+++ b/mrbgems/mruby-metaprog/test/metaprog.rb
@@ -1,17 +1,3 @@
-assert('Kernel#__send__', '15.3.1.3.4') do
- # test with block
- l = __send__(:lambda) do
- true
- end
-
- assert_true l.call
- assert_equal Proc, l.class
- # test with argument
- assert_true __send__(:respond_to?, :nil?)
- # test without argument and without block
- assert_equal String, __send__(:to_s).class
-end
-
assert('Kernel#send', '15.3.1.3.44') do
# test with block
l = send(:lambda) do
@@ -34,6 +20,32 @@ assert('Kernel#instance_variable_defined?', '15.3.1.3.20') do
assert_false o.instance_variable_defined?("@b")
assert_true o.instance_variable_defined?("@a"[0,2])
assert_true o.instance_variable_defined?("@abc"[0,2])
+ assert_raise(NameError) { o.instance_variable_defined?("@0") }
+end
+
+assert('Kernel#instance_variable_get', '15.3.1.3.21') do
+ o = Class.new { attr_accessor :foo, :bar }.new
+ o.foo = "one"
+ o.bar = 2
+ assert_equal("one", o.instance_variable_get(:@foo))
+ assert_equal(2, o.instance_variable_get("@bar"))
+ assert_equal(nil, o.instance_variable_get(:@baz))
+ %w[foo @1].each do |n|
+ assert_raise(NameError) { o.instance_variable_get(n) }
+ end
+end
+
+assert('Kernel#instance_variable_set', '15.3.1.3.22') do
+ o = Class.new { attr_reader :foo, :_bar }.new
+ assert_equal("one", o.instance_variable_set(:@foo, "one"))
+ assert_equal("one", o.foo)
+ assert_equal(2, o.instance_variable_set("@_bar", 2))
+ assert_equal(2, o._bar)
+ %w[@6 @% @@a @ a].each do |n|
+ assert_raise(NameError) { o.instance_variable_set(n, 1) }
+ end
+ assert_raise(FrozenError) { o.freeze.instance_variable_set(:@a, 2) }
+ assert_raise(FrozenError, ArgumentError) { nil.instance_variable_set(:@a, 2) }
end
assert('Kernel#instance_variables', '15.3.1.3.23') do
@@ -75,6 +87,21 @@ assert('Kernel#singleton_methods', '15.3.1.3.45') do
assert_equal singleton_methods.class, Array
end
+assert('Kernel.global_variables', '15.3.1.2.4') do
+ assert_equal Array, Kernel.global_variables.class
+end
+
+assert('Kernel#global_variables', '15.3.1.3.14') do
+ variables1 = global_variables
+ assert_equal Array, variables1.class
+ assert_not_include(variables1, :$kernel_global_variables_test)
+
+ $kernel_global_variables_test = nil
+ variables2 = global_variables
+ assert_include(variables2, :$kernel_global_variables_test)
+ assert_equal(1, variables2.size - variables1.size)
+end
+
assert('Kernel.local_variables', '15.3.1.2.7') do
a, b = 0, 1
a += b
@@ -96,6 +123,24 @@ assert('Kernel#define_singleton_method') do
end
assert_equal :test_method, ret
assert_equal :singleton_method_ok, o.test_method
+ assert_raise(TypeError) { 2.define_singleton_method(:f){} }
+ assert_raise(FrozenError) { [].freeze.define_singleton_method(:f){} }
+end
+
+assert('Kernel#singleton_class') do
+ o1 = Object.new
+ assert_same(o1.singleton_class, class << o1; self end)
+
+ o2 = Object.new
+ sc2 = class << o2; self end
+ assert_same(o2.singleton_class, sc2)
+
+ o3 = Object.new
+ sc3 = o3.singleton_class
+ o3.freeze
+ assert_predicate(sc3, :frozen?)
+
+ assert_predicate(Object.new.freeze.singleton_class, :frozen?)
end
def labeled_module(name, &block)
@@ -125,6 +170,7 @@ assert('Module#class_variable_defined?', '15.2.2.4.16') do
assert_true Test4ClassVariableDefined.class_variable_defined?(:@@cv)
assert_false Test4ClassVariableDefined.class_variable_defined?(:@@noexisting)
+ assert_raise(NameError) { Test4ClassVariableDefined.class_variable_defined?("@@2") }
end
assert('Module#class_variable_get', '15.2.2.4.17') do
@@ -133,6 +179,10 @@ assert('Module#class_variable_get', '15.2.2.4.17') do
end
assert_equal 99, Test4ClassVariableGet.class_variable_get(:@@cv)
+ assert_raise(NameError) { Test4ClassVariableGet.class_variable_get(:@@a) }
+ %w[@@a? @@! @a a].each do |n|
+ assert_raise(NameError) { Test4ClassVariableGet.class_variable_get(n) }
+ end
end
assert('Module#class_variable_set', '15.2.2.4.18') do
@@ -142,12 +192,21 @@ assert('Module#class_variable_set', '15.2.2.4.18') do
@@foo
end
end
-
- assert_true Test4ClassVariableSet.class_variable_set(:@@cv, 99)
- assert_true Test4ClassVariableSet.class_variable_set(:@@foo, 101)
+ assert_equal 99, Test4ClassVariableSet.class_variable_set(:@@cv, 99)
+ assert_equal 101, Test4ClassVariableSet.class_variable_set(:@@foo, 101)
assert_true Test4ClassVariableSet.class_variables.include? :@@cv
assert_equal 99, Test4ClassVariableSet.class_variable_get(:@@cv)
assert_equal 101, Test4ClassVariableSet.new.foo
+ %w[@@ @@1 @@x= @x @ x 1].each do |n|
+ assert_raise(NameError) { Test4ClassVariableSet.class_variable_set(n, 1) }
+ end
+
+ m = Module.new.freeze
+ assert_raise(FrozenError) { m.class_variable_set(:@@cv, 1) }
+
+ parent = Class.new{ class_variable_set(:@@a, nil) }.freeze
+ child = Class.new(parent)
+ assert_raise(FrozenError) { child.class_variable_set(:@@a, 1) }
end
assert('Module#class_variables', '15.2.2.4.19') do
@@ -223,6 +282,15 @@ assert('Module#remove_class_variable', '15.2.2.4.39') do
assert_equal 99, Test4RemoveClassVariable.remove_class_variable(:@@cv)
assert_false Test4RemoveClassVariable.class_variables.include? :@@cv
+ assert_raise(NameError) do
+ Test4RemoveClassVariable.remove_class_variable(:@@cv)
+ end
+ assert_raise(NameError) do
+ Test4RemoveClassVariable.remove_class_variable(:@v)
+ end
+ assert_raise(FrozenError) do
+ Test4RemoveClassVariable.freeze.remove_class_variable(:@@cv)
+ end
end
assert('Module#remove_method', '15.2.2.4.41') do
@@ -230,17 +298,19 @@ assert('Module#remove_method', '15.2.2.4.41') do
class Parent
def hello
end
- end
+ end
- class Child < Parent
+ class Child < Parent
def hello
end
end
end
- assert_true Test4RemoveMethod::Child.class_eval{ remove_method :hello }
- assert_true Test4RemoveMethod::Child.instance_methods.include? :hello
- assert_false Test4RemoveMethod::Child.instance_methods(false).include? :hello
+ klass = Test4RemoveMethod::Child
+ assert_same klass, klass.class_eval{ remove_method :hello }
+ assert_true klass.instance_methods.include? :hello
+ assert_false klass.instance_methods(false).include? :hello
+ assert_raise(FrozenError) { klass.freeze.remove_method :m }
end
assert('Module.nesting', '15.2.2.2.2') do
diff --git a/mrbgems/mruby-method/mrblib/kernel.rb b/mrbgems/mruby-method/mrblib/kernel.rb
index 2efc93f37..eb17df5a6 100644
--- a/mrbgems/mruby-method/mrblib/kernel.rb
+++ b/mrbgems/mruby-method/mrblib/kernel.rb
@@ -3,7 +3,7 @@ module Kernel
m = method(name)
sc = (class <<self; self; end)
if m.owner != sc
- raise NameError, "undefined method `#{name}' for class `#{sc}'"
+ raise NameError, "undefined method '#{name}' for class '#{sc}'"
end
m
end
diff --git a/mrbgems/mruby-method/mrblib/method.rb b/mrbgems/mruby-method/mrblib/method.rb
index f7cefa2e5..56af7cf61 100644
--- a/mrbgems/mruby-method/mrblib/method.rb
+++ b/mrbgems/mruby-method/mrblib/method.rb
@@ -6,18 +6,6 @@ class Method
}
end
- def owner
- @owner
- end
-
- def receiver
- @recv
- end
-
- def name
- @name
- end
-
def <<(other)
->(*args, &block) { call(other.call(*args, &block)) }
end
diff --git a/mrbgems/mruby-method/mrblib/unbound_method.rb b/mrbgems/mruby-method/mrblib/unbound_method.rb
deleted file mode 100644
index 1d3acf3fa..000000000
--- a/mrbgems/mruby-method/mrblib/unbound_method.rb
+++ /dev/null
@@ -1,9 +0,0 @@
-class UnboundMethod
- def owner
- @owner
- end
-
- def name
- @name
- end
-end
diff --git a/mrbgems/mruby-method/src/method.c b/mrbgems/mruby-method/src/method.c
index 600567cac..db5a52440 100644
--- a/mrbgems/mruby-method/src/method.c
+++ b/mrbgems/mruby-method/src/method.c
@@ -11,34 +11,38 @@ method_object_alloc(mrb_state *mrb, struct RClass *mclass)
return (struct RObject*)mrb_obj_alloc(mrb, MRB_TT_OBJECT, mclass);
}
+static void
+bind_check(mrb_state *mrb, mrb_value recv, mrb_value owner)
+{
+ if (mrb_type(owner) != MRB_TT_MODULE &&
+ mrb_class_ptr(owner) != mrb_obj_class(mrb, recv) &&
+ !mrb_obj_is_kind_of(mrb, recv, mrb_class_ptr(owner))) {
+ if (mrb_type(owner) == MRB_TT_SCLASS) {
+ mrb_raise(mrb, E_TYPE_ERROR, "singleton method called for a different object");
+ } else {
+ mrb_raisef(mrb, E_TYPE_ERROR, "bind argument must be an instance of %v", owner);
+ }
+ }
+}
+
static mrb_value
unbound_method_bind(mrb_state *mrb, mrb_value self)
{
struct RObject *me;
- mrb_value owner = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@owner"));
- mrb_value name = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@name"));
- mrb_value proc = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "proc"));
- mrb_value klass = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@klass"));
+ mrb_value owner = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_owner"));
+ mrb_value name = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_name"));
+ mrb_value proc = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_proc"));
+ mrb_value klass = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_klass"));
mrb_value recv;
mrb_get_args(mrb, "o", &recv);
-
- if (mrb_type(owner) != MRB_TT_MODULE &&
- mrb_class_ptr(owner) != mrb_obj_class(mrb, recv) &&
- !mrb_obj_is_kind_of(mrb, recv, mrb_class_ptr(owner))) {
- if (mrb_type(owner) == MRB_TT_SCLASS) {
- mrb_raise(mrb, E_TYPE_ERROR, "singleton method called for a different object");
- } else {
- const char *s = mrb_class_name(mrb, mrb_class_ptr(owner));
- mrb_raisef(mrb, E_TYPE_ERROR, "bind argument must be an instance of %S", mrb_str_new_static(mrb, s, strlen(s)));
- }
- }
+ bind_check(mrb, recv, owner);
me = method_object_alloc(mrb, mrb_class_get(mrb, "Method"));
- mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "@owner"), owner);
- mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "@recv"), recv);
- mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "@name"), name);
- mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "proc"), proc);
- mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "@klass"), klass);
+ mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "_owner"), owner);
+ mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "_recv"), recv);
+ mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "_name"), name);
+ mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "_proc"), proc);
+ mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "_klass"), klass);
return mrb_obj_value(me);
}
@@ -58,22 +62,22 @@ method_eql(mrb_state *mrb, mrb_value self)
if (mrb_class(mrb, self) != mrb_class(mrb, other))
return mrb_false_value();
- klass = mrb_class_ptr(IV_GET(self, "@klass"));
- if (klass != mrb_class_ptr(IV_GET(other, "@klass")))
+ klass = mrb_class_ptr(IV_GET(self, "_klass"));
+ if (klass != mrb_class_ptr(IV_GET(other, "_klass")))
return mrb_false_value();
- owner = mrb_class_ptr(IV_GET(self, "@owner"));
- if (owner != mrb_class_ptr(IV_GET(other, "@owner")))
+ owner = mrb_class_ptr(IV_GET(self, "_owner"));
+ if (owner != mrb_class_ptr(IV_GET(other, "_owner")))
return mrb_false_value();
- receiver = IV_GET(self, "@recv");
- if (!mrb_obj_equal(mrb, receiver, IV_GET(other, "@recv")))
+ receiver = IV_GET(self, "_recv");
+ if (!mrb_obj_equal(mrb, receiver, IV_GET(other, "_recv")))
return mrb_false_value();
- orig_proc = IV_GET(self, "proc");
- other_proc = IV_GET(other, "proc");
+ orig_proc = IV_GET(self, "_proc");
+ other_proc = IV_GET(other, "_proc");
if (mrb_nil_p(orig_proc) && mrb_nil_p(other_proc)) {
- if (mrb_symbol(IV_GET(self, "@name")) == mrb_symbol(IV_GET(other, "@name")))
+ if (mrb_symbol(IV_GET(self, "_name")) == mrb_symbol(IV_GET(other, "_name")))
return mrb_true_value();
else
return mrb_false_value();
@@ -105,18 +109,12 @@ method_eql(mrb_state *mrb, mrb_value self)
#undef IV_GET
static mrb_value
-method_call(mrb_state *mrb, mrb_value self)
+mcall(mrb_state *mrb, mrb_value recv, mrb_value proc, mrb_value name, struct RClass *owner,
+ int argc, mrb_value *argv, mrb_value block)
{
- mrb_value proc = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "proc"));
- mrb_value name = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@name"));
- mrb_value recv = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@recv"));
- struct RClass *owner = mrb_class_ptr(mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@owner")));
- mrb_int argc;
- mrb_value *argv, ret, block;
- mrb_sym orig_mid;
+ mrb_value ret;
+ mrb_sym orig_mid = mrb->c->ci->mid;
- mrb_get_args(mrb, "*&", &argv, &argc, &block);
- orig_mid = mrb->c->ci->mid;
mrb->c->ci->mid = mrb_symbol(name);
if (mrb_nil_p(proc)) {
mrb_value missing_argv = mrb_ary_new_from_values(mrb, argc, argv);
@@ -138,20 +136,49 @@ method_call(mrb_state *mrb, mrb_value self)
}
static mrb_value
+method_call(mrb_state *mrb, mrb_value self)
+{
+ mrb_value proc = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_proc"));
+ mrb_value name = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_name"));
+ mrb_value recv = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_recv"));
+ struct RClass *owner = mrb_class_ptr(mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_owner")));
+ mrb_int argc;
+ mrb_value *argv, block;
+
+ mrb_get_args(mrb, "*&", &argv, &argc, &block);
+ return mcall(mrb, recv, proc, name, owner, argc, argv, block);
+}
+
+static mrb_value
+method_bcall(mrb_state *mrb, mrb_value self)
+{
+ mrb_value proc = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_proc"));
+ mrb_value name = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_name"));
+ mrb_value recv = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_recv"));
+ mrb_value owner = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_owner"));
+ mrb_int argc;
+ mrb_value *argv, block;
+
+ mrb_get_args(mrb, "o*&", &recv, &argv, &argc, &block);
+ bind_check(mrb, recv, owner);
+ return mcall(mrb, recv, proc, name, mrb_class_ptr(owner), argc, argv, block);
+}
+
+static mrb_value
method_unbind(mrb_state *mrb, mrb_value self)
{
struct RObject *ume;
- mrb_value owner = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@owner"));
- mrb_value name = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@name"));
- mrb_value proc = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "proc"));
- mrb_value klass = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@klass"));
+ mrb_value owner = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_owner"));
+ mrb_value name = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_name"));
+ mrb_value proc = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_proc"));
+ mrb_value klass = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_klass"));
ume = method_object_alloc(mrb, mrb_class_get(mrb, "UnboundMethod"));
- mrb_obj_iv_set(mrb, ume, mrb_intern_lit(mrb, "@owner"), owner);
- mrb_obj_iv_set(mrb, ume, mrb_intern_lit(mrb, "@recv"), mrb_nil_value());
- mrb_obj_iv_set(mrb, ume, mrb_intern_lit(mrb, "@name"), name);
- mrb_obj_iv_set(mrb, ume, mrb_intern_lit(mrb, "proc"), proc);
- mrb_obj_iv_set(mrb, ume, mrb_intern_lit(mrb, "@klass"), klass);
+ mrb_obj_iv_set(mrb, ume, mrb_intern_lit(mrb, "_owner"), owner);
+ mrb_obj_iv_set(mrb, ume, mrb_intern_lit(mrb, "_recv"), mrb_nil_value());
+ mrb_obj_iv_set(mrb, ume, mrb_intern_lit(mrb, "_name"), name);
+ mrb_obj_iv_set(mrb, ume, mrb_intern_lit(mrb, "_proc"), proc);
+ mrb_obj_iv_set(mrb, ume, mrb_intern_lit(mrb, "_klass"), klass);
return mrb_obj_value(ume);
}
@@ -170,10 +197,10 @@ method_search_vm(mrb_state *mrb, struct RClass **cp, mrb_sym mid)
static mrb_value
method_super_method(mrb_state *mrb, mrb_value self)
{
- mrb_value recv = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@recv"));
- mrb_value klass = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@klass"));
- mrb_value owner = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@owner"));
- mrb_value name = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@name"));
+ mrb_value recv = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_recv"));
+ mrb_value klass = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_klass"));
+ mrb_value owner = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_owner"));
+ mrb_value name = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_name"));
struct RClass *super, *rklass;
struct RProc *proc;
struct RObject *me;
@@ -199,11 +226,11 @@ method_super_method(mrb_state *mrb, mrb_value self)
super = super->c;
me = method_object_alloc(mrb, mrb_obj_class(mrb, self));
- mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "@owner"), mrb_obj_value(super));
- mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "@recv"), recv);
- mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "@name"), name);
- mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "proc"), mrb_obj_value(proc));
- mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "@klass"), mrb_obj_value(rklass));
+ mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "_owner"), mrb_obj_value(super));
+ mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "_recv"), recv);
+ mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "_name"), name);
+ mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "_proc"), mrb_obj_value(proc));
+ mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "_klass"), mrb_obj_value(rklass));
return mrb_obj_value(me);
}
@@ -211,26 +238,15 @@ method_super_method(mrb_state *mrb, mrb_value self)
static mrb_value
method_arity(mrb_state *mrb, mrb_value self)
{
- mrb_value proc = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "proc"));
- struct RProc *rproc;
- struct RClass *orig;
- mrb_value ret;
-
- if (mrb_nil_p(proc))
- return mrb_fixnum_value(-1);
-
- rproc = mrb_proc_ptr(proc);
- orig = rproc->c;
- rproc->c = mrb->proc_class;
- ret = mrb_funcall(mrb, proc, "arity", 0);
- rproc->c = orig;
- return ret;
+ mrb_value proc = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_proc"));
+ mrb_int arity = mrb_nil_p(proc) ? -1 : mrb_proc_arity(mrb_proc_ptr(proc));
+ return mrb_fixnum_value(arity);
}
static mrb_value
method_source_location(mrb_state *mrb, mrb_value self)
{
- mrb_value proc = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "proc"));
+ mrb_value proc = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_proc"));
struct RProc *rproc;
struct RClass *orig;
mrb_value ret;
@@ -249,7 +265,7 @@ method_source_location(mrb_state *mrb, mrb_value self)
static mrb_value
method_parameters(mrb_state *mrb, mrb_value self)
{
- mrb_value proc = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "proc"));
+ mrb_value proc = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_proc"));
struct RProc *rproc;
struct RClass *orig;
mrb_value ret;
@@ -271,9 +287,9 @@ method_parameters(mrb_state *mrb, mrb_value self)
static mrb_value
method_to_s(mrb_state *mrb, mrb_value self)
{
- mrb_value owner = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@owner"));
- mrb_value klass = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@klass"));
- mrb_value name = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@name"));
+ mrb_value owner = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_owner"));
+ mrb_value klass = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_klass"));
+ mrb_value name = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_name"));
mrb_value str = mrb_str_new_lit(mrb, "#<");
struct RClass *rklass;
@@ -281,16 +297,16 @@ method_to_s(mrb_state *mrb, mrb_value self)
mrb_str_cat_lit(mrb, str, ": ");
rklass = mrb_class_ptr(klass);
if (mrb_class_ptr(owner) == rklass) {
- mrb_str_cat_str(mrb, str, mrb_funcall(mrb, owner, "to_s", 0));
+ mrb_str_cat_str(mrb, str, mrb_str_to_str(mrb, owner));
mrb_str_cat_lit(mrb, str, "#");
- mrb_str_cat_str(mrb, str, mrb_funcall(mrb, name, "to_s", 0));
+ mrb_str_cat_str(mrb, str, mrb_str_to_str(mrb, name));
}
else {
mrb_str_cat_cstr(mrb, str, mrb_class_name(mrb, rklass));
mrb_str_cat_lit(mrb, str, "(");
- mrb_str_cat_str(mrb, str, mrb_funcall(mrb, owner, "to_s", 0));
+ mrb_str_cat_str(mrb, str, mrb_str_to_str(mrb, owner));
mrb_str_cat_lit(mrb, str, ")#");
- mrb_str_cat_str(mrb, str, mrb_funcall(mrb, name, "to_s", 0));
+ mrb_str_cat_str(mrb, str, mrb_str_to_str(mrb, name));
}
mrb_str_cat_lit(mrb, str, ">");
return str;
@@ -300,7 +316,6 @@ static void
mrb_search_method_owner(mrb_state *mrb, struct RClass *c, mrb_value obj, mrb_sym name, struct RClass **owner, struct RProc **proc, mrb_bool unbound)
{
mrb_value ret;
- const char *s;
*owner = c;
*proc = method_search_vm(mrb, owner, name);
@@ -324,13 +339,7 @@ mrb_search_method_owner(mrb_state *mrb, struct RClass *c, mrb_value obj, mrb_sym
return;
name_error:
- s = mrb_class_name(mrb, c);
- mrb_raisef(
- mrb, E_NAME_ERROR,
- "undefined method `%S' for class `%S'",
- mrb_sym2str(mrb, name),
- mrb_str_new_static(mrb, s, strlen(s))
- );
+ mrb_raisef(mrb, E_NAME_ERROR, "undefined method '%n' for class '%C'", name, c);
}
static mrb_value
@@ -346,11 +355,11 @@ mrb_kernel_method(mrb_state *mrb, mrb_value self)
mrb_search_method_owner(mrb, mrb_class(mrb, self), self, name, &owner, &proc, FALSE);
me = method_object_alloc(mrb, mrb_class_get(mrb, "Method"));
- mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "@owner"), mrb_obj_value(owner));
- mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "@recv"), self);
- mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "@name"), mrb_symbol_value(name));
- mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "proc"), proc ? mrb_obj_value(proc) : mrb_nil_value());
- mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "@klass"), mrb_obj_value(mrb_class(mrb, self)));
+ mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "_owner"), mrb_obj_value(owner));
+ mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "_recv"), self);
+ mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "_name"), mrb_symbol_value(name));
+ mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "_proc"), proc ? mrb_obj_value(proc) : mrb_nil_value());
+ mrb_obj_iv_set(mrb, me, mrb_intern_lit(mrb, "_klass"), mrb_obj_value(mrb_class(mrb, self)));
return mrb_obj_value(me);
}
@@ -368,15 +377,33 @@ mrb_module_instance_method(mrb_state *mrb, mrb_value self)
mrb_search_method_owner(mrb, mrb_class_ptr(self), self, name, &owner, &proc, TRUE);
ume = method_object_alloc(mrb, mrb_class_get(mrb, "UnboundMethod"));
- mrb_obj_iv_set(mrb, ume, mrb_intern_lit(mrb, "@owner"), mrb_obj_value(owner));
- mrb_obj_iv_set(mrb, ume, mrb_intern_lit(mrb, "@recv"), mrb_nil_value());
- mrb_obj_iv_set(mrb, ume, mrb_intern_lit(mrb, "@name"), mrb_symbol_value(name));
- mrb_obj_iv_set(mrb, ume, mrb_intern_lit(mrb, "proc"), proc ? mrb_obj_value(proc) : mrb_nil_value());
- mrb_obj_iv_set(mrb, ume, mrb_intern_lit(mrb, "@klass"), self);
+ mrb_obj_iv_set(mrb, ume, mrb_intern_lit(mrb, "_owner"), mrb_obj_value(owner));
+ mrb_obj_iv_set(mrb, ume, mrb_intern_lit(mrb, "_recv"), mrb_nil_value());
+ mrb_obj_iv_set(mrb, ume, mrb_intern_lit(mrb, "_name"), mrb_symbol_value(name));
+ mrb_obj_iv_set(mrb, ume, mrb_intern_lit(mrb, "_proc"), proc ? mrb_obj_value(proc) : mrb_nil_value());
+ mrb_obj_iv_set(mrb, ume, mrb_intern_lit(mrb, "_klass"), self);
return mrb_obj_value(ume);
}
+static mrb_value
+method_owner(mrb_state *mrb, mrb_value self)
+{
+ return mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_owner"));
+}
+
+static mrb_value
+method_receiver(mrb_state *mrb, mrb_value self)
+{
+ return mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_recv"));
+}
+
+static mrb_value
+method_name(mrb_state *mrb, mrb_value self)
+{
+ return mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "_name"));
+}
+
void
mrb_mruby_method_gem_init(mrb_state* mrb)
{
@@ -393,6 +420,9 @@ mrb_mruby_method_gem_init(mrb_state* mrb)
mrb_define_method(mrb, unbound_method, "arity", method_arity, MRB_ARGS_NONE());
mrb_define_method(mrb, unbound_method, "source_location", method_source_location, MRB_ARGS_NONE());
mrb_define_method(mrb, unbound_method, "parameters", method_parameters, MRB_ARGS_NONE());
+ mrb_define_method(mrb, unbound_method, "bind_call", method_bcall, MRB_ARGS_REQ(1)|MRB_ARGS_ANY());
+ mrb_define_method(mrb, unbound_method, "owner", method_owner, MRB_ARGS_NONE());
+ mrb_define_method(mrb, unbound_method, "name", method_name, MRB_ARGS_NONE());
mrb_undef_class_method(mrb, method, "new");
mrb_define_method(mrb, method, "==", method_eql, MRB_ARGS_REQ(1));
@@ -406,6 +436,9 @@ mrb_mruby_method_gem_init(mrb_state* mrb)
mrb_define_method(mrb, method, "arity", method_arity, MRB_ARGS_NONE());
mrb_define_method(mrb, method, "source_location", method_source_location, MRB_ARGS_NONE());
mrb_define_method(mrb, method, "parameters", method_parameters, MRB_ARGS_NONE());
+ mrb_define_method(mrb, method, "owner", method_owner, MRB_ARGS_NONE());
+ mrb_define_method(mrb, method, "receiver", method_receiver, MRB_ARGS_NONE());
+ mrb_define_method(mrb, method, "name", method_name, MRB_ARGS_NONE());
mrb_define_method(mrb, mrb->kernel_module, "method", mrb_kernel_method, MRB_ARGS_REQ(1));
diff --git a/mrbgems/mruby-method/test/method.rb b/mrbgems/mruby-method/test/method.rb
index dfddde9cc..641979d71 100644
--- a/mrbgems/mruby-method/test/method.rb
+++ b/mrbgems/mruby-method/test/method.rb
@@ -21,7 +21,7 @@ class Interpreter
}
def interpret(string)
@ret = ""
- string.each_char {|b| Dispatcher[b].bind(self).call }
+ string.split("").each {|b| Dispatcher[b].bind(self).call }
end
end
@@ -441,3 +441,11 @@ assert 'UnboundMethod#bind' do
assert_raise(TypeError) { Array.instance_method(:each).bind(1) }
assert_kind_of Method, Object.instance_method(:object_id).bind(Object.new)
end
+
+assert 'UnboundMethod#bind_call' do
+ m = Array.instance_method(:size)
+ assert_equal(:size, m.name)
+ assert_equal(0, m.bind_call([]))
+ assert_equal(1, m.bind_call([1]))
+ assert_equal(2, m.bind_call([1,2]))
+end
diff --git a/mrbgems/mruby-numeric-ext/mrblib/numeric_ext.rb b/mrbgems/mruby-numeric-ext/mrblib/numeric_ext.rb
index f250538fe..576605cb1 100644
--- a/mrbgems/mruby-numeric-ext/mrblib/numeric_ext.rb
+++ b/mrbgems/mruby-numeric-ext/mrblib/numeric_ext.rb
@@ -1,8 +1,4 @@
-module Integral
- def div(other)
- self.divmod(other)[0]
- end
-
+class Numeric
def zero?
self == 0
end
diff --git a/mrbgems/mruby-numeric-ext/src/numeric_ext.c b/mrbgems/mruby-numeric-ext/src/numeric_ext.c
index cd8bbf187..f8aff54bc 100644
--- a/mrbgems/mruby-numeric-ext/src/numeric_ext.c
+++ b/mrbgems/mruby-numeric-ext/src/numeric_ext.c
@@ -1,38 +1,6 @@
#include <limits.h>
#include <mruby.h>
-
-static inline mrb_int
-to_int(mrb_state *mrb, mrb_value x)
-{
- x = mrb_to_int(mrb, x);
- return mrb_fixnum(x);
-}
-
-/*
- * Document-method: Integer#chr
- * call-seq:
- * int.chr -> string
- *
- * Returns a string containing the character represented by the +int+'s value
- * according to +encoding+.
- *
- * 65.chr #=> "A"
- * 230.chr #=> "\xE6"
- */
-static mrb_value
-mrb_int_chr(mrb_state *mrb, mrb_value x)
-{
- mrb_int chr;
- char c;
-
- chr = to_int(mrb, x);
- if (chr >= (1 << CHAR_BIT)) {
- mrb_raisef(mrb, E_RANGE_ERROR, "%S out of char range", x);
- }
- c = (char)chr;
-
- return mrb_str_new(mrb, &c, 1);
-}
+#include <mruby/numeric.h>
/*
* call-seq:
@@ -46,7 +14,7 @@ mrb_int_allbits(mrb_state *mrb, mrb_value self)
mrb_int n, m;
mrb_get_args(mrb, "i", &m);
- n = to_int(mrb, self);
+ n = mrb_int(mrb, self);
return mrb_bool_value((n & m) == m);
}
@@ -62,7 +30,7 @@ mrb_int_anybits(mrb_state *mrb, mrb_value self)
mrb_int n, m;
mrb_get_args(mrb, "i", &m);
- n = to_int(mrb, self);
+ n = mrb_int(mrb, self);
return mrb_bool_value((n & m) != 0);
}
@@ -78,7 +46,7 @@ mrb_int_nobits(mrb_state *mrb, mrb_value self)
mrb_int n, m;
mrb_get_args(mrb, "i", &m);
- n = to_int(mrb, self);
+ n = mrb_int(mrb, self);
return mrb_bool_value((n & m) == 0);
}
@@ -87,10 +55,22 @@ mrb_mruby_numeric_ext_gem_init(mrb_state* mrb)
{
struct RClass *i = mrb_module_get(mrb, "Integral");
- mrb_define_method(mrb, i, "chr", mrb_int_chr, MRB_ARGS_NONE());
mrb_define_method(mrb, i, "allbits?", mrb_int_allbits, MRB_ARGS_REQ(1));
mrb_define_method(mrb, i, "anybits?", mrb_int_anybits, MRB_ARGS_REQ(1));
mrb_define_method(mrb, i, "nobits?", mrb_int_nobits, MRB_ARGS_REQ(1));
+
+#ifndef MRB_WITHOUT_FLOAT
+ mrb_define_const(mrb, mrb->float_class, "RADIX", mrb_fixnum_value(MRB_FLT_RADIX));
+ mrb_define_const(mrb, mrb->float_class, "MANT_DIG", mrb_fixnum_value(MRB_FLT_MANT_DIG));
+ mrb_define_const(mrb, mrb->float_class, "EPSILON", mrb_float_value(mrb, MRB_FLT_EPSILON));
+ mrb_define_const(mrb, mrb->float_class, "DIG", mrb_fixnum_value(MRB_FLT_DIG));
+ mrb_define_const(mrb, mrb->float_class, "MIN_EXP", mrb_fixnum_value(MRB_FLT_MIN_EXP));
+ mrb_define_const(mrb, mrb->float_class, "MIN", mrb_float_value(mrb, MRB_FLT_MIN));
+ mrb_define_const(mrb, mrb->float_class, "MIN_10_EXP", mrb_fixnum_value(MRB_FLT_MIN_10_EXP));
+ mrb_define_const(mrb, mrb->float_class, "MAX_EXP", mrb_fixnum_value(MRB_FLT_MAX_EXP));
+ mrb_define_const(mrb, mrb->float_class, "MAX", mrb_float_value(mrb, MRB_FLT_MAX));
+ mrb_define_const(mrb, mrb->float_class, "MAX_10_EXP", mrb_fixnum_value(MRB_FLT_MAX_10_EXP));
+#endif /* MRB_WITHOUT_FLOAT */
}
void
diff --git a/mrbgems/mruby-numeric-ext/test/numeric.rb b/mrbgems/mruby-numeric-ext/test/numeric.rb
index c85cb61f2..efdf25a34 100644
--- a/mrbgems/mruby-numeric-ext/test/numeric.rb
+++ b/mrbgems/mruby-numeric-ext/test/numeric.rb
@@ -1,14 +1,6 @@
##
# Numeric(Ext) Test
-assert('Integer#chr') do
- assert_equal("A", 65.chr)
- assert_equal("B", 0x42.chr)
-
- # multibyte encoding (not support yet)
- assert_raise(RangeError) { 256.chr }
-end
-
assert('Integer#div') do
assert_equal 52, 365.div(7)
end
diff --git a/mrbgems/mruby-object-ext/mrbgem.rake b/mrbgems/mruby-object-ext/mrbgem.rake
index 6d14b4a51..1aea2c8cd 100644
--- a/mrbgems/mruby-object-ext/mrbgem.rake
+++ b/mrbgems/mruby-object-ext/mrbgem.rake
@@ -1,5 +1,5 @@
MRuby::Gem::Specification.new('mruby-object-ext') do |spec|
spec.license = 'MIT'
spec.author = 'mruby developers'
- spec.summary = 'Object class extension'
+ spec.summary = 'extensional methods shared by all objects'
end
diff --git a/mrbgems/mruby-object-ext/mrblib/object.rb b/mrbgems/mruby-object-ext/mrblib/object.rb
index 581156cb0..f014df469 100644
--- a/mrbgems/mruby-object-ext/mrblib/object.rb
+++ b/mrbgems/mruby-object-ext/mrblib/object.rb
@@ -1,4 +1,18 @@
-class Object
+module Kernel
+ # call-seq:
+ # obj.yield_self {|_obj|...} -> an_object
+ # obj.then {|_obj|...} -> an_object
+ #
+ # Yields <i>obj</i> and returns the result.
+ #
+ # 'my string'.yield_self {|s|s.upcase} #=> "MY STRING"
+ #
+ def yield_self(&block)
+ return to_enum :yield_self unless block
+ block.call(self)
+ end
+ alias then yield_self
+
##
# call-seq:
# obj.tap{|x|...} -> obj
diff --git a/mrbgems/mruby-object-ext/src/object.c b/mrbgems/mruby-object-ext/src/object.c
index b076b3ec0..0aedc9a73 100644
--- a/mrbgems/mruby-object-ext/src/object.c
+++ b/mrbgems/mruby-object-ext/src/object.c
@@ -1,6 +1,7 @@
#include <mruby.h>
#include <mruby/array.h>
#include <mruby/class.h>
+#include <mruby/hash.h>
#include <mruby/proc.h>
/*
@@ -33,6 +34,19 @@ nil_to_f(mrb_state *mrb, mrb_value obj)
/*
* call-seq:
+ * nil.to_h -> {}
+ *
+ * Always returns an empty hash.
+ */
+
+static mrb_value
+nil_to_h(mrb_state *mrb, mrb_value obj)
+{
+ return mrb_hash_new(mrb);
+}
+
+/*
+ * call-seq:
* nil.to_i -> 0
*
* Always returns zero.
@@ -46,6 +60,22 @@ nil_to_i(mrb_state *mrb, mrb_value obj)
/*
* call-seq:
+ * obj.itself -> an_object
+ *
+ * Returns <i>obj</i>.
+ *
+ * string = 'my string' #=> "my string"
+ * string.itself.object_id == string.object_id #=> true
+ *
+ */
+static mrb_value
+mrb_f_itself(mrb_state *mrb, mrb_value self)
+{
+ return self;
+}
+
+/*
+ * call-seq:
* obj.instance_exec(arg...) {|var...| block } -> obj
*
* Executes the given block within the context of the receiver
@@ -101,9 +131,12 @@ mrb_mruby_object_ext_gem_init(mrb_state* mrb)
#ifndef MRB_WITHOUT_FLOAT
mrb_define_method(mrb, n, "to_f", nil_to_f, MRB_ARGS_NONE());
#endif
+ mrb_define_method(mrb, n, "to_h", nil_to_h, MRB_ARGS_NONE());
mrb_define_method(mrb, n, "to_i", nil_to_i, MRB_ARGS_NONE());
- mrb_define_method(mrb, mrb->kernel_module, "instance_exec", mrb_obj_instance_exec, MRB_ARGS_ANY() | MRB_ARGS_BLOCK());
+ mrb_define_method(mrb, mrb->kernel_module, "itself", mrb_f_itself, MRB_ARGS_NONE());
+
+ mrb_define_method(mrb, mrb_class_get(mrb, "BasicObject"), "instance_exec", mrb_obj_instance_exec, MRB_ARGS_ANY() | MRB_ARGS_BLOCK());
}
void
diff --git a/mrbgems/mruby-object-ext/test/nil.rb b/mrbgems/mruby-object-ext/test/nil.rb
index fbff20629..9975e785a 100644
--- a/mrbgems/mruby-object-ext/test/nil.rb
+++ b/mrbgems/mruby-object-ext/test/nil.rb
@@ -7,6 +7,10 @@ assert('NilClass#to_f') do
assert_equal 0.0, nil.to_f
end
+assert('NilClass#to_h') do
+ assert_equal Hash.new, nil.to_h
+end
+
assert('NilClass#to_i') do
assert_equal 0, nil.to_i
end
diff --git a/mrbgems/mruby-objectspace/test/objectspace.rb b/mrbgems/mruby-objectspace/test/objectspace.rb
index 8db89eeaf..9c44c2157 100644
--- a/mrbgems/mruby-objectspace/test/objectspace.rb
+++ b/mrbgems/mruby-objectspace/test/objectspace.rb
@@ -56,5 +56,5 @@ assert('ObjectSpace.each_object') do
end
assert 'Check class pointer of ObjectSpace.each_object.' do
- ObjectSpace.each_object { |obj| !obj }
+ assert_nothing_raised { ObjectSpace.each_object { |obj| !obj } }
end
diff --git a/mrbgems/mruby-pack/.gitignore b/mrbgems/mruby-pack/.gitignore
deleted file mode 100644
index 55ef3162f..000000000
--- a/mrbgems/mruby-pack/.gitignore
+++ /dev/null
@@ -1,5 +0,0 @@
-gem_*
-gem-*
-mrb-*.a
-src/*.o
-/tmp
diff --git a/mrbgems/mruby-pack/.travis.yml b/mrbgems/mruby-pack/.travis.yml
deleted file mode 100644
index ffe227284..000000000
--- a/mrbgems/mruby-pack/.travis.yml
+++ /dev/null
@@ -1,2 +0,0 @@
-script:
- - "ruby run_test.rb all test"
diff --git a/mrbgems/mruby-pack/packtest.rb b/mrbgems/mruby-pack/packtest.rb
deleted file mode 100644
index 459447af7..000000000
--- a/mrbgems/mruby-pack/packtest.rb
+++ /dev/null
@@ -1,157 +0,0 @@
-# encoding: ascii
-
-# a = Array, s = String, t = Template
-
-def packtest(a, s, t)
- begin
- r = a.pack(t)
- return if r == s
- puts "#{a.inspect}.pack(#{t.inspect}) -> #{r.inspect} should be #{s.inspect}"
- rescue => r
- unless r.is_a? s
- puts "#{a.inspect}.pack(#{t.inspect}) -> #{r.inspect} should be #{s.inspect}"
- end
- end
-end
-
-def unpacktest(a, s, t)
- r = s.unpack(t)
- return if r == a
- puts "#{s.inspect}.unpack(#{t.inspect}) -> #{r.inspect} should be #{a.inspect}"
-end
-
-def pptest(a, s, t)
- packtest(a, s, t)
- unpacktest(a, s, t)
-end
-
-pptest [1], "\x01", "C"
-
-packtest [1.1], "\x01", "C"
-packtest [-1], "\xff", "C"
-packtest [1,2], "\x01\x02", "C2"
-#packtest [1], "X", ArgumentError
-
-unpacktest [48, nil], "0", "CC"
-unpacktest [160, -96], "\xa0\xa0", "Cc"
-unpacktest [49, 50, 51], "123", "C*"
-
-pptest [12849], "12", "S"
-unpacktest [nil], "0", "S"
-unpacktest [12849, nil], "123", "SS"
-unpacktest [12849], "123", "S*"
-
-pptest [10000], "\x27\x10", "s>"
-pptest [-10000], "\xd8\xf0", "s>"
-pptest [50000], "\xc3\x50", "S>"
-
-pptest [10000], "\x10\x27", "s<"
-pptest [-10000], "\xf0\xd8", "s<"
-pptest [50000], "\x50\xc3", "S<"
-
-pptest [1000000000], "\x3b\x9a\xca\x00", "l>"
-pptest [-1000000000], "\xc4\x65\x36\x00", "l>"
-
-pptest [1], "\x01\x00\x00\x00", "L<"
-pptest [258], "\x02\x01\x00\x00", "L<"
-pptest [66051], "\x03\x02\x01\x00", "L<"
-pptest [16909060], "\x04\x03\x02\x01", "L<"
-pptest [16909060], "\x01\x02\x03\x04", "L>"
-
-packtest [-1], "\xff\xff\xff\xff", "L<"
-
-pptest [1000000000], "\x00\x00\x00\x00\x3b\x9a\xca\x00", "q>"
-pptest [-1000000000], "\xff\xff\xff\xff\xc4\x65\x36\x00", "q>"
-
-if (2**33).is_a? Fixnum
- pptest [81985529216486895], "\x01\x23\x45\x67\x89\xab\xcd\xef", "q>"
- pptest [-1167088121787636991], "\x01\x23\x45\x67\x89\xab\xcd\xef", "q<"
-end
-
-pptest [16909060], "\x01\x02\x03\x04", "N"
-pptest [258], "\x01\x02", "n"
-pptest [32769], "\x80\x01", "n"
-
-pptest [16909060], "\x04\x03\x02\x01", "V"
-pptest [258], "\x02\x01", "v"
-
-packtest [""], "", "m"
-packtest ["a"], "YQ==\n", "m"
-packtest ["ab"], "YWI=\n", "m"
-packtest ["abc"], "YWJj\n", "m"
-packtest ["abcd"], "YWJjZA==\n", "m"
-
-unpacktest [""], "", "m"
-unpacktest ["a"], "YQ==\n", "m"
-unpacktest ["ab"], "YWI=\n", "m"
-unpacktest ["abc"], "YWJj\n", "m"
-unpacktest ["abcd"], "YWJjZA==\n", "m"
-
-packtest [""], "\0", "H"
-packtest ["3"], "0", "H"
-packtest ["34"], "", "H0"
-packtest ["34"], "0", "H"
-packtest ["34"], "4", "H2"
-packtest ["34"], "4\0", "H3"
-packtest ["3456"], "4P", "H3"
-packtest ["34563"], "4V0", "H*"
-packtest ["5a"], "Z", "H*"
-packtest ["5A"], "Z", "H*"
-
-unpacktest [""], "", "H"
-unpacktest [""], "0", "H0"
-unpacktest ["3"], "0", "H"
-unpacktest ["30"], "0", "H2"
-unpacktest ["30"], "0", "H3"
-unpacktest ["303"], "01", "H3"
-unpacktest ["303132"], "012", "H*"
-unpacktest ["3031", 50], "012", "H4C"
-unpacktest ["5a"], "Z", "H*"
-
-packtest [""], "\0", "h"
-packtest ["3"], "\03", "h"
-packtest ["34"], "", "h0"
-packtest ["34"], "\03", "h"
-packtest ["34"], "C", "h2"
-packtest ["34"], "C\0", "h3"
-packtest ["3456"], "C\05", "h3"
-packtest ["34563"], "Ce\03", "h*"
-
-packtest [""], " ", "A"
-unpacktest [""], "", "A"
-pptest ["1"], "1", "A"
-pptest ["1"], "1 ", "A2"
-unpacktest ["1"], "1", "A2"
-unpacktest ["1"], "1 ", "A2"
-unpacktest ["1"], "1\0", "A2"
-packtest ["12"], "1", "A"
-unpacktest ["1"], "12", "A"
-pptest ["123"], "123", "A*"
-packtest ["1","2"], "2", "A0A"
-unpacktest ["","2"], "2", "A0A"
-
-packtest [""], "\0", "a"
-unpacktest [""], "", "a"
-pptest ["1"], "1", "a"
-pptest ["1 "], "1 ", "a2"
-pptest ["1\0"], "1\0", "a2"
-packtest ["1"], "1\0", "a2"
-pptest ["123"], "123", "a*"
-
-packtest [""], "\0", "Z"
-unpacktest [""], "", "Z"
-pptest ["1"], "1", "Z"
-pptest ["1"], "1\0", "Z2"
-pptest ["1 "], "1 ", "Z2"
-pptest ["123"], "123\0", "Z*"
-pptest ["1","2"], "12", "ZZ"
-pptest ["1","2"], "1\0002", "Z*Z"
-unpacktest ["1","3"], "1\00023", "Z3Z"
-
-packtest [1, 2], "\x01\x02", "CyC"
-
-packtest [65], "A", 'U'
-packtest [59411], "\xEE\xA0\x93", 'U'
-
-pptest [1], "\x00\x01", "xC"
-unpacktest [2], "\xcc\x02", "xC"
diff --git a/mrbgems/mruby-pack/run_test.rb b/mrbgems/mruby-pack/run_test.rb
deleted file mode 100644
index d9566a2a6..000000000
--- a/mrbgems/mruby-pack/run_test.rb
+++ /dev/null
@@ -1,26 +0,0 @@
-#!/usr/bin/env ruby
-#
-# mrbgems test runner
-#
-
-gemname = File.basename(File.dirname(File.expand_path __FILE__))
-
-if __FILE__ == $0
- repository, dir = 'https://github.com/mruby/mruby.git', 'tmp/mruby'
- build_args = ARGV
- build_args = ['all', 'test'] if build_args.nil? or build_args.empty?
-
- Dir.mkdir 'tmp' unless File.exist?('tmp')
- unless File.exist?(dir)
- system "git clone #{repository} #{dir}"
- end
-
- exit system(%Q[cd #{dir}; MRUBY_CONFIG=#{File.expand_path __FILE__} ruby minirake #{build_args.join(' ')}])
-end
-
-MRuby::Build.new do |conf|
- toolchain :gcc
- conf.gembox 'default'
-
- conf.gem File.expand_path(File.dirname(__FILE__))
-end
diff --git a/mrbgems/mruby-pack/src/pack.c b/mrbgems/mruby-pack/src/pack.c
index 2e68f35ed..159ba09ac 100644
--- a/mrbgems/mruby-pack/src/pack.c
+++ b/mrbgems/mruby-pack/src/pack.c
@@ -3,7 +3,7 @@
*/
#include "mruby.h"
-#include "error.h"
+#include "mruby/error.h"
#include "mruby/array.h"
#include "mruby/class.h"
#include "mruby/numeric.h"
@@ -118,9 +118,9 @@ make_base64_dec_tab(void)
base64_dec_tab['a' + i] = i + 26;
for (i = 0; i < 10; i++)
base64_dec_tab['0' + i] = i + 52;
- base64_dec_tab['+'] = 62;
- base64_dec_tab['/'] = 63;
- base64_dec_tab['='] = PACK_BASE64_PADDING;
+ base64_dec_tab['+'+0] = 62;
+ base64_dec_tab['/'+0] = 63;
+ base64_dec_tab['='+0] = PACK_BASE64_PADDING;
}
static mrb_value
@@ -529,8 +529,8 @@ utf8_to_uv(mrb_state *mrb, const char *p, long *lenp)
mrb_raise(mrb, E_ARGUMENT_ERROR, "malformed UTF-8 character");
}
if (n > *lenp) {
- mrb_raisef(mrb, E_ARGUMENT_ERROR, "malformed UTF-8 character (expected %S bytes, given %S bytes)",
- mrb_fixnum_value(n), mrb_fixnum_value(*lenp));
+ mrb_raisef(mrb, E_ARGUMENT_ERROR, "malformed UTF-8 character (expected %d bytes, given %d bytes)",
+ n, *lenp);
}
*lenp = n--;
if (n != 0) {
@@ -627,7 +627,7 @@ unpack_a(mrb_state *mrb, const void *src, int slen, mrb_value ary, long count, u
}
}
else if (!(flags & PACK_FLAG_a)) { /* "A" */
- while (copylen > 0 && (sptr[copylen - 1] == '\0' || isspace(sptr[copylen - 1]))) {
+ while (copylen > 0 && (sptr[copylen - 1] == '\0' || ISSPACE(sptr[copylen - 1]))) {
copylen--;
}
}
@@ -976,7 +976,7 @@ alias:
case 4: t = 'L'; goto alias;
case 8: t = 'Q'; goto alias;
default:
- mrb_raisef(mrb, E_RUNTIME_ERROR, "mruby-pack does not support sizeof(int) == %S", mrb_fixnum_value(sizeof(int)));
+ mrb_raisef(mrb, E_RUNTIME_ERROR, "mruby-pack does not support sizeof(int) == %d", (int)sizeof(int));
}
break;
case 'i':
@@ -985,7 +985,7 @@ alias:
case 4: t = 'l'; goto alias;
case 8: t = 'q'; goto alias;
default:
- mrb_raisef(mrb, E_RUNTIME_ERROR, "mruby-pack does not support sizeof(int) == %S", mrb_fixnum_value(sizeof(int)));
+ mrb_raisef(mrb, E_RUNTIME_ERROR, "mruby-pack does not support sizeof(int) == %d", (int)sizeof(int));
}
break;
case 'L':
@@ -1002,7 +1002,7 @@ alias:
case 'm':
dir = PACK_DIR_BASE64;
type = PACK_TYPE_STRING;
- flags |= PACK_FLAG_WIDTH;
+ flags |= PACK_FLAG_WIDTH | PACK_FLAG_COUNT2;
break;
case 'N': /* = "L>" */
dir = PACK_DIR_LONG;
@@ -1072,21 +1072,21 @@ alias:
/* read suffix [0-9*_!<>] */
while (tmpl->idx < tlen) {
ch = tptr[tmpl->idx++];
- if (isdigit(ch)) {
+ if (ISDIGIT(ch)) {
count = ch - '0';
- while (tmpl->idx < tlen && isdigit(tptr[tmpl->idx])) {
- count = count * 10 + (tptr[tmpl->idx++] - '0');
- if (count < 0) {
+ while (tmpl->idx < tlen && ISDIGIT(tptr[tmpl->idx])) {
+ int ch = tptr[tmpl->idx++] - '0';
+ if (count+ch > INT_MAX/10) {
mrb_raise(mrb, E_RUNTIME_ERROR, "too big template length");
}
+ count = count * 10 + ch;
}
continue; /* special case */
} else if (ch == '*') {
count = -1;
} else if (ch == '_' || ch == '!' || ch == '<' || ch == '>') {
if (strchr("sSiIlLqQ", (int)t) == NULL) {
- char ch_str = (char)ch;
- mrb_raisef(mrb, E_ARGUMENT_ERROR, "'%S' allowed only after types sSiIlLqQ", mrb_str_new(mrb, &ch_str, 1));
+ mrb_raisef(mrb, E_ARGUMENT_ERROR, "'%c' allowed only after types sSiIlLqQ", ch);
}
if (ch == '_' || ch == '!') {
flags |= PACK_FLAG_s;
@@ -1155,7 +1155,7 @@ mrb_pack_pack(mrb_state *mrb, mrb_value ary)
#endif
else if (type == PACK_TYPE_STRING) {
if (!mrb_string_p(o)) {
- mrb_raisef(mrb, E_TYPE_ERROR, "can't convert %S into String", mrb_class_path(mrb, mrb_obj_class(mrb, o)));
+ mrb_raisef(mrb, E_TYPE_ERROR, "can't convert %T into String", o);
}
}
@@ -1195,7 +1195,7 @@ mrb_pack_pack(mrb_state *mrb, mrb_value ary)
default:
break;
}
- if (dir == PACK_DIR_STR) { /* always consumes 1 entry */
+ if (dir == PACK_DIR_STR || dir == PACK_DIR_BASE64) { /* always consumes 1 entry */
aidx++;
break;
}
@@ -1248,6 +1248,9 @@ pack_unpack(mrb_state *mrb, mrb_value str, int single)
case PACK_DIR_STR:
srcidx += unpack_a(mrb, sptr, srclen - srcidx, result, count, flags);
break;
+ case PACK_DIR_BASE64:
+ srcidx += unpack_m(mrb, sptr, srclen - srcidx, result, flags);
+ break;
}
continue;
}
@@ -1274,9 +1277,6 @@ pack_unpack(mrb_state *mrb, mrb_value str, int single)
case PACK_DIR_QUAD:
srcidx += unpack_q(mrb, sptr, srclen - srcidx, result, flags);
break;
- case PACK_DIR_BASE64:
- srcidx += unpack_m(mrb, sptr, srclen - srcidx, result, flags);
- break;
#ifndef MRB_WITHOUT_FLOAT
case PACK_DIR_FLOAT:
srcidx += unpack_float(mrb, sptr, srclen - srcidx, result, flags);
@@ -1298,7 +1298,12 @@ pack_unpack(mrb_state *mrb, mrb_value str, int single)
if (single) break;
}
- if (single) return RARRAY_PTR(result)[0];
+ if (single) {
+ if (RARRAY_LEN(result) > 0) {
+ return RARRAY_PTR(result)[0];
+ }
+ return mrb_nil_value();
+ }
return result;
}
diff --git a/mrbgems/mruby-pack/test/pack.rb b/mrbgems/mruby-pack/test/pack.rb
index 1788c2b72..6832adcc7 100644
--- a/mrbgems/mruby-pack/test/pack.rb
+++ b/mrbgems/mruby-pack/test/pack.rb
@@ -1,101 +1,95 @@
+PACK_IS_LITTLE_ENDIAN = "\x01\00".unpack('S')[0] == 0x01
+
+def assert_pack tmpl, packed, unpacked
+ t = tmpl.inspect
+ assert "assert_pack" do
+ assert_equal packed, unpacked.pack(tmpl), "#{unpacked.inspect}.pack(#{t})"
+ assert_equal unpacked, packed.unpack(tmpl), "#{packed.inspect}.unpack(#{t})"
+ end
+end
+
# pack & unpack 'm' (base64)
assert('[""].pack("m")') do
- ary = ""
- str = ""
- [ary].pack("m") == str and
- str.unpack("m") == [ary]
+ assert_pack "m", "", [""]
end
assert('["\0"].pack("m")') do
- ary = "\0"
- str = "AA==\n"
- [ary].pack("m") == str and
- str.unpack("m") == [ary]
+ assert_pack "m", "AA==\n", ["\0"]
end
assert('["\0\0"].pack("m")') do
- ary = "\0\0"
- str = "AAA=\n"
- [ary].pack("m") == str and
- str.unpack("m") == [ary]
+ assert_pack "m", "AAA=\n", ["\0\0"]
end
assert('["\0\0\0"].pack("m")') do
- ary = "\0\0\0"
- str = "AAAA\n"
- [ary].pack("m") == str and
- str.unpack("m") == [ary]
+ assert_pack "m", "AAAA\n", ["\0\0\0"]
end
assert('["abc..xyzABC..XYZ"].pack("m")') do
- ["abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"].pack("m") == "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKS0xNTk9QUVJT\nVFVWV1hZWg==\n"
+ assert_pack "m", "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKS0xNTk9QUVJT\nVFVWV1hZWg==\n", ["abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"]
end
assert('"YWJ...".unpack("m") should "abc..xyzABC..XYZ"') do
- str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
- "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKS0xNTk9QUVJT\nVFVWV1hZWg==\n".unpack("m") == [str] and
- "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWg==\n".unpack("m") == [str]
+ ary = ["abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"]
+ assert_equal ary, "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKS0xNTk9QUVJT\nVFVWV1hZWg==\n".unpack("m")
+ assert_equal ary, "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWg==\n".unpack("m")
+end
+
+assert('["A", "B"].pack') do
+ assert_equal "QQ==\n", ["A", "B"].pack("m50")
+ assert_equal ["A"], "QQ==\n".unpack("m50")
+ assert_equal "QQ==Qg==", ["A", "B"].pack("m0 m0")
+ assert_equal ["A", "B"], "QQ==Qg==".unpack("m10 m10")
+end
+
+assert('["abc..xyzABC..XYZ"].pack("m0")') do
+ assert_pack "m0", "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWg==", ["abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"]
end
# pack & unpack 'H'
assert('["3031"].pack("H*")') do
- ary = "3031"
- str = "01"
- [ary].pack("H*") == str and
- str.unpack("H*") == [ary]
+ assert_pack "H*", "01", ["3031"]
end
assert('["10"].pack("H*")') do
- ary = "10"
- str = "\020"
- [ary].pack("H*") == str and
- str.unpack("H*") == [ary]
+ assert_pack "H*", "\020", ["10"]
end
assert('[0,1,127,128,255].pack("C*")') do
- ary = [ 0, 1, 127, 128, 255 ]
- str = "\x00\x01\x7F\x80\xFF"
- ary.pack("C*") == str and str.unpack("C*") == ary
+ assert_pack "C*", "\x00\x01\x7F\x80\xFF", [0, 1, 127, 128, 255]
end
# pack "a"
assert('["abc"].pack("a")') do
- ["abc"].pack("a") == "a" and
- ["abc"].pack("a*") == "abc" and
- ["abc"].pack("a4") == "abc\0"
+ assert_equal "a", ["abc"].pack("a")
+ assert_equal "abc", ["abc"].pack("a*")
+ assert_equal "abc\0", ["abc"].pack("a4")
end
# upack "a"
assert('["abc"].pack("a")') do
- "abc\0".unpack("a4") == ["abc\0"] and
- "abc ".unpack("a4") == ["abc "]
+ assert_equal ["abc\0"], "abc\0".unpack("a4")
+ assert_equal ["abc "], "abc ".unpack("a4")
end
# pack "A"
assert('["abc"].pack("A")') do
- ["abc"].pack("A") == "a" and
- ["abc"].pack("A*") == "abc" and
- ["abc"].pack("A4") == "abc "
+ assert_equal "a", ["abc"].pack("A")
+ assert_equal "abc", ["abc"].pack("A*")
+ assert_equal "abc ", ["abc"].pack("A4")
end
# upack "A"
assert('["abc"].pack("A")') do
- "abc\0".unpack("A4") == ["abc"] and
- "abc ".unpack("A4") == ["abc"]
+ assert_equal ["abc"], "abc\0".unpack("A4")
+ assert_equal ["abc"], "abc ".unpack("A4")
end
# regression tests
assert('issue #1') do
- [1, 2].pack("nn") == "\000\001\000\002"
+ assert_equal "\000\001\000\002", [1, 2].pack("nn")
end
-def assert_pack tmpl, packed, unpacked
- assert_equal packed, unpacked.pack(tmpl)
- assert_equal unpacked, packed.unpack(tmpl)
-end
-
-PACK_IS_LITTLE_ENDIAN = "\x01\00".unpack('S')[0] == 0x01
-
assert 'pack float' do
assert_pack 'e', "\x00\x00@@", [3.0]
assert_pack 'g', "@@\x00\x00", [3.0]
diff --git a/mrbgems/mruby-proc-ext/src/proc.c b/mrbgems/mruby-proc-ext/src/proc.c
index 4b85c245d..c9041ec75 100644
--- a/mrbgems/mruby-proc-ext/src/proc.c
+++ b/mrbgems/mruby-proc-ext/src/proc.c
@@ -25,8 +25,8 @@ mrb_proc_source_location(mrb_state *mrb, mrb_value self)
int32_t line;
const char *filename;
- filename = mrb_debug_get_filename(irep, 0);
- line = mrb_debug_get_line(irep, 0);
+ filename = mrb_debug_get_filename(mrb, irep, 0);
+ line = mrb_debug_get_line(mrb, irep, 0);
return (!filename && line == -1)? mrb_nil_value()
: mrb_assoc_new(mrb, mrb_str_new_cstr(mrb, filename), mrb_fixnum_value(line));
@@ -38,7 +38,7 @@ mrb_proc_inspect(mrb_state *mrb, mrb_value self)
{
struct RProc *p = mrb_proc_ptr(self);
mrb_value str = mrb_str_new_lit(mrb, "#<Proc:");
- mrb_str_concat(mrb, str, mrb_ptr_to_str(mrb, mrb_cptr(self)));
+ mrb_str_cat_str(mrb, str, mrb_ptr_to_str(mrb, mrb_cptr(self)));
if (!MRB_PROC_CFUNC_P(p)) {
mrb_irep *irep = p->body.irep;
@@ -46,13 +46,13 @@ mrb_proc_inspect(mrb_state *mrb, mrb_value self)
int32_t line;
mrb_str_cat_lit(mrb, str, "@");
- filename = mrb_debug_get_filename(irep, 0);
+ filename = mrb_debug_get_filename(mrb, irep, 0);
mrb_str_cat_cstr(mrb, str, filename ? filename : "-");
mrb_str_cat_lit(mrb, str, ":");
- line = mrb_debug_get_line(irep, 0);
+ line = mrb_debug_get_line(mrb, irep, 0);
if (line != -1) {
- str = mrb_format(mrb, "%S:%S", str, mrb_fixnum_value(line));
+ mrb_str_concat(mrb, str, mrb_fixnum_value(line));
}
else {
mrb_str_cat_lit(mrb, str, "-");
diff --git a/mrbgems/mruby-proc-ext/test/proc.rb b/mrbgems/mruby-proc-ext/test/proc.rb
index 1220841c8..a6321d371 100644
--- a/mrbgems/mruby-proc-ext/test/proc.rb
+++ b/mrbgems/mruby-proc-ext/test/proc.rb
@@ -1,16 +1,32 @@
##
# Proc(Ext) Test
+def enable_debug_info?
+ return @enable_debug_info unless @enable_debug_info == nil
+ begin
+ raise
+ rescue => e
+ @enable_debug_info = !e.backtrace.empty?
+ end
+end
+
assert('Proc#source_location') do
- loc = Proc.new {}.source_location
- next true if loc.nil?
- assert_equal loc[0][-7, 7], 'proc.rb'
- assert_equal loc[1], 5
+ skip unless enable_debug_info?
+ file, line = Proc.new{}.source_location
+ assert_equal __FILE__, file
+ assert_equal __LINE__ - 2, line
end
assert('Proc#inspect') do
ins = Proc.new{}.inspect
- assert_kind_of String, ins
+ if enable_debug_info?
+ metas = %w(\\ * ? [ ] { })
+ file = __FILE__.split("").map{|c| metas.include?(c) ? "\\#{c}" : c}.join
+ line = __LINE__ - 4
+ else
+ file = line = "-"
+ end
+ assert_match "#<Proc:0x*@#{file}:#{line}>", ins
end
assert('Proc#parameters') do
diff --git a/mrbgems/mruby-random/src/mt19937ar.c b/mrbgems/mruby-random/src/mt19937ar.c
deleted file mode 100644
index 405bd5c20..000000000
--- a/mrbgems/mruby-random/src/mt19937ar.c
+++ /dev/null
@@ -1,224 +0,0 @@
-/*
-** mt19937ar.c - MT Random functions
-**
-** Copyright (C) 1997 - 2016, Makoto Matsumoto and Takuji Nishimura,
-** All rights reserved.
-**
-** Permission is hereby granted, free of charge, to any person obtaining
-** a copy of this software and associated documentation files (the
-** "Software"), to deal in the Software without restriction, including
-** without limitation the rights to use, copy, modify, merge, publish,
-** distribute, sublicense, and/or sell copies of the Software, and to
-** permit persons to whom the Software is furnished to do so, subject to
-** the following conditions:
-**
-** The above copyright notice and this permission notice shall be
-** included in all copies or substantial portions of the Software.
-**
-** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
-** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-**
-** [ MIT license: http://www.opensource.org/licenses/mit-license.php ]
-**
-** Any feedback is very welcome.
-** http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
-** email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
-**
-** This version is modified by mruby developers. If you see any problem,
-** contact us first at https://github.com/mruby/mruby/issues
-*/
-
-#include <mruby.h>
-#include "mt19937ar.h"
-
-/* Period parameters */
-/* #define N 624 */
-#define M 397
-#define MATRIX_A 0x9908b0dfUL /* constant vector a */
-#define UPPER_MASK 0x80000000UL /* most significant w-r bits */
-#define LOWER_MASK 0x7fffffffUL /* least significant r bits */
-
-#if 0 /* dead_code */
-static unsigned long mt[N]; /* the array for the state vector */
-static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */
-#endif /* dead_code */
-
-void mrb_random_init_genrand(mt_state *t, unsigned long s)
-{
- t->mt[0]= s & 0xffffffffUL;
- for (t->mti=1; t->mti<N; t->mti++) {
- t->mt[t->mti] = (1812433253UL * (t->mt[t->mti-1] ^ (t->mt[t->mti-1] >> 30)) + t->mti);
- t->mt[t->mti] &= 0xffffffffUL;
- }
-}
-
-unsigned long mrb_random_genrand_int32(mt_state *t)
-{
- unsigned long y;
- static const unsigned long mag01[2]={0x0UL, MATRIX_A};
- /* mag01[x] = x * MATRIX_A for x=0,1 */
-
- if (t->mti >= N) { /* generate N words at one time */
- int kk;
-
- if (t->mti == N+1) /* if init_genrand() has not been called, */
- mrb_random_init_genrand(t, 5489UL); /* a default initial seed is used */
-
- for (kk=0;kk<N-M;kk++) {
- y = (t->mt[kk]&UPPER_MASK)|(t->mt[kk+1]&LOWER_MASK);
- t->mt[kk] = t->mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL];
- }
- for (;kk<N-1;kk++) {
- y = (t->mt[kk]&UPPER_MASK)|(t->mt[kk+1]&LOWER_MASK);
- t->mt[kk] = t->mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL];
- }
- y = (t->mt[N-1]&UPPER_MASK)|(t->mt[0]&LOWER_MASK);
- t->mt[N-1] = t->mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL];
-
- t->mti = 0;
- }
-
- y = t->mt[t->mti++];
-
- /* Tempering */
- y ^= (y >> 11);
- y ^= (y << 7) & 0x9d2c5680UL;
- y ^= (y << 15) & 0xefc60000UL;
- y ^= (y >> 18);
-
- t->gen.int_ = y;
-
- return y;
-}
-
-double mrb_random_genrand_real1(mt_state *t)
-{
- mrb_random_genrand_int32(t);
- t->gen.double_ = t->gen.int_*(1.0/4294967295.0);
- return t->gen.double_;
- /* divided by 2^32-1 */
-}
-
-#if 0 /* dead_code */
-/* initializes mt[N] with a seed */
-void init_genrand(unsigned long s)
-{
- mt[0]= s & 0xffffffffUL;
- for (mti=1; mti<N; mti++) {
- mt[mti] = (1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
- /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
- /* In the previous versions, MSBs of the seed affect */
- /* only MSBs of the array mt[]. */
- /* 2002/01/09 modified by Makoto Matsumoto */
- mt[mti] &= 0xffffffffUL;
- /* for >32 bit machines */
- }
-}
-
-/* initialize by an array with array-length */
-/* init_key is the array for initializing keys */
-/* key_length is its length */
-/* slight change for C++, 2004/2/26 */
-void init_by_array(unsigned long init_key[], int key_length)
-{
- int i, j, k;
- init_genrand(19650218UL);
- i=1; j=0;
- k = (N>key_length ? N : key_length);
- for (; k; k--) {
- mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL))
- + init_key[j] + j; /* non linear */
- mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
- i++; j++;
- if (i>=N) { mt[0] = mt[N-1]; i=1; }
- if (j>=key_length) j=0;
- }
- for (k=N-1; k; k--) {
- mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL))
- - i; /* non linear */
- mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
- i++;
- if (i>=N) { mt[0] = mt[N-1]; i=1; }
- }
-
- mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */
-}
-
-/* generates a random number on [0,0xffffffff]-interval */
-unsigned long genrand_int32(void)
-{
- unsigned long y;
- static const unsigned long mag01[2]={0x0UL, MATRIX_A};
- /* mag01[x] = x * MATRIX_A for x=0,1 */
-
- if (mti >= N) { /* generate N words at one time */
- int kk;
-
- if (mti == N+1) /* if init_genrand() has not been called, */
- init_genrand(5489UL); /* a default initial seed is used */
-
- for (kk=0;kk<N-M;kk++) {
- y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
- mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL];
- }
- for (;kk<N-1;kk++) {
- y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
- mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL];
- }
- y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
- mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL];
-
- mti = 0;
- }
-
- y = mt[mti++];
-
- /* Tempering */
- y ^= (y >> 11);
- y ^= (y << 7) & 0x9d2c5680UL;
- y ^= (y << 15) & 0xefc60000UL;
- y ^= (y >> 18);
-
- return y;
-}
-
-/* generates a random number on [0,0x7fffffff]-interval */
-long genrand_int31(void)
-{
- return (long)(genrand_int32()>>1);
-}
-
-/* generates a random number on [0,1]-real-interval */
-double genrand_real1(void)
-{
- return genrand_int32()*(1.0/4294967295.0);
- /* divided by 2^32-1 */
-}
-
-/* generates a random number on [0,1)-real-interval */
-double genrand_real2(void)
-{
- return genrand_int32()*(1.0/4294967296.0);
- /* divided by 2^32 */
-}
-
-/* generates a random number on (0,1)-real-interval */
-double genrand_real3(void)
-{
- return (((double)genrand_int32()) + 0.5)*(1.0/4294967296.0);
- /* divided by 2^32 */
-}
-
-/* generates a random number on [0,1) with 53-bit resolution*/
-double genrand_res53(void)
-{
- unsigned long a=genrand_int32()>>5, b=genrand_int32()>>6;
- return(a*67108864.0+b)*(1.0/9007199254740992.0);
-}
-/* These real versions are due to Isaku Wada, 2002/01/09 added */
-#endif /* dead_code */
diff --git a/mrbgems/mruby-random/src/mt19937ar.h b/mrbgems/mruby-random/src/mt19937ar.h
deleted file mode 100644
index 7d382320d..000000000
--- a/mrbgems/mruby-random/src/mt19937ar.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
-** mt19937ar.h - MT Random functions
-**
-** Copyright (C) 1997 - 2016, Makoto Matsumoto and Takuji Nishimura,
-** All rights reserved.
-**
-** Permission is hereby granted, free of charge, to any person obtaining
-** a copy of this software and associated documentation files (the
-** "Software"), to deal in the Software without restriction, including
-** without limitation the rights to use, copy, modify, merge, publish,
-** distribute, sublicense, and/or sell copies of the Software, and to
-** permit persons to whom the Software is furnished to do so, subject to
-** the following conditions:
-**
-** The above copyright notice and this permission notice shall be
-** included in all copies or substantial portions of the Software.
-**
-** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
-** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-**
-** [ MIT license: http://www.opensource.org/licenses/mit-license.php ]
-**
-** Any feedback is very welcome.
-** http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
-** email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
-**
-** This version is modified by mruby developers. If you see any problem,
-** contact us first at https://github.com/mruby/mruby/issues
-*/
-
-#define N 624
-
-typedef struct {
- unsigned long mt[N];
- int mti;
- union {
- unsigned long int_;
- double double_;
- } gen;
-
- mrb_int seed;
- mrb_bool has_seed : 1;
-} mt_state;
-
-void mrb_random_init_genrand(mt_state *, unsigned long);
-unsigned long mrb_random_genrand_int32(mt_state *);
-double mrb_random_genrand_real1(mt_state *t);
-
-/* initializes mt[N] with a seed */
-void init_genrand(unsigned long s);
-
-/* initialize by an array with array-length */
-/* init_key is the array for initializing keys */
-/* key_length is its length */
-/* slight change for C++, 2004/2/26 */
-void init_by_array(unsigned long init_key[], int key_length);
-
-/* generates a random number on [0,0xffffffff]-interval */
-unsigned long genrand_int32(void);
-
-/* generates a random number on [0,0x7fffffff]-interval */
-long genrand_int31(void);
-
-/* These real versions are due to Isaku Wada, 2002/01/09 added */
-/* generates a random number on [0,1]-real-interval */
-double genrand_real1(void);
-
-/* generates a random number on [0,1)-real-interval */
-double genrand_real2(void);
-
-/* generates a random number on (0,1)-real-interval */
-double genrand_real3(void);
-
-/* generates a random number on [0,1) with 53-bit resolution*/
-double genrand_res53(void);
diff --git a/mrbgems/mruby-random/src/random.c b/mrbgems/mruby-random/src/random.c
index 68209840a..af9876ce7 100644
--- a/mrbgems/mruby-random/src/random.c
+++ b/mrbgems/mruby-random/src/random.c
@@ -9,62 +9,105 @@
#include <mruby/class.h>
#include <mruby/data.h>
#include <mruby/array.h>
-#include "mt19937ar.h"
+#include <mruby/istruct.h>
+#if INT32_MAX <= INTPTR_MAX
+# define XORSHIFT96
+# define NSEEDS 3
+#else
+# define NSEEDS 4
+#endif
+#define LASTSEED (NSEEDS-1)
#include <time.h>
-static char const MT_STATE_KEY[] = "$mrb_i_mt_state";
-
-static const struct mrb_data_type mt_state_type = {
- MT_STATE_KEY, mrb_free,
-};
-
-static mrb_value mrb_random_rand(mrb_state *mrb, mrb_value self);
-static mrb_value mrb_random_srand(mrb_state *mrb, mrb_value self);
+typedef struct rand_state {
+ uint32_t seed[NSEEDS];
+} rand_state;
static void
-mt_srand(mt_state *t, unsigned long seed)
+rand_init(rand_state *t)
{
- mrb_random_init_genrand(t, seed);
+ t->seed[0] = 123456789;
+ t->seed[1] = 362436069;
+ t->seed[2] = 521288629;
+#ifndef XORSHIFT96
+ t->seed[3] = 88675123;
+#endif
}
-static unsigned long
-mt_rand(mt_state *t)
+static uint32_t
+rand_seed(rand_state *t, uint32_t seed)
{
- return mrb_random_genrand_int32(t);
+ uint32_t old_seed = t->seed[LASTSEED];
+ rand_init(t);
+ t->seed[LASTSEED] = seed;
+ return old_seed;
}
-static double
-mt_rand_real(mt_state *t)
+#ifdef XORSHIFT96
+static uint32_t
+rand_uint32(rand_state *state)
{
- return mrb_random_genrand_real1(t);
+ uint32_t *seed = state->seed;
+ uint32_t x = seed[0];
+ uint32_t y = seed[1];
+ uint32_t z = seed[2];
+ uint32_t t;
+
+ t = (x ^ (x << 3)) ^ (y ^ (y >> 19)) ^ (z ^ (z << 6));
+ x = y; y = z; z = t;
+ seed[0] = x;
+ seed[1] = y;
+ seed[2] = z;
+
+ return z;
}
-
-static mrb_value
-mrb_random_mt_srand(mrb_state *mrb, mt_state *t, mrb_value seed)
+#else /* XORSHIFT96 */
+static uint32_t
+rand_uint32(rand_state *state)
{
- if (mrb_nil_p(seed)) {
- seed = mrb_fixnum_value((mrb_int)(time(NULL) + mt_rand(t)));
- if (mrb_fixnum(seed) < 0) {
- seed = mrb_fixnum_value(0 - mrb_fixnum(seed));
- }
- }
-
- mt_srand(t, (unsigned) mrb_fixnum(seed));
+ uint32_t *seed = state->seed;
+ uint32_t x = seed[0];
+ uint32_t y = seed[1];
+ uint32_t z = seed[2];
+ uint32_t w = seed[3];
+ uint32_t t;
+
+ t = x ^ (x << 11);
+ x = y; y = z; z = w;
+ w = (w ^ (w >> 19)) ^ (t ^ (t >> 8));
+ seed[0] = x;
+ seed[1] = y;
+ seed[2] = z;
+ seed[3] = w;
+
+ return w;
+}
+#endif /* XORSHIFT96 */
- return seed;
+#ifndef MRB_WITHOUT_FLOAT
+static double
+rand_real(rand_state *t)
+{
+ uint32_t x = rand_uint32(t);
+ return x*(1.0/4294967295.0);
}
+#endif
static mrb_value
-mrb_random_mt_rand(mrb_state *mrb, mt_state *t, mrb_value max)
+random_rand(mrb_state *mrb, rand_state *t, mrb_value max)
{
mrb_value value;
if (mrb_fixnum(max) == 0) {
- value = mrb_float_value(mrb, mt_rand_real(t));
+#ifndef MRB_WITHOUT_FLOAT
+ value = mrb_float_value(mrb, rand_real(t));
+#else
+ mrb_raise(mrb, E_ARGUMENT_ERROR, "Float not supported");
+#endif
}
else {
- value = mrb_fixnum_value(mt_rand(t) % mrb_fixnum(max));
+ value = mrb_fixnum_value(rand_uint32(t) % mrb_fixnum(max));
}
return value;
@@ -90,106 +133,74 @@ get_opt(mrb_state* mrb)
return arg;
}
-static mrb_value
-get_random(mrb_state *mrb) {
- return mrb_const_get(mrb,
- mrb_obj_value(mrb_class_get(mrb, "Random")),
- mrb_intern_lit(mrb, "DEFAULT"));
-}
-
-static mt_state *
-get_random_state(mrb_state *mrb)
-{
- mrb_value random_val = get_random(mrb);
- return DATA_GET_PTR(mrb, random_val, &mt_state_type, mt_state);
+static void
+random_check(mrb_state *mrb, mrb_value random) {
+ struct RClass *c = mrb_class_get(mrb, "Random");
+ if (!mrb_obj_is_kind_of(mrb, random, c) || mrb_type(random) != MRB_TT_ISTRUCT) {
+ mrb_raise(mrb, E_TYPE_ERROR, "Random instance required");
+ }
}
static mrb_value
-mrb_random_g_rand(mrb_state *mrb, mrb_value self)
-{
- mrb_value random = get_random(mrb);
- return mrb_random_rand(mrb, random);
+random_default(mrb_state *mrb) {
+ struct RClass *c = mrb_class_get(mrb, "Random");
+ mrb_value d = mrb_const_get(mrb, mrb_obj_value(c), mrb_intern_lit(mrb, "DEFAULT"));
+ if (!mrb_obj_is_kind_of(mrb, d, c)) {
+ mrb_raise(mrb, E_TYPE_ERROR, "Random::DEFAULT replaced");
+ }
+ return d;
}
-static mrb_value
-mrb_random_g_srand(mrb_state *mrb, mrb_value self)
-{
- mrb_value random = get_random(mrb);
- return mrb_random_srand(mrb, random);
-}
+#define random_ptr(v) (rand_state*)mrb_istruct_ptr(v)
+#define random_default_state(mrb) random_ptr(random_default(mrb))
static mrb_value
-mrb_random_init(mrb_state *mrb, mrb_value self)
+random_m_init(mrb_state *mrb, mrb_value self)
{
mrb_value seed;
- mt_state *t;
+ rand_state *t;
seed = get_opt(mrb);
-
/* avoid memory leaks */
- t = (mt_state*)DATA_PTR(self);
- if (t) {
- mrb_free(mrb, t);
- }
- mrb_data_init(self, NULL, &mt_state_type);
-
- t = (mt_state *)mrb_malloc(mrb, sizeof(mt_state));
- t->mti = N + 1;
-
- seed = mrb_random_mt_srand(mrb, t, seed);
+ t = random_ptr(self);
if (mrb_nil_p(seed)) {
- t->has_seed = FALSE;
+ rand_init(t);
}
else {
- mrb_assert(mrb_fixnum_p(seed));
- t->has_seed = TRUE;
- t->seed = mrb_fixnum(seed);
+ rand_seed(t, (uint32_t)mrb_fixnum(seed));
}
- mrb_data_init(self, t, &mt_state_type);
-
return self;
}
-static void
-mrb_random_rand_seed(mrb_state *mrb, mt_state *t)
-{
- if (!t->has_seed) {
- mrb_random_mt_srand(mrb, t, mrb_nil_value());
- }
-}
-
static mrb_value
-mrb_random_rand(mrb_state *mrb, mrb_value self)
+random_m_rand(mrb_state *mrb, mrb_value self)
{
mrb_value max;
- mt_state *t = DATA_GET_PTR(mrb, self, &mt_state_type, mt_state);
+ rand_state *t = random_ptr(self);
max = get_opt(mrb);
- mrb_random_rand_seed(mrb, t);
- return mrb_random_mt_rand(mrb, t, max);
+ return random_rand(mrb, t, max);
}
static mrb_value
-mrb_random_srand(mrb_state *mrb, mrb_value self)
+random_m_srand(mrb_state *mrb, mrb_value self)
{
- mrb_value seed;
- mrb_value old_seed;
- mt_state *t = DATA_GET_PTR(mrb, self, &mt_state_type, mt_state);
-
- seed = get_opt(mrb);
- seed = mrb_random_mt_srand(mrb, t, seed);
- old_seed = t->has_seed? mrb_fixnum_value(t->seed) : mrb_nil_value();
- if (mrb_nil_p(seed)) {
- t->has_seed = FALSE;
+ uint32_t seed;
+ uint32_t old_seed;
+ mrb_value sv;
+ rand_state *t = random_ptr(self);
+
+ sv = get_opt(mrb);
+ if (mrb_nil_p(sv)) {
+ seed = (uint32_t)time(NULL) + rand_uint32(t);
}
else {
- mrb_assert(mrb_fixnum_p(seed));
- t->has_seed = TRUE;
- t->seed = mrb_fixnum(seed);
+ seed = (uint32_t)mrb_fixnum(sv);
}
+ old_seed = rand_seed(t, seed);
- return old_seed;
+ return mrb_fixnum_value((mrb_int)old_seed);
}
/*
@@ -203,25 +214,28 @@ static mrb_value
mrb_ary_shuffle_bang(mrb_state *mrb, mrb_value ary)
{
mrb_int i;
- mt_state *random = NULL;
+ mrb_value max;
+ mrb_value r = mrb_nil_value();
+ rand_state *random;
if (RARRAY_LEN(ary) > 1) {
- mrb_get_args(mrb, "|d", &random, &mt_state_type);
+ mrb_get_args(mrb, "|o", &r);
- if (random == NULL) {
- random = get_random_state(mrb);
+ if (mrb_nil_p(r)) {
+ random = random_default_state(mrb);
+ }
+ else {
+ random_check(mrb, r);
+ random = random_ptr(r);
}
- mrb_random_rand_seed(mrb, random);
-
mrb_ary_modify(mrb, mrb_ary_ptr(ary));
-
+ max = mrb_fixnum_value(RARRAY_LEN(ary));
for (i = RARRAY_LEN(ary) - 1; i > 0; i--) {
mrb_int j;
mrb_value *ptr = RARRAY_PTR(ary);
mrb_value tmp;
-
- j = mrb_fixnum(mrb_random_mt_rand(mrb, random, mrb_fixnum_value(RARRAY_LEN(ary))));
+ j = mrb_fixnum(random_rand(mrb, random, max));
tmp = ptr[i];
ptr[i] = ptr[j];
@@ -268,15 +282,18 @@ mrb_ary_sample(mrb_state *mrb, mrb_value ary)
{
mrb_int n = 0;
mrb_bool given;
- mt_state *random = NULL;
+ mrb_value r = mrb_nil_value();
+ rand_state *random;
mrb_int len;
- mrb_get_args(mrb, "|i?d", &n, &given, &random, &mt_state_type);
- if (random == NULL) {
- random = get_random_state(mrb);
+ mrb_get_args(mrb, "|i?o", &n, &given, &r);
+ if (mrb_nil_p(r)) {
+ random = random_default_state(mrb);
+ }
+ else {
+ random_check(mrb, r);
+ random = random_ptr(r);
}
- mrb_random_rand_seed(mrb, random);
- mt_rand(random);
len = RARRAY_LEN(ary);
if (!given) { /* pick one element */
switch (len) {
@@ -285,7 +302,7 @@ mrb_ary_sample(mrb_state *mrb, mrb_value ary)
case 1:
return RARRAY_PTR(ary)[0];
default:
- return RARRAY_PTR(ary)[mt_rand(random) % len];
+ return RARRAY_PTR(ary)[rand_uint32(random) % len];
}
}
else {
@@ -300,7 +317,7 @@ mrb_ary_sample(mrb_state *mrb, mrb_value ary)
for (;;) {
retry:
- r = mt_rand(random) % len;
+ r = (mrb_int)(rand_uint32(random) % len);
for (j=0; j<i; j++) {
if (mrb_fixnum(RARRAY_PTR(result)[j]) == r) {
@@ -318,23 +335,39 @@ mrb_ary_sample(mrb_state *mrb, mrb_value ary)
}
}
+static mrb_value
+random_f_rand(mrb_state *mrb, mrb_value self)
+{
+ rand_state *t = random_default_state(mrb);
+ return random_rand(mrb, t, get_opt(mrb));
+}
+
+static mrb_value
+random_f_srand(mrb_state *mrb, mrb_value self)
+{
+ mrb_value random = random_default(mrb);
+ return random_m_srand(mrb, random);
+}
+
void mrb_mruby_random_gem_init(mrb_state *mrb)
{
struct RClass *random;
struct RClass *array = mrb->array_class;
- mrb_define_method(mrb, mrb->kernel_module, "rand", mrb_random_g_rand, MRB_ARGS_OPT(1));
- mrb_define_method(mrb, mrb->kernel_module, "srand", mrb_random_g_srand, MRB_ARGS_OPT(1));
+ mrb_assert(sizeof(rand_state) <= ISTRUCT_DATA_SIZE);
+
+ mrb_define_method(mrb, mrb->kernel_module, "rand", random_f_rand, MRB_ARGS_OPT(1));
+ mrb_define_method(mrb, mrb->kernel_module, "srand", random_f_srand, MRB_ARGS_OPT(1));
random = mrb_define_class(mrb, "Random", mrb->object_class);
- MRB_SET_INSTANCE_TT(random, MRB_TT_DATA);
- mrb_define_class_method(mrb, random, "rand", mrb_random_g_rand, MRB_ARGS_OPT(1));
- mrb_define_class_method(mrb, random, "srand", mrb_random_g_srand, MRB_ARGS_OPT(1));
+ MRB_SET_INSTANCE_TT(random, MRB_TT_ISTRUCT);
+ mrb_define_class_method(mrb, random, "rand", random_f_rand, MRB_ARGS_OPT(1));
+ mrb_define_class_method(mrb, random, "srand", random_f_srand, MRB_ARGS_OPT(1));
- mrb_define_method(mrb, random, "initialize", mrb_random_init, MRB_ARGS_OPT(1));
- mrb_define_method(mrb, random, "rand", mrb_random_rand, MRB_ARGS_OPT(1));
- mrb_define_method(mrb, random, "srand", mrb_random_srand, MRB_ARGS_OPT(1));
+ mrb_define_method(mrb, random, "initialize", random_m_init, MRB_ARGS_OPT(1));
+ mrb_define_method(mrb, random, "rand", random_m_rand, MRB_ARGS_OPT(1));
+ mrb_define_method(mrb, random, "srand", random_m_srand, MRB_ARGS_OPT(1));
mrb_define_method(mrb, array, "shuffle", mrb_ary_shuffle, MRB_ARGS_OPT(1));
mrb_define_method(mrb, array, "shuffle!", mrb_ary_shuffle_bang, MRB_ARGS_OPT(1));
diff --git a/mrbgems/mruby-random/src/random.h b/mrbgems/mruby-random/src/random.h
deleted file mode 100644
index a4785ae5a..000000000
--- a/mrbgems/mruby-random/src/random.h
+++ /dev/null
@@ -1,12 +0,0 @@
-/*
-** random.h - Random module
-**
-** See Copyright Notice in mruby.h
-*/
-
-#ifndef MRUBY_RANDOM_H
-#define MRUBY_RANDOM_H
-
-void mrb_mruby_random_gem_init(mrb_state *mrb);
-
-#endif
diff --git a/mrbgems/mruby-random/test/random.rb b/mrbgems/mruby-random/test/random.rb
index 1653ae4a6..cf4a55141 100644
--- a/mrbgems/mruby-random/test/random.rb
+++ b/mrbgems/mruby-random/test/random.rb
@@ -1,48 +1,58 @@
##
# Random Test
-assert("Random#srand") do
+assert("Random.new") do
r1 = Random.new(123)
r2 = Random.new(123)
- r1.rand == r2.rand
+ r3 = Random.new(124)
+ assert_equal(r1.rand, r2.rand)
+ assert_not_equal(r1.rand, r3.rand)
end
-assert("Kernel::srand") do
+assert("Kernel.srand") do
srand(234)
r1 = rand
srand(234)
r2 = rand
- r1 == r2
+ srand(235)
+ r3 = rand
+ assert_equal(r1, r2)
+ assert_not_equal(r1, r3)
end
-assert("Random::srand") do
+assert("Random.srand") do
Random.srand(345)
r1 = rand
srand(345)
r2 = Random.rand
- r1 == r2
+ Random.srand(346)
+ r3 = rand
+ assert_equal(r1, r2)
+ assert_not_equal(r1, r3)
end
-assert("fixnum") do
- rand(3).class == Fixnum
-end
-
-assert("float") do
- rand.class == Float
+assert("return class of Kernel.rand") do
+ assert_kind_of(Fixnum, rand(3))
+ assert_kind_of(Fixnum, rand(1.5))
+ assert_kind_of(Float, rand)
+ assert_kind_of(Float, rand(0.5))
end
assert("Array#shuffle") do
- ary = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+ orig = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+ ary = orig.dup
shuffled = ary.shuffle
-
- ary == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and shuffled != ary and 10.times { |x| ary.include? x }
+ assert_equal(orig, ary)
+ assert_not_equal(ary, shuffled)
+ assert_equal(orig, shuffled.sort)
end
assert('Array#shuffle!') do
- ary = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- ary.shuffle!
-
- ary != [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and 10.times { |x| ary.include? x }
+ orig = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+ ary = orig.dup
+ assert_same(ary, ary.shuffle!)
+ assert_not_equal(orig, ary)
+ assert_equal(orig, ary.sort)
end
assert("Array#shuffle(random)") do
@@ -52,12 +62,12 @@ assert("Array#shuffle(random)") do
end
# verify that the same seed causes the same results
- ary1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- shuffle1 = ary1.shuffle Random.new 345
- ary2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- shuffle2 = ary2.shuffle Random.new 345
-
- ary1 != shuffle1 and 10.times { |x| shuffle1.include? x } and shuffle1 == shuffle2
+ ary = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+ shuffled1 = ary.shuffle Random.new 345
+ shuffled2 = ary.shuffle Random.new 345
+ shuffled3 = ary.shuffle Random.new 346
+ assert_equal(shuffled1, shuffled2)
+ assert_not_equal(shuffled1, shuffled3)
end
assert('Array#shuffle!(random)') do
@@ -71,6 +81,42 @@ assert('Array#shuffle!(random)') do
ary1.shuffle! Random.new 345
ary2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
ary2.shuffle! Random.new 345
+ ary3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+ ary3.shuffle! Random.new 346
+ assert_equal(ary1, ary2)
+ assert_not_equal(ary1, ary3)
+end
+
+assert('Array#sample') do
+ 100.times do
+ assert_include([0, 1, 2], [2, 1, 0].sample)
+ [2, 1, 0].sample(2).each { |sample| assert_include([0, 1, 2], sample) }
+ h = {}
+ (1..10).to_a.sample(7).each do |sample|
+ assert_not_include(h, sample)
+ h[sample] = true
+ end
+ end
+
+ assert_nil([].sample)
+ assert_equal([], [].sample(1))
+ assert_equal([], [2, 1].sample(0))
+ assert_raise(TypeError) { [2, 1].sample(true) }
+ assert_raise(ArgumentError) { [2, 1].sample(-1) }
+end
- ary1 != [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and 10.times { |x| ary1.include? x } and ary1 == ary2
+assert('Array#sample(random)') do
+ assert_raise(TypeError) do
+ # this will cause an exception due to the wrong argument
+ [1, 2].sample(2, "Not a Random instance")
+ end
+
+ # verify that the same seed causes the same results
+ ary = (1..10).to_a
+ srand(15)
+ samples1 = ary.sample(4)
+ samples2 = ary.sample(4, Random.new(15))
+ samples3 = ary.sample(4, Random.new(16))
+ assert_equal(samples1, samples2)
+ assert_not_equal(samples1, samples3)
end
diff --git a/mrbgems/mruby-range-ext/mrblib/range.rb b/mrbgems/mruby-range-ext/mrblib/range.rb
index de7925ba7..a213beb57 100644
--- a/mrbgems/mruby-range-ext/mrblib/range.rb
+++ b/mrbgems/mruby-range-ext/mrblib/range.rb
@@ -25,4 +25,42 @@ class Range
end
ary
end
+
+ def max(&block)
+ val = self.first
+ last = self.last
+ return super if block
+
+ # fast path for numerics
+ if val.kind_of?(Numeric) && last.kind_of?(Numeric)
+ raise TypeError if exclude_end? && !last.kind_of?(Fixnum)
+ return nil if val > last
+ return nil if val == last && exclude_end?
+
+ max = last
+ max -= 1 if exclude_end?
+ return max
+ end
+
+ # delegate to Enumerable
+ super
+ end
+
+ def min(&block)
+ val = self.first
+ last = self.last
+ return super if block
+
+ # fast path for numerics
+ if val.kind_of?(Numeric) && last.kind_of?(Numeric)
+ return nil if val > last
+ return nil if val == last && exclude_end?
+
+ min = val
+ return min
+ end
+
+ # delegate to Enumerable
+ super
+ end
end
diff --git a/mrbgems/mruby-range-ext/src/range.c b/mrbgems/mruby-range-ext/src/range.c
index 1f6690904..36b684fad 100644
--- a/mrbgems/mruby-range-ext/src/range.c
+++ b/mrbgems/mruby-range-ext/src/range.c
@@ -5,24 +5,16 @@
static mrb_bool
r_le(mrb_state *mrb, mrb_value a, mrb_value b)
{
- mrb_value r = mrb_funcall(mrb, a, "<=>", 1, b); /* compare result */
- /* output :a < b => -1, a = b => 0, a > b => +1 */
-
- if (mrb_fixnum_p(r)) {
- mrb_int c = mrb_fixnum(r);
- if (c == 0 || c == -1) return TRUE;
- }
+ mrb_int n = mrb_cmp(mrb, a, b);
+ if (n == 0 || n == -1) return TRUE;
return FALSE;
}
static mrb_bool
r_lt(mrb_state *mrb, mrb_value a, mrb_value b)
{
- mrb_value r = mrb_funcall(mrb, a, "<=>", 1, b);
- /* output :a < b => -1, a = b => 0, a > b => +1 */
-
- return mrb_fixnum_p(r) && mrb_fixnum(r) == -1;
+ return mrb_cmp(mrb, a, b) == -1;
}
/*
@@ -106,6 +98,7 @@ range_last(mrb_state *mrb, mrb_value range)
* ('a'..'z').size #=> nil
*/
+#ifndef MRB_WITHOUT_FLOAT
static mrb_value
range_size(mrb_state *mrb, mrb_value range)
{
@@ -158,6 +151,28 @@ range_size(mrb_state *mrb, mrb_value range)
}
return mrb_nil_value();
}
+#else
+static mrb_value
+range_size(mrb_state *mrb, mrb_value range)
+{
+ struct RRange *r = mrb_range_ptr(mrb, range);
+ mrb_value beg, end;
+ mrb_int excl;
+
+ beg = RANGE_BEG(r);
+ end = RANGE_END(r);
+ excl = RANGE_EXCL(r) ? 0 : 1;
+
+ if (mrb_fixnum_p(beg) && mrb_fixnum_p(end)) {
+ mrb_int a = mrb_fixnum(beg);
+ mrb_int b = mrb_fixnum(end);
+ mrb_int c = b - a + excl;
+
+ return mrb_fixnum_value(c);
+ }
+ return mrb_nil_value();
+}
+#endif /* MRB_WITHOUT_FLOAT */
void
mrb_mruby_range_ext_gem_init(mrb_state* mrb)
diff --git a/mrbgems/mruby-range-ext/test/range.rb b/mrbgems/mruby-range-ext/test/range.rb
index efcbdabe4..865e46d02 100644
--- a/mrbgems/mruby-range-ext/test/range.rb
+++ b/mrbgems/mruby-range-ext/test/range.rb
@@ -10,6 +10,8 @@ end
assert('Range#first') do
assert_equal 10, (10..20).first
assert_equal [10, 11, 12], (10..20).first(3)
+
+ skip unless Object.const_defined?(:Float)
assert_equal [0, 1, 2], (0..Float::INFINITY).first(3)
end
@@ -23,10 +25,118 @@ end
assert('Range#size') do
assert_equal 42, (1..42).size
assert_equal 41, (1...42).size
+ assert_nil ('a'..'z').size
+
+ skip unless Object.const_defined?(:Float)
assert_equal 6, (1...6.3).size
assert_equal 5, (1...6.0).size
assert_equal 5, (1.1...6).size
assert_equal 15, (1.0..15.9).size
assert_equal Float::INFINITY, (0..Float::INFINITY).size
- assert_nil ('a'..'z').size
+end
+
+assert('Range#max') do
+ # returns the maximum value in the range when called with no arguments
+ assert_equal 10, (1..10).max
+ assert_equal 9, (1...10).max
+ assert_equal 536870911, (0...2**29).max
+
+ # returns nil when the endpoint is less than the start point
+ assert_equal nil, (100..10).max
+
+ # returns nil when the endpoint equals the start point and the range is exclusive
+ assert_equal nil, (5...5).max
+
+ # returns the endpoint when the endpoint equals the start point and the range is inclusive
+ assert_equal 5, (5..5).max
+
+ skip unless Object.const_defined?(:Float)
+
+ # returns the maximum value in the Float range when called with no arguments
+ assert_equal 908.1111, (303.20..908.1111).max
+
+ # raises TypeError when called on an exclusive range and a non Integer value
+ assert_raise(TypeError) { (303.20...908.1111).max }
+
+ # returns nil when the endpoint is less than the start point in a Float range
+ assert_equal nil, (3003.20..908.1111).max
+end
+
+assert('Range#max given a block') do
+ # passes each pair of values in the range to the block
+ acc = []
+ (1..10).max do |a, b|
+ acc << a
+ acc << b
+ a
+ end
+ (1..10).each do |value|
+ assert_true acc.include?(value)
+ end
+
+ # passes each pair of elements to the block in reversed order
+ acc = []
+ (1..5).max do |a, b|
+ acc << [a, b]
+ a
+ end
+ assert_equal [[2, 1], [3, 2], [4, 3], [5, 4]], acc
+
+ # returns the element the block determines to be the maximum
+ assert_equal 1, ((1..3).max { |_a, _b| -3 })
+
+ # returns nil when the endpoint is less than the start point
+ assert_equal nil, ((100..10).max { |x, y| x <=> y })
+ assert_equal nil, ((5...5).max { |x, y| x <=> y })
+end
+
+assert('Range#min') do
+ # returns the minimum value in the range when called with no arguments
+ assert_equal 1, (1..10).min
+ assert_equal 1, (1...10).min
+
+ # returns nil when the start point is greater than the endpoint
+ assert_equal nil, (100..10).min
+
+ # returns nil when the endpoint equals the start point and the range is exclusive
+ assert_equal nil, (5...5).max
+
+ # returns the endpoint when the endpoint equals the start point and the range is inclusive
+ assert_equal 5, (5..5).max
+
+ skip unless Object.const_defined?(:Float)
+
+ # returns the minimum value in the Float range when called with no arguments
+ assert_equal 303.20, (303.20..908.1111).min
+
+ # returns nil when the start point is greater than the endpoint in a Float range
+ assert_equal nil, (3003.20..908.1111).max
+end
+
+assert('Range#min given a block') do
+ # passes each pair of values in the range to the block
+ acc = []
+ (1..10).min do |a, b|
+ acc << a
+ acc << b
+ a
+ end
+ (1..10).each do |value|
+ assert_true acc.include?(value)
+ end
+
+ # passes each pair of elements to the block in reversed order
+ acc = []
+ (1..5).min do |a, b|
+ acc << [a, b]
+ a
+ end
+ assert_equal [[2, 1], [3, 1], [4, 1], [5, 1]], acc
+
+ # returns the element the block determines to be the minimum
+ assert_equal 3, ((1..3).min { |_a, _b| -3 })
+
+ # returns nil when the start point is greater than the endpoint
+ assert_equal nil, ((100..10).min { |x, y| x <=> y })
+ assert_equal nil, ((5...5).min { |x, y| x <=> y })
end
diff --git a/mrbgems/mruby-rational/mrbgem.rake b/mrbgems/mruby-rational/mrbgem.rake
new file mode 100644
index 000000000..4b540dec4
--- /dev/null
+++ b/mrbgems/mruby-rational/mrbgem.rake
@@ -0,0 +1,5 @@
+MRuby::Gem::Specification.new('mruby-rational') do |spec|
+ spec.license = 'MIT'
+ spec.author = 'mruby developers'
+ spec.summary = 'Rational class'
+end
diff --git a/mrbgems/mruby-rational/mrblib/rational.rb b/mrbgems/mruby-rational/mrblib/rational.rb
new file mode 100644
index 000000000..c0b16a6ae
--- /dev/null
+++ b/mrbgems/mruby-rational/mrblib/rational.rb
@@ -0,0 +1,117 @@
+class Rational < Numeric
+ def inspect
+ "(#{to_s})"
+ end
+
+ def to_s
+ "#{numerator}/#{denominator}"
+ end
+
+ def *(rhs)
+ if rhs.is_a? Rational
+ Rational(numerator * rhs.numerator, denominator * rhs.denominator)
+ elsif rhs.is_a? Integer
+ Rational(numerator * rhs, denominator)
+ elsif rhs.is_a? Numeric
+ numerator * rhs / denominator
+ end
+ end
+
+ def +(rhs)
+ if rhs.is_a? Rational
+ Rational(numerator * rhs.denominator + rhs.numerator * denominator, denominator * rhs.denominator)
+ elsif rhs.is_a? Integer
+ Rational(numerator + rhs * denominator, denominator)
+ elsif rhs.is_a? Numeric
+ (numerator + rhs * denominator) / denominator
+ end
+ end
+
+ def -(rhs)
+ if rhs.is_a? Rational
+ Rational(numerator * rhs.denominator - rhs.numerator * denominator, denominator * rhs.denominator)
+ elsif rhs.is_a? Integer
+ Rational(numerator - rhs * denominator, denominator)
+ elsif rhs.is_a? Numeric
+ (numerator - rhs * denominator) / denominator
+ end
+ end
+
+ def /(rhs)
+ if rhs.is_a? Rational
+ Rational(numerator * rhs.denominator, denominator * rhs.numerator)
+ elsif rhs.is_a? Integer
+ Rational(numerator, denominator * rhs)
+ elsif rhs.is_a? Numeric
+ numerator / rhs / denominator
+ end
+ end
+
+ def <=>(rhs)
+ if rhs.is_a?(Integral)
+ return numerator <=> rhs if denominator == 1
+ rhs = Rational(rhs)
+ end
+
+ case rhs
+ when Rational
+ (numerator * rhs.denominator - denominator * rhs.numerator) <=> 0
+ when Numeric
+ (rhs <=> self)&.-@
+ else
+ nil
+ end
+ end
+
+ def ==(rhs)
+ return true if self.equal?(rhs)
+ if rhs.is_a?(Integral) && denominator == 1
+ return numerator == rhs
+ end
+ if rhs.is_a?(Rational)
+ numerator * rhs.denominator == denominator * rhs.numerator
+ else
+ rhs == self
+ end
+ end
+end
+
+class Numeric
+ def to_r
+ Rational(self, 1)
+ end
+end
+
+module Kernel
+ def Rational(numerator, denominator = 1)
+ a = numerator
+ b = denominator
+ a, b = b, a % b until b == 0
+ Rational._new(numerator.div(a), denominator.div(a))
+ end
+
+ [:+, :-, :*, :/, :<=>, :==, :<, :<=, :>, :>=].each do |op|
+ Fixnum.instance_eval do
+ original_operator_name = "__original_operator_#{op}_rational"
+ alias_method original_operator_name, op
+ define_method op do |rhs|
+ if rhs.is_a? Rational
+ Rational(self).__send__(op, rhs)
+ else
+ __send__(original_operator_name, rhs)
+ end
+ end
+ end
+ Float.instance_eval do
+ original_operator_name = "__original_operator_#{op}_rational"
+ alias_method original_operator_name, op
+ define_method op do |rhs|
+ if rhs.is_a? Rational
+ rhs = rhs.to_f
+ end
+ __send__(original_operator_name, rhs)
+ end
+ end if Object.const_defined?(:Float)
+ end
+end
+
diff --git a/mrbgems/mruby-rational/src/rational.c b/mrbgems/mruby-rational/src/rational.c
new file mode 100644
index 000000000..09bd68003
--- /dev/null
+++ b/mrbgems/mruby-rational/src/rational.c
@@ -0,0 +1,209 @@
+#include <mruby.h>
+#include <mruby/class.h>
+#include <mruby/string.h>
+#include <mruby/numeric.h>
+
+struct mrb_rational {
+ mrb_int numerator;
+ mrb_int denominator;
+};
+
+#if MRB_INT_MAX <= INTPTR_MAX
+
+#define RATIONAL_USE_ISTRUCT
+/* use TT_ISTRUCT */
+#include <mruby/istruct.h>
+
+#define rational_ptr(mrb, v) (struct mrb_rational*)mrb_istruct_ptr(v)
+
+static struct RBasic*
+rational_alloc(mrb_state *mrb, struct RClass *c, struct mrb_rational **p)
+{
+ struct RIStruct *s;
+
+ s = (struct RIStruct*)mrb_obj_alloc(mrb, MRB_TT_ISTRUCT, c);
+ *p = (struct mrb_rational*)s->inline_data;
+
+ return (struct RBasic*)s;
+}
+
+#else
+/* use TT_DATA */
+#include <mruby/data.h>
+
+static const struct mrb_data_type mrb_rational_type = {"Rational", mrb_free};
+
+static struct RBasic*
+rational_alloc(mrb_state *mrb, struct RClass *c, struct mrb_rational **p)
+{
+ struct RData *d;
+
+ Data_Make_Struct(mrb, c, struct mrb_rational, &mrb_rational_type, *p, d);
+
+ return (struct RBasic*)d;
+}
+
+static struct mrb_rational*
+rational_ptr(mrb_state *mrb, mrb_value v)
+{
+ struct mrb_rational *p;
+
+ p = DATA_GET_PTR(mrb, v, &mrb_rational_type, struct mrb_rational);
+ if (!p) {
+ mrb_raise(mrb, E_ARGUMENT_ERROR, "uninitialized rational");
+ }
+ return p;
+}
+#endif
+
+static mrb_value
+rational_numerator(mrb_state *mrb, mrb_value self)
+{
+ struct mrb_rational *p = rational_ptr(mrb, self);
+ return mrb_fixnum_value(p->numerator);
+}
+
+static mrb_value
+rational_denominator(mrb_state *mrb, mrb_value self)
+{
+ struct mrb_rational *p = rational_ptr(mrb, self);
+ return mrb_fixnum_value(p->denominator);
+}
+
+static mrb_value
+rational_new(mrb_state *mrb, mrb_int numerator, mrb_int denominator)
+{
+ struct RClass *c = mrb_class_get(mrb, "Rational");
+ struct mrb_rational *p;
+ struct RBasic *rat = rational_alloc(mrb, c, &p);
+ p->numerator = numerator;
+ p->denominator = denominator;
+ MRB_SET_FROZEN_FLAG(rat);
+ return mrb_obj_value(rat);
+}
+
+static mrb_value
+rational_s_new(mrb_state *mrb, mrb_value self)
+{
+ mrb_int numerator, denominator;
+
+#ifdef MRB_WITHOUT_FLOAT
+ mrb_get_args(mrb, "ii", &numerator, &denominator);
+#else
+
+#define DROP_PRECISION(cond, num, denom) \
+ do { \
+ while (cond) { \
+ num /= 2; \
+ denom /= 2; \
+ } \
+ } while (0)
+
+ mrb_value numv, denomv;
+
+ mrb_get_args(mrb, "oo", &numv, &denomv);
+ if (mrb_fixnum_p(numv)) {
+ numerator = mrb_fixnum(numv);
+
+ if (mrb_fixnum_p(denomv)) {
+ denominator = mrb_fixnum(denomv);
+ }
+ else {
+ mrb_float denomf = mrb_to_flo(mrb, denomv);
+
+ DROP_PRECISION(denomf < MRB_INT_MIN || denomf > MRB_INT_MAX, numerator, denomf);
+ denominator = denomf;
+ }
+ }
+ else {
+ mrb_float numf = mrb_to_flo(mrb, numv);
+
+ if (mrb_fixnum_p(denomv)) {
+ denominator = mrb_fixnum(denomv);
+ }
+ else {
+ mrb_float denomf = mrb_to_flo(mrb, denomv);
+
+ DROP_PRECISION(denomf < MRB_INT_MIN || denomf > MRB_INT_MAX, numf, denomf);
+ denominator = denomf;
+ }
+
+ DROP_PRECISION(numf < MRB_INT_MIN || numf > MRB_INT_MAX, numf, denominator);
+ numerator = numf;
+ }
+#endif
+
+ return rational_new(mrb, numerator, denominator);
+}
+
+#ifndef MRB_WITHOUT_FLOAT
+static mrb_value
+rational_to_f(mrb_state *mrb, mrb_value self)
+{
+ struct mrb_rational *p = rational_ptr(mrb, self);
+ mrb_float f = (mrb_float)p->numerator / (mrb_float)p->denominator;
+
+ return mrb_float_value(mrb, f);
+}
+#endif
+
+static mrb_value
+rational_to_i(mrb_state *mrb, mrb_value self)
+{
+ struct mrb_rational *p = rational_ptr(mrb, self);
+ if (p->denominator == 0) {
+ mrb_raise(mrb, mrb_exc_get(mrb, "StandardError"), "divided by 0");
+ }
+ return mrb_fixnum_value(p->numerator / p->denominator);
+}
+
+static mrb_value
+rational_to_r(mrb_state *mrb, mrb_value self)
+{
+ return self;
+}
+
+static mrb_value
+rational_negative_p(mrb_state *mrb, mrb_value self)
+{
+ struct mrb_rational *p = rational_ptr(mrb, self);
+ if (p->numerator < 0) {
+ return mrb_true_value();
+ }
+ return mrb_false_value();
+}
+
+static mrb_value
+fix_to_r(mrb_state *mrb, mrb_value self)
+{
+ return rational_new(mrb, mrb_fixnum(self), 1);
+}
+
+void mrb_mruby_rational_gem_init(mrb_state *mrb)
+{
+ struct RClass *rat;
+
+ rat = mrb_define_class(mrb, "Rational", mrb_class_get(mrb, "Numeric"));
+#ifdef RATIONAL_USE_ISTRUCT
+ MRB_SET_INSTANCE_TT(rat, MRB_TT_ISTRUCT);
+ mrb_assert(sizeof(struct mrb_rational) < ISTRUCT_DATA_SIZE);
+#else
+ MRB_SET_INSTANCE_TT(rat, MRB_TT_DATA);
+#endif
+ mrb_undef_class_method(mrb, rat, "new");
+ mrb_define_class_method(mrb, rat, "_new", rational_s_new, MRB_ARGS_REQ(2));
+ mrb_define_method(mrb, rat, "numerator", rational_numerator, MRB_ARGS_NONE());
+ mrb_define_method(mrb, rat, "denominator", rational_denominator, MRB_ARGS_NONE());
+#ifndef MRB_WITHOUT_FLOAT
+ mrb_define_method(mrb, rat, "to_f", rational_to_f, MRB_ARGS_NONE());
+#endif
+ mrb_define_method(mrb, rat, "to_i", rational_to_i, MRB_ARGS_NONE());
+ mrb_define_method(mrb, rat, "to_r", rational_to_r, MRB_ARGS_NONE());
+ mrb_define_method(mrb, rat, "negative?", rational_negative_p, MRB_ARGS_NONE());
+ mrb_define_method(mrb, mrb->fixnum_class, "to_r", fix_to_r, MRB_ARGS_NONE());
+}
+
+void
+mrb_mruby_rational_gem_final(mrb_state* mrb)
+{
+}
diff --git a/mrbgems/mruby-rational/test/rational.rb b/mrbgems/mruby-rational/test/rational.rb
new file mode 100644
index 000000000..a8ebb8ea2
--- /dev/null
+++ b/mrbgems/mruby-rational/test/rational.rb
@@ -0,0 +1,308 @@
+class UserDefinedNumeric < Numeric
+ def initialize(n)
+ @n = n
+ end
+
+ def <=>(rhs)
+ return nil unless rhs.respond_to?(:to_i)
+ rhs = rhs.to_i
+ rhs < 0 ? nil : @n <=> rhs
+ end
+
+ def inspect
+ "#{self.class}(#{@n})"
+ end
+end
+
+class ComplexLikeNumeric < UserDefinedNumeric
+ def ==(rhs)
+ @n == 0 && rhs == 0
+ end
+
+ undef <=>
+end
+
+def assert_rational(exp, real)
+ assert "assert_rational" do
+ assert_float exp.numerator, real.numerator
+ assert_float exp.denominator, real.denominator
+ end
+end
+
+def assert_equal_rational(exp, o1, o2)
+ assert "assert_equal_rational" do
+ if exp
+ assert_operator(o1, :==, o2)
+ assert_not_operator(o1, :!=, o2)
+ else
+ assert_not_operator(o1, :==, o2)
+ assert_operator(o1, :!=, o2)
+ end
+ end
+end
+
+def assert_cmp(exp, o1, o2)
+ if exp == (o1 <=> o2)
+ pass
+ else
+ flunk "", " Expected #{o1.inspect} <=> #{o2.inspect} to be #{exp}."
+ end
+end
+
+assert 'Rational' do
+ r = 5r
+ assert_equal(Rational, r.class)
+ assert_equal([5, 1], [r.numerator, r.denominator])
+end
+
+assert 'Kernel#Rational' do
+ r = Rational(4,10)
+ assert_equal(2, r.numerator)
+ assert_equal(5, r.denominator)
+
+ r = Rational(3)
+ assert_equal(3, r.numerator)
+ assert_equal(1, r.denominator)
+
+ assert_raise(ArgumentError) { Rational() }
+ assert_raise(ArgumentError) { Rational(1,2,3) }
+end
+
+assert 'Rational#to_f' do
+ assert_float(2.0, Rational(2).to_f)
+ assert_float(2.25, Rational(9, 4).to_f)
+ assert_float(-0.75, Rational(-3, 4).to_f)
+ assert_float(6.666666666666667, Rational(20, 3).to_f)
+end
+
+assert 'Rational#to_i' do
+ assert_equal(0, Rational(2, 3).to_i)
+ assert_equal(3, Rational(3).to_i)
+ assert_equal(300, Rational(300.6).to_i)
+ assert_equal(1, Rational(98, 71).to_i)
+ assert_equal(-15, Rational(-30, 2).to_i)
+end
+
+assert 'Rational#*' do
+ assert_rational(Rational(4, 9), Rational(2, 3) * Rational(2, 3))
+ assert_rational(Rational(900, 1), Rational(900) * Rational(1))
+ assert_rational(Rational(1, 1), Rational(-2, 9) * Rational(-9, 2))
+ assert_rational(Rational(9, 2), Rational(9, 8) * 4)
+ assert_float( 21.77777777777778, Rational(20, 9) * 9.8)
+end
+
+assert 'Rational#+' do
+ assert_rational(Rational(4, 3), Rational(2, 3) + Rational(2, 3))
+ assert_rational(Rational(901, 1), Rational(900) + Rational(1))
+ assert_rational(Rational(-85, 18), Rational(-2, 9) + Rational(-9, 2))
+ assert_rational(Rational(41, 8), Rational(9, 8) + 4)
+ assert_float( 12.022222222222222, Rational(20, 9) + 9.8)
+end
+
+assert 'Rational#-' do
+ assert_rational(Rational(0, 1), Rational(2, 3) - Rational(2, 3))
+ assert_rational(Rational(899, 1), Rational(900) - Rational(1))
+ assert_rational(Rational(77, 18), Rational(-2, 9) - Rational(-9, 2))
+ assert_rational(Rational(-23, 8), Rational(9, 8) - 4)
+ assert_float( -7.577777777777778, Rational(20, 9) - 9.8)
+end
+
+assert 'Rational#/' do
+ assert_rational(Rational(1, 1), Rational(2, 3) / Rational(2, 3))
+ assert_rational(Rational(900, 1), Rational(900) / Rational(1))
+ assert_rational(Rational(4, 81), Rational(-2, 9) / Rational(-9, 2))
+ assert_rational(Rational(9, 32), Rational(9, 8) / 4)
+ assert_float( 0.22675736961451246, Rational(20, 9) / 9.8)
+end
+
+assert 'Rational#==, Rational#!=' do
+ assert_equal_rational(true, Rational(1,1), Rational(1))
+ assert_equal_rational(true, Rational(-1,1), -1r)
+ assert_equal_rational(true, Rational(13,4), 3.25)
+ assert_equal_rational(true, Rational(13,3.25), Rational(4,1))
+ assert_equal_rational(true, Rational(-3,-4), Rational(3,4))
+ assert_equal_rational(true, Rational(-4,5), Rational(4,-5))
+ assert_equal_rational(true, Rational(4,2), 2)
+ assert_equal_rational(true, Rational(-4,2), -2)
+ assert_equal_rational(true, Rational(4,-2), -2)
+ assert_equal_rational(true, Rational(4,2), 2.0)
+ assert_equal_rational(true, Rational(-4,2), -2.0)
+ assert_equal_rational(true, Rational(4,-2), -2.0)
+ assert_equal_rational(true, Rational(8,6), Rational(4,3))
+ assert_equal_rational(false, Rational(13,4), 3)
+ assert_equal_rational(false, Rational(13,4), 3.3)
+ assert_equal_rational(false, Rational(2,1), 1r)
+ assert_equal_rational(false, Rational(1), nil)
+ assert_equal_rational(false, Rational(1), '')
+ assert_equal_rational(true, 0r, UserDefinedNumeric.new(0))
+ assert_equal_rational(true, 1r, UserDefinedNumeric.new(1))
+ assert_equal_rational(false, 1r, UserDefinedNumeric.new(2))
+ assert_equal_rational(false, -1r, UserDefinedNumeric.new(-1))
+ assert_equal_rational(true, 0r, ComplexLikeNumeric.new(0))
+ assert_equal_rational(false, 1r, ComplexLikeNumeric.new(1))
+ assert_equal_rational(false, 1r, ComplexLikeNumeric.new(2))
+end
+
+assert 'Fixnum#==(Rational), Fixnum#!=(Rational)' do
+ assert_equal_rational(true, 2, Rational(4,2))
+ assert_equal_rational(true, -2, Rational(-4,2))
+ assert_equal_rational(true, -2, Rational(4,-2))
+ assert_equal_rational(false, 3, Rational(13,4))
+end
+
+assert 'Float#==(Rational), Float#!=(Rational)' do
+ assert_equal_rational(true, 2.0, Rational(4,2))
+ assert_equal_rational(true, -2.0, Rational(-4,2))
+ assert_equal_rational(true, -2.0, Rational(4,-2))
+ assert_equal_rational(false, 3.3, Rational(13,4))
+end
+
+assert 'Rational#<=>' do
+ assert_cmp(-1, Rational(-1), Rational(0))
+ assert_cmp(0, Rational(0), Rational(0))
+ assert_cmp(1, Rational(1), Rational(0))
+ assert_cmp(-1, Rational(-1), 0)
+ assert_cmp(0, Rational(0), 0)
+ assert_cmp(1, Rational(1), 0)
+ assert_cmp(-1, Rational(-1), 0.0)
+ assert_cmp(0, Rational(0), 0.0)
+ assert_cmp(1, Rational(1), 0.0)
+ assert_cmp(-1, Rational(1,2), Rational(2,3))
+ assert_cmp(0, Rational(2,3), Rational(2,3))
+ assert_cmp(1, Rational(2,3), Rational(1,2))
+ assert_cmp(1, Rational(2,3), Rational(1,2))
+ assert_cmp(1, Rational(0), Rational(-1))
+ assert_cmp(-1, Rational(0), Rational(1))
+ assert_cmp(1, Rational(2,3), Rational(1,2))
+ assert_cmp(0, Rational(2,3), Rational(2,3))
+ assert_cmp(-1, Rational(1,2), Rational(2,3))
+ assert_cmp(-1, Rational(1,2), Rational(2,3))
+ assert_cmp(nil, 3r, "3")
+ assert_cmp(1, 3r, UserDefinedNumeric.new(2))
+ assert_cmp(0, 3r, UserDefinedNumeric.new(3))
+ assert_cmp(-1, 3r, UserDefinedNumeric.new(4))
+ assert_cmp(nil, Rational(-3), UserDefinedNumeric.new(5))
+ assert_raise(NoMethodError) { 0r <=> ComplexLikeNumeric.new(0) }
+ assert_raise(NoMethodError) { 1r <=> ComplexLikeNumeric.new(2) }
+end
+
+assert 'Fixnum#<=>(Rational)' do
+ assert_cmp(-1, -2, Rational(-9,5))
+ assert_cmp(0, 5, 5r)
+ assert_cmp(1, 3, Rational(8,3))
+end
+
+assert 'Float#<=>(Rational)' do
+ assert_cmp(-1, -2.1, Rational(-9,5))
+ assert_cmp(0, 5.0, 5r)
+ assert_cmp(1, 2.7, Rational(8,3))
+end
+
+assert 'Rational#<' do
+ assert_operator(Rational(1,2), :<, Rational(2,3))
+ assert_not_operator(Rational(2,3), :<, Rational(2,3))
+ assert_operator(Rational(2,3), :<, 1)
+ assert_not_operator(2r, :<, 2)
+ assert_not_operator(Rational(2,3), :<, -3)
+ assert_operator(Rational(-4,3), :<, -0.3)
+ assert_not_operator(Rational(13,4), :<, 3.25)
+ assert_not_operator(Rational(2,3), :<, 0.6)
+ assert_raise(ArgumentError) { 1r < "2" }
+end
+
+assert 'Fixnum#<(Rational)' do
+ assert_not_operator(1, :<, Rational(2,3))
+ assert_not_operator(2, :<, 2r)
+ assert_operator(-3, :<, Rational(2,3))
+end
+
+assert 'Float#<(Rational)' do
+ assert_not_operator(-0.3, :<, Rational(-4,3))
+ assert_not_operator(3.25, :<, Rational(13,4))
+ assert_operator(0.6, :<, Rational(2,3))
+end
+
+assert 'Rational#<=' do
+ assert_operator(Rational(1,2), :<=, Rational(2,3))
+ assert_operator(Rational(2,3), :<=, Rational(2,3))
+ assert_operator(Rational(2,3), :<=, 1)
+ assert_operator(2r, :<=, 2)
+ assert_not_operator(Rational(2,3), :<=, -3)
+ assert_operator(Rational(-4,3), :<=, -0.3)
+ assert_operator(Rational(13,4), :<=, 3.25)
+ assert_not_operator(Rational(2,3), :<=, 0.6)
+ assert_raise(ArgumentError) { 1r <= "2" }
+end
+
+assert 'Fixnum#<=(Rational)' do
+ assert_not_operator(1, :<=, Rational(2,3))
+ assert_operator(2, :<=, 2r)
+ assert_operator(-3, :<=, Rational(2,3))
+end
+
+assert 'Float#<=(Rational)' do
+ assert_not_operator(-0.3, :<=, Rational(-4,3))
+ assert_operator(3.25, :<=, Rational(13,4))
+ assert_operator(0.6, :<=, Rational(2,3))
+end
+
+assert 'Rational#>' do
+ assert_not_operator(Rational(1,2), :>, Rational(2,3))
+ assert_not_operator(Rational(2,3), :>, Rational(2,3))
+ assert_not_operator(Rational(2,3), :>, 1)
+ assert_not_operator(2r, :>, 2)
+ assert_operator(Rational(2,3), :>, -3)
+ assert_not_operator(Rational(-4,3), :>, -0.3)
+ assert_not_operator(Rational(13,4), :>, 3.25)
+ assert_operator(Rational(2,3), :>, 0.6)
+ assert_raise(ArgumentError) { 1r > "2" }
+end
+
+assert 'Fixnum#>(Rational)' do
+ assert_operator(1, :>, Rational(2,3))
+ assert_not_operator(2, :>, 2r)
+ assert_not_operator(-3, :>, Rational(2,3))
+end
+
+assert 'Float#>(Rational)' do
+ assert_operator(-0.3, :>, Rational(-4,3))
+ assert_not_operator(3.25, :>, Rational(13,4))
+ assert_not_operator(0.6, :>, Rational(2,3))
+end
+
+assert 'Rational#>=' do
+ assert_not_operator(Rational(1,2), :>=, Rational(2,3))
+ assert_operator(Rational(2,3), :>=, Rational(2,3))
+ assert_not_operator(Rational(2,3), :>=, 1)
+ assert_operator(2r, :>=, 2)
+ assert_operator(Rational(2,3), :>=, -3)
+ assert_not_operator(Rational(-4,3), :>=, -0.3)
+ assert_operator(Rational(13,4), :>=, 3.25)
+ assert_operator(Rational(2,3), :>=, 0.6)
+ assert_raise(ArgumentError) { 1r >= "2" }
+end
+
+assert 'Fixnum#>=(Rational)' do
+ assert_operator(1, :>=, Rational(2,3))
+ assert_operator(2, :>=, 2r)
+ assert_not_operator(-3, :>=, Rational(2,3))
+end
+
+assert 'Float#>=(Rational)' do
+ assert_operator(-0.3, :>=, Rational(-4,3))
+ assert_operator(3.25, :>=, Rational(13,4))
+ assert_not_operator(0.6, :>=, Rational(2,3))
+end
+
+assert 'Rational#negative?' do
+ assert_predicate(Rational(-2,3), :negative?)
+ assert_predicate(Rational(2,-3), :negative?)
+ assert_not_predicate(Rational(2,3), :negative?)
+ assert_not_predicate(Rational(0), :negative?)
+end
+
+assert 'Rational#frozen?' do
+ assert_predicate(1r, :frozen?)
+ assert_predicate(Rational(2,3), :frozen?)
+ assert_predicate(4/5r, :frozen?)
+end
diff --git a/mrbgems/mruby-sleep/.gitignore b/mrbgems/mruby-sleep/.gitignore
deleted file mode 100644
index b9f9e71df..000000000
--- a/mrbgems/mruby-sleep/.gitignore
+++ /dev/null
@@ -1,4 +0,0 @@
-/mruby
-
-*.so
-*.a \ No newline at end of file
diff --git a/mrbgems/mruby-sleep/.travis.yml b/mrbgems/mruby-sleep/.travis.yml
deleted file mode 100644
index ad6b007b6..000000000
--- a/mrbgems/mruby-sleep/.travis.yml
+++ /dev/null
@@ -1,29 +0,0 @@
-dist: trusty
-
-language: c
-compiler:
- - gcc
- - clang
-env:
- - MRUBY_VERSION=1.2.0
- - MRUBY_VERSION=master
-matrix:
- allow_failures:
- - env: MRUBY_VERSION=master
-branches:
- only:
- - master
-addons:
- apt:
- packages:
- - rake
- - bison
- - git
- - gperf
- # - aclocal
- # - automake
- # - autoconf
- # - autotools-dev
-
-script:
- - rake test \ No newline at end of file
diff --git a/mrbgems/mruby-sleep/.travis_build_config.rb b/mrbgems/mruby-sleep/.travis_build_config.rb
deleted file mode 100644
index b32e38a9d..000000000
--- a/mrbgems/mruby-sleep/.travis_build_config.rb
+++ /dev/null
@@ -1,6 +0,0 @@
-MRuby::Build.new do |conf|
- toolchain :gcc
- conf.gembox 'default'
- conf.gem '../mruby-sleep'
- conf.enable_test
-end
diff --git a/mrbgems/mruby-sleep/Rakefile b/mrbgems/mruby-sleep/Rakefile
deleted file mode 100644
index 5e3c46173..000000000
--- a/mrbgems/mruby-sleep/Rakefile
+++ /dev/null
@@ -1,29 +0,0 @@
-MRUBY_CONFIG=File.expand_path(ENV["MRUBY_CONFIG"] || ".travis_build_config.rb")
-MRUBY_VERSION=ENV["MRUBY_VERSION"] || "1.2.0"
-
-file :mruby do
- cmd = "git clone --depth=1 git://github.com/mruby/mruby.git"
- if MRUBY_VERSION != 'master'
- cmd << " && cd mruby"
- cmd << " && git fetch --tags && git checkout $(git rev-parse #{MRUBY_VERSION})"
- end
- sh cmd
-end
-
-desc "compile binary"
-task :compile => :mruby do
- sh "cd mruby && MRUBY_CONFIG=#{MRUBY_CONFIG} rake all"
-end
-
-desc "test"
-task :test => :mruby do
- sh "cd mruby && MRUBY_CONFIG=#{MRUBY_CONFIG} rake all test"
-end
-
-desc "cleanup"
-task :clean do
- exit 0 unless File.directory?('mruby')
- sh "cd mruby && rake deep_clean"
-end
-
-task :default => :compile
diff --git a/mrbgems/mruby-socket/.travis.yml b/mrbgems/mruby-socket/.travis.yml
deleted file mode 100644
index 6476289bd..000000000
--- a/mrbgems/mruby-socket/.travis.yml
+++ /dev/null
@@ -1,4 +0,0 @@
-language: c
-sudo: false
-script:
- - "ruby run_test.rb all test"
diff --git a/mrbgems/mruby-socket/README.md b/mrbgems/mruby-socket/README.md
index 7428cfa6c..ceb50c651 100644
--- a/mrbgems/mruby-socket/README.md
+++ b/mrbgems/mruby-socket/README.md
@@ -20,7 +20,7 @@ Date: Tue, 21 May 2013 04:31:30 GMT
```
## Requirement
-- [iij/mruby-io](https://github.com/iij/mruby-io) mrbgem
+- [mruby-io](https://github.com/mruby/mruby/tree/master/mrbgems/mruby-io) mrbgem
- [iij/mruby-mtest](https://github.com/iij/mruby-mtest) mrgbem to run tests
- system must have RFC3493 basic socket interface
- and some POSIX API...
diff --git a/mrbgems/mruby-socket/run_test.rb b/mrbgems/mruby-socket/run_test.rb
deleted file mode 100644
index 87a222f16..000000000
--- a/mrbgems/mruby-socket/run_test.rb
+++ /dev/null
@@ -1,28 +0,0 @@
-#!/usr/bin/env ruby
-#
-# mrbgems test runner
-#
-
-if __FILE__ == $0
- repository, dir = 'https://github.com/mruby/mruby.git', 'tmp/mruby'
- build_args = ARGV
-
- Dir.mkdir 'tmp' unless File.exist?('tmp')
- unless File.exist?(dir)
- system "git clone #{repository} #{dir}"
- end
-
- exit system(%Q[cd #{dir}; MRUBY_CONFIG=#{File.expand_path __FILE__} ruby minirake #{build_args.join(' ')}])
-end
-
-MRuby::Build.new do |conf|
- toolchain :gcc
- conf.gembox 'default'
-
- conf.gem :git => 'https://github.com/iij/mruby-mtest.git'
- conf.gem :git => 'https://github.com/iij/mruby-io.git'
- conf.gem :git => 'https://github.com/iij/mruby-pack.git'
-
- conf.gem File.expand_path(File.dirname(__FILE__))
- conf.enable_test
-end
diff --git a/mrbgems/mruby-socket/src/socket.c b/mrbgems/mruby-socket/src/socket.c
index dff176778..53f761617 100644
--- a/mrbgems/mruby-socket/src/socket.c
+++ b/mrbgems/mruby-socket/src/socket.c
@@ -38,9 +38,10 @@
#include "mruby/array.h"
#include "mruby/class.h"
#include "mruby/data.h"
+#include "mruby/numeric.h"
#include "mruby/string.h"
#include "mruby/variable.h"
-#include "error.h"
+#include "mruby/error.h"
#include "mruby/ext/io.h"
@@ -130,7 +131,7 @@ mrb_addrinfo_getaddrinfo(mrb_state *mrb, mrb_value klass)
mrb_get_args(mrb, "oo|oooi", &nodename, &service, &family, &socktype, &protocol, &flags);
if (mrb_string_p(nodename)) {
- hostname = mrb_str_to_cstr(mrb, nodename);
+ hostname = RSTRING_CSTR(mrb, nodename);
} else if (mrb_nil_p(nodename)) {
hostname = NULL;
} else {
@@ -138,9 +139,9 @@ mrb_addrinfo_getaddrinfo(mrb_state *mrb, mrb_value klass)
}
if (mrb_string_p(service)) {
- servname = mrb_str_to_cstr(mrb, service);
+ servname = RSTRING_CSTR(mrb, service);
} else if (mrb_fixnum_p(service)) {
- servname = mrb_str_to_cstr(mrb, mrb_funcall(mrb, service, "to_s", 0));
+ servname = RSTRING_PTR(mrb_fixnum_to_str(mrb, service, 10));
} else if (mrb_nil_p(service)) {
servname = NULL;
} else {
@@ -170,7 +171,7 @@ mrb_addrinfo_getaddrinfo(mrb_state *mrb, mrb_value klass)
error = getaddrinfo(hostname, servname, &hints, &res0);
if (error) {
- mrb_raisef(mrb, E_SOCKET_ERROR, "getaddrinfo: %S", mrb_str_new_cstr(mrb, gai_strerror(error)));
+ mrb_raisef(mrb, E_SOCKET_ERROR, "getaddrinfo: %s", gai_strerror(error));
}
mrb_cv_set(mrb, klass, mrb_intern_lit(mrb, "_lastai"), mrb_cptr_value(mrb, res0));
@@ -205,7 +206,7 @@ mrb_addrinfo_getnameinfo(mrb_state *mrb, mrb_value self)
}
error = getnameinfo((struct sockaddr *)RSTRING_PTR(sastr), (socklen_t)RSTRING_LEN(sastr), RSTRING_PTR(host), NI_MAXHOST, RSTRING_PTR(serv), NI_MAXSERV, (int)flags);
if (error) {
- mrb_raisef(mrb, E_SOCKET_ERROR, "getnameinfo: %S", mrb_str_new_cstr(mrb, gai_strerror(error)));
+ mrb_raisef(mrb, E_SOCKET_ERROR, "getnameinfo: %s", gai_strerror(error));
}
ary = mrb_ary_new_capa(mrb, 2);
mrb_str_resize(mrb, host, strlen(RSTRING_PTR(host)));
@@ -475,7 +476,7 @@ mrb_basicsocket_setsockopt(mrb_state *mrb, mrb_value self)
optname = mrb_fixnum(mrb_funcall(mrb, so, "optname", 0));
optval = mrb_funcall(mrb, so, "data", 0);
} else {
- mrb_raisef(mrb, E_ARGUMENT_ERROR, "wrong number of arguments (%S for 3)", mrb_fixnum_value(argc));
+ mrb_raisef(mrb, E_ARGUMENT_ERROR, "wrong number of arguments (%i for 3)", argc);
}
s = socket_fd(mrb, self);
@@ -701,7 +702,7 @@ mrb_socket_sockaddr_un(mrb_state *mrb, mrb_value klass)
mrb_get_args(mrb, "S", &path);
if ((size_t)RSTRING_LEN(path) > sizeof(sunp->sun_path) - 1) {
- mrb_raisef(mrb, E_ARGUMENT_ERROR, "too long unix socket path (max: %S bytes)", mrb_fixnum_value(sizeof(sunp->sun_path) - 1));
+ mrb_raisef(mrb, E_ARGUMENT_ERROR, "too long unix socket path (max: %d bytes)", (int)sizeof(sunp->sun_path) - 1);
}
s = mrb_str_buf_new(mrb, sizeof(struct sockaddr_un));
sunp = (struct sockaddr_un *)RSTRING_PTR(s);
diff --git a/mrbgems/mruby-socket/test/socket.rb b/mrbgems/mruby-socket/test/socket.rb
index efd8fc28e..b64a67919 100644
--- a/mrbgems/mruby-socket/test/socket.rb
+++ b/mrbgems/mruby-socket/test/socket.rb
@@ -28,7 +28,7 @@ assert('Socket#recvfrom') do
rstr, ai = s.recvfrom sstr.size
assert_equal sstr, rstr
- assert_true "127.0.0.1", ai.ip_address
+ assert_equal "127.0.0.1", ai.ip_address
ensure
s.close rescue nil
c.close rescue nil
diff --git a/mrbgems/mruby-sprintf/src/sprintf.c b/mrbgems/mruby-sprintf/src/sprintf.c
index 985ffe276..c8d51962e 100644
--- a/mrbgems/mruby-sprintf/src/sprintf.c
+++ b/mrbgems/mruby-sprintf/src/sprintf.c
@@ -81,7 +81,7 @@ mrb_fix2binstr(mrb_state *mrb, mrb_value x, int base)
char d;
if (base != 2) {
- mrb_raisef(mrb, E_ARGUMENT_ERROR, "invalid radix %S", mrb_fixnum_value(base));
+ mrb_raisef(mrb, E_ARGUMENT_ERROR, "invalid radix %d", base);
}
if (val == 0) {
return mrb_str_new_lit(mrb, "0");
@@ -144,10 +144,10 @@ check_next_arg(mrb_state *mrb, int posarg, int nextarg)
{
switch (posarg) {
case -1:
- mrb_raisef(mrb, E_ARGUMENT_ERROR, "unnumbered(%S) mixed with numbered", mrb_fixnum_value(nextarg));
+ mrb_raisef(mrb, E_ARGUMENT_ERROR, "unnumbered(%d) mixed with numbered", nextarg);
break;
case -2:
- mrb_raisef(mrb, E_ARGUMENT_ERROR, "unnumbered(%S) mixed with named", mrb_fixnum_value(nextarg));
+ mrb_raisef(mrb, E_ARGUMENT_ERROR, "unnumbered(%d) mixed with named", nextarg);
break;
default:
break;
@@ -158,26 +158,26 @@ static void
check_pos_arg(mrb_state *mrb, mrb_int posarg, mrb_int n)
{
if (posarg > 0) {
- mrb_raisef(mrb, E_ARGUMENT_ERROR, "numbered(%S) after unnumbered(%S)",
- mrb_fixnum_value(n), mrb_fixnum_value(posarg));
+ mrb_raisef(mrb, E_ARGUMENT_ERROR, "numbered(%i) after unnumbered(%i)",
+ n, posarg);
}
if (posarg == -2) {
- mrb_raisef(mrb, E_ARGUMENT_ERROR, "numbered(%S) after named", mrb_fixnum_value(n));
+ mrb_raisef(mrb, E_ARGUMENT_ERROR, "numbered(%i) after named", n);
}
if (n < 1) {
- mrb_raisef(mrb, E_ARGUMENT_ERROR, "invalid index - %S$", mrb_fixnum_value(n));
+ mrb_raisef(mrb, E_ARGUMENT_ERROR, "invalid index - %i$", n);
}
}
static void
-check_name_arg(mrb_state *mrb, int posarg, const char *name, mrb_int len)
+check_name_arg(mrb_state *mrb, int posarg, const char *name, size_t len)
{
if (posarg > 0) {
- mrb_raisef(mrb, E_ARGUMENT_ERROR, "named%S after unnumbered(%S)",
- mrb_str_new(mrb, (name), (len)), mrb_fixnum_value(posarg));
+ mrb_raisef(mrb, E_ARGUMENT_ERROR, "named%l after unnumbered(%d)",
+ name, len, posarg);
}
if (posarg == -1) {
- mrb_raisef(mrb, E_ARGUMENT_ERROR, "named%S after numbered", mrb_str_new(mrb, (name), (len)));
+ mrb_raisef(mrb, E_ARGUMENT_ERROR, "named%l after numbered", name, len);
}
}
@@ -580,7 +580,7 @@ mrb_str_format(mrb_state *mrb, mrb_int argc, const mrb_value *argv, mrb_value fm
retry:
switch (*p) {
default:
- mrb_raisef(mrb, E_ARGUMENT_ERROR, "malformed format string - \\%%S", mrb_str_new(mrb, p, 1));
+ mrb_raisef(mrb, E_ARGUMENT_ERROR, "malformed format string - %%%c", *p);
break;
case ' ':
@@ -619,7 +619,7 @@ retry:
GETNUM(n, width);
if (*p == '$') {
if (!mrb_undef_p(nextvalue)) {
- mrb_raisef(mrb, E_ARGUMENT_ERROR, "value given twice - %S$", mrb_fixnum_value(n));
+ mrb_raisef(mrb, E_ARGUMENT_ERROR, "value given twice - %i$", n);
}
nextvalue = GETPOSARG(n);
p++;
@@ -639,14 +639,14 @@ retry:
for (; p < end && *p != term; )
p++;
if (id) {
- mrb_raisef(mrb, E_ARGUMENT_ERROR, "name%S after <%S>",
- mrb_str_new(mrb, start, p - start + 1), mrb_sym2str(mrb, id));
+ mrb_raisef(mrb, E_ARGUMENT_ERROR, "name%l after <%n>",
+ start, p - start + 1, id);
}
symname = mrb_str_new(mrb, start + 1, p - start - 1);
id = mrb_intern_str(mrb, symname);
- nextvalue = GETNAMEARG(mrb_symbol_value(id), start, (mrb_int)(p - start + 1));
+ nextvalue = GETNAMEARG(mrb_symbol_value(id), start, p - start + 1);
if (mrb_undef_p(nextvalue)) {
- mrb_raisef(mrb, E_KEY_ERROR, "key%S not found", mrb_str_new(mrb, start, p - start + 1));
+ mrb_raisef(mrb, E_KEY_ERROR, "key%l not found", start, p - start + 1);
}
if (term == '}') goto format_s;
p++;
@@ -1089,7 +1089,7 @@ retry:
if (posarg >= 0 && nextarg < argc) {
const char *mesg = "too many arguments for format string";
if (mrb_test(ruby_debug)) mrb_raise(mrb, E_ARGUMENT_ERROR, mesg);
- if (mrb_test(ruby_verbose)) mrb_warn(mrb, "%S", mrb_str_new_cstr(mrb, mesg));
+ if (mrb_test(ruby_verbose)) mrb_warn(mrb, "%s", mesg);
}
#endif
mrb_str_resize(mrb, result, blen);
diff --git a/mrbgems/mruby-string-ext/mrbgem.rake b/mrbgems/mruby-string-ext/mrbgem.rake
index 9812f2cc9..f2df5a783 100644
--- a/mrbgems/mruby-string-ext/mrbgem.rake
+++ b/mrbgems/mruby-string-ext/mrbgem.rake
@@ -2,5 +2,4 @@ MRuby::Gem::Specification.new('mruby-string-ext') do |spec|
spec.license = 'MIT'
spec.author = 'mruby developers'
spec.summary = 'String class extension'
- spec.add_test_dependency 'mruby-enumerator', core: 'mruby-enumerator'
end
diff --git a/mrbgems/mruby-string-ext/mrblib/string.rb b/mrbgems/mruby-string-ext/mrblib/string.rb
index 2a323c858..e57d75355 100644
--- a/mrbgems/mruby-string-ext/mrblib/string.rb
+++ b/mrbgems/mruby-string-ext/mrblib/string.rb
@@ -93,7 +93,7 @@ class String
# "hello".rstrip! #=> nil
#
def rstrip!
- raise RuntimeError, "can't modify frozen String" if frozen?
+ raise FrozenError, "can't modify frozen String" if frozen?
s = self.rstrip
(s == self) ? nil : self.replace(s)
end
@@ -310,11 +310,15 @@ class String
end
end
+ ##
+ # Call the given block for each character of
+ # +self+.
def each_char(&block)
return to_enum :each_char unless block
-
- split('').each do |i|
- block.call(i)
+ pos = 0
+ while pos < self.size
+ block.call(self[pos])
+ pos += 1
end
self
end
@@ -410,7 +414,7 @@ class String
e = max.ord
while c <= e
break if exclusive and c == e
- yield c.chr
+ yield c.chr(__ENCODING__)
c += 1
end
return self
diff --git a/mrbgems/mruby-string-ext/src/string.c b/mrbgems/mruby-string-ext/src/string.c
index ba7e3c610..f1d31888d 100644
--- a/mrbgems/mruby-string-ext/src/string.c
+++ b/mrbgems/mruby-string-ext/src/string.c
@@ -5,82 +5,90 @@
#include <mruby/string.h>
#include <mruby/range.h>
-static mrb_value
-mrb_str_getbyte(mrb_state *mrb, mrb_value str)
-{
- mrb_int pos;
- mrb_get_args(mrb, "i", &pos);
+#define ENC_ASCII_8BIT "ASCII-8BIT"
+#define ENC_BINARY "BINARY"
+#define ENC_UTF8 "UTF-8"
- if (pos < 0)
- pos += RSTRING_LEN(str);
- if (pos < 0 || RSTRING_LEN(str) <= pos)
- return mrb_nil_value();
+#define ENC_COMP_P(enc, enc_lit) \
+ str_casecmp_p(RSTRING_PTR(enc), RSTRING_LEN(enc), enc_lit, sizeof(enc_lit"")-1)
+
+#ifdef MRB_WITHOUT_FLOAT
+# define mrb_float_p(o) FALSE
+#endif
- return mrb_fixnum_value((unsigned char)RSTRING_PTR(str)[pos]);
+static mrb_bool
+str_casecmp_p(const char *s1, mrb_int len1, const char *s2, mrb_int len2)
+{
+ const char *e1, *e2;
+
+ if (len1 != len2) return FALSE;
+ e1 = s1 + len1;
+ e2 = s2 + len2;
+ while (s1 < e1 && s2 < e2) {
+ if (*s1 != *s2 && TOUPPER(*s1) != TOUPPER(*s2)) return FALSE;
+ ++s1;
+ ++s2;
+ }
+ return TRUE;
}
static mrb_value
-mrb_str_setbyte(mrb_state *mrb, mrb_value str)
+int_chr_binary(mrb_state *mrb, mrb_value num)
{
- mrb_int pos, byte;
- mrb_int len;
-
- mrb_get_args(mrb, "ii", &pos, &byte);
-
- len = RSTRING_LEN(str);
- if (pos < -len || len <= pos)
- mrb_raisef(mrb, E_INDEX_ERROR, "index %S is out of array", mrb_fixnum_value(pos));
- if (pos < 0)
- pos += len;
+ mrb_int cp = mrb_int(mrb, num);
+ char c;
+ mrb_value str;
- mrb_str_modify(mrb, mrb_str_ptr(str));
- byte &= 0xff;
- RSTRING_PTR(str)[pos] = (unsigned char)byte;
- return mrb_fixnum_value((unsigned char)byte);
+ if (cp < 0 || 0xff < cp) {
+ mrb_raisef(mrb, E_RANGE_ERROR, "%v out of char range", num);
+ }
+ c = (char)cp;
+ str = mrb_str_new(mrb, &c, 1);
+ RSTR_SET_ASCII_FLAG(mrb_str_ptr(str));
+ return str;
}
+#ifdef MRB_UTF8_STRING
static mrb_value
-mrb_str_byteslice(mrb_state *mrb, mrb_value str)
+int_chr_utf8(mrb_state *mrb, mrb_value num)
{
- mrb_value a1;
+ mrb_int cp = mrb_int(mrb, num);
+ char utf8[4];
mrb_int len;
+ mrb_value str;
+ uint32_t ascii_flag = 0;
- if (mrb_get_argc(mrb) == 2) {
- mrb_int pos;
- mrb_get_args(mrb, "ii", &pos, &len);
- return mrb_str_substr(mrb, str, pos, len);
+ if (cp < 0 || 0x10FFFF < cp) {
+ mrb_raisef(mrb, E_RANGE_ERROR, "%v out of char range", num);
}
- mrb_get_args(mrb, "o|i", &a1, &len);
- switch (mrb_type(a1)) {
- case MRB_TT_RANGE:
- {
- mrb_int beg;
-
- len = RSTRING_LEN(str);
- switch (mrb_range_beg_len(mrb, a1, &beg, &len, len, TRUE)) {
- case 0: /* not range */
- break;
- case 1: /* range */
- return mrb_str_substr(mrb, str, beg, len);
- case 2: /* out of range */
- mrb_raisef(mrb, E_RANGE_ERROR, "%S out of range", a1);
- break;
- }
- return mrb_nil_value();
- }
-#ifndef MRB_WITHOUT_FLOAT
- case MRB_TT_FLOAT:
- a1 = mrb_fixnum_value((mrb_int)mrb_float(a1));
- /* fall through */
-#endif
- case MRB_TT_FIXNUM:
- return mrb_str_substr(mrb, str, mrb_fixnum(a1), 1);
- default:
- mrb_raise(mrb, E_TYPE_ERROR, "wrong type of argument");
+ if (cp < 0x80) {
+ utf8[0] = (char)cp;
+ len = 1;
+ ascii_flag = MRB_STR_ASCII;
}
- /* not reached */
- return mrb_nil_value();
+ else if (cp < 0x800) {
+ utf8[0] = (char)(0xC0 | (cp >> 6));
+ utf8[1] = (char)(0x80 | (cp & 0x3F));
+ len = 2;
+ }
+ else if (cp < 0x10000) {
+ utf8[0] = (char)(0xE0 | (cp >> 12));
+ utf8[1] = (char)(0x80 | ((cp >> 6) & 0x3F));
+ utf8[2] = (char)(0x80 | ( cp & 0x3F));
+ len = 3;
+ }
+ else {
+ utf8[0] = (char)(0xF0 | (cp >> 18));
+ utf8[1] = (char)(0x80 | ((cp >> 12) & 0x3F));
+ utf8[2] = (char)(0x80 | ((cp >> 6) & 0x3F));
+ utf8[3] = (char)(0x80 | ( cp & 0x3F));
+ len = 4;
+ }
+ str = mrb_str_new(mrb, utf8, len);
+ mrb_str_ptr(str)->flags |= ascii_flag;
+ return str;
}
+#endif
/*
* call-seq:
@@ -137,8 +145,6 @@ mrb_str_swapcase(mrb_state *mrb, mrb_value self)
return str;
}
-static mrb_value mrb_fixnum_chr(mrb_state *mrb, mrb_value num);
-
/*
* call-seq:
* str << integer -> str
@@ -148,7 +154,8 @@ static mrb_value mrb_fixnum_chr(mrb_state *mrb, mrb_value num);
*
* Append---Concatenates the given object to <i>str</i>. If the object is a
* <code>Integer</code>, it is considered as a codepoint, and is converted
- * to a character before concatenation.
+ * to a character before concatenation
+ * (equivalent to <code>str.concat(integer.chr(__ENCODING__))</code>).
*
* a = "hello "
* a << "world" #=> "hello world"
@@ -160,8 +167,12 @@ mrb_str_concat_m(mrb_state *mrb, mrb_value self)
mrb_value str;
mrb_get_args(mrb, "o", &str);
- if (mrb_fixnum_p(str))
- str = mrb_fixnum_chr(mrb, str);
+ if (mrb_fixnum_p(str) || mrb_float_p(str))
+#ifdef MRB_UTF8_STRING
+ str = int_chr_utf8(mrb, str);
+#else
+ str = int_chr_binary(mrb, str);
+#endif
else
str = mrb_ensure_string_type(mrb, str);
mrb_str_concat(mrb, self, str);
@@ -507,8 +518,7 @@ str_tr(mrb_state *mrb, mrb_value str, mrb_value p1, mrb_value p2, mrb_bool squee
continue;
}
if (c > 0x80) {
- mrb_raisef(mrb, E_ARGUMENT_ERROR, "character (%S) out of range",
- mrb_fixnum_value((mrb_int)c));
+ mrb_raisef(mrb, E_ARGUMENT_ERROR, "character (%i) out of range", c);
}
lastch = c;
s[i] = (char)c;
@@ -812,7 +822,7 @@ mrb_str_count(mrb_state *mrb, mrb_value str)
tr_parse_pattern(mrb, &pat, v_pat, TRUE);
tr_compile_pattern(&pat, v_pat, bitmap);
tr_free_pattern(mrb, &pat);
-
+
s = RSTRING_PTR(str);
len = RSTRING_LEN(str);
for (i = 0; i < len; i++) {
@@ -848,49 +858,42 @@ mrb_str_chr(mrb_state *mrb, mrb_value self)
return mrb_str_substr(mrb, self, 0, 1);
}
+/*
+ * call-seq:
+ * int.chr([encoding]) -> string
+ *
+ * Returns a string containing the character represented by the +int+'s value
+ * according to +encoding+. +"ASCII-8BIT"+ (+"BINARY"+) and +"UTF-8"+ (only
+ * with +MRB_UTF8_STRING+) can be specified as +encoding+ (default is
+ * +"ASCII-8BIT"+).
+ *
+ * 65.chr #=> "A"
+ * 230.chr #=> "\xE6"
+ * 230.chr("ASCII-8BIT") #=> "\xE6"
+ * 230.chr("UTF-8") #=> "\u00E6"
+ */
static mrb_value
-mrb_fixnum_chr(mrb_state *mrb, mrb_value num)
+mrb_int_chr(mrb_state *mrb, mrb_value num)
{
- mrb_int cp = mrb_fixnum(num);
-#ifdef MRB_UTF8_STRING
- char utf8[4];
- mrb_int len;
-
- if (cp < 0 || 0x10FFFF < cp) {
- mrb_raisef(mrb, E_RANGE_ERROR, "%S out of char range", num);
- }
- if (cp < 0x80) {
- utf8[0] = (char)cp;
- len = 1;
+ mrb_value enc;
+ mrb_bool enc_given;
+
+ mrb_get_args(mrb, "|S?", &enc, &enc_given);
+ if (!enc_given ||
+ ENC_COMP_P(enc, ENC_ASCII_8BIT) ||
+ ENC_COMP_P(enc, ENC_BINARY)) {
+ return int_chr_binary(mrb, num);
}
- else if (cp < 0x800) {
- utf8[0] = (char)(0xC0 | (cp >> 6));
- utf8[1] = (char)(0x80 | (cp & 0x3F));
- len = 2;
- }
- else if (cp < 0x10000) {
- utf8[0] = (char)(0xE0 | (cp >> 12));
- utf8[1] = (char)(0x80 | ((cp >> 6) & 0x3F));
- utf8[2] = (char)(0x80 | ( cp & 0x3F));
- len = 3;
+#ifdef MRB_UTF8_STRING
+ else if (ENC_COMP_P(enc, ENC_UTF8)) {
+ return int_chr_utf8(mrb, num);
}
+#endif
else {
- utf8[0] = (char)(0xF0 | (cp >> 18));
- utf8[1] = (char)(0x80 | ((cp >> 12) & 0x3F));
- utf8[2] = (char)(0x80 | ((cp >> 6) & 0x3F));
- utf8[3] = (char)(0x80 | ( cp & 0x3F));
- len = 4;
- }
- return mrb_str_new(mrb, utf8, len);
-#else
- char c;
-
- if (cp < 0 || 0xff < cp) {
- mrb_raisef(mrb, E_RANGE_ERROR, "%S out of char range", num);
+ mrb_raisef(mrb, E_ARGUMENT_ERROR, "unknown encoding name - %v", enc);
}
- c = (char)cp;
- return mrb_str_new(mrb, &c, 1);
-#endif
+ /* not reached */
+ return mrb_nil_value();
}
/*
@@ -1078,7 +1081,7 @@ mrb_str_del_prefix_bang(mrb_state *mrb, mrb_value self)
if (plen > slen) return mrb_nil_value();
s = RSTR_PTR(str);
if (memcmp(s, ptr, plen) != 0) return mrb_nil_value();
- if (!MRB_FROZEN_P(str) && (RSTR_SHARED_P(str) || RSTR_FSHARED_P(str))) {
+ if (!mrb_frozen_p(str) && (RSTR_SHARED_P(str) || RSTR_FSHARED_P(str))) {
str->as.heap.ptr += plen;
}
else {
@@ -1135,7 +1138,7 @@ mrb_str_del_suffix_bang(mrb_state *mrb, mrb_value self)
if (plen > slen) return mrb_nil_value();
s = RSTR_PTR(str);
if (memcmp(s+slen-plen, ptr, plen) != 0) return mrb_nil_value();
- if (!MRB_FROZEN_P(str) && (RSTR_SHARED_P(str) || RSTR_FSHARED_P(str))) {
+ if (!mrb_frozen_p(str) && (RSTR_SHARED_P(str) || RSTR_FSHARED_P(str))) {
/* no need to modify string */
}
else {
@@ -1199,9 +1202,6 @@ mrb_mruby_string_ext_gem_init(mrb_state* mrb)
struct RClass * s = mrb->string_class;
mrb_define_method(mrb, s, "dump", mrb_str_dump, MRB_ARGS_NONE());
- mrb_define_method(mrb, s, "getbyte", mrb_str_getbyte, MRB_ARGS_REQ(1));
- mrb_define_method(mrb, s, "setbyte", mrb_str_setbyte, MRB_ARGS_REQ(2));
- mrb_define_method(mrb, s, "byteslice", mrb_str_byteslice, MRB_ARGS_REQ(1)|MRB_ARGS_OPT(1));
mrb_define_method(mrb, s, "swapcase!", mrb_str_swapcase_bang, MRB_ARGS_NONE());
mrb_define_method(mrb, s, "swapcase", mrb_str_swapcase, MRB_ARGS_NONE());
mrb_define_method(mrb, s, "concat", mrb_str_concat_m, MRB_ARGS_REQ(1));
@@ -1231,7 +1231,8 @@ mrb_mruby_string_ext_gem_init(mrb_state* mrb)
mrb_define_method(mrb, s, "delete_suffix", mrb_str_del_suffix, MRB_ARGS_REQ(1));
mrb_define_method(mrb, s, "__lines", mrb_str_lines, MRB_ARGS_NONE());
- mrb_define_method(mrb, mrb->fixnum_class, "chr", mrb_fixnum_chr, MRB_ARGS_NONE());
+
+ mrb_define_method(mrb, mrb_module_get(mrb, "Integral"), "chr", mrb_int_chr, MRB_ARGS_OPT(1));
}
void
diff --git a/mrbgems/mruby-string-ext/test/numeric.rb b/mrbgems/mruby-string-ext/test/numeric.rb
new file mode 100644
index 000000000..dfcb9ebf4
--- /dev/null
+++ b/mrbgems/mruby-string-ext/test/numeric.rb
@@ -0,0 +1,29 @@
+# coding: utf-8
+
+assert('Integer#chr') do
+ assert_equal("A", 65.chr)
+ assert_equal("B", 0x42.chr)
+ assert_equal("\xab", 171.chr)
+ assert_raise(RangeError) { -1.chr }
+ assert_raise(RangeError) { 256.chr }
+
+ assert_equal("A", 65.chr("ASCII-8BIT"))
+ assert_equal("B", 0x42.chr("BINARY"))
+ assert_equal("\xab", 171.chr("ascii-8bit"))
+ assert_raise(RangeError) { -1.chr("binary") }
+ assert_raise(RangeError) { 256.chr("Ascii-8bit") }
+ assert_raise(ArgumentError) { 65.chr("ASCII") }
+ assert_raise(ArgumentError) { 65.chr("ASCII-8BIT", 2) }
+ assert_raise(TypeError) { 65.chr(:BINARY) }
+
+ if __ENCODING__ == "ASCII-8BIT"
+ assert_raise(ArgumentError) { 65.chr("UTF-8") }
+ else
+ assert_equal("A", 65.chr("UTF-8"))
+ assert_equal("B", 0x42.chr("UTF-8"))
+ assert_equal("«", 171.chr("utf-8"))
+ assert_equal("あ", 12354.chr("Utf-8"))
+ assert_raise(RangeError) { -1.chr("utf-8") }
+ assert_raise(RangeError) { 0x110000.chr.chr("UTF-8") }
+ end
+end
diff --git a/mrbgems/mruby-string-ext/test/range.rb b/mrbgems/mruby-string-ext/test/range.rb
new file mode 100644
index 000000000..80c286850
--- /dev/null
+++ b/mrbgems/mruby-string-ext/test/range.rb
@@ -0,0 +1,26 @@
+assert('Range#max') do
+ # returns the maximum value in the range when called with no arguments
+ assert_equal 'l', ('f'..'l').max
+ assert_equal 'e', ('a'...'f').max
+
+ # returns nil when the endpoint is less than the start point
+ assert_equal nil, ('z'..'l').max
+end
+
+assert('Range#max given a block') do
+ # returns nil when the endpoint is less than the start point
+ assert_equal nil, (('z'..'l').max { |x, y| x <=> y })
+end
+
+assert('Range#min') do
+ # returns the minimum value in the range when called with no arguments
+ assert_equal 'f', ('f'..'l').min
+
+ # returns nil when the start point is greater than the endpoint
+ assert_equal nil, ('z'..'l').min
+end
+
+assert('Range#min given a block') do
+ # returns nil when the start point is greater than the endpoint
+ assert_equal nil, (('z'..'l').min { |x, y| x <=> y })
+end
diff --git a/mrbgems/mruby-string-ext/test/string.rb b/mrbgems/mruby-string-ext/test/string.rb
index 7c96ab694..6914fe31d 100644
--- a/mrbgems/mruby-string-ext/test/string.rb
+++ b/mrbgems/mruby-string-ext/test/string.rb
@@ -2,93 +2,81 @@
##
# String(Ext) Test
-UTF8STRING = ("\343\201\202".size == 1)
+UTF8STRING = __ENCODING__ == "UTF-8"
-assert('String#getbyte') do
- str1 = "hello"
- bytes1 = [104, 101, 108, 108, 111]
- assert_equal bytes1[0], str1.getbyte(0)
- assert_equal bytes1[-1], str1.getbyte(-1)
- assert_equal bytes1[6], str1.getbyte(6)
-
- str2 = "\xFF"
- bytes2 = [0xFF]
- assert_equal bytes2[0], str2.getbyte(0)
-end
-
-assert('String#setbyte') do
- str1 = "hello"
- h = "H".getbyte(0)
- str1.setbyte(0, h)
- assert_equal(h, str1.getbyte(0))
- assert_equal("Hello", str1)
-end
-
-assert('String#byteslice') do
- str1 = "hello"
- assert_equal("e", str1.byteslice(1))
- assert_equal("o", str1.byteslice(-1))
- assert_equal("ell", str1.byteslice(1..3))
- assert_equal("el", str1.byteslice(1...3))
+def assert_upto(exp, receiver, *args)
+ act = []
+ receiver.upto(*args) { |v| act << v }
+ assert_equal exp, act
end
assert('String#dump') do
- ("\1" * 100).dump # should not raise an exception - regress #1210
- "\0".inspect == "\"\\000\"" and
- "foo".dump == "\"foo\""
+ assert_equal("\"\\x00\"", "\0".dump)
+ assert_equal("\"foo\"", "foo".dump)
+ assert_nothing_raised { ("\1" * 100).dump } # regress #1210
end
assert('String#strip') do
s = " abc "
- "".strip == "" and " \t\r\n\f\v".strip == "" and
- "\0a\0".strip == "\0a" and
- "abc".strip == "abc" and
- " abc".strip == "abc" and
- "abc ".strip == "abc" and
- " abc ".strip == "abc" and
- s == " abc "
+ assert_equal("abc", s.strip)
+ assert_equal(" abc ", s)
+ assert_equal("", "".strip)
+ assert_equal("", " \t\r\n\f\v".strip)
+ assert_equal("\0a", "\0a\0".strip)
+ assert_equal("abc", "abc".strip)
+ assert_equal("abc", " abc".strip)
+ assert_equal("abc", "abc ".strip)
end
assert('String#lstrip') do
s = " abc "
- s.lstrip
- "".lstrip == "" and " \t\r\n\f\v".lstrip == "" and
- "\0a\0".lstrip == "\0a\0" and
- "abc".lstrip == "abc" and
- " abc".lstrip == "abc" and
- "abc ".lstrip == "abc " and
- " abc ".lstrip == "abc " and
- s == " abc "
+ assert_equal("abc ", s.lstrip)
+ assert_equal(" abc ", s)
+ assert_equal("", "".lstrip)
+ assert_equal("", " \t\r\n\f\v".lstrip)
+ assert_equal("\0a\0", "\0a\0".lstrip)
+ assert_equal("abc", "abc".lstrip)
+ assert_equal("abc", " abc".lstrip)
+ assert_equal("abc ", "abc ".lstrip)
end
assert('String#rstrip') do
s = " abc "
- s.rstrip
- "".rstrip == "" and " \t\r\n\f\v".rstrip == "" and
- "\0a\0".rstrip == "\0a" and
- "abc".rstrip == "abc" and
- " abc".rstrip == " abc" and
- "abc ".rstrip == "abc" and
- " abc ".rstrip == " abc" and
- s == " abc "
+ assert_equal(" abc", s.rstrip)
+ assert_equal(" abc ", s)
+ assert_equal("", "".rstrip)
+ assert_equal("", " \t\r\n\f\v".rstrip)
+ assert_equal("\0a", "\0a\0".rstrip)
+ assert_equal("abc", "abc".rstrip)
+ assert_equal(" abc", " abc".rstrip)
+ assert_equal("abc", "abc ".rstrip)
end
assert('String#strip!') do
s = " abc "
t = "abc"
- s.strip! == "abc" and s == "abc" and t.strip! == nil
+ assert_equal("abc", s.strip!)
+ assert_equal("abc", s)
+ assert_nil(t.strip!)
+ assert_equal("abc", t)
end
assert('String#lstrip!') do
s = " abc "
t = "abc "
- s.lstrip! == "abc " and s == "abc " and t.lstrip! == nil
+ assert_equal("abc ", s.lstrip!)
+ assert_equal("abc ", s)
+ assert_nil(t.lstrip!)
+ assert_equal("abc ", t)
end
assert('String#rstrip!') do
s = " abc "
t = " abc"
- s.rstrip! == " abc" and s == " abc" and t.rstrip! == nil
+ assert_equal(" abc", s.rstrip!)
+ assert_equal(" abc", s)
+ assert_nil(t.rstrip!)
+ assert_equal(" abc", t)
end
assert('String#swapcase') do
@@ -106,8 +94,15 @@ end
assert('String#concat') do
assert_equal "Hello World!", "Hello " << "World" << 33
assert_equal "Hello World!", "Hello ".concat("World").concat(33)
-
assert_raise(TypeError) { "".concat(Object.new) }
+
+ if UTF8STRING
+ assert_equal "H«", "H" << 0xab
+ assert_equal "Hは", "H" << 12399
+ else
+ assert_equal "H\xab", "H" << 0xab
+ assert_raise(RangeError) { "H" << 12399 }
+ end
end
assert('String#casecmp') do
@@ -127,7 +122,7 @@ assert('String#count') do
assert_equal 4, s.count("a0-9")
end
-assert('String#tr') do
+assert('String#tr') do
assert_equal "ABC", "abc".tr('a-z', 'A-Z')
assert_equal "hippo", "hello".tr('el', 'ip')
assert_equal "Ruby", "Lisp".tr("Lisp", "Ruby")
@@ -141,7 +136,7 @@ assert('String#tr!') do
assert_equal "ab12222hijklmnopqR", s
end
-assert('String#tr_s') do
+assert('String#tr_s') do
assert_equal "hero", "hello".tr_s('l', 'r')
assert_equal "h*o", "hello".tr_s('el', '*')
assert_equal "hhxo", "hello".tr_s('el', 'hx')
@@ -237,12 +232,6 @@ assert('String#oct') do
assert_equal (-8), "-10".oct
end
-assert('String#chr') do
- assert_equal "a", "abcde".chr
- # test Fixnum#chr as well
- assert_equal "a", 97.chr
-end
-
assert('String#lines') do
assert_equal ["Hel\n", "lo\n", "World!"], "Hel\nlo\nWorld!".lines
assert_equal ["Hel\n", "lo\n", "World!\n"], "Hel\nlo\nWorld!\n".lines
@@ -529,16 +518,15 @@ assert('String#rjust should raise on zero width padding') do
end
assert('String#upto') do
- assert_equal %w(a8 a9 b0 b1 b2 b3 b4 b5 b6), "a8".upto("b6").to_a
- assert_equal ["9", "10", "11"], "9".upto("11").to_a
- assert_equal [], "25".upto("5").to_a
- assert_equal ["07", "08", "09", "10", "11"], "07".upto("11").to_a
-
-if UTF8STRING
- assert_equal ["あ", "ぃ", "い", "ぅ", "う", "ぇ", "え", "ぉ", "お"], "あ".upto("お").to_a
-end
-
- assert_equal ["9", ":", ";", "<", "=", ">", "?", "@", "A"], "9".upto("A").to_a
+ assert_upto %w(a8 a9 b0 b1 b2 b3 b4 b5 b6), "a8", "b6"
+ assert_upto ["9", "10", "11"], "9", "11"
+ assert_upto [], "25", "5"
+ assert_upto ["07", "08", "09", "10", "11"], "07", "11"
+ assert_upto ["9", ":", ";", "<", "=", ">", "?", "@", "A"], "9", "A"
+
+ if UTF8STRING
+ assert_upto %w(あ ぃ い ぅ う ぇ え ぉ お), "あ", "お"
+ end
a = "aa"
start = "aa"
@@ -620,8 +608,11 @@ assert('String#ord(UTF-8)') do
end if UTF8STRING
assert('String#chr') do
+ assert_equal "a", "abcde".chr
assert_equal "h", "hello!".chr
+ assert_equal "", "".chr
end
+
assert('String#chr(UTF-8)') do
assert_equal "こ", "こんにちは世界!".chr
end if UTF8STRING
@@ -647,19 +638,19 @@ assert('String#chars(UTF-8)') do
end if UTF8STRING
assert('String#each_char') do
- s = ""
+ chars = []
"hello!".each_char do |x|
- s += x
+ chars << x
end
- assert_equal "hello!", s
+ assert_equal ["h", "e", "l", "l", "o", "!"], chars
end
assert('String#each_char(UTF-8)') do
- s = ""
+ chars = []
"こんにちは世界!".each_char do |x|
- s += x
+ chars << x
end
- assert_equal "こんにちは世界!", s
+ assert_equal ["こ", "ん", "に", "ち", "は", "世", "界", "!"], chars
end if UTF8STRING
assert('String#codepoints') do
diff --git a/mrbgems/mruby-struct/mrblib/struct.rb b/mrbgems/mruby-struct/mrblib/struct.rb
index 7cf3dd3ab..7682ac033 100644
--- a/mrbgems/mruby-struct/mrblib/struct.rb
+++ b/mrbgems/mruby-struct/mrblib/struct.rb
@@ -46,7 +46,9 @@ if Object.const_defined?(:Struct)
ary
end
- def _inspect
+ def _inspect(recur_list)
+ return "#<struct #{self.class}:...>" if recur_list[self.object_id]
+ recur_list[self.object_id] = true
name = self.class.to_s
if name[0] == "#"
str = "#<struct "
@@ -55,7 +57,7 @@ if Object.const_defined?(:Struct)
end
buf = []
self.each_pair do |k,v|
- buf.push [k.to_s + "=" + v._inspect]
+ buf.push [k.to_s + "=" + v._inspect(recur_list)]
end
str + buf.join(", ") + ">"
end
@@ -70,34 +72,29 @@ if Object.const_defined?(:Struct)
# 15.2.18.4.10(x)
#
def inspect
- begin
- self._inspect
- rescue SystemStackError
- "#<struct #{self.class.to_s}:...>"
- end
+ self._inspect({})
end
##
# 15.2.18.4.11(x)
#
alias to_s inspect
- end
- ##
- # call-seq:
- # hsh.dig(key,...) -> object
- #
- # Extracts the nested value specified by the sequence of <i>key</i>
- # objects by calling +dig+ at each step, returning +nil+ if any
- # intermediate step is +nil+.
- #
- def dig(idx,*args)
- n = self[idx]
- if args.size > 0
- n&.dig(*args)
- else
- n
+ ##
+ # call-seq:
+ # hsh.dig(key,...) -> object
+ #
+ # Extracts the nested value specified by the sequence of <i>key</i>
+ # objects by calling +dig+ at each step, returning +nil+ if any
+ # intermediate step is +nil+.
+ #
+ def dig(idx,*args)
+ n = self[idx]
+ if args.size > 0
+ n&.dig(*args)
+ else
+ n
+ end
end
end
end
-
diff --git a/mrbgems/mruby-struct/src/struct.c b/mrbgems/mruby-struct/src/struct.c
index 832583f35..ebe711ed3 100644
--- a/mrbgems/mruby-struct/src/struct.c
+++ b/mrbgems/mruby-struct/src/struct.c
@@ -66,8 +66,8 @@ struct_members(mrb_state *mrb, mrb_value s)
}
else {
mrb_raisef(mrb, E_TYPE_ERROR,
- "struct size differs (%S required %S given)",
- mrb_fixnum_value(RARRAY_LEN(members)), mrb_fixnum_value(RSTRUCT_LEN(s)));
+ "struct size differs (%i required %i given)",
+ RARRAY_LEN(members), RSTRUCT_LEN(s));
}
}
return members;
@@ -87,10 +87,7 @@ mrb_struct_s_members_m(mrb_state *mrb, mrb_value klass)
static void
mrb_struct_modify(mrb_state *mrb, mrb_value strct)
{
- if (MRB_FROZEN_P(mrb_basic_ptr(strct))) {
- mrb_raise(mrb, E_FROZEN_ERROR, "can't modify frozen struct");
- }
-
+ mrb_check_frozen(mrb, mrb_basic_ptr(strct));
mrb_write_barrier(mrb, mrb_basic_ptr(strct));
}
@@ -126,19 +123,29 @@ mrb_struct_ref(mrb_state *mrb, mrb_value obj)
static mrb_sym
mrb_id_attrset(mrb_state *mrb, mrb_sym id)
{
+#define ONSTACK_ALLOC_MAX 32
+#define ONSTACK_STRLEN_MAX (ONSTACK_ALLOC_MAX - 1) /* '=' character */
+
const char *name;
char *buf;
mrb_int len;
mrb_sym mid;
+ char onstack[ONSTACK_ALLOC_MAX];
name = mrb_sym2name_len(mrb, id, &len);
- buf = (char *)mrb_malloc(mrb, (size_t)len+2);
+ if (len > ONSTACK_STRLEN_MAX) {
+ buf = (char *)mrb_malloc(mrb, (size_t)len+1);
+ }
+ else {
+ buf = onstack;
+ }
memcpy(buf, name, (size_t)len);
buf[len] = '=';
- buf[len+1] = '\0';
mid = mrb_intern(mrb, buf, len+1);
- mrb_free(mrb, buf);
+ if (buf != onstack) {
+ mrb_free(mrb, buf);
+ }
return mid;
}
@@ -161,20 +168,6 @@ mrb_struct_set_m(mrb_state *mrb, mrb_value obj)
return val;
}
-static mrb_bool
-is_local_id(mrb_state *mrb, const char *name)
-{
- if (!name) return FALSE;
- return !ISUPPER(name[0]);
-}
-
-static mrb_bool
-is_const_id(mrb_state *mrb, const char *name)
-{
- if (!name) return FALSE;
- return ISUPPER(name[0]);
-}
-
static void
make_struct_define_accessors(mrb_state *mrb, mrb_value members, struct RClass *c)
{
@@ -185,19 +178,15 @@ make_struct_define_accessors(mrb_state *mrb, mrb_value members, struct RClass *c
for (i=0; i<len; i++) {
mrb_sym id = mrb_symbol(ptr_members[i]);
- const char *name = mrb_sym2name_len(mrb, id, NULL);
-
- if (is_local_id(mrb, name) || is_const_id(mrb, name)) {
- mrb_method_t m;
- mrb_value at = mrb_fixnum_value(i);
- struct RProc *aref = mrb_proc_new_cfunc_with_env(mrb, mrb_struct_ref, 1, &at);
- struct RProc *aset = mrb_proc_new_cfunc_with_env(mrb, mrb_struct_set_m, 1, &at);
- MRB_METHOD_FROM_PROC(m, aref);
- mrb_define_method_raw(mrb, c, id, m);
- MRB_METHOD_FROM_PROC(m, aset);
- mrb_define_method_raw(mrb, c, mrb_id_attrset(mrb, id), m);
- mrb_gc_arena_restore(mrb, ai);
- }
+ mrb_method_t m;
+ mrb_value at = mrb_fixnum_value(i);
+ struct RProc *aref = mrb_proc_new_cfunc_with_env(mrb, mrb_struct_ref, 1, &at);
+ struct RProc *aset = mrb_proc_new_cfunc_with_env(mrb, mrb_struct_set_m, 1, &at);
+ MRB_METHOD_FROM_PROC(m, aref);
+ mrb_define_method_raw(mrb, c, id, m);
+ MRB_METHOD_FROM_PROC(m, aset);
+ mrb_define_method_raw(mrb, c, mrb_id_attrset(mrb, id), m);
+ mrb_gc_arena_restore(mrb, ai);
}
}
@@ -215,11 +204,11 @@ make_struct(mrb_state *mrb, mrb_value name, mrb_value members, struct RClass *kl
/* old style: should we warn? */
mrb_to_str(mrb, name);
id = mrb_obj_to_sym(mrb, name);
- if (!is_const_id(mrb, mrb_sym2name_len(mrb, id, NULL))) {
- mrb_name_error(mrb, id, "identifier %S needs to be constant", name);
+ if (!mrb_const_name_p(mrb, RSTRING_PTR(name), RSTRING_LEN(name))) {
+ mrb_name_error(mrb, id, "identifier %v needs to be constant", name);
}
if (mrb_const_defined_at(mrb, mrb_obj_value(klass), id)) {
- mrb_warn(mrb, "redefining constant Struct::%S", name);
+ mrb_warn(mrb, "redefining constant Struct::%v", name);
mrb_const_remove(mrb, mrb_obj_value(klass), id);
}
c = mrb_define_class_under(mrb, klass, RSTRING_PTR(name), klass);
@@ -399,23 +388,22 @@ struct_aref_sym(mrb_state *mrb, mrb_value obj, mrb_sym id)
return ptr[i];
}
}
- mrb_raisef(mrb, E_INDEX_ERROR, "'%S' is not a struct member", mrb_sym2str(mrb, id));
+ mrb_name_error(mrb, id, "no member '%n' in struct", id);
return mrb_nil_value(); /* not reached */
}
static mrb_value
struct_aref_int(mrb_state *mrb, mrb_value s, mrb_int i)
{
- if (i < 0) i = RSTRUCT_LEN(s) + i;
- if (i < 0)
- mrb_raisef(mrb, E_INDEX_ERROR,
- "offset %S too small for struct(size:%S)",
- mrb_fixnum_value(i), mrb_fixnum_value(RSTRUCT_LEN(s)));
- if (RSTRUCT_LEN(s) <= i)
+ mrb_int idx = i < 0 ? RSTRUCT_LEN(s) + i : i;
+
+ if (idx < 0)
+ mrb_raisef(mrb, E_INDEX_ERROR,
+ "offset %i too small for struct(size:%i)", i, RSTRUCT_LEN(s));
+ if (RSTRUCT_LEN(s) <= idx)
mrb_raisef(mrb, E_INDEX_ERROR,
- "offset %S too large for struct(size:%S)",
- mrb_fixnum_value(i), mrb_fixnum_value(RSTRUCT_LEN(s)));
- return RSTRUCT_PTR(s)[i];
+ "offset %i too large for struct(size:%i)", i, RSTRUCT_LEN(s));
+ return RSTRUCT_PTR(s)[idx];
}
/* 15.2.18.4.2 */
@@ -447,7 +435,7 @@ mrb_struct_aref(mrb_state *mrb, mrb_value s)
mrb_value sym = mrb_check_intern_str(mrb, idx);
if (mrb_nil_p(sym)) {
- mrb_name_error(mrb, mrb_intern_str(mrb, idx), "no member '%S' in struct", idx);
+ mrb_name_error(mrb, mrb_intern_str(mrb, idx), "no member '%v' in struct", idx);
}
idx = sym;
}
@@ -475,7 +463,7 @@ mrb_struct_aset_sym(mrb_state *mrb, mrb_value s, mrb_sym id, mrb_value val)
return val;
}
}
- mrb_name_error(mrb, id, "no member '%S' in struct", mrb_sym2str(mrb, id));
+ mrb_name_error(mrb, id, "no member '%n' in struct", id);
return val; /* not reach */
}
@@ -514,7 +502,7 @@ mrb_struct_aset(mrb_state *mrb, mrb_value s)
mrb_value sym = mrb_check_intern_str(mrb, idx);
if (mrb_nil_p(sym)) {
- mrb_name_error(mrb, mrb_intern_str(mrb, idx), "no member '%S' in struct", idx);
+ mrb_name_error(mrb, mrb_intern_str(mrb, idx), "no member '%v' in struct", idx);
}
idx = sym;
}
@@ -526,13 +514,11 @@ mrb_struct_aset(mrb_state *mrb, mrb_value s)
if (i < 0) i = RSTRUCT_LEN(s) + i;
if (i < 0) {
mrb_raisef(mrb, E_INDEX_ERROR,
- "offset %S too small for struct(size:%S)",
- mrb_fixnum_value(i), mrb_fixnum_value(RSTRUCT_LEN(s)));
+ "offset %i too small for struct(size:%i)", i, RSTRUCT_LEN(s));
}
if (RSTRUCT_LEN(s) <= i) {
mrb_raisef(mrb, E_INDEX_ERROR,
- "offset %S too large for struct(size:%S)",
- mrb_fixnum_value(i), mrb_fixnum_value(RSTRUCT_LEN(s)));
+ "offset %i too large for struct(size:%i)", i, RSTRUCT_LEN(s));
}
mrb_struct_modify(mrb, s);
return RSTRUCT_PTR(s)[i] = val;
diff --git a/mrbgems/mruby-struct/test/struct.rb b/mrbgems/mruby-struct/test/struct.rb
index 982e344e2..93930730b 100644
--- a/mrbgems/mruby-struct/test/struct.rb
+++ b/mrbgems/mruby-struct/test/struct.rb
@@ -116,9 +116,10 @@ assert('struct dup') do
end
assert('struct inspect') do
- c = Struct.new(:m1, :m2, :m3, :m4, :m5)
- cc = c.new(1,2,3,4,5)
- assert_equal "#<struct m1=1, m2=2, m3=3, m4=4, m5=5>", cc.inspect
+ c = Struct.new(:m1, :m2, :m3, :m4, :m5, :recur)
+ cc = c.new(1,2,3,4,5,nil)
+ cc.recur = cc
+ assert_equal "#<struct m1=1, m2=2, m3=3, m4=4, m5=5, recur=#<struct #{cc.class}:...>>", cc.inspect
end
assert('Struct#length, Struct#size') do
@@ -152,14 +153,14 @@ assert("Struct#dig") do
assert_equal 1, a.dig(1, 0)
end
-assert("Struct.new removes existing constant") do
- skip "redefining Struct with same name cause warnings"
- begin
- assert_not_equal Struct.new("Test", :a), Struct.new("Test", :a, :b)
- ensure
- Struct.remove_const :Test
- end
-end
+# TODO: suppress redefining Struct warning during test
+# assert("Struct.new removes existing constant") do
+# begin
+# assert_not_equal Struct.new("Test", :a), Struct.new("Test", :a, :b)
+# ensure
+# Struct.remove_const :Test
+# end
+# end
assert("Struct#initialize_copy requires struct to be the same type") do
begin
@@ -181,6 +182,10 @@ assert("Struct.new does not allow array") do
end
end
+assert("Struct.new does not allow invalid class name") do
+ assert_raise(NameError) { Struct.new("Test-", :a) }
+end
+
assert("Struct.new generates subclass of Struct") do
begin
original_struct = Struct
@@ -199,7 +204,7 @@ assert 'Struct#freeze' do
assert_equal :test, o.m
o.freeze
- assert_raise(RuntimeError) { o.m = :modify }
- assert_raise(RuntimeError) { o[:m] = :modify }
+ assert_raise(FrozenError) { o.m = :modify }
+ assert_raise(FrozenError) { o[:m] = :modify }
assert_equal :test, o.m
end
diff --git a/mrbgems/mruby-symbol-ext/src/symbol.c b/mrbgems/mruby-symbol-ext/src/symbol.c
index a992dbfce..ccb2971dc 100644
--- a/mrbgems/mruby-symbol-ext/src/symbol.c
+++ b/mrbgems/mruby-symbol-ext/src/symbol.c
@@ -1,11 +1,7 @@
#include <mruby.h>
#include <mruby/khash.h>
#include <mruby/array.h>
-
-typedef struct symbol_name {
- size_t len;
- const char *name;
-} symbol_name;
+#include <mruby/string.h>
/*
* call-seq:
@@ -22,6 +18,7 @@ typedef struct symbol_name {
* :Tms, :getwd, :$=, :ThreadGroup,
* :wait2, :$>]
*/
+#ifdef MRB_ENABLE_ALL_SYMBOLS
static mrb_value
mrb_sym_all_symbols(mrb_state *mrb, mrb_value self)
{
@@ -29,11 +26,13 @@ mrb_sym_all_symbols(mrb_state *mrb, mrb_value self)
mrb_value ary = mrb_ary_new_capa(mrb, mrb->symidx);
for (i=1, lim=mrb->symidx+1; i<lim; i++) {
- mrb_ary_push(mrb, ary, mrb_symbol_value(i));
+ mrb_sym sym = i<<1;
+ mrb_ary_push(mrb, ary, mrb_symbol_value(sym));
}
return ary;
}
+#endif
/*
* call-seq:
@@ -45,7 +44,13 @@ static mrb_value
mrb_sym_length(mrb_state *mrb, mrb_value self)
{
mrb_int len;
+#ifdef MRB_UTF8_STRING
+ mrb_int byte_len;
+ const char *name = mrb_sym2name_len(mrb, mrb_symbol(self), &byte_len);
+ len = mrb_utf8_len(name, byte_len);
+#else
mrb_sym2name_len(mrb, mrb_symbol(self), &len);
+#endif
return mrb_fixnum_value(len);
}
@@ -53,7 +58,9 @@ void
mrb_mruby_symbol_ext_gem_init(mrb_state* mrb)
{
struct RClass *s = mrb->symbol_class;
+#ifdef MRB_ENABLE_ALL_SYMBOLS
mrb_define_class_method(mrb, s, "all_symbols", mrb_sym_all_symbols, MRB_ARGS_NONE());
+#endif
mrb_define_method(mrb, s, "length", mrb_sym_length, MRB_ARGS_NONE());
mrb_define_method(mrb, s, "size", mrb_sym_length, MRB_ARGS_NONE());
}
diff --git a/mrbgems/mruby-symbol-ext/test/symbol.rb b/mrbgems/mruby-symbol-ext/test/symbol.rb
index 63c1bd826..db686e5f4 100644
--- a/mrbgems/mruby-symbol-ext/test/symbol.rb
+++ b/mrbgems/mruby-symbol-ext/test/symbol.rb
@@ -1,15 +1,27 @@
+# coding: utf-8
##
# Symbol(Ext) Test
-assert('Symbol.all_symbols') do
- foo = [:__symbol_test_1, :__symbol_test_2, :__symbol_test_3].sort
- symbols = Symbol.all_symbols.select{|sym|sym.to_s.include? '__symbol_test'}.sort
- assert_equal foo, symbols
-end
-
-assert("Symbol#length") do
- assert_equal 5, :hello.size
- assert_equal 5, :mruby.length
+if Symbol.respond_to?(:all_symbols)
+ assert('Symbol.all_symbols') do
+ foo = [:__symbol_test_1, :__symbol_test_2, :__symbol_test_3].sort
+ symbols = Symbol.all_symbols.select{|sym|sym.to_s.include? '__symbol_test'}.sort
+ assert_equal foo, symbols
+ end
+end
+
+%w[size length].each do |n|
+ assert("Symbol##{n}") do
+ assert_equal 5, :hello.__send__(n)
+ assert_equal 4, :"aA\0b".__send__(n)
+ if __ENCODING__ == "UTF-8"
+ assert_equal 8, :"こんにちは世界!".__send__(n)
+ assert_equal 4, :"aあ\0b".__send__(n)
+ else
+ assert_equal 22, :"こんにちは世界!".__send__(n)
+ assert_equal 6, :"aあ\0b".__send__(n)
+ end
+ end
end
assert("Symbol#capitalize") do
diff --git a/mrbgems/mruby-test/driver.c b/mrbgems/mruby-test/driver.c
index 434d1fee5..a5f723927 100644
--- a/mrbgems/mruby-test/driver.c
+++ b/mrbgems/mruby-test/driver.c
@@ -18,8 +18,10 @@
#include <mruby/variable.h>
#include <mruby/array.h>
-void
-mrb_init_mrbtest(mrb_state *);
+extern const uint8_t mrbtest_assert_irep[];
+
+void mrbgemtest_init(mrb_state* mrb);
+void mrb_init_test_vformat(mrb_state* mrb);
/* Print a short remark for the user */
static void
@@ -29,56 +31,182 @@ print_hint(void)
}
static int
-check_error(mrb_state *mrb)
-{
- /* Error check */
- /* $ko_test and $kill_test should be 0 */
- mrb_value ko_test = mrb_gv_get(mrb, mrb_intern_lit(mrb, "$ko_test"));
- mrb_value kill_test = mrb_gv_get(mrb, mrb_intern_lit(mrb, "$kill_test"));
-
- return mrb_fixnum_p(ko_test) && mrb_fixnum(ko_test) == 0 && mrb_fixnum_p(kill_test) && mrb_fixnum(kill_test) == 0;
-}
-
-static int
eval_test(mrb_state *mrb)
{
/* evaluate the test */
- mrb_funcall(mrb, mrb_top_self(mrb), "report", 0);
+ mrb_value result = mrb_funcall(mrb, mrb_top_self(mrb), "report", 0);
/* did an exception occur? */
if (mrb->exc) {
mrb_print_error(mrb);
mrb->exc = 0;
return EXIT_FAILURE;
}
- else if (!check_error(mrb)) {
- return EXIT_FAILURE;
+ else {
+ return mrb_bool(result) ? EXIT_SUCCESS : EXIT_FAILURE;
}
- return EXIT_SUCCESS;
}
-static void
-t_printstr(mrb_state *mrb, mrb_value obj)
+/* Implementation of print due to the reason that there might be no print */
+static mrb_value
+t_print(mrb_state *mrb, mrb_value self)
+{
+ mrb_value *argv;
+ mrb_int argc;
+ mrb_int i;
+
+ mrb_get_args(mrb, "*!", &argv, &argc);
+ for (i = 0; i < argc; ++i) {
+ mrb_value s = mrb_obj_as_string(mrb, argv[i]);
+ fwrite(RSTRING_PTR(s), RSTRING_LEN(s), 1, stdout);
+ }
+ fflush(stdout);
+
+ return mrb_nil_value();
+}
+
+#define UNESCAPE(p, endp) ((p) != (endp) && *(p) == '\\' ? (p)+1 : (p))
+#define CHAR_CMP(c1, c2) ((unsigned char)(c1) - (unsigned char)(c2))
+
+static const char *
+str_match_bracket(const char *p, const char *pat_end,
+ const char *s, const char *str_end)
+{
+ mrb_bool ok = FALSE, negated = FALSE;
+
+ if (p == pat_end) return NULL;
+ if (*p == '!' || *p == '^') {
+ negated = TRUE;
+ ++p;
+ }
+
+ while (*p != ']') {
+ const char *t1 = p;
+ if ((t1 = UNESCAPE(t1, pat_end)) == pat_end) return NULL;
+ if ((p = t1 + 1) == pat_end) return NULL;
+ if (p[0] == '-' && p[1] != ']') {
+ const char *t2 = p + 1;
+ if ((t2 = UNESCAPE(t2, pat_end)) == pat_end) return NULL;
+ p = t2 + 1;
+ if (!ok && CHAR_CMP(*t1, *s) <= 0 && CHAR_CMP(*s, *t2) <= 0) ok = TRUE;
+ }
+ else {
+ if (!ok && CHAR_CMP(*t1, *s) == 0) ok = TRUE;
+ }
+ }
+
+ return ok == negated ? NULL : p + 1;
+}
+
+static mrb_bool
+str_match_no_brace_p(const char *pat, mrb_int pat_len,
+ const char *str, mrb_int str_len)
{
- char *s;
- mrb_int len;
-
- if (mrb_string_p(obj)) {
- s = RSTRING_PTR(obj);
- len = RSTRING_LEN(obj);
- fwrite(s, len, 1, stdout);
- fflush(stdout);
+ const char *p = pat, *s = str;
+ const char *pat_end = pat + pat_len, *str_end = str + str_len;
+ const char *p_tmp = NULL, *s_tmp = NULL;
+
+ for (;;) {
+ if (p == pat_end) return s == str_end;
+ switch (*p) {
+ case '*':
+ do { ++p; } while (p != pat_end && *p == '*');
+ if (UNESCAPE(p, pat_end) == pat_end) return TRUE;
+ if (s == str_end) return FALSE;
+ p_tmp = p;
+ s_tmp = s;
+ continue;
+ case '?':
+ if (s == str_end) return FALSE;
+ ++p;
+ ++s;
+ continue;
+ case '[': {
+ const char *t;
+ if (s == str_end) return FALSE;
+ if ((t = str_match_bracket(p+1, pat_end, s, str_end))) {
+ p = t;
+ ++s;
+ continue;
+ }
+ goto L_failed;
+ }
+ }
+
+ /* ordinary */
+ p = UNESCAPE(p, pat_end);
+ if (s == str_end) return p == pat_end;
+ if (p == pat_end) goto L_failed;
+ if (*p++ != *s++) goto L_failed;
+ continue;
+
+ L_failed:
+ if (p_tmp && s_tmp) {
+ /* try next '*' position */
+ p = p_tmp;
+ s = ++s_tmp;
+ continue;
+ }
+
+ return FALSE;
}
}
-mrb_value
-mrb_t_printstr(mrb_state *mrb, mrb_value self)
+#define COPY_AND_INC(dst, src, len) \
+ do { memcpy(dst, src, len); dst += len; } while (0)
+
+static mrb_bool
+str_match_p(mrb_state *mrb,
+ const char *pat, mrb_int pat_len,
+ const char *str, mrb_int str_len)
{
- mrb_value argv;
+ const char *p = pat, *pat_end = pat + pat_len;
+ const char *lbrace = NULL, *rbrace = NULL;
+ int nest = 0;
+ mrb_bool ret = FALSE;
+
+ for (; p != pat_end; ++p) {
+ if (*p == '{' && nest++ == 0) lbrace = p;
+ else if (*p == '}' && lbrace && --nest == 0) { rbrace = p; break; }
+ else if (*p == '\\' && ++p == pat_end) break;
+ }
+
+ if (lbrace && rbrace) {
+ /* expand brace */
+ char *ex_pat = (char *)mrb_malloc(mrb, pat_len-2); /* expanded pattern */
+ char *ex_p = ex_pat;
+
+ COPY_AND_INC(ex_p, pat, lbrace-pat);
+ p = lbrace;
+ while (p < rbrace) {
+ char *orig_ex_p = ex_p;
+ const char *t = ++p;
+ for (nest = 0; p < rbrace && !(*p == ',' && nest == 0); ++p) {
+ if (*p == '{') ++nest;
+ else if (*p == '}') --nest;
+ else if (*p == '\\' && ++p == rbrace) break;
+ }
+ COPY_AND_INC(ex_p, t, p-t);
+ COPY_AND_INC(ex_p, rbrace+1, pat_end-rbrace-1);
+ if ((ret = str_match_p(mrb, ex_pat, ex_p-ex_pat, str, str_len))) break;
+ ex_p = orig_ex_p;
+ }
+ mrb_free(mrb, ex_pat);
+ }
+ else if (!lbrace && !rbrace) {
+ ret = str_match_no_brace_p(pat, pat_len, str, str_len);
+ }
- mrb_get_args(mrb, "o", &argv);
- t_printstr(mrb, argv);
+ return ret;
+}
- return argv;
+static mrb_value
+m_str_match_p(mrb_state *mrb, mrb_value self)
+{
+ const char *pat, *str;
+ mrb_int pat_len, str_len;
+
+ mrb_get_args(mrb, "ss", &pat, &pat_len, &str, &str_len);
+ return mrb_bool_value(str_match_p(mrb, pat, pat_len, str, str_len));
}
void
@@ -87,7 +215,8 @@ mrb_init_test_driver(mrb_state *mrb, mrb_bool verbose)
struct RClass *krn, *mrbtest;
krn = mrb->kernel_module;
- mrb_define_method(mrb, krn, "__t_printstr__", mrb_t_printstr, MRB_ARGS_REQ(1));
+ mrb_define_method(mrb, krn, "t_print", t_print, MRB_ARGS_ANY());
+ mrb_define_method(mrb, krn, "_str_match?", m_str_match_p, MRB_ARGS_REQ(2));
mrbtest = mrb_define_module(mrb, "Mrbtest");
@@ -103,6 +232,8 @@ mrb_init_test_driver(mrb_state *mrb, mrb_bool verbose)
#endif
#endif
+ mrb_init_test_vformat(mrb);
+
if (verbose) {
mrb_gv_set(mrb, mrb_intern_lit(mrb, "$mrbtest_verbose"), mrb_true_value());
}
@@ -130,6 +261,8 @@ mrb_t_pass_result(mrb_state *mrb_dst, mrb_state *mrb_src)
TEST_COUNT_PASS(ok_test);
TEST_COUNT_PASS(ko_test);
TEST_COUNT_PASS(kill_test);
+ TEST_COUNT_PASS(warning_test);
+ TEST_COUNT_PASS(skip_test);
#undef TEST_COUNT_PASS
@@ -167,7 +300,8 @@ main(int argc, char **argv)
}
mrb_init_test_driver(mrb, verbose);
- mrb_init_mrbtest(mrb);
+ mrb_load_irep(mrb, mrbtest_assert_irep);
+ mrbgemtest_init(mrb);
ret = eval_test(mrb);
mrb_close(mrb);
diff --git a/mrbgems/mruby-test/init_mrbtest.c b/mrbgems/mruby-test/init_mrbtest.c
deleted file mode 100644
index 7678a5200..000000000
--- a/mrbgems/mruby-test/init_mrbtest.c
+++ /dev/null
@@ -1,39 +0,0 @@
-#include <stdlib.h>
-#include <mruby.h>
-#include <mruby/irep.h>
-#include <mruby/variable.h>
-
-extern const uint8_t mrbtest_assert_irep[];
-
-void mrbgemtest_init(mrb_state* mrb);
-void mrb_init_test_driver(mrb_state* mrb, mrb_bool verbose);
-void mrb_t_pass_result(mrb_state *mrb_dst, mrb_state *mrb_src);
-
-void
-mrb_init_mrbtest(mrb_state *mrb)
-{
- mrb_state *core_test;
-
- mrb_load_irep(mrb, mrbtest_assert_irep);
-
- core_test = mrb_open_core(mrb_default_allocf, NULL);
- if (core_test == NULL) {
- fprintf(stderr, "Invalid mrb_state, exiting %s", __FUNCTION__);
- exit(EXIT_FAILURE);
- }
- mrb_init_test_driver(core_test, mrb_test(mrb_gv_get(mrb, mrb_intern_lit(mrb, "$mrbtest_verbose"))));
- mrb_load_irep(core_test, mrbtest_assert_irep);
- mrb_t_pass_result(mrb, core_test);
-
-#ifndef DISABLE_GEMS
- mrbgemtest_init(mrb);
-#endif
-
- if (mrb->exc) {
- mrb_print_error(mrb);
- mrb_close(mrb);
- exit(EXIT_FAILURE);
- }
- mrb_close(core_test);
-}
-
diff --git a/mrbgems/mruby-test/mrbgem.rake b/mrbgems/mruby-test/mrbgem.rake
index 61bdf9ced..bf90e0791 100644
--- a/mrbgems/mruby-test/mrbgem.rake
+++ b/mrbgems/mruby-test/mrbgem.rake
@@ -15,8 +15,9 @@ MRuby::Gem::Specification.new('mruby-test') do |spec|
mrbtest_lib = libfile("#{build_dir}/mrbtest")
mrbtest_objs = []
- driver_obj = objfile("#{build_dir}/driver")
- # driver = "#{spec.dir}/driver.c"
+ driver_objs = Dir.glob("#{dir}/*.{c,cpp,cxx,cc,m,asm,s,S}").map do |f|
+ objfile(f.relative_path_from(dir).to_s.pathmap("#{build_dir}/%X"))
+ end
assert_c = "#{build_dir}/assert.c"
assert_rb = "#{MRUBY_ROOT}/test/assert.rb"
@@ -133,7 +134,7 @@ MRuby::Gem::Specification.new('mruby-test') do |spec|
end
unless build.build_mrbtest_lib_only?
- file exec => [driver_obj, mlib, mrbtest_lib, build.libmruby_static] do |t|
+ file exec => [*driver_objs, mlib, mrbtest_lib, build.libmruby_static] do |t|
gem_flags = build.gems.map { |g| g.linker.flags }
gem_flags_before_libraries = build.gems.map { |g| g.linker.flags_before_libraries }
gem_flags_after_libraries = build.gems.map { |g| g.linker.flags_after_libraries }
@@ -144,8 +145,6 @@ MRuby::Gem::Specification.new('mruby-test') do |spec|
end
end
- init = "#{spec.dir}/init_mrbtest.c"
-
# store the last gem selection and make the re-build
# of the test gem depending on a change to the gem
# selection
@@ -164,7 +163,7 @@ MRuby::Gem::Specification.new('mruby-test') do |spec|
file clib => active_gems_path if active_gem_list != current_gem_list
file mlib => clib
- file clib => [init, build.mrbcfile, __FILE__] do |_t|
+ file clib => [build.mrbcfile, __FILE__] do |_t|
_pp "GEN", "*.rb", "#{clib.relative_path}"
FileUtils.mkdir_p File.dirname(clib)
open(clib, 'w') do |f|
@@ -177,7 +176,8 @@ MRuby::Gem::Specification.new('mruby-test') do |spec|
f.puts %Q[ * All manual changes will get lost.]
f.puts %Q[ */]
f.puts %Q[]
- f.puts IO.read(init)
+ f.puts %Q[struct mrb_state;]
+ f.puts %Q[typedef struct mrb_state mrb_state;]
build.gems.each do |g|
f.puts %Q[void GENERATED_TMP_mrb_#{g.funcname}_gem_test(mrb_state *mrb);]
end
diff --git a/mrbgems/mruby-test/vformat.c b/mrbgems/mruby-test/vformat.c
new file mode 100644
index 000000000..6984aaeb1
--- /dev/null
+++ b/mrbgems/mruby-test/vformat.c
@@ -0,0 +1,200 @@
+#include <string.h>
+#include <mruby.h>
+#include <mruby/class.h>
+#include <mruby/data.h>
+#include <mruby/string.h>
+
+#ifdef MRB_WITHOUT_FLOAT
+typedef mrb_int mrb_float;
+#define mrb_float(o) mrb_fixnum(o)
+#endif
+
+#define NATIVE_TYPES \
+ char c; \
+ int d; \
+ mrb_float f; \
+ mrb_int i; \
+/* size_t l; */\
+ mrb_sym n; \
+ char *s; \
+ struct RClass *C
+
+#define NATIVE_DEFINE_TYPE_FUNC(t) \
+ static mrb_value \
+ native_s_##t(mrb_state *mrb, mrb_value klass) \
+ { \
+ mrb_value obj, type = mrb_fixnum_value(ARG_##t); \
+ mrb_get_args(mrb, "o", &obj); \
+ return mrb_funcall(mrb, klass, "new", 2, type, obj); \
+ }
+
+#define NATIVE_DEFINE_TYPE_METHOD(t) \
+ mrb_define_class_method(mrb, n, #t, native_s_##t, MRB_ARGS_REQ(1))
+
+typedef enum {
+ ARG_c,
+ ARG_d,
+ ARG_f,
+ ARG_i,
+/* ARG_l,*/
+ ARG_n,
+ ARG_s,
+ ARG_C,
+ ARG_v,
+} VFArgumentType;
+
+typedef struct {
+ VFArgumentType type;
+ union { NATIVE_TYPES; };
+} VFNative;
+
+typedef struct {
+ VFArgumentType type;
+ union {
+ NATIVE_TYPES;
+ mrb_value v;
+ };
+} VFArgument;
+
+static void
+native_free(mrb_state *mrb, void *data)
+{
+ VFNative *native = (VFNative*)data;
+ if (native->type == ARG_s) mrb_free(mrb, native->s);
+ mrb_free(mrb, native);
+}
+
+static const struct mrb_data_type native_data_type = {
+ "TestVFormat::Native", native_free
+};
+
+static mrb_value
+native_initialize(mrb_state *mrb, mrb_value self)
+{
+ VFNative data, *datap;
+ mrb_int type;
+ mrb_value obj;
+
+ mrb_get_args(mrb, "io", &type, &obj);
+ data.type = (VFArgumentType)type;
+ switch (data.type) {
+ case ARG_c: data.c = RSTRING_PTR(obj)[0]; break;
+ case ARG_d: data.d = (int)mrb_fixnum(obj); break;
+ case ARG_f: data.f = mrb_float(obj); break;
+ case ARG_i: data.i = mrb_fixnum(obj); break;
+/* case ARG_l: data.l = (size_t)mrb_fixnum(obj); break;*/
+ case ARG_n: data.n = mrb_symbol(obj); break;
+ case ARG_s: data.s = (char*)mrb_malloc(mrb, RSTRING_LEN(obj) + 1);
+ memcpy(data.s, RSTRING_PTR(obj), RSTRING_LEN(obj));
+ data.s[RSTRING_LEN(obj)] = '\0'; break;
+ case ARG_C: data.C = mrb_class_ptr(obj); break;
+ default: mrb_raise(mrb, E_ARGUMENT_ERROR, "unknown type");
+ }
+ datap = (VFNative*)mrb_malloc(mrb, sizeof(VFNative));
+ *datap = data;
+ mrb_data_init(self, datap, &native_data_type);
+ return self;
+}
+
+NATIVE_DEFINE_TYPE_FUNC(c)
+NATIVE_DEFINE_TYPE_FUNC(d)
+NATIVE_DEFINE_TYPE_FUNC(f)
+NATIVE_DEFINE_TYPE_FUNC(i)
+/*NATIVE_DEFINE_TYPE_FUNC(l)*/
+NATIVE_DEFINE_TYPE_FUNC(n)
+NATIVE_DEFINE_TYPE_FUNC(s)
+NATIVE_DEFINE_TYPE_FUNC(C)
+
+static VFArgument*
+arg_from_obj(mrb_state *mrb, mrb_value obj, struct RClass *native_class,
+ VFArgument *vf_arg)
+{
+ if (mrb_obj_is_instance_of(mrb, obj, native_class)) {
+ const VFNative *native = (VFNative*)DATA_PTR(obj);
+ *(VFNative*)vf_arg = *native;
+ }
+ else {
+ vf_arg->v = obj;
+ vf_arg->type = ARG_v;
+ }
+ return vf_arg;
+}
+
+#define VF_FORMAT_INIT(klass) \
+ struct RClass *vf_native_class = \
+ mrb_class_get_under(mrb, mrb_class_ptr(klass), "Native"); \
+ VFArgument vf_args[2];
+
+#define VF_ARG(args, idx) \
+ arg_from_obj(mrb, args[idx], vf_native_class, &vf_args[idx])
+
+#define VF_FORMAT0(fmt) mrb_format(mrb, fmt);
+#define VF_FORMAT1(fmt, args) \
+ (VF_ARG(args, 0), VF_FORMAT_TYPED(fmt, 1, vf_args, NULL))
+#define VF_FORMAT2(fmt, args) ( \
+ VF_ARG(args, 0), VF_ARG(args, 1), \
+ VF_FORMAT2_COND_EXPR(fmt, vf_args, vf_args+1, c) : \
+ VF_FORMAT2_COND_EXPR(fmt, vf_args, vf_args+1, d) : \
+ VF_FORMAT2_COND_EXPR(fmt, vf_args, vf_args+1, f) : \
+ VF_FORMAT2_COND_EXPR(fmt, vf_args, vf_args+1, i) : \
+/* VF_FORMAT2_COND_EXPR(fmt, vf_args, vf_args+1, l) : */\
+ VF_FORMAT2_COND_EXPR(fmt, vf_args, vf_args+1, n) : \
+ VF_FORMAT2_COND_EXPR(fmt, vf_args, vf_args+1, s) : \
+ VF_FORMAT2_COND_EXPR(fmt, vf_args, vf_args+1, C) : \
+ VF_FORMAT2_COND_EXPR(fmt, vf_args, vf_args+1, v) : \
+ mrb_nil_value() /* not reached */ \
+)
+#define VF_FORMAT2_COND_EXPR(fmt, a1, a2, t) \
+ a1->type == ARG_##t ? VF_FORMAT_TYPED(fmt, 2, a2, (a1)->t)
+#define VF_FORMAT_TYPED(fmt, n_arg, type_a, v1) \
+ VF_FORMAT_TYPED_COND_EXPR(fmt, n_arg, type_a, v1, c) : \
+ VF_FORMAT_TYPED_COND_EXPR(fmt, n_arg, type_a, v1, d) : \
+ VF_FORMAT_TYPED_COND_EXPR(fmt, n_arg, type_a, v1, f) : \
+ VF_FORMAT_TYPED_COND_EXPR(fmt, n_arg, type_a, v1, i) : \
+/* VF_FORMAT_TYPED_COND_EXPR(fmt, n_arg, type_a, v1, l) : */\
+ VF_FORMAT_TYPED_COND_EXPR(fmt, n_arg, type_a, v1, n) : \
+ VF_FORMAT_TYPED_COND_EXPR(fmt, n_arg, type_a, v1, s) : \
+ VF_FORMAT_TYPED_COND_EXPR(fmt, n_arg, type_a, v1, C) : \
+ VF_FORMAT_TYPED_COND_EXPR(fmt, n_arg, type_a, v1, v) : \
+ mrb_nil_value() /* not reached */
+#define VF_FORMAT_TYPED_COND_EXPR(fmt, n_arg, type_a, v1, t) \
+ (type_a)->type == ARG_##t ? n_arg == 1 ? \
+ mrb_format(mrb, fmt, (type_a)->t) : mrb_format(mrb, fmt, v1, (type_a)->t)
+
+static mrb_value
+vf_s_format(mrb_state *mrb, mrb_value klass)
+{
+ mrb_value fmt_str, args[2];
+ mrb_int argc = mrb_get_args(mrb, "S|oo", &fmt_str, args, args+1);
+ const char *fmt = RSTRING_CSTR(mrb, fmt_str);
+
+ VF_FORMAT_INIT(klass);
+
+ switch (argc) {
+ case 1: return VF_FORMAT0(fmt);
+ case 2: return VF_FORMAT1(fmt, args);
+ case 3: return VF_FORMAT2(fmt, args);
+ default: return mrb_nil_value(); /* not reached */
+ }
+}
+
+void
+mrb_init_test_vformat(mrb_state *mrb)
+{
+ struct RClass *vf, *n;
+
+ vf = mrb_define_module(mrb, "TestVFormat");
+ mrb_define_class_method(mrb, vf, "format", vf_s_format, MRB_ARGS_ARG(1,2));
+
+ n = mrb_define_class_under(mrb, vf, "Native", mrb->object_class);
+ MRB_SET_INSTANCE_TT(n, MRB_TT_DATA);
+ NATIVE_DEFINE_TYPE_METHOD(c);
+ NATIVE_DEFINE_TYPE_METHOD(d);
+ NATIVE_DEFINE_TYPE_METHOD(f);
+ NATIVE_DEFINE_TYPE_METHOD(i);
+/* NATIVE_DEFINE_TYPE_METHOD(l);*/
+ NATIVE_DEFINE_TYPE_METHOD(n);
+ NATIVE_DEFINE_TYPE_METHOD(s);
+ NATIVE_DEFINE_TYPE_METHOD(C);
+ mrb_define_method(mrb, n, "initialize", native_initialize, MRB_ARGS_REQ(2));
+}
diff --git a/mrbgems/mruby-time/include/mruby/time.h b/mrbgems/mruby-time/include/mruby/time.h
index d71f4ccd3..1adcfd49c 100644
--- a/mrbgems/mruby-time/include/mruby/time.h
+++ b/mrbgems/mruby-time/include/mruby/time.h
@@ -8,6 +8,7 @@
#define MRUBY_TIME_H
#include "mruby/common.h"
+#include <time.h>
MRB_BEGIN_DECL
@@ -18,7 +19,7 @@ typedef enum mrb_timezone {
MRB_TIMEZONE_LAST = 3
} mrb_timezone;
-MRB_API mrb_value mrb_time_at(mrb_state *mrb, double sec, double usec, mrb_timezone timezone);
+MRB_API mrb_value mrb_time_at(mrb_state *mrb, time_t sec, time_t usec, mrb_timezone timezone);
MRB_END_DECL
diff --git a/mrbgems/mruby-time/src/time.c b/mrbgems/mruby-time/src/time.c
index d70fb442c..9b0549bea 100644
--- a/mrbgems/mruby-time/src/time.c
+++ b/mrbgems/mruby-time/src/time.c
@@ -4,8 +4,10 @@
** See Copyright Notice in mruby.h
*/
+#ifndef MRB_WITHOUT_FLOAT
#include <math.h>
-#include <time.h>
+#endif
+
#include <mruby.h>
#include <mruby/class.h>
#include <mruby/data.h>
@@ -17,7 +19,10 @@
#include <string.h>
#endif
+#include <stdlib.h>
+
#define NDIV(x,y) (-(-((x)+1)/(y))-1)
+#define TO_S_FMT "%Y-%m-%d %H:%M:%S "
#if defined(_MSC_VER) && _MSC_VER < 1800
double round(double x) {
@@ -25,8 +30,10 @@ double round(double x) {
}
#endif
-#if !defined(__MINGW64__) && defined(_WIN32)
-# define llround(x) round(x)
+#ifdef MRB_WITHOUT_FLOAT
+# if !defined(__MINGW64__) && defined(_WIN32)
+# define llround(x) round(x)
+# endif
#endif
#if defined(__MINGW64__) || defined(__MINGW32__)
@@ -197,21 +204,96 @@ struct mrb_time {
static const struct mrb_data_type mrb_time_type = { "Time", mrb_free };
+#ifndef MRB_WITHOUT_FLOAT
+void mrb_check_num_exact(mrb_state *mrb, mrb_float num);
+typedef mrb_float mrb_sec;
+#define mrb_sec_value(mrb, sec) mrb_float_value(mrb, sec)
+#else
+typedef mrb_int mrb_sec;
+#define mrb_sec_value(mrb, sec) mrb_fixnum_value(sec)
+#endif
+
+#ifdef MRB_TIME_T_UINT
+typedef uint64_t mrb_time_int;
+# define MRB_TIME_MIN 0
+# define MRB_TIME_MAX (sizeof(time_t) <= 4 ? UINT32_MAX : UINT64_MAX)
+#else
+typedef int64_t mrb_time_int;
+# define MRB_TIME_MIN (sizeof(time_t) <= 4 ? INT32_MIN : INT64_MIN)
+# define MRB_TIME_MAX (sizeof(time_t) <= 4 ? INT32_MAX : INT64_MAX)
+#endif
+
+static time_t
+mrb_to_time_t(mrb_state *mrb, mrb_value obj, time_t *usec)
+{
+ time_t t;
+
+ switch (mrb_type(obj)) {
+#ifndef MRB_WITHOUT_FLOAT
+ case MRB_TT_FLOAT:
+ {
+ mrb_float f = mrb_float(obj);
+
+ mrb_check_num_exact(mrb, f);
+ if (f > (mrb_float)MRB_TIME_MAX || (mrb_float)MRB_TIME_MIN > f) {
+ goto out_of_range;
+ }
+
+ if (usec) {
+ t = (time_t)f;
+ *usec = (time_t)llround((f - t) * 1.0e+6);
+ }
+ else {
+ t = (time_t)llround(f);
+ }
+ }
+ break;
+#endif /* MRB_WITHOUT_FLOAT */
+ default:
+ case MRB_TT_FIXNUM:
+ {
+ mrb_int i = mrb_int(mrb, obj);
+
+ if ((mrb_time_int)i > MRB_TIME_MAX || MRB_TIME_MIN > i) {
+ goto out_of_range;
+ }
+
+ t = (time_t)i;
+ if (usec) { *usec = 0; }
+ }
+ break;
+ }
+
+ return t;
+
+out_of_range:
+ mrb_raisef(mrb, E_ARGUMENT_ERROR, "%v out of Time range", obj);
+
+ /* not reached */
+ if (usec) { *usec = 0; }
+ return 0;
+}
+
/** Updates the datetime of a mrb_time based on it's timezone and
-seconds setting. Returns self on success, NULL of failure. */
+ seconds setting. Returns self on success, NULL of failure.
+ if `dealloc` is set `true`, it frees `self` on error. */
static struct mrb_time*
-time_update_datetime(mrb_state *mrb, struct mrb_time *self)
+time_update_datetime(mrb_state *mrb, struct mrb_time *self, int dealloc)
{
struct tm *aid;
+ time_t t = self->sec;
if (self->timezone == MRB_TIMEZONE_UTC) {
- aid = gmtime_r(&self->sec, &self->datetime);
+ aid = gmtime_r(&t, &self->datetime);
}
else {
- aid = localtime_r(&self->sec, &self->datetime);
+ aid = localtime_r(&t, &self->datetime);
}
if (!aid) {
- mrb_raisef(mrb, E_ARGUMENT_ERROR, "%S out of Time range", mrb_float_value(mrb, (mrb_float)self->sec));
+ mrb_sec sec = (mrb_sec)t;
+
+ if (dealloc) mrb_free(mrb, self);
+ mrb_raisef(mrb, E_ARGUMENT_ERROR, "%v out of Time range", mrb_sec_value(mrb, sec));
/* not reached */
return NULL;
}
@@ -228,40 +310,15 @@ mrb_time_wrap(mrb_state *mrb, struct RClass *tc, struct mrb_time *tm)
return mrb_obj_value(Data_Wrap_Struct(mrb, tc, &mrb_time_type, tm));
}
-void mrb_check_num_exact(mrb_state *mrb, mrb_float num);
-
/* Allocates a mrb_time object and initializes it. */
static struct mrb_time*
-time_alloc(mrb_state *mrb, double sec, double usec, enum mrb_timezone timezone)
+time_alloc_time(mrb_state *mrb, time_t sec, time_t usec, enum mrb_timezone timezone)
{
struct mrb_time *tm;
- time_t tsec = 0;
- mrb_check_num_exact(mrb, (mrb_float)sec);
- mrb_check_num_exact(mrb, (mrb_float)usec);
-#ifndef MRB_TIME_T_UINT
- if (sizeof(time_t) == 4 && (sec > (double)INT32_MAX || (double)INT32_MIN > sec)) {
- goto out_of_range;
- }
- if (sizeof(time_t) == 8 && (sec > (double)INT64_MAX || (double)INT64_MIN > sec)) {
- goto out_of_range;
- }
-#else
- if (sizeof(time_t) == 4 && (sec > (double)UINT32_MAX || (double)0 > sec)) {
- goto out_of_range;
- }
- if (sizeof(time_t) == 8 && (sec > (double)UINT64_MAX || (double)0 > sec)) {
- goto out_of_range;
- }
-#endif
- tsec = (time_t)sec;
- if ((sec > 0 && tsec < 0) || (sec < 0 && (double)tsec > sec)) {
- out_of_range:
- mrb_raisef(mrb, E_ARGUMENT_ERROR, "%S out of Time range", mrb_float_value(mrb, sec));
- }
tm = (struct mrb_time *)mrb_malloc(mrb, sizeof(struct mrb_time));
- tm->sec = tsec;
- tm->usec = (time_t)llround((sec - tm->sec) * 1.0e6 + usec);
+ tm->sec = sec;
+ tm->usec = usec;
if (tm->usec < 0) {
long sec2 = (long)NDIV(tm->usec,1000000); /* negative div */
tm->usec -= sec2 * 1000000;
@@ -273,13 +330,30 @@ time_alloc(mrb_state *mrb, double sec, double usec, enum mrb_timezone timezone)
tm->sec += sec2;
}
tm->timezone = timezone;
- time_update_datetime(mrb, tm);
+ time_update_datetime(mrb, tm, TRUE);
return tm;
}
+static struct mrb_time*
+time_alloc(mrb_state *mrb, mrb_value sec, mrb_value usec, enum mrb_timezone timezone)
+{
+ time_t tsec, tusec;
+
+ tsec = mrb_to_time_t(mrb, sec, &tusec);
+ tusec += mrb_to_time_t(mrb, usec, NULL);
+
+ return time_alloc_time(mrb, tsec, tusec, timezone);
+}
+
static mrb_value
-mrb_time_make(mrb_state *mrb, struct RClass *c, double sec, double usec, enum mrb_timezone timezone)
+mrb_time_make_time(mrb_state *mrb, struct RClass *c, time_t sec, time_t usec, enum mrb_timezone timezone)
+{
+ return mrb_time_wrap(mrb, c, time_alloc_time(mrb, sec, usec, timezone));
+}
+
+static mrb_value
+mrb_time_make(mrb_state *mrb, struct RClass *c, mrb_value sec, mrb_value usec, enum mrb_timezone timezone)
{
return mrb_time_wrap(mrb, c, time_alloc(mrb, sec, usec, timezone));
}
@@ -287,24 +361,24 @@ mrb_time_make(mrb_state *mrb, struct RClass *c, double sec, double usec, enum mr
static struct mrb_time*
current_mrb_time(mrb_state *mrb)
{
+ struct mrb_time tmzero = {0};
struct mrb_time *tm;
+ time_t sec, usec;
- tm = (struct mrb_time *)mrb_malloc(mrb, sizeof(*tm));
#if defined(TIME_UTC) && !defined(__ANDROID__)
{
struct timespec ts;
if (timespec_get(&ts, TIME_UTC) == 0) {
- mrb_free(mrb, tm);
mrb_raise(mrb, E_RUNTIME_ERROR, "timespec_get() failed for unknown reasons");
}
- tm->sec = ts.tv_sec;
- tm->usec = ts.tv_nsec / 1000;
+ sec = ts.tv_sec;
+ usec = ts.tv_nsec / 1000;
}
#elif defined(NO_GETTIMEOFDAY)
{
static time_t last_sec = 0, last_usec = 0;
- tm->sec = time(NULL);
+ sec = time(NULL);
if (tm->sec != last_sec) {
last_sec = tm->sec;
last_usec = 0;
@@ -313,19 +387,22 @@ current_mrb_time(mrb_state *mrb)
/* add 1 usec to differentiate two times */
last_usec += 1;
}
- tm->usec = last_usec;
+ usec = last_usec;
}
#else
{
struct timeval tv;
gettimeofday(&tv, NULL);
- tm->sec = tv.tv_sec;
- tm->usec = tv.tv_usec;
+ sec = tv.tv_sec;
+ usec = tv.tv_usec;
}
#endif
+ tm = (struct mrb_time *)mrb_malloc(mrb, sizeof(*tm));
+ *tm = tmzero;
+ tm->sec = sec; tm->usec = usec;
tm->timezone = MRB_TIMEZONE_LOCAL;
- time_update_datetime(mrb, tm);
+ time_update_datetime(mrb, tm, TRUE);
return tm;
}
@@ -338,9 +415,9 @@ mrb_time_now(mrb_state *mrb, mrb_value self)
}
MRB_API mrb_value
-mrb_time_at(mrb_state *mrb, double sec, double usec, enum mrb_timezone zone)
+mrb_time_at(mrb_state *mrb, time_t sec, time_t usec, enum mrb_timezone zone)
{
- return mrb_time_make(mrb, mrb_class_get(mrb, "Time"), sec, usec, zone);
+ return mrb_time_make_time(mrb, mrb_class_get(mrb, "Time"), sec, usec, zone);
}
/* 15.2.19.6.1 */
@@ -348,10 +425,12 @@ mrb_time_at(mrb_state *mrb, double sec, double usec, enum mrb_timezone zone)
static mrb_value
mrb_time_at_m(mrb_state *mrb, mrb_value self)
{
- mrb_float f, f2 = 0;
+ mrb_value sec;
+ mrb_value usec = mrb_fixnum_value(0);
+
+ mrb_get_args(mrb, "o|o", &sec, &usec);
- mrb_get_args(mrb, "f|f", &f, &f2);
- return mrb_time_make(mrb, mrb_class_ptr(self), f, f2, MRB_TIMEZONE_LOCAL);
+ return mrb_time_make(mrb, mrb_class_ptr(self), sec, usec, MRB_TIMEZONE_LOCAL);
}
static struct mrb_time*
@@ -388,7 +467,7 @@ time_mktime(mrb_state *mrb, mrb_int ayear, mrb_int amonth, mrb_int aday,
mrb_raise(mrb, E_ARGUMENT_ERROR, "Not a valid time.");
}
- return time_alloc(mrb, (double)nowsecs, (double)ausec, timezone);
+ return time_alloc_time(mrb, nowsecs, ausec, timezone);
}
/* 15.2.19.6.2 */
@@ -474,18 +553,19 @@ mrb_time_cmp(mrb_state *mrb, mrb_value self)
static mrb_value
mrb_time_plus(mrb_state *mrb, mrb_value self)
{
- mrb_float f;
+ mrb_value o;
struct mrb_time *tm;
+ time_t sec, usec;
- mrb_get_args(mrb, "f", &f);
+ mrb_get_args(mrb, "o", &o);
tm = time_get_ptr(mrb, self);
- return mrb_time_make(mrb, mrb_obj_class(mrb, self), (double)tm->sec+f, (double)tm->usec, tm->timezone);
+ sec = mrb_to_time_t(mrb, o, &usec);
+ return mrb_time_make_time(mrb, mrb_obj_class(mrb, self), tm->sec+sec, tm->usec+usec, tm->timezone);
}
static mrb_value
mrb_time_minus(mrb_state *mrb, mrb_value self)
{
- mrb_float f;
mrb_value other;
struct mrb_time *tm, *tm2;
@@ -493,13 +573,22 @@ mrb_time_minus(mrb_state *mrb, mrb_value self)
tm = time_get_ptr(mrb, self);
tm2 = DATA_CHECK_GET_PTR(mrb, other, &mrb_time_type, struct mrb_time);
if (tm2) {
- f = (mrb_float)(tm->sec - tm2->sec)
- + (mrb_float)(tm->usec - tm2->usec) / 1.0e6;
+#ifndef MRB_WITHOUT_FLOAT
+ mrb_float f;
+ f = (mrb_sec)(tm->sec - tm2->sec)
+ + (mrb_sec)(tm->usec - tm2->usec) / 1.0e6;
return mrb_float_value(mrb, f);
+#else
+ mrb_int f;
+ f = tm->sec - tm2->sec;
+ if (tm->usec < tm2->usec) f--;
+ return mrb_fixnum_value(f);
+#endif
}
else {
- mrb_get_args(mrb, "f", &f);
- return mrb_time_make(mrb, mrb_obj_class(mrb, self), (double)tm->sec-f, (double)tm->usec, tm->timezone);
+ time_t sec, usec;
+ sec = mrb_to_time_t(mrb, other, &usec);
+ return mrb_time_make_time(mrb, mrb_obj_class(mrb, self), tm->sec-sec, tm->usec-usec, tm->timezone);
}
}
@@ -572,10 +661,9 @@ mrb_time_asctime(mrb_state *mrb, mrb_value self)
#else
char buf[256];
- len = snprintf(buf, sizeof(buf), "%s %s %02d %02d:%02d:%02d %s%d",
+ len = snprintf(buf, sizeof(buf), "%s %s %2d %02d:%02d:%02d %.4d",
wday_names[d->tm_wday], mon_names[d->tm_mon], d->tm_mday,
d->tm_hour, d->tm_min, d->tm_sec,
- tm->timezone == MRB_TIMEZONE_UTC ? "UTC " : "",
d->tm_year + 1900);
#endif
return mrb_str_new(mrb, buf, len);
@@ -616,7 +704,7 @@ mrb_time_getutc(mrb_state *mrb, mrb_value self)
tm2 = (struct mrb_time *)mrb_malloc(mrb, sizeof(*tm));
*tm2 = *tm;
tm2->timezone = MRB_TIMEZONE_UTC;
- time_update_datetime(mrb, tm2);
+ time_update_datetime(mrb, tm2, TRUE);
return mrb_time_wrap(mrb, mrb_obj_class(mrb, self), tm2);
}
@@ -631,7 +719,7 @@ mrb_time_getlocal(mrb_state *mrb, mrb_value self)
tm2 = (struct mrb_time *)mrb_malloc(mrb, sizeof(*tm));
*tm2 = *tm;
tm2->timezone = MRB_TIMEZONE_LOCAL;
- time_update_datetime(mrb, tm2);
+ time_update_datetime(mrb, tm2, TRUE);
return mrb_time_wrap(mrb, mrb_obj_class(mrb, self), tm2);
}
@@ -709,7 +797,7 @@ mrb_time_localtime(mrb_state *mrb, mrb_value self)
tm = time_get_ptr(mrb, self);
tm->timezone = MRB_TIMEZONE_LOCAL;
- time_update_datetime(mrb, tm);
+ time_update_datetime(mrb, tm, FALSE);
return self;
}
@@ -757,7 +845,7 @@ mrb_time_sec(mrb_state *mrb, mrb_value self)
return mrb_fixnum_value(tm->datetime.tm_sec);
}
-
+#ifndef MRB_WITHOUT_FLOAT
/* 15.2.19.7.24 */
/* Returns a Float with the time since the epoch in seconds. */
static mrb_value
@@ -768,32 +856,37 @@ mrb_time_to_f(mrb_state *mrb, mrb_value self)
tm = time_get_ptr(mrb, self);
return mrb_float_value(mrb, (mrb_float)tm->sec + (mrb_float)tm->usec/1.0e6);
}
+#endif
/* 15.2.19.7.25 */
-/* Returns a Fixnum with the time since the epoch in seconds. */
+/* Returns an Integer with the time since the epoch in seconds. */
static mrb_value
mrb_time_to_i(mrb_state *mrb, mrb_value self)
{
struct mrb_time *tm;
tm = time_get_ptr(mrb, self);
+#ifndef MRB_WITHOUT_FLOAT
if (tm->sec > MRB_INT_MAX || tm->sec < MRB_INT_MIN) {
return mrb_float_value(mrb, (mrb_float)tm->sec);
}
+#endif
return mrb_fixnum_value((mrb_int)tm->sec);
}
/* 15.2.19.7.26 */
-/* Returns a Float with the time since the epoch in microseconds. */
+/* Returns an Integer with the time since the epoch in microseconds. */
static mrb_value
mrb_time_usec(mrb_state *mrb, mrb_value self)
{
struct mrb_time *tm;
tm = time_get_ptr(mrb, self);
+#ifndef MRB_WITHOUT_FLOAT
if (tm->usec > MRB_INT_MAX || tm->usec < MRB_INT_MIN) {
return mrb_float_value(mrb, (mrb_float)tm->usec);
}
+#endif
return mrb_fixnum_value((mrb_int)tm->usec);
}
@@ -806,7 +899,7 @@ mrb_time_utc(mrb_state *mrb, mrb_value self)
tm = time_get_ptr(mrb, self);
tm->timezone = MRB_TIMEZONE_UTC;
- time_update_datetime(mrb, tm);
+ time_update_datetime(mrb, tm, FALSE);
return self;
}
@@ -821,6 +914,46 @@ mrb_time_utc_p(mrb_state *mrb, mrb_value self)
return mrb_bool_value(tm->timezone == MRB_TIMEZONE_UTC);
}
+static size_t
+time_to_s_utc(mrb_state *mrb, struct mrb_time *tm, char *buf, size_t buf_len)
+{
+ return strftime(buf, buf_len, TO_S_FMT "UTC", &tm->datetime);
+}
+
+static size_t
+time_to_s_local(mrb_state *mrb, struct mrb_time *tm, char *buf, size_t buf_len)
+{
+#if defined(_MSC_VER) && _MSC_VER < 1900 || defined(__MINGW64__) || defined(__MINGW32__)
+ struct tm datetime = {0};
+ time_t utc_sec = timegm(&tm->datetime);
+ size_t len;
+ int offset;
+
+ if (utc_sec == (time_t)-1) {
+ mrb_raise(mrb, E_ARGUMENT_ERROR, "Not a valid time.");
+ }
+ offset = abs((int)(utc_sec - tm->sec) / 60);
+ datetime.tm_year = 100;
+ datetime.tm_hour = offset / 60;
+ datetime.tm_min = offset % 60;
+ len = strftime(buf, buf_len, TO_S_FMT, &tm->datetime);
+ buf[len++] = utc_sec < tm->sec ? '-' : '+';
+
+ return len + strftime(buf + len, buf_len - len, "%H%M", &datetime);
+#else
+ return strftime(buf, buf_len, TO_S_FMT "%z", &tm->datetime);
+#endif
+}
+
+static mrb_value
+mrb_time_to_s(mrb_state *mrb, mrb_value self)
+{
+ char buf[64];
+ struct mrb_time *tm = time_get_ptr(mrb, self);
+ mrb_bool utc = tm->timezone == MRB_TIMEZONE_UTC;
+ size_t len = (utc ? time_to_s_utc : time_to_s_local)(mrb, tm, buf, sizeof(buf));
+ return mrb_str_new(mrb, buf, len);
+}
void
mrb_mruby_time_gem_init(mrb_state* mrb)
@@ -841,8 +974,8 @@ mrb_mruby_time_gem_init(mrb_state* mrb)
mrb_define_method(mrb, tc, "<=>" , mrb_time_cmp , MRB_ARGS_REQ(1)); /* 15.2.19.7.1 */
mrb_define_method(mrb, tc, "+" , mrb_time_plus , MRB_ARGS_REQ(1)); /* 15.2.19.7.2 */
mrb_define_method(mrb, tc, "-" , mrb_time_minus , MRB_ARGS_REQ(1)); /* 15.2.19.7.3 */
- mrb_define_method(mrb, tc, "to_s" , mrb_time_asctime, MRB_ARGS_NONE());
- mrb_define_method(mrb, tc, "inspect", mrb_time_asctime, MRB_ARGS_NONE());
+ mrb_define_method(mrb, tc, "to_s" , mrb_time_to_s , MRB_ARGS_NONE());
+ mrb_define_method(mrb, tc, "inspect", mrb_time_to_s , MRB_ARGS_NONE());
mrb_define_method(mrb, tc, "asctime", mrb_time_asctime, MRB_ARGS_NONE()); /* 15.2.19.7.4 */
mrb_define_method(mrb, tc, "ctime" , mrb_time_asctime, MRB_ARGS_NONE()); /* 15.2.19.7.5 */
mrb_define_method(mrb, tc, "day" , mrb_time_day , MRB_ARGS_NONE()); /* 15.2.19.7.6 */
@@ -862,7 +995,9 @@ mrb_mruby_time_gem_init(mrb_state* mrb)
mrb_define_method(mrb, tc, "sec" , mrb_time_sec, MRB_ARGS_NONE()); /* 15.2.19.7.23 */
mrb_define_method(mrb, tc, "to_i", mrb_time_to_i, MRB_ARGS_NONE()); /* 15.2.19.7.25 */
+#ifndef MRB_WITHOUT_FLOAT
mrb_define_method(mrb, tc, "to_f", mrb_time_to_f, MRB_ARGS_NONE()); /* 15.2.19.7.24 */
+#endif
mrb_define_method(mrb, tc, "usec", mrb_time_usec, MRB_ARGS_NONE()); /* 15.2.19.7.26 */
mrb_define_method(mrb, tc, "utc" , mrb_time_utc, MRB_ARGS_NONE()); /* 15.2.19.7.27 */
mrb_define_method(mrb, tc, "utc?", mrb_time_utc_p,MRB_ARGS_NONE()); /* 15.2.19.7.28 */
diff --git a/mrbgems/mruby-time/test/time.rb b/mrbgems/mruby-time/test/time.rb
index 54c446ca3..be1de7bc6 100644
--- a/mrbgems/mruby-time/test/time.rb
+++ b/mrbgems/mruby-time/test/time.rb
@@ -2,11 +2,11 @@
# Time ISO Test
assert('Time.new', '15.2.3.3.3') do
- Time.new.class == Time
+ assert_equal(Time, Time.new.class)
end
assert('Time', '15.2.19') do
- Time.class == Class
+ assert_equal(Class, Time.class)
end
assert('Time.at', '15.2.19.6.1') do
@@ -21,30 +21,58 @@ assert('Time.at', '15.2.19.6.1') do
end
assert('Time.gm', '15.2.19.6.2') do
- Time.gm(2012, 12, 23)
+ t = Time.gm(2012, 9, 23)
+ assert_operator(2012, :eql?, t.year)
+ assert_operator( 9, :eql?, t.month)
+ assert_operator( 23, :eql?, t.day)
+ assert_operator( 0, :eql?, t.hour)
+ assert_operator( 0, :eql?, t.min)
+ assert_operator( 0, :eql?, t.sec)
+ assert_operator( 0, :eql?, t.usec)
end
assert('Time.local', '15.2.19.6.3') do
- Time.local(2012, 12, 23)
+ t = Time.local(2014, 12, 27, 18)
+ assert_operator(2014, :eql?, t.year)
+ assert_operator( 12, :eql?, t.month)
+ assert_operator( 27, :eql?, t.day)
+ assert_operator( 18, :eql?, t.hour)
+ assert_operator( 0, :eql?, t.min)
+ assert_operator( 0, :eql?, t.sec)
+ assert_operator( 0, :eql?, t.usec)
end
assert('Time.mktime', '15.2.19.6.4') do
- Time.mktime(2012, 12, 23)
+ t = Time.mktime(2013, 10, 4, 6, 15, 58, 3485)
+ assert_operator(2013, :eql?, t.year)
+ assert_operator( 10, :eql?, t.month)
+ assert_operator( 4, :eql?, t.day)
+ assert_operator( 6, :eql?, t.hour)
+ assert_operator( 15, :eql?, t.min)
+ assert_operator( 58, :eql?, t.sec)
+ assert_operator(3485, :eql?, t.usec)
end
assert('Time.now', '15.2.19.6.5') do
- Time.now.class == Time
+ assert_equal(Time, Time.now.class)
end
assert('Time.utc', '15.2.19.6.6') do
- Time.utc(2012, 12, 23)
+ t = Time.utc(2034)
+ assert_operator(2034, :eql?, t.year)
+ assert_operator( 1, :eql?, t.month)
+ assert_operator( 1, :eql?, t.day)
+ assert_operator( 0, :eql?, t.hour)
+ assert_operator( 0, :eql?, t.min)
+ assert_operator( 0, :eql?, t.sec)
+ assert_operator( 0, :eql?, t.usec)
end
assert('Time#+', '15.2.19.7.1') do
t1 = Time.at(1300000000.0)
t2 = t1.+(60)
- assert_equal(t2.utc.asctime, "Sun Mar 13 07:07:40 UTC 2011")
+ assert_equal("Sun Mar 13 07:07:40 2011", t2.utc.asctime)
assert_raise(FloatDomainError) { Time.at(0) + Float::NAN }
assert_raise(FloatDomainError) { Time.at(0) + Float::INFINITY }
@@ -55,7 +83,7 @@ assert('Time#-', '15.2.19.7.2') do
t1 = Time.at(1300000000.0)
t2 = t1.-(60)
- assert_equal(t2.utc.asctime, "Sun Mar 13 07:05:40 UTC 2011")
+ assert_equal("Sun Mar 13 07:05:40 2011", t2.utc.asctime)
assert_raise(FloatDomainError) { Time.at(0) - Float::NAN }
assert_raise(FloatDomainError) { Time.at(0) - Float::INFINITY }
@@ -67,30 +95,30 @@ assert('Time#<=>', '15.2.19.7.3') do
t2 = Time.at(1400000000.0)
t3 = Time.at(1500000000.0)
- t2.<=>(t1) == 1 and
- t2.<=>(t2) == 0 and
- t2.<=>(t3) == -1 and
- t2.<=>(nil) == nil
+ assert_equal(1, t2 <=> t1)
+ assert_equal(0, t2 <=> t2)
+ assert_equal(-1, t2 <=> t3)
+ assert_nil(t2 <=> nil)
end
assert('Time#asctime', '15.2.19.7.4') do
- Time.at(1300000000.0).utc.asctime == "Sun Mar 13 07:06:40 UTC 2011"
+ assert_equal("Thu Mar 4 05:06:07 1982", Time.gm(1982,3,4,5,6,7).asctime)
end
assert('Time#ctime', '15.2.19.7.5') do
- Time.at(1300000000.0).utc.ctime == "Sun Mar 13 07:06:40 UTC 2011"
+ assert_equal("Thu Oct 24 15:26:47 2013", Time.gm(2013,10,24,15,26,47).ctime)
end
assert('Time#day', '15.2.19.7.6') do
- Time.gm(2012, 12, 23).day == 23
+ assert_equal(23, Time.gm(2012, 12, 23).day)
end
assert('Time#dst?', '15.2.19.7.7') do
- not Time.gm(2012, 12, 23).utc.dst?
+ assert_not_predicate(Time.gm(2012, 12, 23).utc, :dst?)
end
assert('Time#getgm', '15.2.19.7.8') do
- Time.at(1300000000.0).getgm.asctime == "Sun Mar 13 07:06:40 UTC 2011"
+ assert_equal("Sun Mar 13 07:06:40 2011", Time.at(1300000000.0).getgm.asctime)
end
assert('Time#getlocal', '15.2.19.7.9') do
@@ -98,114 +126,121 @@ assert('Time#getlocal', '15.2.19.7.9') do
t2 = Time.at(1300000000.0)
t3 = t1.getlocal
- t1 == t3 and t3 == t2.getlocal
+ assert_equal(t1, t3)
+ assert_equal(t3, t2.getlocal)
end
assert('Time#getutc', '15.2.19.7.10') do
- Time.at(1300000000.0).getutc.asctime == "Sun Mar 13 07:06:40 UTC 2011"
+ assert_equal("Sun Mar 13 07:06:40 2011", Time.at(1300000000.0).getutc.asctime)
end
assert('Time#gmt?', '15.2.19.7.11') do
- Time.at(1300000000.0).utc.gmt?
+ assert_predicate(Time.at(1300000000.0).utc, :gmt?)
end
# ATM not implemented
# assert('Time#gmt_offset', '15.2.19.7.12') do
assert('Time#gmtime', '15.2.19.7.13') do
- Time.at(1300000000.0).gmtime
+ t = Time.now
+ assert_predicate(t.gmtime, :gmt?)
+ assert_predicate(t, :gmt?)
end
# ATM not implemented
# assert('Time#gmtoff', '15.2.19.7.14') do
assert('Time#hour', '15.2.19.7.15') do
- Time.gm(2012, 12, 23, 7, 6).hour == 7
+ assert_equal(7, Time.gm(2012, 12, 23, 7, 6).hour)
end
# ATM doesn't really work
# assert('Time#initialize', '15.2.19.7.16') do
assert('Time#initialize_copy', '15.2.19.7.17') do
- time_tmp_2 = Time.at(7.0e6)
- time_tmp_2.clone == time_tmp_2
+ t = Time.at(7.0e6)
+ assert_equal(t, t.clone)
end
assert('Time#localtime', '15.2.19.7.18') do
- t1 = Time.at(1300000000.0)
- t2 = Time.at(1300000000.0)
+ t1 = Time.utc(2014, 5 ,6)
+ t2 = Time.utc(2014, 5 ,6)
+ t3 = t2.getlocal
- t1.localtime
- t1 == t2.getlocal
+ assert_equal(t3, t1.localtime)
+ assert_equal(t3, t1)
end
assert('Time#mday', '15.2.19.7.19') do
- Time.gm(2012, 12, 23).mday == 23
+ assert_equal(23, Time.gm(2012, 12, 23).mday)
end
assert('Time#min', '15.2.19.7.20') do
- Time.gm(2012, 12, 23, 7, 6).min == 6
+ assert_equal(6, Time.gm(2012, 12, 23, 7, 6).min)
end
assert('Time#mon', '15.2.19.7.21') do
- Time.gm(2012, 12, 23).mon == 12
+ assert_equal(12, Time.gm(2012, 12, 23).mon)
end
assert('Time#month', '15.2.19.7.22') do
- Time.gm(2012, 12, 23).month == 12
+ assert_equal(12, Time.gm(2012, 12, 23).month)
end
assert('Times#sec', '15.2.19.7.23') do
- Time.gm(2012, 12, 23, 7, 6, 40).sec == 40
+ assert_equal(40, Time.gm(2012, 12, 23, 7, 6, 40).sec)
end
assert('Time#to_f', '15.2.19.7.24') do
- Time.at(1300000000.0).to_f == 1300000000.0
+ assert_operator(2.0, :eql?, Time.at(2).to_f)
end
assert('Time#to_i', '15.2.19.7.25') do
- Time.at(1300000000.0).to_i == 1300000000
+ assert_operator(2, :eql?, Time.at(2.0).to_i)
end
assert('Time#usec', '15.2.19.7.26') do
- Time.at(1300000000.0).usec == 0
+ assert_equal(0, Time.at(1300000000.0).usec)
end
assert('Time#utc', '15.2.19.7.27') do
- Time.at(1300000000.0).utc
+ t = Time.now
+ assert_predicate(t.utc, :gmt?)
+ assert_predicate(t, :gmt?)
end
assert('Time#utc?', '15.2.19.7.28') do
- Time.at(1300000000.0).utc.utc?
+ assert_predicate(Time.at(1300000000.0).utc, :utc?)
end
# ATM not implemented
# assert('Time#utc_offset', '15.2.19.7.29') do
assert('Time#wday', '15.2.19.7.30') do
- Time.gm(2012, 12, 23).wday == 0
+ assert_equal(0, Time.gm(2012, 12, 23).wday)
end
assert('Time#yday', '15.2.19.7.31') do
- Time.gm(2012, 12, 23).yday == 358
+ assert_equal(358, Time.gm(2012, 12, 23).yday)
end
assert('Time#year', '15.2.19.7.32') do
- Time.gm(2012, 12, 23).year == 2012
+ assert_equal(2012, Time.gm(2012, 12, 23).year)
end
assert('Time#zone', '15.2.19.7.33') do
- Time.at(1300000000.0).utc.zone == 'UTC'
+ assert_equal('UTC', Time.at(1300000000.0).utc.zone)
end
# Not ISO specified
assert('Time#to_s') do
- Time.at(1300000000.0).utc.to_s == "Sun Mar 13 07:06:40 UTC 2011"
+ assert_equal("2003-04-05 06:07:08 UTC", Time.gm(2003,4,5,6,7,8,9).to_s)
end
assert('Time#inspect') do
- Time.at(1300000000.0).utc.inspect == "Sun Mar 13 07:06:40 UTC 2011"
+ assert_match("2013-10-28 16:27:48 [+-][0-9][0-9][0-9][0-9]",
+ Time.local(2013,10,28,16,27,48).inspect)
end
assert('day of week methods') do
@@ -224,7 +259,7 @@ assert('2000 times 500us make a second') do
2000.times do
t += 0.0005
end
- t.usec == 0
+ assert_equal(0, t.usec)
end
assert('Time.gm with Dec 31 23:59:59 1969 raise ArgumentError') do