--- Build strict file-reference rules for Lua source files
-- @module formats.lua.references

local lua_references = {}

-- Standalone Lua file calls are references; object methods with the same names are not
-- Pattern breakdown: frontiers reject word, dot, and colon neighbors; spaces and one opening parenthesis are optional
local require_prefix = "%f[%w_%.:]require%f[^%w_%.:]%s*%(?%s*"
local dofile_prefix = "%f[%w_%.:]dofile%f[^%w_%.:]%s*%(?%s*"
local loadfile_prefix = "%f[%w_%.:]loadfile%f[^%w_%.:]%s*%(?%s*"

--- Convert one Lua module name into the filenames used by the standard module layout
-- @param reference table parsed module reference
-- @return table candidates
local function module_candidates(reference)
	local module_path = reference.path:gsub("%.", PATHSEP)

	return {
		module_path .. ".lua",
		module_path .. PATHSEP .. "init.lua",
	}
end

--- Return module and direct file-loading references
-- @return table rules
function lua_references.new()
	return {
		{ prefix = require_prefix, open = "\"", close = "\"", candidates = module_candidates },
		{ prefix = require_prefix, open = "'", close = "'", candidates = module_candidates },
		{ prefix = dofile_prefix, open = "\"", close = "\"" },
		{ prefix = dofile_prefix, open = "'", close = "'" },
		{ prefix = loadfile_prefix, open = "\"", close = "\"" },
		{ prefix = loadfile_prefix, open = "'", close = "'" },
	}
end

return lua_references
