Change soft-fail to use the config, rather than env
[rbx.git] / README-DEVELOPERS
blobe2488d8603bcc949f80d99ec6396186a94b525a9
1 # vim: tw=65
3 General help and instructions on writing code for Rubinius.
6 0. Further Reading
7 ==================
8 At some point, you should read everything in doc/. It is not
9 necessary to understand or memorise everything but it will
10 help with the big picture at least!
13 1. Files and Directories
14 ========================
15 Get to know your way around the place!
17 * .load_order.txt
18   Explains the dependencies between files so the VM can load them
19   in the correct order.
21 * kernel/
22   The Ruby half of the implementation. The classes, methods etc.
23   that make up the Ruby language environment are defined here.
24   Further divided into..
26 * runtime/platform.conf
27   kernel/platform/
28   Platform-dependent code wrappers that can then be used in other
29   kernel code. platform.conf is an autogenerated file that defines
30   various platform-dependent constants, offsets etc.
32 * kernel/bootstrap/
33   Minimal set of incomplete core classes that is used to load up
34   the rest of the system. Any code that requires Rubinius' special
35   abilities needs to be here too.
37 * kernel/core/
38   Complete implementation of the core classes. Builds on and/or
39   overrides bootstrap/. Theoretically this code should be portable
40   so all Rubinius-dependent stuff such as primitives goes in
41   bootstrap/ also.
43 * runtime/
44   Contains run-time compiled files for Rubinius. You'll use these
45   files when running shotgun/rubinius
47 * runtime/stable/*
48   Known-good versions of the Ruby libraries that are used by the
49   compiler to make sure you can recompile in case you break one
50   of the core classes.
52 * shotgun/
53   The C parts. This top-level directory contains most of the build
54   process configuration as well as the very short main.c.
56 * shotgun/lib/
57   All of the C code that implements the VM as well as the extremely
58   bare-bones versions of some Ruby constructs.
60 * shotgun/external_libs/
61   Libraries required by Rubinius, bundled for convenience.
63 * lib/
64   All Ruby Stdlib libraries that are verified to work as well as
65   any Rubinius-specific standard libraries. Of special interest
66   here are three subdirectories:
68 * lib/bin/
69   Some utility programs such as lib/bin/compile.rb which is used
70   to compile files during the build process.
72 * lib/ext/
73   C extensions that use Subtend.
75 * lib/compiler/
76   This is the compiler (implemented completely in Ruby.)
78 * stdlib/
79   This is the Ruby Stdlib, copied straight from the distribution.
80   These libraries do not yet work on Rubinius (or have not been
81   tried.) When a library is verified to work, it is copied to
82   lib/ instead.
84 * bin/
85   Various utility programs like bin/mspec (the spec runner frontend).
87 * benchmark/
88   All benchmarks live here. The rubinius/ subdirectory is not in
89   any way Rubinius-only, all those benchmarks were just written 
90   as part of this project (the rest are from somewhere else.)
92 * spec/ and test/
93   These contain the behaviour specification and verification files.
94   See section 3 for information about specs. The test/ directory is
95   deprecated but some old test code lives here.
98 Notes: Occasionally working with kernel/ you may seem classes that
99        are not completely defined or looks strange. Remember that
100        some classes are set up in the VM and we are basically just
101        reopening those classes.
104 2. Working with Kernel classes
105 ==============================
107 Any time you make a change here -- or anywhere else for that
108 matter -- make sure you do a full rebuild to pick up the changes,
109 then run the related specs, and then 'run bin/mspec ci' to make
110 sure that also the *unrelated* specs still work (minimal-seeming
111 changes may have broad consequences.)
113 There are a few special forms that are used in bootstrap/ as well
114 as core/ such as @ivar_as_index@ (see 2.2) which maps instance
115 variable names to internal fields. These impose special restrictions
116 on their usage so it is best to follow the example of existing
117 code when dealing with these. Broadly speaking, if something looks
118 "unrubyish", there is probably a good reason for it so make sure
119 to ask before doing any "cosmetic" changes -- and to run CI after.
121 If you modify a kernel class, you need to `rake build` after to
122 have the changes picked up. With some exceptions, you should not
123 regenerate the stable files. They will in most cases work just fine
124 even without the newest code. `rake build:stable` is the command
125 for that.
127 If you create a new file in one of the kernel subdirectories, it
128 will be necessary to regenerate the .load_order.txt file in the
129 equivalent runtime subdirectory in order to get your class loaded
130 when Rubinius starts up. Use the rake task build:load_order to
131 regenerate the .load_order.txt files.
133 Due to the dependencies inherent in writing the Core in Ruby, there
134 is one idiom used that may confuse on first sight. Many methods are
135 called #some_method_cv and the _cv stands for 'core version,' not
136 one of the other things you thought it might be. The idea is that
137 a simple version of a given method is used until everything is
138 safely loaded, at which point it is replaced by the real version.
139 This happens in WhateverClass.after_loaded (and it is NOT automated.)
142 2.1 Safe Math Compiler Plugin
143 -----------------------------
145 Since the core libraries are built of the same blocks as any other
146 Ruby code and since Ruby is a dynamic language with open classes and
147 late binding, it is possible to change fundamental classes like
148 Fixnum in ways that violate the semantics that other classes depend
149 on. For example, imagine we did the following:
151     class Fixnum
152       def +(other)
153         (self + other) % 5
154       end
155     end
157 While it is certainly possible to redefine fixed point arithmetic plus
158 to be modulo 5, doing so will certainly cause some class like Array to
159 be unable to calculate the correct length when it needs to. The dynamic
160 nature of Ruby is one of its cherished features but it is also truly a
161 double-edged sword in some respects.
163 In Stdlib, the 'mathn' library redefines Fixnum#/ in an unsafe and
164 incompatible manner. The library aliases Fixnum#/ to Fixnum#quo,
165 which returns a Float by default.
167 Because of this there is a special compiler plugin that emits a different
168 method name when it encounters the #/ method. The compiler emits #divide
169 instead of #/. The numeric classes Fixnum, Bignum, Float, and Numeric all
170 define this method.
172 The `-frbx-safe-math` switch is used during the compilation of the Core
173 libraries to enable the plugin. During regular 'user code' compilation,
174 the plugin is not enabled. This enables us to support mathn without
175 breaking the core libraries or forcing inconvenient practices.
178 2.2 ivar_as_index
179 -----------------
181 As described above, you'll see calls to @ivar_as_index@ kernel code.
182 This maps the class's numbered fields to ivar names, but ONLY for
183 that file.
185 You can NOT access those names using the @name syntax outside of that
186 file. (Doing so will cause maddeningly odd behavior and errors.)
188 For instance, if you make a subclass of IO, you can NOT access @descriptor
189 directly in your subclass. You must go through methods to access it only.
190 Notably, you can NOT just use the @#attr_*@ methods for this. The methods
191 must be completely written out so that the instance variable label can
192 be picked up to be translated.
195 2.3 Kernel- and user-land
196 -------------------------
198 Rubinius is in many ways architected like an operating system, so some
199 OS world terms may be easiest to describe the two modes that Rubinius
200 operates under:
202 'Kernel-land' describes how code in kernel/ is executed. Everything else
203 is 'user-land.'
205 Kernel-land has a number of restrictions to keep things sane and simple:
207 * #public, #private, #protected, #module_function require method names
208   as arguments. The 0-argument version that allows toggling visibility
209   in a class or module body is not available.
211 * Restricted use of executable code in class, module and script (file)
212   bodies. @SOME_CONSTANT = :foo@ is perfectly fine, of course, but for
213   example different 'memoizations' or other calculation should not be
214   present. Code inside methods has no restrictions, broadly speaking,
215   but keep dependency issues in mind for methods that may get called
216   during the instantiation of the rest of the kernel code.
218 * @#after_loaded@ hooks can be used to perform more complex/extended
219   setup or calculations for kernel classes. The @_cv@ methods mentioned
220   above, for example, are replaced over the simpler bootstrap versions
221   in the @#after_loaded@ hooks of the respective classes. @#after_loaded@
222   is not magic, and will not be automatically called. If adding a new
223   one, have kernel/loader.rb call it (at this point the system is
224   fully up.)
226 * Kernel-land code does not use handle defining methods through
227   @Module#__add_method__@ nor @MetaClass#attach_method@. It adds
228   and attaches methods directly in the VM. This is necessary for
229   bootstrapping.
231 * Any use of string-based eval in the kernel must go through discussion.
234 3. Specs (Specifications)
235 =========================
237 Probably the first or second thing you hear about Rubinius when
238 speaking to any of the developers is a mention of The Specs. It
239 is a crucial part of Rubinius.
241 Rubinius itself is being developed using the Behaviour-Driven
242 Design approach (a refinement of Test-Driven Design) where each
243 aspect of the behaviour of the code is first specified using the
244 spec format and only then implemented to pass those specs.
246 In addition to this, we have undertaken the ambitious task of
247 specifying the entirety of the Ruby language as well as its Core
248 and Stdlib libraries in this format which both allows us to
249 ensure our implementation is conformant with the Ruby standard
250 and, more importantly, to actually *define* that standard since
251 there currently is no formal specification of Ruby.
253 The de facto standard of BDD is set by "RSpec":http://rspec.info,
254 the project conceived to implement the then-new way of coding.
255 Their website is fairly useful as a tutorial as well, although
256 the spec syntax (particularly as used in Rubinius) is not very
257 complex at all.
259 Currently we actually use a compatible but vastly simpler
260 implementation specifically developed as a part of Rubinius
261 called MSpec (for mini-RSpec, as it was originally needed because
262 the code in RSpec was too complex to be run on our
263 not-yet-complete Ruby implementation.)
265 Specs live in the spec/ directory. The spec/ directory contains
266 two copies of the RubySpecs (http://rubyspec.org). The
267 spec/frozen directory is a git submodule and is synchronized with
268 the tag files in spec/tags/frozen. The tag files are used to
269 exclude known failures. The spec/frozen specs are used as a CI
270 (continuous integration) process to ensure that new code does not
271 cause regressions. The spec/ruby directory is a git clone of the
272 RubySpecs and is included for the convenience of adding to the
273 RubySpecs from within the Rubinius repository.
275 All the other directories under the spec directory except for
276 spec/ruby and spec/frozen are for specs specific to Rubinius. The
277 directories are self-explanatory. For example, the spec/compiler
278 directory is for specs for the Rubinius compiler. Three
279 directories could be confusing so those are described in more
280 detail here.
282 The spec/core directory is for Rubinius specific extensions to
283 MatzRuby core library. For example, Rubinius has a Tuple and
284 ByteArray class. The specs for these are under the spec/core
285 directory. This directory is also for Rubinius specific
286 extensions to methods of the MatzRuby core library classes. For
287 example, Rubinius handles coercion of Bignum and other numeric
288 differently. The spec/core directory parallels the purpose of the
289 spec/ruby/1.8/core directory from the RubySpecs.
291 The spec/language directory contains Rubinius specific specs
292 related to the Ruby language. The directory parallels the
293 spec/ruby/1.8/language directory.
295 The spec/library directory contains Rubinius specific standard
296 library classes (e.g. Actor, VMActor) and Rubinius specific
297 behavior of methods of MatzRuby standard library classes.
299 The specs are run with the bin/mspec command. See the help output
300 from bin/mspec -h and refer to the links below for more details.
301 In general, to run the specs for a specific spec file, use:
303   bin/mspec spec/some/spec_file.rb
305 The CI specs are run with rake spec or bin/mspec ci. CI is very
306 important for any Rubinius developer: before each commit,
307 bin/mspec ci should be run and should finish without error. It
308 makes it very easy to ensure that your change did not break
309 other, seemingly unrelated things because it exercises all areas
310 of specs. A clean bin/mspec ci run gives confidence that your
311 code is correct. Since there are a very large body of specs, the
312 CI specs run by bin/mspec ci do not include the Ruby standard
313 library specs. To run these specs as well, use rake spec:full or
314 bin/mspec ci -B full.mspec.
316 For a deeper overview, tutorials, help and other information
317 about Rubinius' specs, start here:
319 http://rubyspec.org
320 http://rubinius.lighthouseapp.com/projects/5089/the-rubinius-specs
323 4. Libraries and C: Primitives vs. FFI
324 ======================================
326 There are two ways to "drop to C" in Rubinius. Firstly, primitives
327 are special instructions that are specifically defined in the VM.
328 In general they are operations that are impossible to do in the
329 Ruby layer such as opening a file. Primitives should be used to
330 access the functionality of the VM from inside Ruby.
332 FFI or Foreign Function Interface, on the other hand, is meant as
333 a generalised method of accessing system libraries. FFI is able to
334 automatically generate the bridge code needed to call out to some
335 library and get the result back into Ruby. FFI functions at runtime
336 as real machine code generation so that it is not necessary to have
337 anything compiled beforehand. FFI should be used to access the code
338 outside of Rubinius, whether it is system libraries or some type of
339 extension code, for example.
341 There is also a specific Rubinius extension layer called Subtend.
342 It emulates the extension interface of Ruby to allow old Ruby
343 extensions to work with Rubinius.  See doc/subtend.txt.
346 4.1 Primitives
347 ==============
348 Using the above rationale, if you need to implement a primitive:
350 * Give the primitive a sane name
351 * Implement the primitive in shotgun/lib/primitives.rb using the
352   name you chose as the method name.
353 * Enter the primitive name as a symbol at the BOTTOM of the Array
354   in shotgun/lib/primitive_names.rb.
355 * `rake build`
357 This makes your primitive available in the Ruby layer using the
358 special form @Ruby.primitive :primitive_name@. Primitives have a
359 few rules and chief among them is that a primitive must be the
360 first instruction in the method that it appears in. Partially for
361 this reason all primitives should reside in a wrapper method in
362 bootstrap/ (the other part is that core/ should be implementation
363 independent and primitives are not.)
365 In addition to this, primitives have another property that may
366 seem unintuitive: anything that appears below the primitive form
367 in the wrapper method is executed if the primitive FAILS and only
368 if it fails. There is no exception handling syntax involved. So
369 this is a typical pattern:
371     # kernel/bootstrap/whatever.rb
372     def self.prim_primitive_name()
373       Ruby.primitive :primitive_name
374       raise SomeError, "Whatever I was doing just failed."
375     end
377     # kernel/core/whatever.rb
378     def self.primitive_name()
379       self.prim_primitive_name
380       ...
381     end
383 To have a primitive fail, the primitive body (in primitives.rb)
384 should return FALSE; this will cause the code following the
385 Ruby.primitive line to be run. This provides a fallback so that
386 the operation can be retried in Ruby.
388 If a primitive cannot be retried in Ruby or if there is some
389 additional information that needs to be passed along to create
390 the exception, it may raise an exception using a couple of macros:
392 * RAISE(exc_class, msg) will raise an exception of type exc_class
393   and with a message of msg, e.g.
395     RAISE("ArgumentError", "Invalid argument");
397 * RAISE_FROM_ERRNO(msg) will raise an Errno exception with the
398   specified msg.
400 If you need to change the signature of a primitive, follow this
401 procedure:
402   1. change the signature of the kernel method that calls the
403      VM primitive
404   2. change any calls to the kernel method in the kernel/**
405      code to use the new signature, then recompile
406   3. run rake build:stable
407   4. change the actual primitive in the VM and recompile again
408   5. run bin/mspec ci -B full.mspec OR rake spec:full
410 4.2 FFI
411 -------
413 Module#attach_function allows a C function to be called from Ruby
414 code using FFI.
416 Module#attach_function takes the C function name, the ruby module
417 function to bind it to, the C argument types, and the C return type.
418 For a list of C argument types, see kernel/platform/ffi.rb.
420 Currently, FFI does not support C functions with more than 6
421 arguments.
423 When the C function will be filling in a String, be sure the Ruby
424 String is large enough. For the C function rbx_Digest_MD5_Finish,
425 the digest string is allocated with a 16 character length.  The
426 string is passed to md5_finish which calls rbx_Digest_MD5_Finish
427 which fills in the string with the digest.
429   class Digest::MD5
430     attach_function nil, 'rbx_Digest_MD5_Finish', :md5_finish,
431                     [:pointer, :string], :void
433     def finish
434       digest = ' ' * 16
435       self.class.md5_finish @context, digest
436       digest
437     end
438   end
440 For a complete additional example, see digest/md5.rb.
443 5. Debugging: debugger, GDB, valgrind
444 =====================================
446 With Rubinius, there are two distinct things that may need
447 debugging (sometimes at the same time.) There is the Ruby
448 code, for which 'debugger' exists. debugger is a full-speed
449 debugger, which means that there is no extra compilation or
450 flags to enable it but at the same time, code normally does
451 not suffer a performance penalty from the infrastructure.
452 This is achieved using a combination of bytecode substitution
453 and Rubinius' Channel IO interface. Multithreaded debugging
454 is supported (credit for the debugger goes to Adam Gardiner.)
456 On the C side, the trusty workhorse is the Gnu Debugger or
457 GDB. In addition there is support built in for Valgrind, a
458 memory checker/lint/debugger/analyzer hybrid.
461 5.1 debugger
462 ------------
463 The nonchalantly named debugger is specifically the debugger
464 for Ruby code, although it does also allow examining the VM
465 as it runs. The easiest way to start it is to insert either
466 a @breakpoint@ or @debugger@ method call anywhere in your
467 source code. Upon running this method, the debugger starts
468 up and awaits your command at the instruction where the
469 @breakpoint@ or @debugger@ method used to be. For a full
470 explanation of the debugger, refer to [currently the source
471 but hopefully docs shortly.] You will see this prompt and
472 there is a trusty command you can try to get started:
474     rbx:debug> help
477 5.2 GDB
478 -------
479 To really be able to use GDB, make sure that you build Rubinius
480 with DEV=1 set. This disables optimisations and adds debugging
481 symbols.
483 There are two ways to access GDB for Rubinius. You can simply
484 run shotgun/rubinius with gdb (use the builtin support so you
485 do not need to worry about linking etc.):
487 * Run `shotgun/rubinius --gdb`, place a breakpoint (break main,
488   for example) and then r(un.)
489 * Alternatively, you can run and then hit ^C to interrupt.
491 You can also drop into GDB from Ruby code with @Kernel#yield_gdb@
492 which uses a rather rude but very effective method of stopping
493 execution to start up GDB. To continue past the @yield_gdb@,
494 j(ump) to one line after the line that you have stopped on.
496 Useful gdb commands and functions (remember, using the p(rint)
497 command in GDB you can access pretty much any C function in
498 Rubinius):
500 * rbt
501   Prints the backtrace of the Ruby side of things. Use this in
502   conjunction with gdb's own bt which shows the C backtrace.
504 * p _inspect(OBJECT)
505   Useful information about a given Ruby object.
508 5.3 Valgrind
509 ------------
510 Valgrind is a program for debugging, profiling and memory-checking
511 programs. The invocation is just  `shotgun/rubinius --valgrind`.
512 See http://valgrind.org for usage information.
514 5.4 Tracing
515 -----------
517 Excessive tracing can rapidly fill your screen up with crap.  To enable it,
519   RBX=rbx.debug.trace shotgun/rubinius ...
521 === END ===