Sha256: f406facc7cc920d25a2494b872fa8cf880bdcc102caa9d6c91e7268b6acbbb8a

Contents?: true

Size: 1.94 KB

Versions: 1

Compression:

Stored size: 1.94 KB

Contents

=begin copyright
    rubylexer - a ruby lexer written in ruby
    Copyright (C) 2004,2005  Caleb Clausen

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
=end


class SymbolTable
   def initialize
      #note: below Stack means Array (used as a stack)
      @symbols={} #Hash of String to Stack of Object(user-defined)
      @locals_lists=[{}] #Stack of Hash of String to Boolean
   end

   def start_block
      assert @locals_lists.last
      @locals_lists.push({})
      assert @locals_lists.last
   end

   def end_block
      assert @locals_lists.last
      list=@locals_lists.pop
      list or raise "unbalanced end block"
      list.each_key {|sym|
         @symbols[sym].pop
         @symbols[sym].empty? and @symbols[sym]=nil
      }
      assert @locals_lists.last
   end

   def [](name)
      assert @locals_lists.last
      (stack=@symbols[name]) and stack.last
   end

   alias === []

   def []=(name, val)
      assert @locals_lists.last
      if @locals_lists.last and @locals_lists.last[name]
         #already defined in this block
         @symbols[name][-1]=val #overwrite current value
      else
         stack=(@symbols[name] ||= [])
         stack.push val
         @locals_lists.last[name]=true
      end
      assert @locals_lists.last
      return val
   end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rubylexer-0.6.2 symboltable.rb