--- Build strict file-reference rules for Pascal source files
-- @module formats.pascal.references

local common = require("core.common")
local pascal_references = {}

-- Pattern breakdown: unit lists begin after 'uses'; the later form reaches names following commas
local uses_first_prefix = "^%s*uses%s+"
local uses_later_prefix = ",%s*"
local uses_file_prefix = "^%s*uses%s+.-%f[%a]in%f[^%w_]%s*"
local include_prefix = "%{%$i%s+"
local include_long_prefix = "%{%$include%s+"
local uses_line_pattern = common.caseless_pattern(uses_first_prefix)
local unit_file_suffix = common.caseless_pattern("^%s+in%f[^%w_]")

--- Return whether one unit name ends at a valid list boundary
-- @param reference table parsed unit reference
-- @param line_text string complete source line
-- @return boolean accepted
local function is_unit(reference, line_text)
	return line_text:match(uses_line_pattern) ~= nil
		and reference.path:match("^[%a_][%w_%.]*$") ~= nil
		and (line_text:sub(reference.col2):match("^%s*[,;]") ~= nil
			or line_text:sub(reference.col2):match(unit_file_suffix) ~= nil)
end

--- Convert one Pascal unit into common source filenames
-- @param reference table parsed unit reference
-- @return table candidates
local function unit_candidates(reference)
	return {
		reference.path .. ".pas",
		reference.path .. ".pp",
	}
end

--- Return unit, explicit unit-file, and compiler-include references
-- @return table rules
function pascal_references.new()
	return {
		{ prefix = uses_file_prefix, open = "'", close = "'", caseless = true },
		{ prefix = uses_first_prefix, chars = "[%w_%.]", validate = is_unit, candidates = unit_candidates, caseless = true },
		{ prefix = uses_later_prefix, chars = "[%w_%.]", validate = is_unit, candidates = unit_candidates },
		{ prefix = include_prefix, open = "'", close = "'", caseless = true },
		{ prefix = include_long_prefix, open = "'", close = "'", caseless = true },
		{ prefix = include_prefix, caseless = true },
		{ prefix = include_long_prefix, caseless = true },
	}
end

return pascal_references
