computable-pandoc/src/literate.lua

342 lines
10 KiB
Lua
Raw Normal View History

2023-03-28 14:25:02 -06:00
---------------------------------- LITERATE ----------------------------------
2023-03-09 20:13:01 -06:00
-- Stores all literate stuff
2023-03-11 14:14:24 -06:00
local lit = {}
2023-03-10 21:09:31 -06:00
-- Indicates status
2023-03-20 19:28:32 -06:00
lit.status = true
-- Stores literate functions
lit.fns = {}
-- Returns specific grammar
2023-04-03 12:39:11 -06:00
function lit.g(name)
-- Stores all grammars
2023-06-15 18:42:23 -06:00
local grammars = {}
-- Shortcuts
2023-06-16 11:04:17 -06:00
local P, S, R, Cf, Cc, Ct, V, Cs, Cg, Cb, B, C, Cmt =
2023-07-01 11:03:35 -06:00
lpeg.P,
lpeg.S,
lpeg.R,
lpeg.Cf,
lpeg.Cc,
lpeg.Ct,
lpeg.V,
lpeg.Cs,
lpeg.Cg,
lpeg.Cb,
lpeg.B,
lpeg.C,
lpeg.Cmt
2023-06-16 11:04:17 -06:00
2023-04-03 12:39:11 -06:00
-- Lexical elements
2023-07-01 11:03:35 -06:00
local newline = P("\r") ^ -1 * P("\n")
local space = S(" \t")
local anyspace = S(" \t\r\n")
2023-04-03 12:39:11 -06:00
local spot = (1 - anyspace)
local any = (spot + space)
2023-07-01 11:03:35 -06:00
local yamlheader = space ^ 0 * P("---") * space ^ 0 * newline
local yamlfooter = space ^ 0 * P("...") * space ^ 0 * newline ^ -1
local yamlbody = -yamlfooter * any ^ 0 * newline
local label = R("az", "AZ") * R("az", "AZ", "09", "__") ^ 0
local ref = -B("\\") * P("#") * C(label)
local notref = (1 - ref) ^ 0
2023-06-15 18:42:23 -06:00
-- Function declaration grammar
2023-07-01 11:03:35 -06:00
grammars["declaration"] = P({
"Declaration",
Declaration = Ct(V("YAML") * V("Code"), "name"),
YAML = C(yamlheader * yamlbody ^ 0 * yamlfooter),
Code = C((any + newline) ^ 0),
})
2023-04-03 12:39:11 -06:00
-- Argument references grammar
2023-07-01 11:03:35 -06:00
grammars["references"] = notref
* P({
"References",
References = Ct((ref * notref) ^ 0),
})
* -1
2023-06-15 18:42:23 -06:00
2023-04-03 12:39:11 -06:00
return grammars[name]
end
2023-03-28 14:25:02 -06:00
-- Prints located messages
2023-06-16 11:04:17 -06:00
function lit.puts(yaml_key, ...)
-- Returns debug level as number
2023-04-03 12:39:11 -06:00
local function debuglevel(str)
if str == "ERROR" then
lit.status = false
return 2
elseif str == "WARNING" then
return 1
else
return 0
end
end
-- Gets located message
2023-04-03 12:39:11 -06:00
local function getmsg(key, ...)
local msg = pandoc.metatotable(pandoc.read([[`locale()`]]).meta)
local levelname, level, lang = "INFO", 0, os.lang()
2023-04-03 12:39:11 -06:00
for mtype, msgs in pairs(msg) do
if msgs[key] then
key = (msgs[key][lang] ~= nil and msgs[key][lang] or msgs[key]["en"])
2023-07-01 11:03:35 -06:00
for i, str in ipairs({ ... }) do
2023-06-16 11:04:17 -06:00
key = key:gsub("#" .. i, str)
end
2023-04-03 12:39:11 -06:00
levelname, level = mtype, debuglevel(mtype)
break
end
end
2023-06-16 11:04:17 -06:00
return key, levelname, level
end
2023-04-03 12:39:11 -06:00
local verbosity = debuglevel(PANDOC_STATE.verbosity)
2023-06-16 11:04:17 -06:00
local msg, levelname, level = getmsg(yaml_key, ...)
2023-07-01 11:03:35 -06:00
if level >= verbosity then print("[" .. levelname .. "] [LIT] " .. msg) end
end
-- Parses and evaluates literate functions in document
2023-04-17 18:59:58 -06:00
function lit.exam(doc)
-- Extracts function declarations
local function extract(codeblock)
-- Checks function declarations
local function check(match)
-- Stores valid declaration
local declaration = {}
2023-04-20 14:37:10 -06:00
-- Valid metadata structure
local metastruct = {
["mandatory"] = {
-- Value as table == whole patterns to match
2023-07-01 11:03:35 -06:00
["id"] = { "%a[_%w]*" },
2023-04-20 14:37:10 -06:00
},
["optional"] = {
["lang"] = {
2023-07-01 11:03:35 -06:00
"lua",
"fennel",
"python",
"js",
"ruby",
"lisp",
"graphviz",
2023-06-16 11:04:17 -06:00
},
2023-07-01 11:03:35 -06:00
["cmd"] = { ".+" },
2023-04-20 14:37:10 -06:00
-- Value as string == type to match
["args"] = "table",
["shift"] = "boolean",
["wipe"] = "boolean",
["typed"] = "boolean",
["link"] = "path",
["img"] = "path",
["alt"] = "string",
["dump"] = "path",
["quote"] = "boolean",
},
}
-- Language commands
-- Eachs command is a table of table;
-- First table indicates one or more internal or external evaluations
-- Second table indicates one or more commands to try
2023-04-20 14:37:10 -06:00
local langcmds = {
2023-07-01 11:03:35 -06:00
["lua"] = { ["int_eval"] = { "CMD1", "CMD2" } },
["fennel"] = { ["int_eval"] = { "CMD1", "CMD2" } },
["python"] = { ["ext_eval"] = { "CMD1", "CMD2" } },
["js"] = { ["ext_eval"] = { "CMD1", "CMD2" } },
["ruby"] = { ["ext_eval"] = { "CMD1", "CMD2" } },
["lisp"] = { ["ext_eval"] = { "CMD1", "CMD2" } },
["graphviz"] = { ["ext_eval"] = { "CMD1", "CMD2" } },
2023-04-20 14:37:10 -06:00
}
2023-06-16 11:04:17 -06:00
-- Prints error
-- Since error messages debuglevel are "ERROR", lit.status turns false
-- Flush the declaration to avoid storage in lit.fns
2023-04-20 14:37:10 -06:00
local function putserr(...)
lit.puts(...)
declaration = {}
2023-04-20 14:37:10 -06:00
end
-- Adds 'eval' key in declaration
-- This key indicates what to eval
local function addeval()
declaration["eval"] = {}
-- If lang and cmd are present, ignores lang and use cmd as eval
if declaration["lang"] and declaration["cmd"] then
lit.puts("ignore_lang", declaration["cmd"], declaration["lang"])
2023-07-01 11:03:35 -06:00
declaration["eval"] = { ["ext_eval"] = { declaration["cmd"] } }
-- If neither lang or cmd are presents, defaults lang and eval to lua
2023-07-01 11:03:35 -06:00
elseif not declaration["lang"] and not declaration["cmd"] then
declaration["lang"] = "lua"
declaration["eval"] = langcmds["lua"]
-- If only lang present, eval is lang
2023-07-01 11:03:35 -06:00
elseif declaration["lang"] and not declaration["cmd"] then
declaration["eval"] = langcmds[declaration["lang"]]
-- If only cmd present, eval is cmd
2023-07-01 11:03:35 -06:00
elseif not declaration["lang"] and declaration["cmd"] then
declaration["eval"] = { ["ext_eval"] = { declaration["cmd"] } }
2023-04-20 14:37:10 -06:00
end
end
2023-06-16 11:04:17 -06:00
-- Checks for valid command for Unix systems
local function checkcmd()
if declaration["cmd"] then
local cmd = declaration["cmd"]:split()[1]
2023-04-19 12:33:35 -06:00
if os.isunix() then
2023-06-16 11:04:17 -06:00
local status = io.try("type", cmd)
2023-07-01 11:03:35 -06:00
if not status then putserr("invalid_cmd", cmd) end
2023-04-19 12:33:35 -06:00
else
lit.puts("skip_check", "checkcmd")
end
end
end
-- Checks for extra, unwanted and wrong metadata
local function checkextra()
for key, _ in pairs(declaration) do
2023-06-16 11:04:17 -06:00
local missing1 = metastruct["mandatory"][key] == nil
local missing2 = metastruct["optional"][key] == nil
2023-07-01 11:03:35 -06:00
if missing1 and missing2 then putserr("invalid_key", key) end
2023-06-16 11:04:17 -06:00
end
end
-- Checks for valid metadata
local function checkmeta(kind)
-- Checks for valid metadata type
local function checktype(type1, key)
local val = declaration[key]
2023-06-16 11:04:17 -06:00
local type2 = type(val)
if type1 ~= type2 then
if type1 == "path" then
2023-07-01 11:03:35 -06:00
if not (pandoc.path.directory(val):isdir()) then
2023-06-16 11:04:17 -06:00
putserr("invalid_path", val, key)
end
else
putserr("invalid_type", type2, key)
end
end
end
2023-04-04 13:10:50 -06:00
-- Checks for valid metadata pattern
local function checkpattern(table, key)
local val = tostring(declaration[key])
2023-06-16 11:04:17 -06:00
local err = key
for _, pattern in pairs(table) do
if val:match("^" .. pattern .. "$") then
err = ""
break
2023-06-16 11:04:17 -06:00
end
end
2023-07-01 11:03:35 -06:00
if not (err:isempty()) then putserr("invalid_value", val, err) end
2023-06-16 11:04:17 -06:00
end
for key, val in pairs(metastruct[kind]) do
if declaration[key] == nil and kind == "mandatory" then
2023-06-16 11:04:17 -06:00
putserr("no_key", key)
elseif declaration[key] and type(val) == "table" then
checkpattern(val, key)
elseif declaration[key] then
checktype(val, key)
2023-06-16 11:04:17 -06:00
end
end
end
-- Parses metadata
2023-06-16 11:04:17 -06:00
local function parsemeta(yaml)
local isok, res = pcall(pandoc.read, yaml)
2023-07-01 11:03:35 -06:00
if isok and not (pandoc.utils.stringify(res.meta):isempty()) then
declaration = pandoc.metatotable(res.meta)
checkmeta("mandatory")
checkmeta("optional")
checkextra()
checkcmd()
if next(declaration) then addeval() end
elseif isok and pandoc.utils.stringify(res.meta):isempty() then
2023-06-16 11:04:17 -06:00
putserr("meta_empty")
else
putserr("meta_invalid")
end
end
2023-06-15 18:42:23 -06:00
-- TODO
-- Parses code
local function parsecode(rawcode)
local code = ""
local references = lpeg.match(lit.g("references"), rawcode)
2023-06-15 18:42:23 -06:00
if references then
for _, ref in ipairs(references) do
print("reference:", ref)
end
end
declaration["code"] = code
2023-06-15 18:42:23 -06:00
end
if match then
lit.puts("checking", table.concat(match, ""):indent())
parsemeta(match[1])
if next(declaration) then parsecode(match[2]) end
end
return declaration
2023-06-16 11:04:17 -06:00
end
2023-04-04 13:10:50 -06:00
local parsed = check(lpeg.match(lit.g("declaration"), codeblock.text))
if next(parsed) then
-- TODO:
-- Eval parsed lit.fns and modify code block accordingly
lit.fns[parsed["id"]] = parsed
end
2023-04-04 13:10:50 -06:00
return codeblock
2023-06-16 11:04:17 -06:00
end
2023-02-16 19:04:01 -06:00
-- Calls literate functions
local function call(el)
-- TODO
-- Calls literate functions in code inlines
local function codecall(code)
return pandoc.Str("EVAL: " .. pandoc.utils.stringify(code))
end
local function metacall(meta)
local function inlinescall(inlines)
2023-07-01 11:03:35 -06:00
return inlines:walk({
Code = function(code) return codecall(code) end,
})
end
for key, val in pairs(meta) do
if pandoc.utils.type(val) == "Inlines" then
meta[key] = inlinescall(val)
elseif pandoc.utils.type(val) == "List" then
for i, item in ipairs(val) do
if pandoc.utils.type(item) == "Inlines" then
meta[key][i] = inlinescall(item)
end
end
end
end
return meta
end
if pandoc.utils.type(el) == "Meta" then
return metacall(el)
else
return codecall(el)
end
2023-04-17 18:59:58 -06:00
end
-- Asserts literate status
local function assert()
2023-07-01 11:03:35 -06:00
if not lit.status then
2023-04-17 18:59:58 -06:00
lit.puts("aborted")
os.exit(1)
2023-03-20 19:28:32 -06:00
end
2023-04-17 18:59:58 -06:00
end
2023-07-01 11:03:35 -06:00
doc = doc:walk({ CodeBlock = function(block) return extract(block) end })
doc = doc:walk({ Meta = function(meta) return call(meta) end })
doc = doc:walk({ Code = function(code) return call(code) end })
return doc:walk({ Pandoc = function(_) assert() end })
2023-03-10 21:09:31 -06:00
end