SlideShare a Scribd company logo
1 of 59
Download to read offline
An Amateur Smalltalk User’s
                 Observations on Ruby
                 Object Model and Bytecode
                           “freedom” Koan-Sin Tan
                         freedom_at_computer.org
                       RubyConf Taiwan, Dec 8th, 2012




                                     1
Friday, March 22, 13
Or say, learning Ruby, a
                 stupid way


                             2
Friday, March 22, 13
Outline

                       • General introduction
                       • Smalltalk-80 and Ruby object models
                       • Smalltalk-80 and Ruby bytecode

                                           3
Friday, March 22, 13
Who am I
                       •   Learnt to write program on MPF-II
                       •   Used to be a programming language junkie
                       •   Learnt a bit Smalltalk during early '90s, use it on
                           and off
                       •   Recent interest in ST-80 because of Scratch and
                           BYOB/SNAP
                       •   Working on dealing with big.LITTLE system
                       •   Knew little about Ruby

                                                   4
Friday, March 22, 13
MPF-II
                       •   Multi-tech Micro-Professor
                           II, MPF-II

                           •   A not so compatible
                               Apple-][ clone

                           •   6502

                           •   Basic similar to Apple
                               SOFT

                           •   Different monitor

                       •   I got one of this in 1983


                                                        5
Friday, March 22, 13
the first smalltalk-80 I used is on
                 Sun’s SunView, image from Wikipedia
                                  6
Friday, March 22, 13
Smalltalk/V 286, from http://www.drdobbs.com/
                  architecture-and-design/making-smalltalk-with-widgets/
                                        184408550
                                            7
Friday, March 22, 13
Scratch and BYOB/SNAP visual
               programming
                               8
Friday, March 22, 13
ARM big.LITTLE
                             9
Friday, March 22, 13
10
Friday, March 22, 13
What I knew about
                                Ruby
                       • freebsd: portupgrade is written in ruby, http://
                         wiki.freebsd.org/portupgrade
                       • RoR
                         • message passing
                         • temporary variable, block, block arguments
                         • However, a block in ruby is not an object!!
                       • And of course, ruby is more than smalltalk-80
                                              11
Friday, March 22, 13
Smalltalk-80
                       •   Object-Oriented            •   Design Pattern:
                           Programming
                                                          •   if you read GoF
                       •   OO GUI environment,                book, you ran into
                           IDE                                lots Smalltalk patterns
                                                              before
                       •   VM, bytecode
                                                      •   Learning/educational
                       •   Lambda, functional
                           language, block                •   Logo and the dream
                                                              of Dynabook
                       •   Message passing

                                                 12
Friday, March 22, 13
some smalltalk-80 systems
              • Squeak:	
  originally	
  from	
  Alan	
  Kay	
  and	
  other	
  
                veteran	
  Smalltalk	
  guys
              • Pharo:	
  a	
  Squeak	
  fork	
  focusing	
  on	
  providing	
  a	
  
                clean	
  and	
  ready-­‐to-­‐use	
  smalltalk	
  
                environment
              • VisualWorks:	
  the	
  ParcPlace	
  system
              • GNU	
  Smalltalk

                                                13
Friday, March 22, 13
Object Model
                       • Object Model can be used to refer to
                         different things
                       • We just touch what a common language
                         user is aware of, not something like the
                         details of how objects are represented in
                         VMs
                        • I believe you can get more about VM
                           implementations from Sasada-San’s talk

                                            14
Friday, March 22, 13
Smalltalk Object Model
                 •     From "purple book", Chap 16
                 1.    Every class is ultimately a subclass of class Object, except for Object itself,
                       which has no superclass. In particular, Class is a subclass of ClassDescription,
                       which is a subclass of Behavior which is a subclass of Object
                 2.    Every object is an instance of a class
                 3.    Every class is an instance of a metaclass
                 4.    All metaclasses are subclasses of Class
                 5.    Every metaclass is an instance of Metaclass
                 6.    The method of Class and it superclasses support the behavior common to all
                       objects that are classes
                 7.    The methods of instances of Metaclass add the behavior specific to particular
                       classes


                                                            15
Friday, March 22, 13
Smalltalk Object Model
         •10 factorial --> 3628800
         •10 factorial class --> SmallInteger
         •SmallInteger superclass --> Integer
         •Integer	
  superclass	
  --> Number
         •Number	
  superclass	
  --> Magnitude
         •Magnitude	
  superclass	
  --> Object
         •Object	
  superclass	
  -­‐-­‐>	
  ProtoObject
         •ProtoObject	
  superclass	
  -­‐-­‐>	
  nil
                                        16
Friday, March 22, 13
• 10 factorial class allSuperClasses -->   an
                         OrderedCollection(Integer Number
                         Magnitude Object ProtoObject)




                                             17
Friday, March 22, 13
•      SmallInteger class --> SmallInteger class
         •      Integer	
  class	
  --> Integer	
  class
         •      Number	
  class -->	
  Number	
  class
         •      Magnitude	
  class -->	
  Magnitude	
  class
         •      Object	
  class -->	
  Object	
  class
         •      ProtoObject	
  class -->	
  ProtoObject	
  class



                                         18
Friday, March 22, 13
ProtoObject     ProtoObject class


                         Object          Object class


                       Magnitude       Magnitude class


                         Number          Number class


                         Integer         Integer class


                       SmallInteger    SmallInteger class


                           10
                                                                     Key
                                                            instance-of




                           figures modified from “Pharo by Example”



                                                19
Friday, March 22, 13
4. All metaclasses are subclasses of Class
                 5. Every metaclass is an instance of Metaclass




                                         20
Friday, March 22, 13
SmallInteger class superclass --> Integer class
         Integer class superclass --> Number class
         umber class superclass --> Magnitude class
         Magnitude class superclass --> Object class
         Object class superclass --> ProtoObject class
         ProtoObject class superclass --> Class

         Class class class --> Metaclass


                                 21
Friday, March 22, 13
Class class
                                              Class


                       ProtoObject    ProtoObject class

                                                                                  Metaclass class
                         Object         Object class


                       Magnitude      Magnitude class
                                                                            Metaclass
                         Number         Number class


                         Integer        Integer class


                       SmallInteger   SmallInteger class
                                                                      Key
                                                             instance-of
                           10




                                                        22
Friday, March 22, 13
6. The method of Class and it superclasses
                    support the behavior common to all objects
                    that are classes
                 7. The methods of instances of Metaclass add
                    the behavior specific to particular classes



                                        23
Friday, March 22, 13
Class class class --> Metaclass
         Metaclass superclass --> ClassDescription.
         ClassDescription superclass --> Behavior
         Behavior superclass --> Object

         Class class superclass --> ClassDescription class
         ClassDescription class --> superclass Behavior
         class
         Behavior class superclass --> Object class

                                 24
Friday, March 22, 13
Behavior class

                           Behavior
                                          ClassDescription class

                       ClassDescription
                                                  Class class
                                  Class

                 ProtoObject

                                          ProtoObject class                       Metaclass class
                       Object

                                            Object class
                  Magnitude                                                 Metaclass

                                          Magnitude class
                       Number

                                            Number class
                       Integer

                                            Integer class                   Key
                SmallInteger                                       instance-of


                                          SmallInteger class
                         10




                                                            25
Friday, March 22, 13
from “PBE”
                           26
Friday, March 22, 13
• since I cannot find good Ruby tutorial/book
                         similar to blue/purple book, let see check if
                         we can use similar way to explore ruby




                                             27
Friday, March 22, 13
Ruby Metaclass


                       • Singleton class, eigenclass


                                             28
Friday, March 22, 13
from ‘ri Class’ of ruby 1.8
                                                     +------------------+

                                                     |                    |

                                  Object---->(Object)                     |

                                   ^   ^         ^       ^                |

                                   |   |         |       |                |

                                   |   |   +-----+       +---------+      |

                                   |   |   |                       |      |

                                   |   +-----------+               |      |

                                   |       |             |         |      |

                            +------+       |     Module--->(Module)       |

                            |              |             ^         ^      |

                       OtherClass-->(OtherClass)         |         |      |

                                                         |         |      |

                                                     Class---->(Class)    |

                                                         ^                |

                                                         |                |

                                                                        29
                                                         +----------------+

Friday, March 22, 13
from ‘ri Class’ of ruby 1.9
         • All	
  metaclasses	
  are	
  instances	
  of	
  the	
  class	
  `Class'.
                 	
  	
  	
  	
  	
                     +---------+            +-...


                                                        |         |             |


                                        BasicObject-----|-->(BasicObject)-------|-...

                                            ^           |         ^             |


                                            |           |         |             |


                                         Object---------|----->(Object)---------|-...


                                            ^           |         ^             |


                                            |           |         |             |

                                            +-------+   |         +--------+    |


                                            |       |   |         |        |    |


                                            |    Module-|---------|--->(Module)-|-...


                                            |       ^   |         |        ^    |


                                            |       |   |         |        |    |

                                            |     Class-|---------|---->(Class)-|-...


                                            |       ^   |         |        ^    |


                                            |       +---+         |        +----+


                                            |                     |


                      obj--->OtherClass---------->(OtherClass)-----------...
                                                                                        30
Friday, March 22, 13
Ruby Eigenclass hierarchy
                 noway:work freedom$ ruby -v                           freedom@freedom-desktop:~$ ruby -v
                                                                       ruby 1.9.3p0 (2011-10-30 revision 33570) [arm-linux-
                 ruby 1.8.7 (2012-02-08 patchlevel 358)                  eabi]
                 [universal-darwin12.0]                                freedom@freedom-desktop:~$ irb -v
                                                                       irb 0.9.6(09/06/30)
                 noway:work freedom$ irb -v                            freedom@freedom-desktop:~$ irb
                                                                       irb(main):001:0> 1.class
                 irb 0.9.5(05/04/13)                                   => Fixnum
                                                                       irb(main):002:0> 1.class.class
                 noway:work freedom$ irb                               => Class
                                                                       irb(main):003:0> 1.class.class.superclass
                 >> 1.class                                            => Module
                                                                       irb(main):004:0> 1.class.class.superclass.superclass
                 => Fixnum                                             => Object
                                                                       irb(main):005:0>
                 >> 1.class.class                                        1.class.class.superclass.superclass.superclass
                                                                       => BasicObject
                 => Class                                              irb(main):006:0>
                                                                         1.class.class.superclass.superclass.superclass.supercl
                 >> 1.class.class.superclass                             ass
                                                                       => nil
                 => Module                                             irb(main):007:0>

                 >> 1.class.class.superclass.superclass

                 => Object

                 >>
                 1.class.class.superclass.superclass.superclass

                 => nil

                 >>                                               31
Friday, March 22, 13
>> 1.class.ancestors
                       => [Fixnum, Integer, Precision, Numeric,
                       Comparable, Object, Kernel]




                                              32
Friday, March 22, 13
$ rbenv exec irb     meta.rb

                       rb(main):001:0> 1.class.class

                       => Class

                       irb(main):002:0> 1.class.class.ancestors

                       => [Class, Module, Object, Kernel, BasicObject]

                       $rbenv exec irb    meta.rb

                       meta.rb(main):001:0> class Object

                       meta.rb(main):002:1>           def metaclass

                       meta.rb(main):003:2>                 class << self; self; end

                       meta.rb(main):004:2>           end

                       meta.rb(main):005:1> end

                       => nil

                       meta.rb(main):006:0>

                       meta.rb(main):007:0* 1.class.metaclass

                       => #<Class:Fixnum>

                       eta.rb(main):008:0> 1.class.metaclass.superclass

                       => #<Class:Integer>

                       meta.rb(main):009:0> 1.class.metaclass.ancestors

                       => [Class, Module, Object, Kernel, BasicObject]




                                                                                   33
Friday, March 22, 13
meta.rb(main):009:0> 1.class.metaclass.ancestors

                       => [Class, Module, Object, Kernel, BasicObject]

                 •     hmm..., back to superclass

                       meta.rb(main):010:0> 1.class.metaclass.superclass.superclass

                       => #<Class:Numeric>

                       meta.rb(main):011:0> 1.class.metaclass.superclass.superclass.superclass

                       => #<Class:Object>

                       meta.rb(main):012:0>
                       1.class.metaclass.superclass.superclass.superclass.superclass

                       => #<Class:BasicObject>

                       meta.rb(main):013:0>
                       1.class.metaclass.superclass.superclass.superclass.superclass.superclass

                       => Class




                                                           34
Friday, March 22, 13
Ruby's Object Hierarchy 2
                                                                        Basic         instance   ! != == __id__ __send__ equal?
                                                                        Object        methods      instance_eval instance_exec



                                                                                                               !~ <=> === =~ class clone
                                                                         super                   define_singleton_method display dup eigen_class
                                                                         class                      eigen_methods enum_for eql? extend freeze
                                                                                                 frozen? hash initialize_clone initialize_dup inspect
                                                                                                       instance_of? instance_variable_defined?
                                                                                                    instance_variable_get instance_variable_set
                                                       included                       instance        instance_variables is_a? kind_of? method
                                              Kernel                    Object        methods           methods nil? object_id private_methods
                                                       modules                                            protected_methods public_method
                                                                                                      public_methods public_send respond_to?
                                                                                                     respond_to_missing? send singleton_class
                                                                                                 singleton_methods taint tainted? tap to_enum to_s
                                                                                                            trust untaint untrust untrusted?
                                                                         super
                                                                         class
                                                                                                       < <= > >= ancestors autoload autoload?
                                                                                                   class_eval class_exec class_variable_defined?
                                                                                                        class_variable_get class_variable_set
                                                                        Module                        class_variables const_defined? const_get
                                                                                      instance       const_missing const_set constants include?
                                                                                      methods            included_modules instance_method
                                                                                                 instance_methods method_defined? module_eval
                                                                                                      module_exec name private_class_method
                                                                                                     private_constant private_instance_methods
                                                                                                               private_method_defined?
                                                                         super                               protected_instance_methods
                                                                                                 protected_method_defined? public_class_method
                                                                         class                        public_constant public_instance_method
                                                                                                 public_instance_methods public_method_defined?
                                                                                                                remove_class_variable


                                                                        Class
                                                                                      instance




        •So Ruby’s object hierarchy
                                                                                      methods
                                                                                                         allocate new superclass
                                                                         super
                                                          methods        class




        should be similar to this             Basic
                                              Object
                                                       eigen
                                                       class
                                                                       #<Class:
                                                                     BasicObject>
                                                                                      instance
                                                                                      methods




        •http://drtom.schank.ch/posts/         super
                                               class      methods
                                                                         super
                                                                         class




        2011/12/11/                           Object
                                                       eigen
                                                       class
                                                                    #<Class:Object>
                                                                                      instance
                                                                                      methods




        Rubys_Object_Model_and_Eige            super
                                               class     methods
                                                                         super
                                                                         class




        nclasses/
                                                                                      instance                   try_convert
                                                       eigen
                                              String   class
                                                                    #<Class:String>   methods
                                                                                                       Thomas Schank © 2011 (CC BY-ND)




                                         35
Friday, March 22, 13
Bytecode
                       •   Bytecode is not new at all
                           •   Smalltalk is one of early bytecode users
                       •   Smalltalk bytecode
                           •   end of Chapter 26, http://
                               www.mirandabanda.org/bluebook/
                               bluebook_chapter26.html#TheBytecodes26
                           •   Chap. 28, http://www.mirandabanda.org/
                               bluebook/bluebook_chapter28.html

                                                  36
Friday, March 22, 13
Smalltalk bytecode categories
         • pushes
           • indicates	
  the	
  source	
  of	
  an	
  object	
  to	
  be	
  added	
  to	
  the	
  top	
  of	
  the	
  
             interpreter's	
  stack
         • stores
           • indicates	
  the	
  variable	
  whose	
  value	
  should	
  be	
  changed
         • sends
           • specifies	
  the	
  selector	
  of	
  a	
  message	
  to	
  be	
  sent	
  and	
  how	
  many	
  
             arguments	
  it	
  should	
  have.
         • returns
           • 	
  a	
  value	
  is	
  returned	
  for	
  the	
  message	
  that	
  invoked	
  that	
  
             CompiledMethod
         • and	
  jumps
           • you	
  know	
  what	
  these	
  are                37
Friday, March 22, 13
Smalltalk	
  bytecodes
        Range          Bits                               FuncQon
        0-­‐15         0000iiii                           Push	
  Receiver	
  Variable	
  #iiii
        16-­‐31        0001iiii                           Push	
  Temporary	
  LocaQon	
  #iiii
        32-­‐63        001iiiii                           Push	
  Literal	
  Constant	
  #iiiii
        64-­‐95        010iiiii                           Push	
  Literal	
  Variable	
  #iiiii
        96-­‐103       01100iii                           Pop	
  and	
  Store	
  Receiver	
  Variable	
  #iii
        104-­‐111      01101iii                           Pop	
  and	
  Store	
  Temporary	
  LocaQon	
  #iii
        112-­‐119      01110iii                           Push	
  (receiver,	
  true,	
  false,	
  nil,	
  -­‐1,	
  0,	
  1,	
  2)	
  [iii]
        120-­‐123      011110ii                           Return	
  (receiver,	
  true,	
  false,	
  nil)	
  [ii]	
  From	
  Message
        124-­‐125      0111110i                           Return	
  Stack	
  Top	
  From	
  (Message,	
  Block)	
  [i]
        126-­‐127      0111111i                           unused
        128            10000000	
  jjkkkkkk               Push	
  (Receiver	
  Variable,	
  Temporary	
  LocaQon,	
  Literal	
  Constant,	
  Literal	
  Variable)	
  [jj]	
  #kkkkkk
        129            10000001	
  jjkkkkkk               Store	
  (Receiver	
  Variable,	
  Temporary	
  LocaQon,	
  Illegal,	
  Literal	
  Variable)	
  [jj]	
  #kkkkkk
        130            10000010	
  jjkkkkkk               Pop	
  and	
  Store	
  (Receiver	
  Variable,	
  Temporary	
  LocaQon,	
  Illegal,	
  Literal	
  Variable)	
  [jj]	
  #kkkkkk
        131            10000011	
  jjjkkkkk               Send	
  Literal	
  Selector	
  #kkkkk	
  With	
  jjj	
  Arguments
        132            10000100	
  jjjjjjjj	
  kkkkkkkk   Send	
  Literal	
  Selector	
  #kkkkkkkk	
  With	
  jjjjjjjj	
  Arguments
        133            10000101	
  jjjkkkkk               Send	
  Literal	
  Selector	
  #kkkkk	
  To	
  Superclass	
  With	
  jjj	
  Arguments
        134            10000110	
  jjjjjjjj	
  kkkkkkkk   Send	
  Literal	
  Selector	
  #kkkkkkkk	
  To	
  Superclass	
  With	
  jjjjjjjj	
  Arguments
        135            10000111                           Pop	
  Stack	
  Top
        136            10001000                           Duplicate	
  Stack	
  Top
        137            10001001                           Push	
  AcQve	
  Context
        138-­‐143                                         unused
        144-­‐151      10010iii                           Jump	
  iii	
  +	
  1	
  (i.e.,	
  1	
  through	
  8)
        152-­‐159      10011iii                           Pop	
  and	
  Jump	
  0n	
  False	
  iii	
  +1	
  (i.e.,	
  1	
  through	
  8)
        160-­‐167      10100iii	
  jjjjjjjj               Jump(iii	
  -­‐	
  4)	
  *256+jjjjjjjj
        168-­‐171      101010ii	
  jjjjjjjj               Pop	
  and	
  Jump	
  On	
  True	
  ii	
  *256+jjjjjjjj
        172-­‐175      101011ii	
  jjjjjjjj               Pop	
  and	
  Jump	
  On	
  False	
  ii	
  *256+jjjjjjjj
        176-­‐191      1011iiii                           Send	
  ArithmeQc	
  Message	
  #iiii
        192-­‐207      1100iiii                           Send	
  Special	
  Message	
  #iiii
        208-­‐223      1101iiii                           Send	
  Literal	
  Selector	
  #iiii	
  With	
  No	
  Arguments
        224-­‐239      1110iiii                           Send	
  Literal	
  Selector	
  #iiii	
  With	
  1	
  Argument
        240-­‐255      1111iiii                                                                         38
                                                          Send	
  Literal	
  Selector	
  #iiii	
  With	
  2	
  Arguments	
  
Friday, March 22, 13
•      An	
  example	
  method,
              forCompiledMethod
                "to show how CompiledMethod works"

                       | foo |
                       foo := 'test'.
                        ^ 1 + 2
        •      Bytecode:	
  in	
  System	
  Browser	
  of	
  Squeak/Pharo,	
  we	
  can	
  see	
  byteCode	
  easily
              –17      <20>   pushConstant: 'test'
              –18      <68>   popIntoTemp: 0
              –19      <76>   pushConstant: 1
              –20      <77>   pushConstant: 2
              –21      <B0>   send: +
              –22      <7C>   returnTop




                                                              39
Friday, March 22, 13
displaying smalltalk
                               bytecode
                       • CompiledMethod
                       • Class>>compiledMethodAt
                       • (Integer compiledMethodAt: #factorial)
                         symbolic
                       • (RubyConfTW compiledMethodAt:
                         #forCompiledMethd) symbolic
                        • code here
                                           40
Friday, March 22, 13
compiler
                       • Behavior>>compile
                       • compile:
                        compile: code
                          ^self compile: code notifying: nil
                 •      compile:notifying:
                           •   compile:classified: notifying: requestor
                               trailer: ifFail:

                                               41
Friday, March 22, 13
a Simple Behavior>>compile
                 example
                 •     RubyConfTW compile: 'foo^42'
                         •   RubyConfTW will have a new method
                             called foo and the code is to return the
                             ultimate answer
                 •     (RubyConfTW compiledMethodAt: #foo)
                       symbolic
                       '17 <20> pushConstant: 42
                       18 <7C> returnTop’

                                             42
Friday, March 22, 13
add a method

                       | myClass myInstance |  
                       myClass := Behavior new. "create anon behavior"  
                       myClass compile: 'theAnswer ^42'. "add a method for insta
                       nces"  
                       myInstance := myClass new. "create an instance"  
                       Transcript show: myInstance theAnswer; cr. "shows 42" 



                                                  43
Friday, March 22, 13
Ruby bytecode

         • ruby	
  1.8
                o       cannot	
  find	
  easy	
  way	
  to	
  do	
  this
         • ruby	
  1.9	
  and	
  2.0
                o       ruby.c:proc_opQons()
                       §   -­‐-­‐dump=insns
                o   YARV	
  InstrucQon	
  table
                   o hmp://www.atdot.net/yarv/insnstbl.html,	
  
                   o source	
  code,	
  or
                   o you	
  can	
  ask	
  Sasada-­‐san	
  :-­‐)

                                                          44
Friday, March 22, 13
For a simple hello world
              > rbenv exec ruby --dump=insns ~/work/ruby/test.rb
              == disasm: <RubyVM::InstructionSequence:<main>@/Users/freedom/work/ruby/
              test.rb>
              0000 trace            1
              (   1)
              0002 putself
              0003 putstring        "hello, worldn"
              0005 send             <callinfo!mid:print, argc:1, FCALL|ARGS_SKIP>
              0007 leave




                                                45
Friday, March 22, 13
Ruby KERNEL Module
         • it	
  took	
  me	
  some	
  Qme	
  to	
  figure	
  out	
  what	
  puts()	
  and	
  
           other	
  kernel	
  methods	
  are
         • puts	
  ==	
  KERNEL.puts	
  ==	
  $stdout.puts()?,	
  
                 == disasm: <RubyVM::InstructionSequence:<main>@test.rb>=================
                 0000 trace            1                                               (    1)
                 0002 putself
                 0003 putstring        "hello, worldn"
                 0005 send             <callinfo!mid:puts, argc:1, FCALL|ARGS_SKIP>
                 0007 pop
                 0008 trace            1                                               (    2)
                 0010 getinlinecache   17, <ic:0>
                 0013 getconstant      :Kernel
                 0015 setinlinecache   <ic:0>
                 0017 putstring        "hello, worldn"
                 0019 opt_send_simple <callinfo!mid:puts, argc:1, ARGS_SKIP>
                 0021 pop
                 0022 trace            1                                               (    3)
                 0024 getglobal        $stdout
                 0026 putstring        "hello, world"
                 0028 opt_send_simple <callinfo!mid:puts, argc:1, ARGS_SKIP>
                 0030 leave


                                                       46
Friday, March 22, 13
CompiledMethod in
                             Ruby
                 • RubyVM::InstructionSequence
                    • = Class methods:
                      • compile, compile_file, compile_option,
                           compile_option=, disasm, disassemble,
                           load, new
                       • = Instance methods:
                         • disasm, disassemble, eval, inspect, to_a
                                           47
Friday, March 22, 13
CompiledMethod in
                              Ruby
                       filename = ARGV[0]
                       code = RubyVM::InstructionSequence.compile_file filename


                       File.open "bytecode.dump", "w" do |file|
                        file << Marshal.dump(code.to_a)
                       end
                       print code.disasm




                                                 48
Friday, March 22, 13
Load saved instruction sequence
         • there	
  is	
  no	
  RubyVM::InstrucQonSequence.load,	
  but	
  
           there	
  is	
  iseq_s_load()	
  in	
  iseq.c
         #if 0 /* TBD */
             rb_define_method(rb_cISeq, "marshal_dump", iseq_marshal_dump, 0);
             rb_define_method(rb_cISeq, "marshal_load", iseq_marshal_load, 1);
         #endif

             /* disable this feature because there is no verifier. */
             /* rb_define_singleton_method(rb_cISeq, "load", iseq_s_load, -1); */
             (void)iseq_s_load;




         • So,	
  my	
  first	
  reacQon	
  is
             /* disable this feature because there is no verifier. */
             rb_define_singleton_method(rb_cISeq, "load", iseq_s_load, -1);
             // (void)iseq_s_load;




         • And	
  I	
  googled	
  a	
  bit,	
  found	
  that,	
  it	
  seems	
  we	
  can	
  define	
  
           an	
  InstrucQonSequence.load	
  method	
  to	
  use	
  	
  
           iseq_s_load()
           • hmp://bb10.com/ruby-­‐core/2012-­‐07/msg00303.html
                                                                                    49
Friday, March 22, 13
Store and load
                 •     test.rb
                       puts “hello, worldn”
                       puts 1+2
                 •     store-and-load.rb
                       filename = ARGV[0]
                       code = RubyVM::InstructionSequence.compile_file filename


                       File.open "bytecode.dump", "w" do |file|
                          file << Marshal.dump(code.to_a)
                       end
                       code = nil
                       File.open "bytecode.dump", "r" do |file|
                             code = RubyVM::InstructionSequence.load Marshal.restore(file.read)
                       end
                       print code.disasm




                                                             50
Friday, March 22, 13
test.rb
                       ./ruby     --disable-gems ~/work/ruby/load.rb
                       == disasm: <RubyVM::InstructionSequence:<main>@/Users/freedom/work/ruby/
                       test.rb>
                       local table (size: 1, argc: 0 [opts: 0, rest: -1, post: 0, block: -1] s1)
                       0000 trace               1
                       0002 putself
                       0003 putstring           "hello, worldn"
                       0005 send                <callinfo!mid:puts, argc:1, FCALL|ARGS_SKIP>
                       0007 pop
                       0008 trace               1
                       0010 putself
                       0011 putobject           1
                       0013 putobject           2
                       0015 opt_plus            <callinfo!mid:+, argc:1, ARGS_SKIP>
                       0017 send                <callinfo!mid:puts, argc:1, FCALL|ARGS_SKIP>
                       0019 leave



                                                            51
Friday, March 22, 13
With some tweaks and
                 modification to bytecode.dump
                       ./ruby     --disable-gems ~/work/ruby/load.rb
                       == disasm: <RubyVM::InstructionSequence:<main>@/Users/freedom/work/ruby/
                       test.rb>
                       local table (size: 1, argc: 0 [opts: 0, rest: -1, post: 0, block: -1] s1)
                       0000 trace               1
                       0002 putself
                       0003 putstring           "hello, worldn"
                       0005 send                <callinfo!mid:puts, argc:1, FCALL|ARGS_SKIP>
                       0007 pop
                       0008 trace               1
                       0010 putself
                       0011 putobject           1
                       0013 putobject           2
                       0015 opt_plus            <callinfo!mid:+, argc:1, ARGS_SKIP>
                       0017 send                <callinfo!mid:puts, argc:1, FCALL|ARGS_SKIP>
                       0019 answe




                                                             52
Friday, March 22, 13
in case you didn’t get it
                       •   There is a YARV instruction called “answer”
                       •   And, the answer instruction will return “The
                           Answer to Life, the Universe, and Everything”,
                           which you know is 42
                           •   http://en.wikipedia.org/wiki/
                               Answer_to_The_Ultimate_Question_of_Life,_
                               the_Universe,_and_Everything#Answer_to_th
                               e_Ultimate_Question_of_Life.
                               2C_the_Universe.2C_and_Everything_.2842.29

                                                 53
Friday, March 22, 13
Comparing bytecodes
           17      <20>   pushConstant: 'test’
           18      <68>   popIntoTemp: 0
           19      <76>   pushConstant: 1
           20      <77>   pushConstant: 2
           21      <B0>   send: +
           22      <7C>   returnTop

         0000 trace           1
         0002 putself
         0003 putstring       "hello, worldn"
         0005 send            <callinfo!mid:puts, argc:1, FCALL|ARGS_SKIP>
         0007 pop
         0008 trace           1
         0010 putself
         0011 putobject       1
         0013 putobject       2
         0015 opt_plus        <callinfo!mid:+, argc:1, ARGS_SKIP>
         0017 send            <callinfo!mid:puts, argc:1, FCALL|ARGS_SKIP>
         0019 leave


                                                           54
Friday, March 22, 13
•      An	
  example	
  method,
              forCOmpiledMethod2: a and: b
                "to show how CompiledMethod works"

                       | foo |
                       foo := 'test'.
                        ^ a + b
        •      Bytecode:	
  in	
  System	
  Browser	
  of	
  Squeak/Pharo,	
  we	
  can	
  see	
  byteCode	
  easily
              –17      <20>   pushConstant: 'test'
              –18      <68>   popIntoTemp: 2
              –19      <76>   pushTemp: 0
              –20      <77>   pushTemp: 1
              –21      <B0>   send: +
              –22      <7C>   returnTop




                                                              55
Friday, March 22, 13
Some obvious
                                differences
                       • Smalltalk bytecodes are quite low-level, but
                         more consistent?
                         • String is not special
                         • no special optimizations such as ‘op_plus’
                          • but Smalltalk-80 does have some
                             primitive methods
                         • no joke bytecode :-)
                                             56
Friday, March 22, 13
Smalltalk primitive method
         Integer>>+

         + aNumber
             "Refer to the comment in Number + "
             aNumber isInteger ifTrue:
                 [self negative == aNumber negative
                     ifTrue: [^ (self digitAdd: aNumber) normalize]
                     ifFalse: [^ self digitSubtract: aNumber]].
             ^ aNumber adaptToInteger: self andSend: #+

         SmallInteger>>+

         + aNumber
             "Primitive. Add the receiver to the argument and answer with the result
             if it is a SmallInteger. Fail if the argument or the result is not a
             SmallInteger Essential No Lookup. See Object documentation whatIsAPrimitive."

             <primitive: 1>
             ^ super + aNumber




                                                                        57
Friday, March 22, 13
??



                       58
Friday, March 22, 13
Thanks!!



                          59
Friday, March 22, 13

More Related Content

What's hot

Clojure - An Introduction for Lisp Programmers
Clojure - An Introduction for Lisp ProgrammersClojure - An Introduction for Lisp Programmers
Clojure - An Introduction for Lisp Programmerselliando dias
 
Polyglot and functional (Devoxx Nov/2011)
Polyglot and functional (Devoxx Nov/2011)Polyglot and functional (Devoxx Nov/2011)
Polyglot and functional (Devoxx Nov/2011)Martijn Verburg
 
Polyglot and Functional Programming (OSCON 2012)
Polyglot and Functional Programming (OSCON 2012)Polyglot and Functional Programming (OSCON 2012)
Polyglot and Functional Programming (OSCON 2012)Martijn Verburg
 
Modern Java Concurrency (OSCON 2012)
Modern Java Concurrency (OSCON 2012)Modern Java Concurrency (OSCON 2012)
Modern Java Concurrency (OSCON 2012)Martijn Verburg
 
Review Session and Attending Java Interviews
Review Session and Attending Java Interviews Review Session and Attending Java Interviews
Review Session and Attending Java Interviews Hitesh-Java
 
Introduction about Python by JanBask Training
Introduction about Python by JanBask TrainingIntroduction about Python by JanBask Training
Introduction about Python by JanBask TrainingJanBask Training
 
Core java lessons
Core java lessonsCore java lessons
Core java lessonsvivek shah
 
Java Closures
Java ClosuresJava Closures
Java ClosuresBen Evans
 
Intro to Python Workshop San Diego, CA (January 19, 2013)
Intro to Python Workshop San Diego, CA (January 19, 2013)Intro to Python Workshop San Diego, CA (January 19, 2013)
Intro to Python Workshop San Diego, CA (January 19, 2013)Kendall
 
Perl On The JVM (London.pm Talk 2009-04)
Perl On The JVM (London.pm Talk 2009-04)Perl On The JVM (London.pm Talk 2009-04)
Perl On The JVM (London.pm Talk 2009-04)Ben Evans
 
Python Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & stylePython Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & styleKevlin Henney
 
Objective-c for Java Developers
Objective-c for Java DevelopersObjective-c for Java Developers
Objective-c for Java DevelopersMuhammad Abdullah
 
Getting started with Linux and Python by Caffe
Getting started with Linux and Python by CaffeGetting started with Linux and Python by Caffe
Getting started with Linux and Python by CaffeLihang Li
 
From Java to Python: beating the Stockholm syndrome
From Java to Python: beating the Stockholm syndromeFrom Java to Python: beating the Stockholm syndrome
From Java to Python: beating the Stockholm syndromeJavier Arias Losada
 
Introduction to Java 7 (OSCON 2012)
Introduction to Java 7 (OSCON 2012)Introduction to Java 7 (OSCON 2012)
Introduction to Java 7 (OSCON 2012)Martijn Verburg
 
The Economies of Scaling Software
The Economies of Scaling SoftwareThe Economies of Scaling Software
The Economies of Scaling SoftwareAbdelmonaim Remani
 
Python's dynamic nature (rough slides, November 2004)
Python's dynamic nature (rough slides, November 2004)Python's dynamic nature (rough slides, November 2004)
Python's dynamic nature (rough slides, November 2004)Kiran Jonnalagadda
 

What's hot (20)

Clojure - An Introduction for Lisp Programmers
Clojure - An Introduction for Lisp ProgrammersClojure - An Introduction for Lisp Programmers
Clojure - An Introduction for Lisp Programmers
 
Polyglot and functional (Devoxx Nov/2011)
Polyglot and functional (Devoxx Nov/2011)Polyglot and functional (Devoxx Nov/2011)
Polyglot and functional (Devoxx Nov/2011)
 
Polyglot and Functional Programming (OSCON 2012)
Polyglot and Functional Programming (OSCON 2012)Polyglot and Functional Programming (OSCON 2012)
Polyglot and Functional Programming (OSCON 2012)
 
Modern Java Concurrency (OSCON 2012)
Modern Java Concurrency (OSCON 2012)Modern Java Concurrency (OSCON 2012)
Modern Java Concurrency (OSCON 2012)
 
Review Session and Attending Java Interviews
Review Session and Attending Java Interviews Review Session and Attending Java Interviews
Review Session and Attending Java Interviews
 
Introduction about Python by JanBask Training
Introduction about Python by JanBask TrainingIntroduction about Python by JanBask Training
Introduction about Python by JanBask Training
 
Core java lessons
Core java lessonsCore java lessons
Core java lessons
 
Core Java
Core JavaCore Java
Core Java
 
Java Closures
Java ClosuresJava Closures
Java Closures
 
Intro to Python Workshop San Diego, CA (January 19, 2013)
Intro to Python Workshop San Diego, CA (January 19, 2013)Intro to Python Workshop San Diego, CA (January 19, 2013)
Intro to Python Workshop San Diego, CA (January 19, 2013)
 
Introduction To Java.
Introduction To Java.Introduction To Java.
Introduction To Java.
 
Perl On The JVM (London.pm Talk 2009-04)
Perl On The JVM (London.pm Talk 2009-04)Perl On The JVM (London.pm Talk 2009-04)
Perl On The JVM (London.pm Talk 2009-04)
 
Python Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & stylePython Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & style
 
Objective-c for Java Developers
Objective-c for Java DevelopersObjective-c for Java Developers
Objective-c for Java Developers
 
Getting started with Linux and Python by Caffe
Getting started with Linux and Python by CaffeGetting started with Linux and Python by Caffe
Getting started with Linux and Python by Caffe
 
From Java to Python: beating the Stockholm syndrome
From Java to Python: beating the Stockholm syndromeFrom Java to Python: beating the Stockholm syndrome
From Java to Python: beating the Stockholm syndrome
 
Introduction to Java 7 (OSCON 2012)
Introduction to Java 7 (OSCON 2012)Introduction to Java 7 (OSCON 2012)
Introduction to Java 7 (OSCON 2012)
 
Python - the basics
Python - the basicsPython - the basics
Python - the basics
 
The Economies of Scaling Software
The Economies of Scaling SoftwareThe Economies of Scaling Software
The Economies of Scaling Software
 
Python's dynamic nature (rough slides, November 2004)
Python's dynamic nature (rough slides, November 2004)Python's dynamic nature (rough slides, November 2004)
Python's dynamic nature (rough slides, November 2004)
 

Similar to Smalltalk and ruby - 2012-12-08

Ruby for C#-ers (ScanDevConf 2010)
Ruby for C#-ers (ScanDevConf 2010)Ruby for C#-ers (ScanDevConf 2010)
Ruby for C#-ers (ScanDevConf 2010)Thomas Lundström
 
Charla ruby nscodermad
Charla ruby nscodermadCharla ruby nscodermad
Charla ruby nscodermadnscoder_mad
 
GitHub Notable OSS Project
GitHub  Notable OSS ProjectGitHub  Notable OSS Project
GitHub Notable OSS Projectroumia
 
Devoxx%202008%20Tutorial
Devoxx%202008%20TutorialDevoxx%202008%20Tutorial
Devoxx%202008%20Tutorialtutorialsruby
 
Devoxx%202008%20Tutorial
Devoxx%202008%20TutorialDevoxx%202008%20Tutorial
Devoxx%202008%20Tutorialtutorialsruby
 
Adventures of java developer in ruby world
Adventures of java developer in ruby worldAdventures of java developer in ruby world
Adventures of java developer in ruby worldOrest Ivasiv
 
Rake: Not Your Father's Build Tool
Rake: Not Your Father's Build ToolRake: Not Your Father's Build Tool
Rake: Not Your Father's Build Toolfilmprog
 
Introduction to Go
Introduction to GoIntroduction to Go
Introduction to Gozhubert
 
Designing Puppet: Roles/Profiles Pattern
Designing Puppet: Roles/Profiles PatternDesigning Puppet: Roles/Profiles Pattern
Designing Puppet: Roles/Profiles PatternPuppet
 
Practical Groovy Domain-Specific Languages - Guillaume Laforge - Usi 2009
Practical Groovy Domain-Specific Languages - Guillaume Laforge - Usi 2009Practical Groovy Domain-Specific Languages - Guillaume Laforge - Usi 2009
Practical Groovy Domain-Specific Languages - Guillaume Laforge - Usi 2009Guillaume Laforge
 
The Good, the Bad and the Ugly things to do with android
The Good, the Bad and the Ugly things to do with androidThe Good, the Bad and the Ugly things to do with android
The Good, the Bad and the Ugly things to do with androidStanojko Markovik
 
Using puppet, foreman and git to develop and operate a large scale internet s...
Using puppet, foreman and git to develop and operate a large scale internet s...Using puppet, foreman and git to develop and operate a large scale internet s...
Using puppet, foreman and git to develop and operate a large scale internet s...techblog
 
Modules in Java? Finally! (OpenJDK 9 Jigsaw, JSR376)
Modules in Java? Finally! (OpenJDK 9 Jigsaw, JSR376)Modules in Java? Finally! (OpenJDK 9 Jigsaw, JSR376)
Modules in Java? Finally! (OpenJDK 9 Jigsaw, JSR376)Mihail Stoynov
 
Intro to Python for C# Developers
Intro to Python for C# DevelopersIntro to Python for C# Developers
Intro to Python for C# DevelopersSarah Dutkiewicz
 
OpenJDK Penrose Presentation (JavaOne 2012)
OpenJDK Penrose Presentation (JavaOne 2012)OpenJDK Penrose Presentation (JavaOne 2012)
OpenJDK Penrose Presentation (JavaOne 2012)David Bosschaert
 
Mozilla Research Party Talk
Mozilla Research Party TalkMozilla Research Party Talk
Mozilla Research Party TalkBrendan Eich
 

Similar to Smalltalk and ruby - 2012-12-08 (20)

Devoxx Java Social and Agorava
Devoxx Java Social and AgoravaDevoxx Java Social and Agorava
Devoxx Java Social and Agorava
 
Ruby for C#-ers (ScanDevConf 2010)
Ruby for C#-ers (ScanDevConf 2010)Ruby for C#-ers (ScanDevConf 2010)
Ruby for C#-ers (ScanDevConf 2010)
 
Charla ruby nscodermad
Charla ruby nscodermadCharla ruby nscodermad
Charla ruby nscodermad
 
GitHub Notable OSS Project
GitHub  Notable OSS ProjectGitHub  Notable OSS Project
GitHub Notable OSS Project
 
Devoxx%202008%20Tutorial
Devoxx%202008%20TutorialDevoxx%202008%20Tutorial
Devoxx%202008%20Tutorial
 
Devoxx%202008%20Tutorial
Devoxx%202008%20TutorialDevoxx%202008%20Tutorial
Devoxx%202008%20Tutorial
 
Adventures of java developer in ruby world
Adventures of java developer in ruby worldAdventures of java developer in ruby world
Adventures of java developer in ruby world
 
Rake: Not Your Father's Build Tool
Rake: Not Your Father's Build ToolRake: Not Your Father's Build Tool
Rake: Not Your Father's Build Tool
 
Introduction to Go
Introduction to GoIntroduction to Go
Introduction to Go
 
Designing Puppet: Roles/Profiles Pattern
Designing Puppet: Roles/Profiles PatternDesigning Puppet: Roles/Profiles Pattern
Designing Puppet: Roles/Profiles Pattern
 
Stackato v5
Stackato v5Stackato v5
Stackato v5
 
Practical Groovy Domain-Specific Languages - Guillaume Laforge - Usi 2009
Practical Groovy Domain-Specific Languages - Guillaume Laforge - Usi 2009Practical Groovy Domain-Specific Languages - Guillaume Laforge - Usi 2009
Practical Groovy Domain-Specific Languages - Guillaume Laforge - Usi 2009
 
The Good, the Bad and the Ugly things to do with android
The Good, the Bad and the Ugly things to do with androidThe Good, the Bad and the Ugly things to do with android
The Good, the Bad and the Ugly things to do with android
 
Using puppet, foreman and git to develop and operate a large scale internet s...
Using puppet, foreman and git to develop and operate a large scale internet s...Using puppet, foreman and git to develop and operate a large scale internet s...
Using puppet, foreman and git to develop and operate a large scale internet s...
 
Modules in Java? Finally! (OpenJDK 9 Jigsaw, JSR376)
Modules in Java? Finally! (OpenJDK 9 Jigsaw, JSR376)Modules in Java? Finally! (OpenJDK 9 Jigsaw, JSR376)
Modules in Java? Finally! (OpenJDK 9 Jigsaw, JSR376)
 
Intro to Python for C# Developers
Intro to Python for C# DevelopersIntro to Python for C# Developers
Intro to Python for C# Developers
 
OpenJDK Penrose Presentation (JavaOne 2012)
OpenJDK Penrose Presentation (JavaOne 2012)OpenJDK Penrose Presentation (JavaOne 2012)
OpenJDK Penrose Presentation (JavaOne 2012)
 
Stackato v6
Stackato v6Stackato v6
Stackato v6
 
Mozilla Research Party Talk
Mozilla Research Party TalkMozilla Research Party Talk
Mozilla Research Party Talk
 
Scala days mizushima
Scala days mizushimaScala days mizushima
Scala days mizushima
 

More from Koan-Sin Tan

running stable diffusion on android
running stable diffusion on androidrunning stable diffusion on android
running stable diffusion on androidKoan-Sin Tan
 
Exploring Your Apple M1 devices with Open Source Tools
Exploring Your Apple M1 devices with Open Source ToolsExploring Your Apple M1 devices with Open Source Tools
Exploring Your Apple M1 devices with Open Source ToolsKoan-Sin Tan
 
Running TFLite on Your Mobile Devices, 2020
Running TFLite on Your Mobile Devices, 2020Running TFLite on Your Mobile Devices, 2020
Running TFLite on Your Mobile Devices, 2020Koan-Sin Tan
 
Exploring Thermal Related Stuff in iDevices using Open-Source Tool
Exploring Thermal Related Stuff in iDevices using Open-Source ToolExploring Thermal Related Stuff in iDevices using Open-Source Tool
Exploring Thermal Related Stuff in iDevices using Open-Source ToolKoan-Sin Tan
 
TFLite NNAPI and GPU Delegates
TFLite NNAPI and GPU DelegatesTFLite NNAPI and GPU Delegates
TFLite NNAPI and GPU DelegatesKoan-Sin Tan
 
A Sneak Peek of MLIR in TensorFlow
A Sneak Peek of MLIR in TensorFlowA Sneak Peek of MLIR in TensorFlow
A Sneak Peek of MLIR in TensorFlowKoan-Sin Tan
 
A Peek into Google's Edge TPU
A Peek into Google's Edge TPUA Peek into Google's Edge TPU
A Peek into Google's Edge TPUKoan-Sin Tan
 
Why You Cannot Use Neural Engine to Run Your NN Models on A11 Devices?
Why You Cannot Use Neural Engine to Run Your NN Models on A11 Devices?Why You Cannot Use Neural Engine to Run Your NN Models on A11 Devices?
Why You Cannot Use Neural Engine to Run Your NN Models on A11 Devices?Koan-Sin Tan
 
open source nn frameworks on cellphones
open source nn frameworks on cellphonesopen source nn frameworks on cellphones
open source nn frameworks on cellphonesKoan-Sin Tan
 
Introduction to TensorFlow Lite
Introduction to TensorFlow Lite Introduction to TensorFlow Lite
Introduction to TensorFlow Lite Koan-Sin Tan
 
Tensorflow on Android
Tensorflow on AndroidTensorflow on Android
Tensorflow on AndroidKoan-Sin Tan
 
SoC Idling for unconf COSCUP 2016
SoC Idling for unconf COSCUP 2016SoC Idling for unconf COSCUP 2016
SoC Idling for unconf COSCUP 2016Koan-Sin Tan
 
Android Wear and the Future of Smartwatch
Android Wear and the Future of SmartwatchAndroid Wear and the Future of Smartwatch
Android Wear and the Future of SmartwatchKoan-Sin Tan
 
Understanding Android Benchmarks
Understanding Android BenchmarksUnderstanding Android Benchmarks
Understanding Android BenchmarksKoan-Sin Tan
 
Dark Silicon, Mobile Devices, and Possible Open-Source Solutions
Dark Silicon, Mobile Devices, and Possible Open-Source SolutionsDark Silicon, Mobile Devices, and Possible Open-Source Solutions
Dark Silicon, Mobile Devices, and Possible Open-Source SolutionsKoan-Sin Tan
 

More from Koan-Sin Tan (17)

running stable diffusion on android
running stable diffusion on androidrunning stable diffusion on android
running stable diffusion on android
 
Exploring Your Apple M1 devices with Open Source Tools
Exploring Your Apple M1 devices with Open Source ToolsExploring Your Apple M1 devices with Open Source Tools
Exploring Your Apple M1 devices with Open Source Tools
 
A Peek into TFRT
A Peek into TFRTA Peek into TFRT
A Peek into TFRT
 
Running TFLite on Your Mobile Devices, 2020
Running TFLite on Your Mobile Devices, 2020Running TFLite on Your Mobile Devices, 2020
Running TFLite on Your Mobile Devices, 2020
 
Exploring Thermal Related Stuff in iDevices using Open-Source Tool
Exploring Thermal Related Stuff in iDevices using Open-Source ToolExploring Thermal Related Stuff in iDevices using Open-Source Tool
Exploring Thermal Related Stuff in iDevices using Open-Source Tool
 
TFLite NNAPI and GPU Delegates
TFLite NNAPI and GPU DelegatesTFLite NNAPI and GPU Delegates
TFLite NNAPI and GPU Delegates
 
A Sneak Peek of MLIR in TensorFlow
A Sneak Peek of MLIR in TensorFlowA Sneak Peek of MLIR in TensorFlow
A Sneak Peek of MLIR in TensorFlow
 
A Peek into Google's Edge TPU
A Peek into Google's Edge TPUA Peek into Google's Edge TPU
A Peek into Google's Edge TPU
 
Why You Cannot Use Neural Engine to Run Your NN Models on A11 Devices?
Why You Cannot Use Neural Engine to Run Your NN Models on A11 Devices?Why You Cannot Use Neural Engine to Run Your NN Models on A11 Devices?
Why You Cannot Use Neural Engine to Run Your NN Models on A11 Devices?
 
open source nn frameworks on cellphones
open source nn frameworks on cellphonesopen source nn frameworks on cellphones
open source nn frameworks on cellphones
 
Caffe2 on Android
Caffe2 on AndroidCaffe2 on Android
Caffe2 on Android
 
Introduction to TensorFlow Lite
Introduction to TensorFlow Lite Introduction to TensorFlow Lite
Introduction to TensorFlow Lite
 
Tensorflow on Android
Tensorflow on AndroidTensorflow on Android
Tensorflow on Android
 
SoC Idling for unconf COSCUP 2016
SoC Idling for unconf COSCUP 2016SoC Idling for unconf COSCUP 2016
SoC Idling for unconf COSCUP 2016
 
Android Wear and the Future of Smartwatch
Android Wear and the Future of SmartwatchAndroid Wear and the Future of Smartwatch
Android Wear and the Future of Smartwatch
 
Understanding Android Benchmarks
Understanding Android BenchmarksUnderstanding Android Benchmarks
Understanding Android Benchmarks
 
Dark Silicon, Mobile Devices, and Possible Open-Source Solutions
Dark Silicon, Mobile Devices, and Possible Open-Source SolutionsDark Silicon, Mobile Devices, and Possible Open-Source Solutions
Dark Silicon, Mobile Devices, and Possible Open-Source Solutions
 

Recently uploaded

Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 

Recently uploaded (20)

Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 

Smalltalk and ruby - 2012-12-08

  • 1. An Amateur Smalltalk User’s Observations on Ruby Object Model and Bytecode “freedom” Koan-Sin Tan freedom_at_computer.org RubyConf Taiwan, Dec 8th, 2012 1 Friday, March 22, 13
  • 2. Or say, learning Ruby, a stupid way 2 Friday, March 22, 13
  • 3. Outline • General introduction • Smalltalk-80 and Ruby object models • Smalltalk-80 and Ruby bytecode 3 Friday, March 22, 13
  • 4. Who am I • Learnt to write program on MPF-II • Used to be a programming language junkie • Learnt a bit Smalltalk during early '90s, use it on and off • Recent interest in ST-80 because of Scratch and BYOB/SNAP • Working on dealing with big.LITTLE system • Knew little about Ruby 4 Friday, March 22, 13
  • 5. MPF-II • Multi-tech Micro-Professor II, MPF-II • A not so compatible Apple-][ clone • 6502 • Basic similar to Apple SOFT • Different monitor • I got one of this in 1983 5 Friday, March 22, 13
  • 6. the first smalltalk-80 I used is on Sun’s SunView, image from Wikipedia 6 Friday, March 22, 13
  • 7. Smalltalk/V 286, from http://www.drdobbs.com/ architecture-and-design/making-smalltalk-with-widgets/ 184408550 7 Friday, March 22, 13
  • 8. Scratch and BYOB/SNAP visual programming 8 Friday, March 22, 13
  • 9. ARM big.LITTLE 9 Friday, March 22, 13
  • 11. What I knew about Ruby • freebsd: portupgrade is written in ruby, http:// wiki.freebsd.org/portupgrade • RoR • message passing • temporary variable, block, block arguments • However, a block in ruby is not an object!! • And of course, ruby is more than smalltalk-80 11 Friday, March 22, 13
  • 12. Smalltalk-80 • Object-Oriented • Design Pattern: Programming • if you read GoF • OO GUI environment, book, you ran into IDE lots Smalltalk patterns before • VM, bytecode • Learning/educational • Lambda, functional language, block • Logo and the dream of Dynabook • Message passing 12 Friday, March 22, 13
  • 13. some smalltalk-80 systems • Squeak:  originally  from  Alan  Kay  and  other   veteran  Smalltalk  guys • Pharo:  a  Squeak  fork  focusing  on  providing  a   clean  and  ready-­‐to-­‐use  smalltalk   environment • VisualWorks:  the  ParcPlace  system • GNU  Smalltalk 13 Friday, March 22, 13
  • 14. Object Model • Object Model can be used to refer to different things • We just touch what a common language user is aware of, not something like the details of how objects are represented in VMs • I believe you can get more about VM implementations from Sasada-San’s talk 14 Friday, March 22, 13
  • 15. Smalltalk Object Model • From "purple book", Chap 16 1. Every class is ultimately a subclass of class Object, except for Object itself, which has no superclass. In particular, Class is a subclass of ClassDescription, which is a subclass of Behavior which is a subclass of Object 2. Every object is an instance of a class 3. Every class is an instance of a metaclass 4. All metaclasses are subclasses of Class 5. Every metaclass is an instance of Metaclass 6. The method of Class and it superclasses support the behavior common to all objects that are classes 7. The methods of instances of Metaclass add the behavior specific to particular classes 15 Friday, March 22, 13
  • 16. Smalltalk Object Model •10 factorial --> 3628800 •10 factorial class --> SmallInteger •SmallInteger superclass --> Integer •Integer  superclass  --> Number •Number  superclass  --> Magnitude •Magnitude  superclass  --> Object •Object  superclass  -­‐-­‐>  ProtoObject •ProtoObject  superclass  -­‐-­‐>  nil 16 Friday, March 22, 13
  • 17. • 10 factorial class allSuperClasses --> an OrderedCollection(Integer Number Magnitude Object ProtoObject) 17 Friday, March 22, 13
  • 18. SmallInteger class --> SmallInteger class • Integer  class  --> Integer  class • Number  class -->  Number  class • Magnitude  class -->  Magnitude  class • Object  class -->  Object  class • ProtoObject  class -->  ProtoObject  class 18 Friday, March 22, 13
  • 19. ProtoObject ProtoObject class Object Object class Magnitude Magnitude class Number Number class Integer Integer class SmallInteger SmallInteger class 10 Key instance-of figures modified from “Pharo by Example” 19 Friday, March 22, 13
  • 20. 4. All metaclasses are subclasses of Class 5. Every metaclass is an instance of Metaclass 20 Friday, March 22, 13
  • 21. SmallInteger class superclass --> Integer class Integer class superclass --> Number class umber class superclass --> Magnitude class Magnitude class superclass --> Object class Object class superclass --> ProtoObject class ProtoObject class superclass --> Class Class class class --> Metaclass 21 Friday, March 22, 13
  • 22. Class class Class ProtoObject ProtoObject class Metaclass class Object Object class Magnitude Magnitude class Metaclass Number Number class Integer Integer class SmallInteger SmallInteger class Key instance-of 10 22 Friday, March 22, 13
  • 23. 6. The method of Class and it superclasses support the behavior common to all objects that are classes 7. The methods of instances of Metaclass add the behavior specific to particular classes 23 Friday, March 22, 13
  • 24. Class class class --> Metaclass Metaclass superclass --> ClassDescription. ClassDescription superclass --> Behavior Behavior superclass --> Object Class class superclass --> ClassDescription class ClassDescription class --> superclass Behavior class Behavior class superclass --> Object class 24 Friday, March 22, 13
  • 25. Behavior class Behavior ClassDescription class ClassDescription Class class Class ProtoObject ProtoObject class Metaclass class Object Object class Magnitude Metaclass Magnitude class Number Number class Integer Integer class Key SmallInteger instance-of SmallInteger class 10 25 Friday, March 22, 13
  • 26. from “PBE” 26 Friday, March 22, 13
  • 27. • since I cannot find good Ruby tutorial/book similar to blue/purple book, let see check if we can use similar way to explore ruby 27 Friday, March 22, 13
  • 28. Ruby Metaclass • Singleton class, eigenclass 28 Friday, March 22, 13
  • 29. from ‘ri Class’ of ruby 1.8 +------------------+ | | Object---->(Object) | ^ ^ ^ ^ | | | | | | | | +-----+ +---------+ | | | | | | | +-----------+ | | | | | | | +------+ | Module--->(Module) | | | ^ ^ | OtherClass-->(OtherClass) | | | | | | Class---->(Class) | ^ | | | 29 +----------------+ Friday, March 22, 13
  • 30. from ‘ri Class’ of ruby 1.9 • All  metaclasses  are  instances  of  the  class  `Class'.           +---------+ +-... | | | BasicObject-----|-->(BasicObject)-------|-... ^ | ^ | | | | | Object---------|----->(Object)---------|-... ^ | ^ | | | | | +-------+ | +--------+ | | | | | | | | Module-|---------|--->(Module)-|-... | ^ | | ^ | | | | | | | | Class-|---------|---->(Class)-|-... | ^ | | ^ | | +---+ | +----+ | | obj--->OtherClass---------->(OtherClass)-----------... 30 Friday, March 22, 13
  • 31. Ruby Eigenclass hierarchy noway:work freedom$ ruby -v freedom@freedom-desktop:~$ ruby -v ruby 1.9.3p0 (2011-10-30 revision 33570) [arm-linux- ruby 1.8.7 (2012-02-08 patchlevel 358) eabi] [universal-darwin12.0] freedom@freedom-desktop:~$ irb -v irb 0.9.6(09/06/30) noway:work freedom$ irb -v freedom@freedom-desktop:~$ irb irb(main):001:0> 1.class irb 0.9.5(05/04/13) => Fixnum irb(main):002:0> 1.class.class noway:work freedom$ irb => Class irb(main):003:0> 1.class.class.superclass >> 1.class => Module irb(main):004:0> 1.class.class.superclass.superclass => Fixnum => Object irb(main):005:0> >> 1.class.class 1.class.class.superclass.superclass.superclass => BasicObject => Class irb(main):006:0> 1.class.class.superclass.superclass.superclass.supercl >> 1.class.class.superclass ass => nil => Module irb(main):007:0> >> 1.class.class.superclass.superclass => Object >> 1.class.class.superclass.superclass.superclass => nil >> 31 Friday, March 22, 13
  • 32. >> 1.class.ancestors => [Fixnum, Integer, Precision, Numeric, Comparable, Object, Kernel] 32 Friday, March 22, 13
  • 33. $ rbenv exec irb meta.rb rb(main):001:0> 1.class.class => Class irb(main):002:0> 1.class.class.ancestors => [Class, Module, Object, Kernel, BasicObject] $rbenv exec irb meta.rb meta.rb(main):001:0> class Object meta.rb(main):002:1> def metaclass meta.rb(main):003:2> class << self; self; end meta.rb(main):004:2> end meta.rb(main):005:1> end => nil meta.rb(main):006:0> meta.rb(main):007:0* 1.class.metaclass => #<Class:Fixnum> eta.rb(main):008:0> 1.class.metaclass.superclass => #<Class:Integer> meta.rb(main):009:0> 1.class.metaclass.ancestors => [Class, Module, Object, Kernel, BasicObject] 33 Friday, March 22, 13
  • 34. meta.rb(main):009:0> 1.class.metaclass.ancestors => [Class, Module, Object, Kernel, BasicObject] • hmm..., back to superclass meta.rb(main):010:0> 1.class.metaclass.superclass.superclass => #<Class:Numeric> meta.rb(main):011:0> 1.class.metaclass.superclass.superclass.superclass => #<Class:Object> meta.rb(main):012:0> 1.class.metaclass.superclass.superclass.superclass.superclass => #<Class:BasicObject> meta.rb(main):013:0> 1.class.metaclass.superclass.superclass.superclass.superclass.superclass => Class 34 Friday, March 22, 13
  • 35. Ruby's Object Hierarchy 2 Basic instance ! != == __id__ __send__ equal? Object methods instance_eval instance_exec !~ <=> === =~ class clone super define_singleton_method display dup eigen_class class eigen_methods enum_for eql? extend freeze frozen? hash initialize_clone initialize_dup inspect instance_of? instance_variable_defined? instance_variable_get instance_variable_set included instance instance_variables is_a? kind_of? method Kernel Object methods methods nil? object_id private_methods modules protected_methods public_method public_methods public_send respond_to? respond_to_missing? send singleton_class singleton_methods taint tainted? tap to_enum to_s trust untaint untrust untrusted? super class < <= > >= ancestors autoload autoload? class_eval class_exec class_variable_defined? class_variable_get class_variable_set Module class_variables const_defined? const_get instance const_missing const_set constants include? methods included_modules instance_method instance_methods method_defined? module_eval module_exec name private_class_method private_constant private_instance_methods private_method_defined? super protected_instance_methods protected_method_defined? public_class_method class public_constant public_instance_method public_instance_methods public_method_defined? remove_class_variable Class instance •So Ruby’s object hierarchy methods allocate new superclass super methods class should be similar to this Basic Object eigen class #<Class: BasicObject> instance methods •http://drtom.schank.ch/posts/ super class methods super class 2011/12/11/ Object eigen class #<Class:Object> instance methods Rubys_Object_Model_and_Eige super class methods super class nclasses/ instance try_convert eigen String class #<Class:String> methods Thomas Schank © 2011 (CC BY-ND) 35 Friday, March 22, 13
  • 36. Bytecode • Bytecode is not new at all • Smalltalk is one of early bytecode users • Smalltalk bytecode • end of Chapter 26, http:// www.mirandabanda.org/bluebook/ bluebook_chapter26.html#TheBytecodes26 • Chap. 28, http://www.mirandabanda.org/ bluebook/bluebook_chapter28.html 36 Friday, March 22, 13
  • 37. Smalltalk bytecode categories • pushes • indicates  the  source  of  an  object  to  be  added  to  the  top  of  the   interpreter's  stack • stores • indicates  the  variable  whose  value  should  be  changed • sends • specifies  the  selector  of  a  message  to  be  sent  and  how  many   arguments  it  should  have. • returns •  a  value  is  returned  for  the  message  that  invoked  that   CompiledMethod • and  jumps • you  know  what  these  are 37 Friday, March 22, 13
  • 38. Smalltalk  bytecodes Range Bits FuncQon 0-­‐15 0000iiii Push  Receiver  Variable  #iiii 16-­‐31 0001iiii Push  Temporary  LocaQon  #iiii 32-­‐63 001iiiii Push  Literal  Constant  #iiiii 64-­‐95 010iiiii Push  Literal  Variable  #iiiii 96-­‐103 01100iii Pop  and  Store  Receiver  Variable  #iii 104-­‐111 01101iii Pop  and  Store  Temporary  LocaQon  #iii 112-­‐119 01110iii Push  (receiver,  true,  false,  nil,  -­‐1,  0,  1,  2)  [iii] 120-­‐123 011110ii Return  (receiver,  true,  false,  nil)  [ii]  From  Message 124-­‐125 0111110i Return  Stack  Top  From  (Message,  Block)  [i] 126-­‐127 0111111i unused 128 10000000  jjkkkkkk Push  (Receiver  Variable,  Temporary  LocaQon,  Literal  Constant,  Literal  Variable)  [jj]  #kkkkkk 129 10000001  jjkkkkkk Store  (Receiver  Variable,  Temporary  LocaQon,  Illegal,  Literal  Variable)  [jj]  #kkkkkk 130 10000010  jjkkkkkk Pop  and  Store  (Receiver  Variable,  Temporary  LocaQon,  Illegal,  Literal  Variable)  [jj]  #kkkkkk 131 10000011  jjjkkkkk Send  Literal  Selector  #kkkkk  With  jjj  Arguments 132 10000100  jjjjjjjj  kkkkkkkk Send  Literal  Selector  #kkkkkkkk  With  jjjjjjjj  Arguments 133 10000101  jjjkkkkk Send  Literal  Selector  #kkkkk  To  Superclass  With  jjj  Arguments 134 10000110  jjjjjjjj  kkkkkkkk Send  Literal  Selector  #kkkkkkkk  To  Superclass  With  jjjjjjjj  Arguments 135 10000111 Pop  Stack  Top 136 10001000 Duplicate  Stack  Top 137 10001001 Push  AcQve  Context 138-­‐143 unused 144-­‐151 10010iii Jump  iii  +  1  (i.e.,  1  through  8) 152-­‐159 10011iii Pop  and  Jump  0n  False  iii  +1  (i.e.,  1  through  8) 160-­‐167 10100iii  jjjjjjjj Jump(iii  -­‐  4)  *256+jjjjjjjj 168-­‐171 101010ii  jjjjjjjj Pop  and  Jump  On  True  ii  *256+jjjjjjjj 172-­‐175 101011ii  jjjjjjjj Pop  and  Jump  On  False  ii  *256+jjjjjjjj 176-­‐191 1011iiii Send  ArithmeQc  Message  #iiii 192-­‐207 1100iiii Send  Special  Message  #iiii 208-­‐223 1101iiii Send  Literal  Selector  #iiii  With  No  Arguments 224-­‐239 1110iiii Send  Literal  Selector  #iiii  With  1  Argument 240-­‐255 1111iiii 38 Send  Literal  Selector  #iiii  With  2  Arguments   Friday, March 22, 13
  • 39. An  example  method, forCompiledMethod "to show how CompiledMethod works" | foo | foo := 'test'. ^ 1 + 2 • Bytecode:  in  System  Browser  of  Squeak/Pharo,  we  can  see  byteCode  easily –17 <20> pushConstant: 'test' –18 <68> popIntoTemp: 0 –19 <76> pushConstant: 1 –20 <77> pushConstant: 2 –21 <B0> send: + –22 <7C> returnTop 39 Friday, March 22, 13
  • 40. displaying smalltalk bytecode • CompiledMethod • Class>>compiledMethodAt • (Integer compiledMethodAt: #factorial) symbolic • (RubyConfTW compiledMethodAt: #forCompiledMethd) symbolic • code here 40 Friday, March 22, 13
  • 41. compiler • Behavior>>compile • compile: compile: code ^self compile: code notifying: nil • compile:notifying: • compile:classified: notifying: requestor trailer: ifFail: 41 Friday, March 22, 13
  • 42. a Simple Behavior>>compile example • RubyConfTW compile: 'foo^42' • RubyConfTW will have a new method called foo and the code is to return the ultimate answer • (RubyConfTW compiledMethodAt: #foo) symbolic '17 <20> pushConstant: 42 18 <7C> returnTop’ 42 Friday, March 22, 13
  • 43. add a method | myClass myInstance |   myClass := Behavior new. "create anon behavior"   myClass compile: 'theAnswer ^42'. "add a method for insta nces"   myInstance := myClass new. "create an instance"   Transcript show: myInstance theAnswer; cr. "shows 42"  43 Friday, March 22, 13
  • 44. Ruby bytecode • ruby  1.8 o cannot  find  easy  way  to  do  this • ruby  1.9  and  2.0 o ruby.c:proc_opQons() § -­‐-­‐dump=insns o YARV  InstrucQon  table o hmp://www.atdot.net/yarv/insnstbl.html,   o source  code,  or o you  can  ask  Sasada-­‐san  :-­‐) 44 Friday, March 22, 13
  • 45. For a simple hello world > rbenv exec ruby --dump=insns ~/work/ruby/test.rb == disasm: <RubyVM::InstructionSequence:<main>@/Users/freedom/work/ruby/ test.rb> 0000 trace 1 ( 1) 0002 putself 0003 putstring "hello, worldn" 0005 send <callinfo!mid:print, argc:1, FCALL|ARGS_SKIP> 0007 leave 45 Friday, March 22, 13
  • 46. Ruby KERNEL Module • it  took  me  some  Qme  to  figure  out  what  puts()  and   other  kernel  methods  are • puts  ==  KERNEL.puts  ==  $stdout.puts()?,   == disasm: <RubyVM::InstructionSequence:<main>@test.rb>================= 0000 trace 1 ( 1) 0002 putself 0003 putstring "hello, worldn" 0005 send <callinfo!mid:puts, argc:1, FCALL|ARGS_SKIP> 0007 pop 0008 trace 1 ( 2) 0010 getinlinecache 17, <ic:0> 0013 getconstant :Kernel 0015 setinlinecache <ic:0> 0017 putstring "hello, worldn" 0019 opt_send_simple <callinfo!mid:puts, argc:1, ARGS_SKIP> 0021 pop 0022 trace 1 ( 3) 0024 getglobal $stdout 0026 putstring "hello, world" 0028 opt_send_simple <callinfo!mid:puts, argc:1, ARGS_SKIP> 0030 leave 46 Friday, March 22, 13
  • 47. CompiledMethod in Ruby • RubyVM::InstructionSequence • = Class methods: • compile, compile_file, compile_option, compile_option=, disasm, disassemble, load, new • = Instance methods: • disasm, disassemble, eval, inspect, to_a 47 Friday, March 22, 13
  • 48. CompiledMethod in Ruby filename = ARGV[0] code = RubyVM::InstructionSequence.compile_file filename File.open "bytecode.dump", "w" do |file| file << Marshal.dump(code.to_a) end print code.disasm 48 Friday, March 22, 13
  • 49. Load saved instruction sequence • there  is  no  RubyVM::InstrucQonSequence.load,  but   there  is  iseq_s_load()  in  iseq.c #if 0 /* TBD */ rb_define_method(rb_cISeq, "marshal_dump", iseq_marshal_dump, 0); rb_define_method(rb_cISeq, "marshal_load", iseq_marshal_load, 1); #endif /* disable this feature because there is no verifier. */ /* rb_define_singleton_method(rb_cISeq, "load", iseq_s_load, -1); */ (void)iseq_s_load; • So,  my  first  reacQon  is /* disable this feature because there is no verifier. */ rb_define_singleton_method(rb_cISeq, "load", iseq_s_load, -1); // (void)iseq_s_load; • And  I  googled  a  bit,  found  that,  it  seems  we  can  define   an  InstrucQonSequence.load  method  to  use     iseq_s_load() • hmp://bb10.com/ruby-­‐core/2012-­‐07/msg00303.html 49 Friday, March 22, 13
  • 50. Store and load • test.rb puts “hello, worldn” puts 1+2 • store-and-load.rb filename = ARGV[0] code = RubyVM::InstructionSequence.compile_file filename File.open "bytecode.dump", "w" do |file| file << Marshal.dump(code.to_a) end code = nil File.open "bytecode.dump", "r" do |file| code = RubyVM::InstructionSequence.load Marshal.restore(file.read) end print code.disasm 50 Friday, March 22, 13
  • 51. test.rb ./ruby --disable-gems ~/work/ruby/load.rb == disasm: <RubyVM::InstructionSequence:<main>@/Users/freedom/work/ruby/ test.rb> local table (size: 1, argc: 0 [opts: 0, rest: -1, post: 0, block: -1] s1) 0000 trace 1 0002 putself 0003 putstring "hello, worldn" 0005 send <callinfo!mid:puts, argc:1, FCALL|ARGS_SKIP> 0007 pop 0008 trace 1 0010 putself 0011 putobject 1 0013 putobject 2 0015 opt_plus <callinfo!mid:+, argc:1, ARGS_SKIP> 0017 send <callinfo!mid:puts, argc:1, FCALL|ARGS_SKIP> 0019 leave 51 Friday, March 22, 13
  • 52. With some tweaks and modification to bytecode.dump ./ruby --disable-gems ~/work/ruby/load.rb == disasm: <RubyVM::InstructionSequence:<main>@/Users/freedom/work/ruby/ test.rb> local table (size: 1, argc: 0 [opts: 0, rest: -1, post: 0, block: -1] s1) 0000 trace 1 0002 putself 0003 putstring "hello, worldn" 0005 send <callinfo!mid:puts, argc:1, FCALL|ARGS_SKIP> 0007 pop 0008 trace 1 0010 putself 0011 putobject 1 0013 putobject 2 0015 opt_plus <callinfo!mid:+, argc:1, ARGS_SKIP> 0017 send <callinfo!mid:puts, argc:1, FCALL|ARGS_SKIP> 0019 answe 52 Friday, March 22, 13
  • 53. in case you didn’t get it • There is a YARV instruction called “answer” • And, the answer instruction will return “The Answer to Life, the Universe, and Everything”, which you know is 42 • http://en.wikipedia.org/wiki/ Answer_to_The_Ultimate_Question_of_Life,_ the_Universe,_and_Everything#Answer_to_th e_Ultimate_Question_of_Life. 2C_the_Universe.2C_and_Everything_.2842.29 53 Friday, March 22, 13
  • 54. Comparing bytecodes 17 <20> pushConstant: 'test’ 18 <68> popIntoTemp: 0 19 <76> pushConstant: 1 20 <77> pushConstant: 2 21 <B0> send: + 22 <7C> returnTop 0000 trace 1 0002 putself 0003 putstring "hello, worldn" 0005 send <callinfo!mid:puts, argc:1, FCALL|ARGS_SKIP> 0007 pop 0008 trace 1 0010 putself 0011 putobject 1 0013 putobject 2 0015 opt_plus <callinfo!mid:+, argc:1, ARGS_SKIP> 0017 send <callinfo!mid:puts, argc:1, FCALL|ARGS_SKIP> 0019 leave 54 Friday, March 22, 13
  • 55. An  example  method, forCOmpiledMethod2: a and: b "to show how CompiledMethod works" | foo | foo := 'test'. ^ a + b • Bytecode:  in  System  Browser  of  Squeak/Pharo,  we  can  see  byteCode  easily –17 <20> pushConstant: 'test' –18 <68> popIntoTemp: 2 –19 <76> pushTemp: 0 –20 <77> pushTemp: 1 –21 <B0> send: + –22 <7C> returnTop 55 Friday, March 22, 13
  • 56. Some obvious differences • Smalltalk bytecodes are quite low-level, but more consistent? • String is not special • no special optimizations such as ‘op_plus’ • but Smalltalk-80 does have some primitive methods • no joke bytecode :-) 56 Friday, March 22, 13
  • 57. Smalltalk primitive method Integer>>+ + aNumber     "Refer to the comment in Number + "     aNumber isInteger ifTrue:         [self negative == aNumber negative             ifTrue: [^ (self digitAdd: aNumber) normalize]             ifFalse: [^ self digitSubtract: aNumber]].     ^ aNumber adaptToInteger: self andSend: #+ SmallInteger>>+ + aNumber     "Primitive. Add the receiver to the argument and answer with the result     if it is a SmallInteger. Fail if the argument or the result is not a     SmallInteger Essential No Lookup. See Object documentation whatIsAPrimitive."     <primitive: 1>     ^ super + aNumber 57 Friday, March 22, 13
  • 58. ?? 58 Friday, March 22, 13
  • 59. Thanks!! 59 Friday, March 22, 13