Replace object_id for equal? in Matrix specs
[rbx.git] / README-DEVELOPERS
blob5165f1d3e74c7efdd36432b1ece58ec11b14f9c6
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 * kernel/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 and bin/ci.
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/ci to make sure
110 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
244 the 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
248 Core and Stdlib libraries in this format which both allows us
249 to 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 
262 because 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. spec/ruby/ specifies our
266 current target implementation, Ruby 1.8.6-p111 and it is 
267 further split to various subdirectories such as language/
268 for language-level constructs such as, for example, the
269 @if@ statement and core/ for Core library code such as
270 @Array@. 
272 Parallel to this the top-level spec/ directory itself has the
273 subdirectories for Rubinius-specific specs: additions and/or
274 deviations from the standard, Rubinius language constructs 
275 etc. For example, the standard @String@ specs live under the
276 spec/ruby/1.8/core/string/ directory and if Rubinius implements
277 an additional method @String#to_morse@, the specs for it can
278 be found in spec/core/string/. Completely new classes such as
279 @CompiledMethod@ find their specs here as well.
281 The way to run the specs is contained in two small programs:
282 bin/mspec and bin/ci. The former is the "full" version that
283 allows a wider range of options and the latter is a streamlined
284 way of running Continuous Integration (CI) testing. CI is a
285 set of "known-good" specs picked out from the entirety of
286 them (which is what bin/mspec works with) using an automatic
287 exclusion mechanism. CI is very important for any Rubinius
288 developer: before each commit, bin/ci should be run and found
289 to finish without error. It makes it very easy to ensure that
290 your change did not break other, seemingly unrelated things
291 because it exercises all areas of specs. A clean bin/ci run
292 gives confidence that your code is correct.
294 For a deeper overview, tutorials, help and other information
295 about Rubinius' specs, start here:
297 http://rubinius.lighthouseapp.com/projects/5089/specs-overview
300 4. Libraries and C: Primitives vs. FFI
301 ======================================
303 There are two ways to "drop to C" in Rubinius. Firstly, primitives
304 are special instructions that are specifically defined in the VM.
305 In general they are operations that are impossible to do in the
306 Ruby layer such as opening a file. Primitives should be used to
307 access the functionality of the VM from inside Ruby.
309 FFI or Foreign Function Interface, on the other hand, is meant as
310 a generalised method of accessing system libraries. FFI is able to
311 automatically generate the bridge code needed to call out to some
312 library and get the result back into Ruby. FFI functions at runtime
313 as real machine code generation so that it is not necessary to have
314 anything compiled beforehand. FFI should be used to access the code
315 outside of Rubinius, whether it is system libraries or some type of
316 extension code, for example.
318 There is also a specific Rubinius extension layer called Subtend.
319 It emulates the extension interface of Ruby to allow old Ruby
320 extensions to work with Rubinius.
323 4.1 Primitives
324 ==============
325 Using the above rationale, if you need to implement a primitive:
327 * Give the primitive a sane name
328 * Implement the primitive in shotgun/lib/primitives.rb using the
329   name you chose as the method name.
330 * Enter the primitive name as a symbol at the BOTTOM of the Array
331   in shotgun/lib/primitive_names.rb.
332 * `rake build`
334 This makes your primitive available in the Ruby layer using the
335 special form @Ruby.primitive :primitive_name@. Primitives have a
336 few rules and chief among them is that a primitive must be the
337 first instruction in the method that it appears in. Partially for
338 this reason all primitives should reside in a wrapper method in
339 bootstrap/ (the other part is that core/ should be implementation
340 independent and primitives are not.)
342 In addition to this, primitives have another property that may
343 seem unintuitive: anything that appears below the primitive form
344 in the wrapper method is executed if the primitive FAILS and only
345 if it fails. There is no exception handling syntax involved. So
346 this is a typical pattern:
348     # kernel/bootstrap/whatever.rb
349     def self.prim_primitive_name()
350       Ruby.primitive :primitive_name
351       raise SomeError, "Whatever I was doing just failed."
352     end
354     # kernel/core/whatever.rb
355     def self.primitive_name()
356       self.prim_primitive_name
357       ...
358     end
360 To have a primitive fail, the primitive body (in primitives.rb)
361 should return FALSE; this will cause the code following the
362 Ruby.primitive line to be run. This provides a fallback so that
363 the operation can be retried in Ruby.
365 If a primitive cannot be retried in Ruby or if there is some
366 additional information that needs to be passed along to create
367 the exception, it may raise an exception using a couple of macros:
369 * RAISE(exc_class, msg) will raise an exception of type exc_class
370   and with a message of msg, e.g.
372     RAISE("ArgumentError", "Invalid argument");
374 * RAISE_FROM_ERRNO(msg) will raise an Errno exception with the
375   specified msg.
377 If you need to change the signature of a primitive, follow this
378 procedure:
379   1. change the signature of the kernel method that calls the
380      VM primitive
381   2. change any calls to the kernel method in the kernel/**
382      code to use the new signature, then recompile
383   3. run rake build:stable
384   4. change the actual primitive in the VM and recompile again
385   5. run bin/ci
387 4.2 FFI
388 -------
390 Module#attach_function allows a C function to be called from Ruby
391 code using FFI.
393 Module#attach_function takes the C function name, the ruby module
394 function to bind it to, the C argument types, and the C return type.
395 For a list of C argument types, see kernel/platform/ffi.rb.
397 Currently, FFI does not support C functions with more than 6
398 arguments.
400 When the C function will be filling in a String, be sure the Ruby
401 String is large enough. For the C function rbx_Digest_MD5_Finish,
402 the digest string is allocated with a 16 character length.  The
403 string is passed to md5_finish which calls rbx_Digest_MD5_Finish
404 which fills in the string with the digest.
406   class Digest::MD5
407     attach_function nil, 'rbx_Digest_MD5_Finish', :md5_finish,
408                     [:pointer, :string], :void
410     def finish
411       digest = ' ' * 16
412       self.class.md5_finish @context, digest
413       digest
414     end
415   end
417 For a complete additional example, see digest/md5.rb.
420 5. Debugging: debugger, GDB, valgrind
421 =====================================
423 With Rubinius, there are two distinct things that may need
424 debugging (sometimes at the same time.) There is the Ruby
425 code, for which 'debugger' exists. debugger is a full-speed
426 debugger, which means that there is no extra compilation or
427 flags to enable it but at the same time, code normally does
428 not suffer a performance penalty from the infrastructure.
429 This is achieved using a combination of bytecode substitution
430 and Rubinius' Channel IO interface. Multithreaded debugging
431 is supported (credit for the debugger goes to Adam Gardiner.)
433 On the C side, the trusty workhorse is the Gnu Debugger or
434 GDB. In addition there is support built in for Valgrind, a
435 memory checker/lint/debugger/analyzer hybrid.
438 5.1 debugger
439 ------------
440 The nonchalantly named debugger is specifically the debugger
441 for Ruby code, although it does also allow examining the VM
442 as it runs. The easiest way to start it is to insert either
443 a @breakpoint@ or @debugger@ method call anywhere in your
444 source code. Upon running this method, the debugger starts
445 up and awaits your command at the instruction where the
446 @breakpoint@ or @debugger@ method used to be. For a full
447 explanation of the debugger, refer to [currently the source
448 but hopefully docs shortly.] You will see this prompt and
449 there is a trusty command you can try to get started:
451     rbx:debug> help
454 5.2 GDB
455 -------
456 To really be able to use GDB, make sure that you build Rubinius
457 with DEV=1 set. This disables optimisations and adds debugging
458 symbols.
460 There are two ways to access GDB for Rubinius. You can simply
461 run shotgun/rubinius with gdb (use the builtin support so you
462 do not need to worry about linking etc.):
464 * Run `shotgun/rubinius --gdb`, place a breakpoint (break main,
465   for example) and then r(un.)
466 * Alternatively, you can run and then hit ^C to interrupt.
468 You can also drop into GDB from Ruby code with @Kernel#yield_gdb@
469 which uses a rather rude but very effective method of stopping
470 execution to start up GDB. To continue past the @yield_gdb@,
471 j(ump) to one line after the line that you have stopped on.
473 Useful gdb commands and functions (remember, using the p(rint)
474 command in GDB you can access pretty much any C function in
475 Rubinius):
477 * rbt
478   Prints the backtrace of the Ruby side of things. Use this in
479   conjunction with gdb's own bt which shows the C backtrace.
481 * p _inspect(OBJECT)
482   Useful information about a given Ruby object.
485 5.3 Valgrind
486 ------------
487 Valgrind is a program for debugging, profiling and memory-checking
488 programs. The invocation is just  `shotgun/rubinius --valgrind`.
489 See http://valgrind.org for usage information.
491 5.4 Tracing
492 -----------
494 Excessive tracing can rapidly fill your screen up with crap.  To enable it,
496   RBX=rbx.debug.trace shotgun/rubinius ...
498 === END ===