rpl.rb/lib/dictionary.rb

80 lines
1.8 KiB
Ruby
Raw Normal View History

2021-12-07 16:09:17 +01:00
# frozen_string_literal: true
2021-11-10 11:01:26 +01:00
module Rpl
2021-12-07 15:50:58 +01:00
module Lang
2021-12-07 16:09:17 +01:00
class Dictionary
2022-02-09 16:38:09 +01:00
attr_reader :words,
:vars,
2022-02-02 15:20:24 +01:00
:local_vars_layers
2022-02-02 15:48:21 +01:00
def initialize
@words = {}
@vars = {}
@local_vars_layers = []
end
2022-02-09 16:38:09 +01:00
def add_word( names, category, help, implementation )
names.each do |name|
@words[ name ] = { category: category,
help: help,
implementation: implementation }
end
2022-02-02 15:20:24 +01:00
end
def add_var( name, implementation )
@vars[ name ] = implementation
end
def remove_vars( names )
names.each do |name|
@vars.delete( name )
end
2022-02-02 15:20:24 +01:00
end
def remove_var( name )
remove_vars( [name] )
end
def remove_all_vars
@vars = {}
end
def add_local_vars_layer
@local_vars_layers << {}
end
def add_local_var( name, implementation )
@local_vars_layers.last[ name ] = implementation
end
def remove_local_vars( names )
names.each do |name|
@local_vars_layers.last.delete( name )
end
2022-02-02 15:20:24 +01:00
end
def remove_local_var( name )
remove_local_vars( [name] )
end
def remove_local_vars_layer
@local_vars_layers.pop
end
def lookup( name )
# look in local variables from the deepest layer up
2022-02-08 15:45:36 +01:00
local_vars_layer = @local_vars_layers.reverse.find { |layer| layer[ name ] }
word = local_vars_layer.nil? ? nil : local_vars_layer[ name ]
# otherwise look in (global) variables
2022-02-02 15:20:24 +01:00
word ||= @vars[ name ]
# or is it a core word
2022-02-09 16:38:09 +01:00
word ||= @words[ name ].nil? ? nil : @words[ name ][:implementation]
2022-02-02 15:20:24 +01:00
word
end
2021-11-10 11:01:26 +01:00
end
end
end