-- lib/expander.lua
-- $Id: expander.lua,v 1.5 2005/01/12 03:04:23 cpressey Exp $
-- Object that expands ${foo}-patterns in strings.

-- BEGIN lib/expander.lua --

--[[----------]]--
--[[ Expander ]]--
--[[----------]]--

Expander = {}
Expander.new = function(...)
	local e = {}
	local gtables = arg or {}

	--
	-- Command-name expansion.
	--
	-- Specific applications might be able to extend this functionality
	-- by replacing this function with their own version that calls the
	-- original.  For example:
	--
	--	local old_expand = e.expand
	--	e.expand = function(e, str)
	--		new_str = blah(str)
	--		return old_expand(e, new_str)
	--	end
	--
	e.expand = function(e, str, ...)
		local ltables = arg or {}

		local result = string.gsub(str, "%$%{([%w_]+)%}", function(key)
			local i, tab, value

			if table.getn(ltables) > 0 then
				for i, tab in ipairs(ltables) do
					value = tab[key]
					if value then
						return value
					end
				end
			end

			if table.getn(gtables) > 0 then
				for i, tab in ipairs(gtables) do
					value = tab[key]
					if value then
						return value
					end
				end
			end

			if e.warn then
				e:warn(key)
			end

			return "${" .. key .. "}"
		end)

		return result
	end

	--
	-- Warning function.  Specific applications will probably want
	-- to replace this with their own (or nil, to disable it.)
	--
	e.warn = function(e, key)
		print("WARNING: no replacement found for `" .. key .. "'")
	end

	--
	-- Make a distinct copy of this expander.
	--
	e.clone = function(e)
		return Expander.new(unpack(gtables))
	end

	--
	-- Add a table of key->value mappings to this expander.
	--
	e.add_table = function(e, table)
		table.insert(gtables, table)
	end

	return e
end

-- END of lib/expander.lua --
