110 Commits

Author SHA1 Message Date
Yukihiro "Matz" Matsumoto 8956c5abb5 mruby.h: include mruby/presym.h for all source files
Since presym is now mandatory, mruby.h includes presym.h so that
MRB_SYM() macros are available everywhere without explicit include.
Remove redundant #include <mruby/presym.h> from all source files.

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-09 16:50:58 +09:00
Yukihiro "Matz" Matsumoto 613b03ac18 mruby-compiler: add no_return_value context flag for script optimization
when running scripts via mruby -e or file, return values are unused.
this adds a no_return_value flag to skip generating unnecessary code.

for parallel assignment like a,b = 1,2:
- before: 18 bytes, 5 registers, creates temporary array
- after: 5 bytes, 3 registers, direct register assignment, no RETURN

the flag is set only for the main program, not for libraries loaded
with -r option. eval() and mirb continue returning values correctly.

Co-authored-by: Claude <noreply@anthropic.com>
2025-12-21 17:26:49 +09:00
Yukihiro "Matz" Matsumoto 9ad72e3a96 mrbgems: add README documentation for mruby-bin-* gems
- mruby-bin-config
- mruby-bin-debugger
- mruby-bin-mrbc
- mruby-bin-mruby
- mruby-bin-strip

Co-authored-by: Claude <noreply@anthropic.com>
2025-12-11 18:09:10 +09:00
Yukihiro "Matz" Matsumoto 40b0cb98f7 mruby.h: add MRB_OPEN_FAILURE() macro and refactor MRB_OPEN_SUCCESS()
since all current uses check for failure (!MRB_OPEN_SUCCESS), add
MRB_OPEN_FAILURE() as the primary macro for better readability. define
MRB_OPEN_SUCCESS() in terms of MRB_OPEN_FAILURE() to avoid duplication
and optimize the common case. update all usage sites to use the clearer
MRB_OPEN_FAILURE() form.

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-16 06:53:02 +09:00
Yukihiro "Matz" Matsumoto 8e50a45f3e mrb_print_error: handle NULL gracefully to simplify error checking
made mrb_print_error() handle NULL by printing "Failed to allocate
mrb_state" when mrb is NULL. since mrb_close() already handles NULL,
this allows simplified error checking pattern:

  if (!MRB_OPEN_SUCCESS(mrb)) {
    mrb_print_error(mrb);  // handles NULL
    mrb_close(mrb);        // handles NULL
    return EXIT_FAILURE;
  }

updated all binary tools (mruby, mirb, mrdb, mrbtest) to use this
simplified pattern, removing nested if checks.

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-14 00:49:55 +09:00
Yukihiro "Matz" Matsumoto 05ffe0c441 mrb_open: return mrb_state with exc set on init failure
changed mrb_open() and mrb_open_core() to return mrb_state with mrb->exc
set (instead of NULL) when initialization fails. this allows callers to
programmatically inspect error details, which is essential for embedded
systems without stderr. return NULL only for true allocation failure.

added MRB_OPEN_SUCCESS(mrb) macro to check initialization success, since
mrb != NULL no longer guarantees success. updated all binary tools
(mruby, mirb, mrdb, mrbtest) to use new pattern: check MRB_OPEN_SUCCESS,
print exception details via mrb_print_error if available, then mrb_close.

mrb_core_init_protect now preserves exception in mrb->exc instead of
printing and clearing it, giving caller control over error handling.

breaking change: callers must use MRB_OPEN_SUCCESS(mrb) or check both
mrb != NULL && mrb->exc == NULL. old NULL-only checks will miss
initialization failures.

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-13 19:10:46 +09:00
dearblue aac7751ed4 Stop generating unnecessary C++ files in mruby-bin-mruby
This is probably a remnant from when `MRB_TRY()` was used in the past.
2025-08-31 23:15:23 +09:00
Yukihiro "Matz" Matsumoto 9fc58852e3 mruby-compiler: removed mrb_state dependency from two functions
- mrb_ccontext_partial_hook
- mrb_ccontext_cleanup_local_variables
2025-05-19 08:00:36 +09:00
John Bampton 781edbd446 misc: fix spelling 2025-05-14 02:01:02 +10:00
Yukihiro "Matz" Matsumoto 003e0fb330 mruby-print: disable the gem unless explicitly specified
mruby-print is the duplicate of part of mruby-io. You need it only when
limited I/O functionality required.
2025-01-06 13:57:23 +09:00
dearblue 1326017d1d Omit the _WIN64 definition check
Checking the official MSVC documentation, if `_WIN64` is defined, then `_WIN32` is also defined.
https://learn.microsoft.com/en-us/cpp/preprocessor/predefined-macros

I could not find any documentation on MinGW, but I assume it is not a problem.
2024-12-07 22:47:28 +09:00
Yukihiro "Matz" Matsumoto 65e0e5bbd3 class.c (mrb_method_missing): add receiver's class to clarify
We needed to modify a lot of test code that expected the old style.
2024-11-15 15:13:24 +09:00
Yukihiro "Matz" Matsumoto 6c2ed55077 mruby-bin-mruby: remove unused assignments 2024-01-16 12:28:32 +09:00
Yukihiro "Matz" Matsumoto 0e079fe946 mruby-bin-mruby: reduce the scope of a loop variable i 2024-01-15 23:04:18 +09:00
Yukihiro "Matz" Matsumoto 9298dfb927 mruby-bin-mruby: reduce the scope of a local variable c 2024-01-15 23:03:34 +09:00
Yukihiro "Matz" Matsumoto 90fac46751 mruby-bin-mruby: remove unnecessary condition 2024-01-15 23:00:46 +09:00
Yukihiro "Matz" Matsumoto 7e74dbeed3 mruby-bin-mruby: replace mrbc_ prefix by mrb_ccontext 2023-12-06 15:45:01 +09:00
Yukihiro "Matz" Matsumoto eea72ec84a fix spaces in the type cast expressions (cosmetic changes) 2023-05-18 23:29:16 +09:00
dearblue 38d5ed44e1 Avoid exposure for REnv objects
The `REnv` object is difficult to deal with, and it would be ideal if the user did not have to manipulate it directly.
In some previous situations, it was necessary to call `mrb_env_unshare()`, a non-API function, after `mrb_load_string()` or similar.

With this patch, it is no longer necessary for users to use `mrb_env_unshare()` directly, as it is now handled internally simply by using the `mrb_vm_ci_env_clear()` function.
Also, `mrb_vm_ci_env_set()` is demoted from the `MRB_API` function for the same reason.

ref. commit 1ab3da6f08
2023-03-05 17:45:47 +09:00
Yukihiro "Matz" Matsumoto 9c5dc42e59 small cosmetic changes.
I prefer `i++` style unless absolutely necessary.
This commit is an addition to 41e4148.
2022-11-19 17:11:56 +09:00
Yukihiro "Matz" Matsumoto 07470eb538 mruby-exit.c: make exit() to raise SystemExit exception.
Now it allows error handlers to work, unlike `exit!`.
2022-09-21 22:37:23 +09:00
dearblue be3c0e5f4f Improve out-of-memory tolerance of mrb_env_unshare()
Exception raising can now be controlled by the caller.

The main purpose on this patch is:

- Suppress exceptions from `obj_free()` in `src/gc.c` with `mrb_env_unshare()`.

- Consider the possibility that calls to `mrb_malloc()` may cause `e` objects to be subject to GC.

  When control is returned to `mrb_env_unshare()`, `struct free_obj::next` in the same offset as `struct REnv::stack` is rewritten.
  Unexpected results then occur when the object is reused.
  Also, if `mrb_heap_page` containing an `e` object is freed, it may cause `SIGSEGV` at that point.

- Protects the value of the stack on `callinfo` that just exits if GC occurs inside `mrb_env_unshare()`.

  ```ruby
  def m
    b = -> { b }
  end

  p m.call
  # => print block object, not nil
  ```

  This patch does not raise a `NoMemoryError` exception in `mrb_env_unshare()` and can detect that error.
  Thus, the problem fixed in # 3087 is not resurrected.

Also, it may seem that this patch should suppress exceptions raised by `cipop()` during `mrb_protect_error()` and `mrb_vm_exec()` unwinds.
However, `mrb_callinfo::u.env` by `CINFO_DIRECT` is not seen to be set.
So in that case `mrb_env_unshare()` is assumed to be originally exception-free.
2022-07-30 22:32:00 +09:00
Yukihiro "Matz" Matsumoto e24e81cd3c mruby.c: rindex() is not supported by VC. 2022-02-06 22:44:02 +09:00
Yukihiro "Matz" Matsumoto cf00c32e3a mruby.c: -b option should only affects the script.
Not the libraries loaded by `-r`. Instead, `.mrb` extension in the path
should determine whether they are compiled binary.
2022-02-06 22:17:41 +09:00
Chris Reuter 5c4273f944 Added testing support for cross-MinGW builds.
This adds a build_config that will cross-build a Windows executable
using the MinGW cross-compiler and will also run the unit (i.e.
'rake test') using Wine.

For this to work, I made some modifications to the underlying test
scripts as well as some minor changes to a couple of the tests
themselves.
2021-10-21 21:58:45 -04:00
Yukihiro "Matz" Matsumoto f22535045a mruby.c: specify file names for libraries set by -r; fix #5427 2021-04-26 19:00:49 +09:00
Yukihiro "Matz" Matsumoto 4d249c28d9 Skip tests that use Float inside; ref #5421 2021-04-24 12:04:08 +09:00
Yukihiro "Matz" Matsumoto 590c1073fc should have removed codegen error: prefix from the test. 2021-03-31 11:35:56 +09:00
Yukihiro "Matz" Matsumoto bec4d30dc6 Merge branch 'reorganize-ci' of https://github.com/dearblue/mruby into dearblue-reorganize-ci 2021-01-12 18:38:42 +09:00
Yukihiro "Matz" Matsumoto 1310368b3f Silence Windows warnings (cast and setmode). 2021-01-12 16:25:30 +09:00
dearblue 58e9442737 Unified target_class and env of mrb_callinfo
If there is `env`, `env->c` means `target_class`.
2021-01-10 13:23:28 +09:00
KOBAYASHI Shuji 456878ba06 Improve source scanning for presym
The accuracy is greatly improved by using the C preprocessor to scan C
sources for presym. C preprocessor can perfectly interpret all comments and
preprocessor directives, so it can detect all symbols defined, for example
`mrbgems/mruby-socket/src/const.cstub`.

Also, as described later, this change will greatly improve the accuracy of
presym detection from Ruby sources.

## Result

The number of lines in the `presym` file for all gems is as follows:

  ```console
  Previous:   999 (false positive = 89, undetected = 297)
  New:       1207
  ```

## Build process

The new build process (with presym) is as follows:

1. Build `mrbc` without presym (more on building without presym later).
2. Compile Ruby sources to C struct format with the `mrbc` created in
   step 1, and create` mrblib.c` and `gem_init.c`. Note that the symbols
   in the created files are output as `MRB_SYM` family macros or
   `mrb_intern_lit` instead of IDs (details will be described later).
3. C preprocessor processes C sources including the created files of
   step 2 and outputs them as `.i` files. In these files, for example,
   `MRB_IVSYM(foo)` is converted to `<@! "@" "foo" !@>` and
   `mrb_define_module(mrb, "Foo")` is converted to `<@! "Foo" !@>`.
4. Scan the files created in step 3 and create `presym` and` presym.inc`
   files.

The files created in step 2 should output all static symbols defined in Ruby
sources, including local variables, so we can detect all presyms by just
scanning C sources without scanning Ruby sources directly.

Further, by this process, the files to be scanned becomes the same as the
files to be compiled, so that there is no excess or deficiency.

## Related changes

The following changes have been made in relation to realizing this feature.

### Allow build without presym

It enables build without presym to achieve the "Build process: 1". This
incorporates #5202, see its issue for details.

Note that when presym is enabled, even adding a local variable to a Ruby
source may change contents of presym and require recompilation of almost
all C sources. This is inconvenient, especially during trial and error in
development, but this feature is also useful because it does not cause
this problem if presym is disabled.

### Automatically create build target for `mrbc` without presym

The `mrbc` used in the "Build process: 1" will be built by automatically
creating a build target for it. The build name is `SOURCE_BUILD_NAME/mrbc`.

### Constantize output of C struct format by `mrbc`

To realizing the "Build process: 2", as mentioned above, symbol IDs are not
output directly in C struct format output by `mrbc`. As a result, the output
becomes constant regardless of the state of presym at the time of `mrbc`
build, and it is possible to detect symbols of Ruby sources in the same way
as other C sources.

Note that `mrb_intern_lit` is used for symbols that do not become presym,
but in this state, the corresponding element in the symbol array cannot be
statically initialized, so it is initialized at run time (therefore, in this
case, the `const` qualifier is not added to the symbol array).

### Specify arbitrary `mrbc` file

To realizing the "Build process: 2", enabled to specify `mrbc` created by
another build target or pre-built` mrbc`. Use `MRuby::Build#mrbcfile =` to
specify it explicitly. You can omit the "Build process: 1" by specifying
pre-built `mrbc`, and you can always use an optimized build to compile Ruby
sources faster. I think changes that affect the output of `mrbc` are rare,
so in many cases it helps to improve efficiency.

With presym, the build will be a little slower due to more build steps, but
this feature will improve it a bit.

### Create presym files for each build target

This feature was proposed at #5194 and merged once, but was reverted in
5c205e6e due to problems especially with cross-compilation. It has been
introduced again because this change solves the problem.

The presym files will be created below.

* `build/NAME/presym`
* `build/NAME/include/mruby/presym.inc`

### Other changes

* Because presym detection accuracy is greatly improved as mentioned above,
  `MRuby::Gem::Specification#cdump?` is set to true by default, and
  `disable_cdump` is added instead of `enable_cdump`. Also, support for gem
  specific presym files has been discontinued (https://github.com/mruby/mruby/issues/5151#issuecomment-730967232).
* Previously, `mrbc` was automatically created for the `host` build, but it
  will not be created if the build target for `mrbc` mentioned above is
  automatically created. At this time, `mrbc` file of the `mrbc` build is
  copied to` bin/`.
* Two types of `.d` files will be created, `.o.d` and `.i.d`. oThis is
  because if `.i` depends on `presym.inc`, the dependency will circulate, so
  the `.d` file cannot be shared.
* Changed file created with `enable_cxx_exception` to `X-cxx.cxx` from
  `X.cxx` to use the mruby standard Rake rule.

### Note

Almost all C sources will need to be recompiled if there are any changes to
`persym.inc` (if not recompiled properly, it will often result in run-time
error). If `gcc` toolchain is used, dependencies are resolved by the `.d`
file, so it become automatically recompile target, but if not (e.g. MSVC),
it is necessary to manually make it recompile target.

Also, even if `gcc` toolchain is used, it may not become recompile target if
external gems does not use the mruby standard Rake rule. In particular, if
the standard rule is overwritten, such as
https://github.com/mruby/mruby/pull/5112/files, `.d` file will not be read,
so be careful.
2020-12-13 15:27:53 +09:00
KOBAYASHI Shuji 3d056d084a Rename MRB_{ENABLE,DISABLE}_ to MRB_{USE,NO}_; close #5163
|        Previous Name         |        New Name         |
|------------------------------|-------------------------|
| MRB_ENABLE_ALL_SYMBOLS       | MRB_USE_ALL_SYMBOLS     |
| MRB_ENABLE_SYMBOLL_ALL       | MRB_USE_ALL_SYMBOLS     |
| MRB_ENABLE_CXX_ABI           | MRB_USE_CXX_ABI         |
| MRB_ENABLE_CXX_EXCEPTION     | MRB_USE_CXX_EXCEPTION   |
| MRB_ENABLE_DEBUG_HOOK        | MRB_USE_DEBUG_HOOK      |
| MRB_DISABLE_DIRECT_THREADING | MRB_NO_DIRECT_THREADING |
| MRB_DISABLE_STDIO            | MRB_NO_STDIO            |
| ENABLE_LINENOISE             | MRB_USE_LINENOISE       |
| ENABLE_READLINE              | MRB_USE_READLINE        |
| DISABLE_MIRB_UNDERSCORE      | MRB_NO_MIRB_UNDERSCORE  |
| DISABLE_GEMS                 | MRB_NO_GEMS             |

* `MRB_ENABLE_SYMBOLL_ALL` seems to be a typo, so it is fixed.
* `MRB_` prefix is added to those without.
* The previous names can also be used for compatibility.
2020-11-21 21:14:40 +09:00
dearblue a045b6b8d9 Allow to mixed and specify *.rb and *.mrb in bin/mruby
It is not decides by the extension.
In order to be recognized as a `.mrb` file, the following three points must be satisfied:
- File starts with "RITE"
- At least `sizeof(struct rite_binary_header)` bytes can be read
- `NUL` is included in the first 64 bytes of the file
If these are not met, it is judged as a text file and it is processed as a Ruby script.

The `bin/mruby -b` switch is still available which treats the given file as a `.mrb` file.

New `MRB_API` function:
- `include/mruby/compile.h` and `mrbgems/mruby-compiler/core/parse.y`
  - `mrb_load_detect_file_cxt()` (remove with `MRB_DISABLE_STDIO`)

NOTE:
- Even script files now always open in binary mode for `bin/mruby`.
  The `\r\n` is handled by the `nextc()` function already, so there is no problem even on Windows.
- The `nextc0()` function in `mrbgems/mruby-compiler/core/parse.y` can now specify a string buffer and a file pointer at the same time.
  In this case, get it from the string buffer first.

This patch includes modifies by comment of https://github.com/mruby/mruby/pull/5157.
2020-11-21 19:05:46 +09:00
mimaki 943029954f Fix mruby -v option test. 2020-11-01 14:19:19 +09:00
Yukihiro "Matz" Matsumoto 33742d941f Move build_config.rb -> build_config/default.rb; ref #5098
In addition, update the documents referring `build_config.rb` which is
no longer used. The new `build_config.rb` describes the new configuration
structure in the comment.
2020-10-29 11:49:05 +09:00
Yukihiro "Matz" Matsumoto c27e451931 Merge pull request #4933 from dearblue/variables
Fix take over file scope variables with `mruby` and `mirb` command
2020-09-10 18:12:38 +09:00
dearblue 6d80c9505d Remove unused mruby-error in mruby-bin-mruby 2020-04-26 21:16:22 +09:00
dearblue 67606170e3 Add configuration guard for MRB_DISABLE_STDIO
ref #4576 and ref #4947

* Need MRBAPI functions without `MRB_DISABLE_STDIO`:
  * mrbgems/mruby-bin-debugger
  * mrbgems/mruby-bin-mirb
  * mrbgems/mruby-bin-mrbc
  * mrbgems/mruby-bin-mruby
  * mrbgems/mruby-bin-strip
* Need `stdio.h`:
  * mrbgems/mruby-io
  * mrbgems/mruby-print
* Need `snprintf()` in `stdio.h`:
  * mrbgems/mruby-pack
  * mrbgems/mruby-sprintf
2020-03-08 21:57:17 +09:00
dearblue cc1db2d117 Remove unnecessary 'stdio.h'; ref #4947
'stdio.h' is included in 'mruby.h' ('mrbconf.h').

However, keep 'stdio.h' used by mruby-test.
2020-03-08 21:42:09 +09:00
dearblue 9840e5352b Isolate top-level local variables by file scope; fix #4931 2020-01-29 23:30:13 +09:00
dearblue 0aa5aa1de2 Add test for top level local variables are in file scope; ref #4931 2020-01-29 23:29:48 +09:00
dearblue 2bab6e197d Fix take over file scope variables with mruby command
Resolve #4931
2020-01-19 21:52:37 +09:00
Yukihiro "Matz" Matsumoto ef95a9fa93 Use a string as a common regexp representation; ref #4847 2019-11-30 21:10:36 +09:00
KOBAYASHI Shuji 49653b81ea Quit mruby -v immediately if no program is given for Ruby compatibility 2019-11-30 19:52:22 +09:00
KOBAYASHI Shuji df437eebcc Fix mruby --verbose (regression by #4827)
#### Before this patch:

  ```
  $ bin/mruby --verbose -e 'p 1'
  bin/mruby: Cannot open program file: --verbose
  ```

#### After this patch:

  ```
  $ bin/mruby --verbose -e 'p 1'
  00001 NODE_SCOPE:
  (snip)
  irep 0x7fe97041df30 nregs=4 nlocals=1 pools=0 syms=1 reps=0 iseq=11
  file: -e
      1 000 OP_LOADSELF R1
  (snip)

  1
  ```
2019-11-29 19:02:04 +09:00
KOBAYASHI Shuji f4b528e07a Support -- (end of options) to mruby command
#### Before this patch:

  ```
  $ bin/mruby -e 'p ARGV' -- -x
  bin/mruby: invalid option -- (-h will show valid options)
  ```

#### After this patch:

  ```
  $ bin/mruby -e 'p ARGV' -- -x
  ["-x"]
  ```
2019-11-27 19:51:43 +09:00
KOBAYASHI Shuji f9bd414350 Fix ARGV value in mruby command (regression by #4827)
#### Before this patch:

  ```
  $ bin/mruby -e 'p ARGV' a b
  ["bin/mruby", "-e", "p ARGV", "a", "b"]
  ```

#### After this patch:

  ```
  $ bin/mruby -e 'p ARGV' a b
  ["a", "b"]
  ```
2019-11-25 21:56:27 +09:00
KOBAYASHI Shuji 9de7130a9a Support short options concatenation to mruby command
#### Before this patch:

  ```
  $ bin/mruby -ce 1
  bin/mruby: Cannot open program file: 1
  ```

#### After this patch:

  ```
  $ bin/mruby -ce 1
  Syntax OK
  ```
2019-11-17 16:38:50 +09:00
KOBAYASHI Shuji 0cdc984b1c Refine the usage message of mruby command 2019-10-06 19:35:41 +09:00