computable-pandoc/src/literate.lua

309 lines
8.7 KiB
Lua

---------------------------------- LITERATE ----------------------------------
-- Variable for all literate stuff
local lit = {}
-- Status indicator
lit.status = true
-- Grammars
function lit.g(name)
-- Variable for grammars collection
local grammars = {}
-- Lexical elements
local newline = lpeg.P"\r"^-1 * lpeg.P"\n"
local space = lpeg.S" \t"
local anyspace = lpeg.S" \t\r\n"
local spot = (1 - anyspace)
local any = (spot + space)
local yamlheader = space^0 * lpeg.P"---" * space^0 * newline
local yamlfooter = space^0 * lpeg.P"..." * space^0 * newline^-1
local yamlbody = -yamlfooter * any^0 * newline
local id = lpeg.R("az", "AZ") * lpeg.R("az", "AZ", "09")^0
local ref = -lpeg.B"\\" * lpeg.P"#" * lpeg.C(id)
local notref = (1 - ref)^0
-- Declaration grammar
grammars["declaration"] = lpeg.P {
"Declaration";
Declaration = lpeg.Ct(lpeg.V"YAML" * lpeg.V"Code", "name");
YAML = lpeg.C(yamlheader * yamlbody^0 * yamlfooter);
Code = lpeg.C((any + newline)^0);
}
-- References grammar
grammars["references"] = notref * lpeg.P {
"References";
References = lpeg.Ct((ref * notref)^0);
} * -1
return grammars[name]
end
-- Prints located messages
function lit.puts(key, ...)
-- Returns debug level as number
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
local function getmsg(key, ...)
local msg = pandoc.metatotable(pandoc.read([[#locale()]]).meta)
local levelname, level, lang = "INFO", 0, os.lang()
for mtype, msgs in pairs(msg) do
if msgs[key] ~= nil then
key = (msgs[key][lang] ~= nil and msgs[key][lang] or msgs[key]["en"])
for i, str in ipairs({...}) do key = key:gsub("#" .. i, str) end
levelname, level = mtype, debuglevel(mtype)
break
end
end
return key, levelname, level
end
local verbosity = debuglevel(PANDOC_STATE.verbosity)
local msg, levelname, level = getmsg(key, ...)
if level >= verbosity then
print("[" .. levelname .. "] [LIT] " .. msg)
end
end
-- Examinates (parses and evaluates) document
function lit.exam(doc)
-- Evaluates code declaration
-- Evals Lisp code
--[[
local function eval(code)
local is_passed, out = pcall (
function () return fennel.eval(code) end,
function (e) return e end
)
local lua = ""
local out = tostring(out)
local preview = out:gsub("\n.*", "")
if is_passed then
lua = fennel.compileString(code)
end
return {is_passed = is_passed, preview = preview, out = out, lua = lua}
end
]]--
-- Parses code declaration
local function parse(codeblock)
-- Checks code declarations
local function check(parsed)
-- Indicates if checks passes
local ispass = true
-- Valid metadata structure
local metastruct = {
["mandatory"] = {
-- Value as table == whole patterns to match
["id"] = {"%a[_%w]*"},
},
["optional"] = {
["lang"] = {
"lua", "fennel", "python", "js", "ruby", "lisp", "graphviz",
},
["cmd"] = {".+"},
-- 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
local langcmds = {
["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", } },
}
-- Prints error and does not pass the check
local function putserr(...)
lit.puts(...)
ispass = false
end
-- Adds 'eval' key in meta
-- This keys indicates what to eval
local function addeval(meta)
meta["eval"] = {}
if ispass then
if meta["lang"] and meta["cmd"] then
lit.puts("ignore_lang", meta["cmd"], meta["lang"])
meta["eval"] = {["ext_eval"] = { meta["cmd"] } }
elseif not(meta["lang"]) and not(meta["cmd"])then
meta["lang"] = "lua"
meta["eval"] = langcmds["lua"]
elseif meta["lang"] and not(meta["cmd"]) then
meta["eval"] = langcmds[meta["lang"]]
elseif not(meta["lang"]) and meta["cmd"] then
meta["eval"] = {["ext_eval"] = { meta["cmd"] } }
end
end
return meta
end
-- Checks for valid command
local function checkcmd(meta)
if meta["cmd"] then
cmd = meta["cmd"]:split()[1]
if os.isunix() then
status = io.try("type", cmd)
if not(status) then
putserr("invalid_cmd", cmd)
end
else
lit.puts("skip_check", "checkcmd")
end
end
end
-- Checks for extra and unwanted metadata
local function checkextra(meta)
for key, val in pairs(meta) do
local missing1 = metastruct["mandatory"][key] == nil
local missing2 = metastruct["optional"][key] == nil
if missing1 and missing2 then
putserr("invalid_key", key)
end
end
end
-- Checks for valid metadata
local function checkmeta(meta, kind)
-- Checks for valid metadata type
local function checktype(type1, meta, key)
local val = meta[key]
local type2 = type(val)
if type1 ~= type2 then
if type1 == "path" then
if not(pandoc.path.directory(val):isdir()) then
putserr("invalid_path", val, key)
end
else
putserr("invalid_type", type2, key)
end
end
end
-- Checks for valid metadata pattern
local function checkpattern(table, meta, key)
local val = tostring(meta[key])
local err = key
for _, pattern in pairs(table) do
if val:match("^" .. pattern .. "$") then
err = ""
break
end
end
if not(err:isempty()) then
putserr("invalid_value", val, err)
end
end
for key, val in pairs(metastruct[kind]) do
if meta[key] == nil and kind == "mandatory" then
putserr("no_key", key)
elseif meta[key] and type(val) == "table" then
checkpattern(val, meta, key)
elseif meta[key] then
checktype(val, meta, key)
end
end
end
-- Parses metadata
local function parsemeta(yaml)
local isok, res = pcall(pandoc.read, yaml)
local meta = {}
if isok and not(pandoc.utils.stringify(res.meta):isempty()) then
meta = pandoc.metatotable(res.meta)
checkmeta(meta, "mandatory")
checkmeta(meta, "optional")
checkextra(meta)
checkcmd(meta)
elseif isok and pandoc.utils.stringify(res.meta):isempty() then
putserr("meta_empty")
else
putserr("meta_invalid")
end
return addeval(meta)
end
-- TODO
-- NOTE: if not valid code, return meta["eval"] = {}
local function checkcode(code, meta)
references = lpeg.match(lit.g("references"), code)
if references then
for _, ref in ipairs(references) do
print("reference:", ref)
end
end
return "TODO"
end
lit.puts("checking", table.concat(parsed, ""):indent())
local meta = parsemeta(parsed[1])
-- TODO
-- Add each meta to a variable
-- Remove meta if doesn't pass checkcode
meta["code"] = checkcode(parsed[2], meta)
return meta
end
local parsed = lpeg.match(lit.g("declaration"), codeblock.text)
local checked = (parsed ~= nil and check(parsed) or parsed)
-- TODO:
-- evaluated = eval(checked)
-- TODO: write evaluated and do overrides with warns
-- return evaluated
return codeblock
end
-- TODO
-- Evals and inserts inline code
local function insert(code)
return code
end
-- Asserts literate status
local function assert()
if not(lit.status) then
lit.puts("aborted")
os.exit(1)
end
end
return doc:walk { CodeBlock = function(block) return parse(block) end }
:walk { Code = function(inline) return insert(inline) end }
:walk { Pandoc = function(_) assert() end }
end