Add view, positional args, errors gold, and bytecode backend.
Reorganize examples into structure/keywords/errors, launch marqdo view for AST-backed browsing, and ship an M5 stack VM selectable via --backend. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
a29bf6e97b
commit
ac0a3fbced
48 files changed
+3007
-202
No files matched your search
@@ -0,0 +1,339 @@
|
||||
//! HTML shell for `marqdo view`.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use crate::view::render::FileViewModel;
|
||||
|
||||
pub fn escape(s: &str) -> String {
|
||||
s.chars()
|
||||
.map(|c| match c {
|
||||
'&' => "&".into(),
|
||||
'<' => "<".into(),
|
||||
'>' => ">".into(),
|
||||
'"' => """.into(),
|
||||
'\'' => "'".into(),
|
||||
_ => c.to_string(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn layout(title: &str, nav: &str, main: &str) -> String {
|
||||
format!(
|
||||
r##"<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
||||
<title>{title} · marqdo view</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com"/>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,600;9..144,700&family=IBM+Plex+Mono:wght@400;500&family=Sora:wght@400;600&display=swap" rel="stylesheet"/>
|
||||
<style>
|
||||
:root {{
|
||||
--bg0: #0f1c1a;
|
||||
--bg1: #162824;
|
||||
--panel: #1c322d;
|
||||
--ink: #e7f2ee;
|
||||
--muted: #9bb5ac;
|
||||
--accent: #3ecf8e;
|
||||
--accent-dim: #2a9b6a;
|
||||
--call: #5ec8ff;
|
||||
--branch: #f0b429;
|
||||
--loop: #ff7a59;
|
||||
--ret: #c4a7ff;
|
||||
--err: #ff6b6b;
|
||||
--line: rgba(255,255,255,0.08);
|
||||
}}
|
||||
* {{ box-sizing: border-box; }}
|
||||
body {{
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
font-family: "Sora", system-ui, sans-serif;
|
||||
color: var(--ink);
|
||||
background:
|
||||
radial-gradient(1200px 600px at 10% -10%, #1a3d34 0%, transparent 55%),
|
||||
radial-gradient(900px 500px at 100% 0%, #243528 0%, transparent 50%),
|
||||
linear-gradient(165deg, var(--bg0), var(--bg1));
|
||||
}}
|
||||
a {{ color: var(--accent); text-decoration: none; }}
|
||||
a:hover {{ text-decoration: underline; }}
|
||||
.shell {{
|
||||
display: grid;
|
||||
grid-template-columns: minmax(220px, 280px) 1fr;
|
||||
min-height: 100vh;
|
||||
}}
|
||||
@media (max-width: 800px) {{
|
||||
.shell {{ grid-template-columns: 1fr; }}
|
||||
}}
|
||||
.nav {{
|
||||
border-right: 1px solid var(--line);
|
||||
background: rgba(0,0,0,0.22);
|
||||
padding: 1.25rem 1rem 2rem;
|
||||
overflow: auto;
|
||||
}}
|
||||
.brand {{
|
||||
font-family: "Fraunces", Georgia, serif;
|
||||
font-size: 1.45rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.02em;
|
||||
margin: 0 0 0.25rem;
|
||||
}}
|
||||
.brand span {{ color: var(--accent); }}
|
||||
.tagline {{
|
||||
color: var(--muted);
|
||||
font-size: 0.8rem;
|
||||
margin: 0 0 1.25rem;
|
||||
}}
|
||||
.nav h2 {{
|
||||
font-size: 0.7rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.12em;
|
||||
color: var(--muted);
|
||||
margin: 1rem 0 0.4rem;
|
||||
}}
|
||||
.nav ul {{ list-style: none; padding: 0; margin: 0; }}
|
||||
.nav li {{ margin: 0.15rem 0; }}
|
||||
.nav a.file {{
|
||||
display: block;
|
||||
padding: 0.35rem 0.5rem;
|
||||
border-radius: 6px;
|
||||
color: var(--ink);
|
||||
font-family: "IBM Plex Mono", monospace;
|
||||
font-size: 0.78rem;
|
||||
}}
|
||||
.nav a.file:hover, .nav a.file.active {{
|
||||
background: rgba(62, 207, 142, 0.12);
|
||||
text-decoration: none;
|
||||
}}
|
||||
.folder {{ color: var(--muted); font-size: 0.75rem; margin-top: 0.75rem; }}
|
||||
main.panel {{
|
||||
padding: 1.5rem 1.75rem 3rem;
|
||||
overflow: auto;
|
||||
}}
|
||||
h1.page {{
|
||||
font-family: "Fraunces", Georgia, serif;
|
||||
font-size: 1.75rem;
|
||||
margin: 0 0 0.5rem;
|
||||
}}
|
||||
.meta {{ color: var(--muted); font-size: 0.85rem; margin-bottom: 1.5rem; }}
|
||||
section.block {{
|
||||
margin: 1.25rem 0 1.75rem;
|
||||
}}
|
||||
section.block > h2 {{
|
||||
font-size: 0.75rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.1em;
|
||||
color: var(--muted);
|
||||
margin: 0 0 0.65rem;
|
||||
border-bottom: 1px solid var(--line);
|
||||
padding-bottom: 0.35rem;
|
||||
}}
|
||||
.card {{
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 10px;
|
||||
padding: 0.85rem 1rem;
|
||||
margin: 0.55rem 0;
|
||||
}}
|
||||
.fun-card {{ border-left: 3px solid var(--accent); }}
|
||||
.call-card {{ border-left: 3px solid var(--call); }}
|
||||
.branch-card {{ border-left: 3px solid var(--branch); }}
|
||||
.loop-card {{ border-left: 3px solid var(--loop); }}
|
||||
.ret-card {{ border-left: 3px solid var(--ret); }}
|
||||
.badge {{
|
||||
display: inline-block;
|
||||
font-family: "IBM Plex Mono", monospace;
|
||||
font-size: 0.7rem;
|
||||
padding: 0.1rem 0.4rem;
|
||||
border-radius: 4px;
|
||||
background: rgba(255,255,255,0.06);
|
||||
margin-right: 0.35rem;
|
||||
}}
|
||||
.params {{ margin: 0.35rem 0; }}
|
||||
.chip {{
|
||||
display: inline-block;
|
||||
font-family: "IBM Plex Mono", monospace;
|
||||
font-size: 0.75rem;
|
||||
padding: 0.15rem 0.45rem;
|
||||
margin: 0.15rem;
|
||||
border-radius: 999px;
|
||||
background: rgba(62, 207, 142, 0.15);
|
||||
color: var(--accent);
|
||||
}}
|
||||
.nested {{ margin-left: 0.85rem; padding-left: 0.75rem; border-left: 1px dashed var(--line); }}
|
||||
.arm {{
|
||||
margin: 0.4rem 0;
|
||||
padding: 0.5rem 0.65rem;
|
||||
background: rgba(0,0,0,0.2);
|
||||
border-radius: 8px;
|
||||
}}
|
||||
.out {{
|
||||
font-family: "IBM Plex Mono", monospace;
|
||||
font-size: 0.85rem;
|
||||
white-space: pre-wrap;
|
||||
background: #0a1210;
|
||||
border-radius: 8px;
|
||||
padding: 0.85rem 1rem;
|
||||
border: 1px solid var(--line);
|
||||
}}
|
||||
.out.ok {{ box-shadow: inset 3px 0 0 var(--accent-dim); }}
|
||||
.out.fail {{ box-shadow: inset 3px 0 0 var(--err); color: #ffc9c9; }}
|
||||
.source {{
|
||||
font-family: "IBM Plex Mono", monospace;
|
||||
font-size: 0.78rem;
|
||||
white-space: pre-wrap;
|
||||
background: #0a1210;
|
||||
border-radius: 8px;
|
||||
padding: 0.85rem 1rem;
|
||||
border: 1px solid var(--line);
|
||||
line-height: 1.45;
|
||||
}}
|
||||
.err {{ color: var(--err); }}
|
||||
.comment-card {{
|
||||
border-left: 3px solid var(--muted);
|
||||
background: rgba(255,255,255,0.03);
|
||||
}}
|
||||
.comment-text {{
|
||||
color: var(--muted);
|
||||
font-size: 0.9rem;
|
||||
line-height: 1.45;
|
||||
}}
|
||||
code.expr {{
|
||||
font-family: "IBM Plex Mono", monospace;
|
||||
font-size: 0.82rem;
|
||||
color: var(--ink);
|
||||
}}
|
||||
.welcome {{ max-width: 36rem; }}
|
||||
.welcome p {{ color: var(--muted); line-height: 1.55; }}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="shell">
|
||||
<aside class="nav">
|
||||
<p class="brand">marq<span>do</span> view</p>
|
||||
<p class="tagline">Markup structure · live output</p>
|
||||
{nav}
|
||||
</aside>
|
||||
<main class="panel">
|
||||
{main}
|
||||
</main>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
"##,
|
||||
title = escape(title),
|
||||
nav = nav,
|
||||
main = main
|
||||
)
|
||||
}
|
||||
|
||||
pub fn nav_html(files: &[std::path::PathBuf], active: Option<&str>) -> String {
|
||||
let mut out = String::from("<h2>Files</h2><ul>");
|
||||
let mut last_folder = String::new();
|
||||
for f in files {
|
||||
let rel = f.to_string_lossy().replace('\\', "/");
|
||||
let folder = Path::new(&rel)
|
||||
.parent()
|
||||
.map(|p| p.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
if folder != last_folder {
|
||||
if !folder.is_empty() {
|
||||
out.push_str(&format!(
|
||||
"</ul><div class=\"folder\">{}</div><ul>",
|
||||
escape(&folder)
|
||||
));
|
||||
}
|
||||
last_folder = folder;
|
||||
}
|
||||
let name = Path::new(&rel)
|
||||
.file_name()
|
||||
.and_then(|s| s.to_str())
|
||||
.unwrap_or(&rel);
|
||||
let active_cls = if active == Some(rel.as_str()) {
|
||||
" active"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let href = format!("/file?path={}", urlencoding_encode(&rel));
|
||||
out.push_str(&format!(
|
||||
"<li><a class=\"file{active_cls}\" href=\"{href}\">{}</a></li>",
|
||||
escape(name)
|
||||
));
|
||||
}
|
||||
out.push_str("</ul>");
|
||||
out
|
||||
}
|
||||
|
||||
fn urlencoding_encode(s: &str) -> String {
|
||||
let mut out = String::new();
|
||||
for b in s.bytes() {
|
||||
match b {
|
||||
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => {
|
||||
out.push(b as char);
|
||||
}
|
||||
_ => out.push_str(&format!("%{b:02X}")),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn page_index(files: &[std::path::PathBuf], only: Option<&Path>) -> String {
|
||||
let nav = nav_html(files, None);
|
||||
let main = if let Some(p) = only {
|
||||
let rel = p.to_string_lossy().replace('\\', "/");
|
||||
format!(
|
||||
"<div class=\"welcome\"><h1 class=\"page\">Single file</h1><p class=\"meta\">Open <a href=\"/file?path={}\">{}</a></p></div>",
|
||||
urlencoding_encode(&rel),
|
||||
escape(&rel)
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"<div class=\"welcome\"><h1 class=\"page\">Browse</h1><p>Select a <code>.mq.md</code> file in the index. Structure is rendered from the AST; output comes from the same pipeline as <code>marqdo run</code>.</p><p class=\"meta\">{} file(s)</p></div>",
|
||||
files.len()
|
||||
)
|
||||
};
|
||||
layout("index", &nav, &main)
|
||||
}
|
||||
|
||||
pub fn page_file(files: &[std::path::PathBuf], rel: &str, vm: &FileViewModel) -> String {
|
||||
let nav = nav_html(files, Some(rel));
|
||||
let status = if vm.ok { "ok" } else { "fail" };
|
||||
let out_text = if vm.ok {
|
||||
if vm.stdout.is_empty() {
|
||||
"(no stdout)".to_string()
|
||||
} else {
|
||||
escape(&vm.stdout)
|
||||
}
|
||||
} else {
|
||||
escape(&vm.stderr)
|
||||
};
|
||||
let main = format!(
|
||||
r#"
|
||||
<h1 class="page">{title}</h1>
|
||||
<p class="meta">{rel}</p>
|
||||
<section class="block">
|
||||
<h2>Structure</h2>
|
||||
{structure}
|
||||
</section>
|
||||
<section class="block">
|
||||
<h2>Execution</h2>
|
||||
<div class="out {status}">{out}</div>
|
||||
</section>
|
||||
<section class="block">
|
||||
<h2>Source</h2>
|
||||
<pre class="source">{source}</pre>
|
||||
</section>
|
||||
"#,
|
||||
title = escape(
|
||||
Path::new(rel)
|
||||
.file_stem()
|
||||
.and_then(|s| s.to_str())
|
||||
.unwrap_or(rel)
|
||||
),
|
||||
rel = escape(rel),
|
||||
structure = vm.structure_html,
|
||||
status = status,
|
||||
out = out_text,
|
||||
source = escape(&vm.source),
|
||||
);
|
||||
layout(rel, &nav, &main)
|
||||
}
|
||||
+307
@@ -0,0 +1,307 @@
|
||||
//! `marqdo view` — local HTML browser for `.mq.md` structure + output.
|
||||
|
||||
mod html;
|
||||
mod render;
|
||||
|
||||
use std::fs;
|
||||
use std::net::SocketAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use anyhow::{bail, Context, Result};
|
||||
use tiny_http::{Header, Method, Request, Response, Server, StatusCode};
|
||||
|
||||
use crate::view::html::{escape, page_file, page_index};
|
||||
use crate::view::render::{render_module_structure, FileViewModel};
|
||||
use crate::{run_file_capture, RunOptions};
|
||||
|
||||
pub struct ViewOptions {
|
||||
pub path: PathBuf,
|
||||
pub host: String,
|
||||
pub port: u16,
|
||||
pub open_browser: bool,
|
||||
}
|
||||
|
||||
struct ViewRoot {
|
||||
/// Directory that paths are resolved against.
|
||||
root: PathBuf,
|
||||
/// If Some, only this relative file is in scope (single-file mode).
|
||||
only_file: Option<PathBuf>,
|
||||
files: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
/// Block serving until Ctrl+C (process kill).
|
||||
pub fn serve(opts: ViewOptions) -> Result<()> {
|
||||
let root_info = build_root(&opts.path)?;
|
||||
let addr: SocketAddr = format!("{}:{}", opts.host, opts.port)
|
||||
.parse()
|
||||
.context("invalid host/port")?;
|
||||
let server = Server::http(addr).map_err(|e| anyhow::anyhow!("listen {addr}: {e}"))?;
|
||||
let url = format!("http://{}:{}/", opts.host, opts.port);
|
||||
eprintln!("marqdo view: {url}");
|
||||
eprintln!("root: {}", root_info.root.display());
|
||||
eprintln!("{} .mq.md file(s). Ctrl+C to stop.", root_info.files.len());
|
||||
|
||||
if opts.open_browser {
|
||||
let _ = open_url(&url);
|
||||
}
|
||||
|
||||
for request in server.incoming_requests() {
|
||||
if let Err(err) = handle(&root_info, request) {
|
||||
eprintln!("view request error: {err:#}");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn build_root(path: &Path) -> Result<ViewRoot> {
|
||||
let path = if path.exists() {
|
||||
path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
|
||||
} else {
|
||||
bail!("path not found: {}", path.display());
|
||||
};
|
||||
|
||||
if path.is_file() {
|
||||
if !is_mq_md(&path) {
|
||||
bail!("not a .mq.md file: {}", path.display());
|
||||
}
|
||||
let root = path
|
||||
.parent()
|
||||
.map(|p| p.to_path_buf())
|
||||
.unwrap_or_else(|| PathBuf::from("."));
|
||||
let rel = PathBuf::from(path.file_name().unwrap());
|
||||
return Ok(ViewRoot {
|
||||
root,
|
||||
only_file: Some(rel.clone()),
|
||||
files: vec![rel],
|
||||
});
|
||||
}
|
||||
|
||||
if !path.is_dir() {
|
||||
bail!("not a file or directory: {}", path.display());
|
||||
}
|
||||
|
||||
let mut files = Vec::new();
|
||||
collect_mq_md(&path, &path, &mut files)?;
|
||||
files.sort();
|
||||
Ok(ViewRoot {
|
||||
root: path,
|
||||
only_file: None,
|
||||
files,
|
||||
})
|
||||
}
|
||||
|
||||
fn collect_mq_md(root: &Path, dir: &Path, out: &mut Vec<PathBuf>) -> Result<()> {
|
||||
for entry in fs::read_dir(dir).with_context(|| format!("read_dir {}", dir.display()))? {
|
||||
let entry = entry?;
|
||||
let p = entry.path();
|
||||
if p.is_dir() {
|
||||
collect_mq_md(root, &p, out)?;
|
||||
} else if is_mq_md(&p) {
|
||||
let rel = p.strip_prefix(root).unwrap_or(&p).to_path_buf();
|
||||
out.push(rel);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_mq_md(path: &Path) -> bool {
|
||||
path.file_name()
|
||||
.and_then(|s| s.to_str())
|
||||
.map(|s| s.ends_with(".mq.md"))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn handle(root: &ViewRoot, request: Request) -> Result<()> {
|
||||
let url = request.url().to_string();
|
||||
let method = request.method().clone();
|
||||
if method != Method::Get {
|
||||
let resp = Response::from_string("method not allowed").with_status_code(StatusCode(405));
|
||||
let _ = request.respond(resp);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let (path_part, query) = split_url(&url);
|
||||
match path_part {
|
||||
"/" | "/index.html" => {
|
||||
let body = page_index(&root.files, root.only_file.as_deref());
|
||||
respond_html(request, body)
|
||||
}
|
||||
"/file" => {
|
||||
let rel = query_param(query, "path").unwrap_or_default();
|
||||
let resolved = resolve_rel(root, &rel)?;
|
||||
let vm = build_file_view(&resolved, &rel)?;
|
||||
let body = page_file(&root.files, &rel, &vm);
|
||||
respond_html(request, body)
|
||||
}
|
||||
"/api/tree" => {
|
||||
let json = files_json(&root.files);
|
||||
respond_json(request, json)
|
||||
}
|
||||
_ => {
|
||||
let resp = Response::from_string("not found").with_status_code(StatusCode(404));
|
||||
let _ = request.respond(resp);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn build_file_view(abs: &Path, rel: &str) -> Result<FileViewModel> {
|
||||
let source = fs::read_to_string(abs).with_context(|| format!("read {}", abs.display()))?;
|
||||
let structure = match crate::load::load_module(abs) {
|
||||
Ok(module) => render_module_structure(&module, &source),
|
||||
Err(e) => format!(
|
||||
"<div class=\"err\">parse/load error: {}</div>",
|
||||
escape(&format!("{e:#}"))
|
||||
),
|
||||
};
|
||||
let (stdout, stderr, ok) = match run_file_capture(abs, &RunOptions::default()) {
|
||||
Ok(cap) => (cap.stdout, String::new(), true),
|
||||
Err(e) => (String::new(), format!("{e:#}"), false),
|
||||
};
|
||||
Ok(FileViewModel {
|
||||
rel_path: rel.to_string(),
|
||||
source,
|
||||
structure_html: structure,
|
||||
stdout,
|
||||
stderr,
|
||||
ok,
|
||||
})
|
||||
}
|
||||
|
||||
fn resolve_rel(root: &ViewRoot, rel: &str) -> Result<PathBuf> {
|
||||
if rel.is_empty() {
|
||||
bail!("missing path");
|
||||
}
|
||||
let rel_path = PathBuf::from(rel.replace('\\', "/"));
|
||||
if rel_path
|
||||
.components()
|
||||
.any(|c| matches!(c, std::path::Component::ParentDir))
|
||||
{
|
||||
bail!("path escapes root");
|
||||
}
|
||||
if let Some(only) = &root.only_file {
|
||||
if &rel_path != only {
|
||||
bail!("file not in view scope");
|
||||
}
|
||||
} else if !root.files.iter().any(|f| f == &rel_path) {
|
||||
// also allow forward-slash normalized compare
|
||||
let norm = rel_path.to_string_lossy().replace('\\', "/");
|
||||
if !root
|
||||
.files
|
||||
.iter()
|
||||
.any(|f| f.to_string_lossy().replace('\\', "/") == norm)
|
||||
{
|
||||
bail!("unknown file: {rel}");
|
||||
}
|
||||
}
|
||||
let abs = root.root.join(&rel_path);
|
||||
let canon = abs.canonicalize().unwrap_or(abs.clone());
|
||||
let root_canon = root.root.canonicalize().unwrap_or_else(|_| root.root.clone());
|
||||
if !canon.starts_with(&root_canon) {
|
||||
bail!("path escapes root");
|
||||
}
|
||||
if !is_mq_md(&canon) {
|
||||
bail!("not a .mq.md file");
|
||||
}
|
||||
Ok(canon)
|
||||
}
|
||||
|
||||
fn split_url(url: &str) -> (&str, &str) {
|
||||
match url.split_once('?') {
|
||||
Some((p, q)) => (p, q),
|
||||
None => (url, ""),
|
||||
}
|
||||
}
|
||||
|
||||
fn query_param<'a>(query: &'a str, key: &str) -> Option<String> {
|
||||
for pair in query.split('&') {
|
||||
let mut kv = pair.splitn(2, '=');
|
||||
let k = kv.next()?;
|
||||
let v = kv.next().unwrap_or("");
|
||||
if k == key {
|
||||
return Some(urlencoding_decode(v));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn urlencoding_decode(s: &str) -> String {
|
||||
// Minimal decode for %XX and +
|
||||
let mut out = String::new();
|
||||
let bytes = s.as_bytes();
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
match bytes[i] {
|
||||
b'+' => {
|
||||
out.push(' ');
|
||||
i += 1;
|
||||
}
|
||||
b'%' if i + 2 < bytes.len() => {
|
||||
let hex = &s[i + 1..i + 3];
|
||||
if let Ok(v) = u8::from_str_radix(hex, 16) {
|
||||
out.push(v as char);
|
||||
i += 3;
|
||||
} else {
|
||||
out.push('%');
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
c => {
|
||||
out.push(c as char);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn files_json(files: &[PathBuf]) -> String {
|
||||
let list: Vec<String> = files
|
||||
.iter()
|
||||
.map(|f| format!("\"{}\"", escape_json(&f.to_string_lossy().replace('\\', "/"))))
|
||||
.collect();
|
||||
format!("{{\"files\":[{}]}}", list.join(","))
|
||||
}
|
||||
|
||||
fn escape_json(s: &str) -> String {
|
||||
s.replace('\\', "\\\\").replace('"', "\\\"")
|
||||
}
|
||||
|
||||
fn respond_html(request: Request, body: String) -> Result<()> {
|
||||
let header = Header::from_bytes(&b"Content-Type"[..], &b"text/html; charset=utf-8"[..])
|
||||
.map_err(|_| anyhow::anyhow!("header"))?;
|
||||
let resp = Response::from_string(body).with_header(header);
|
||||
request.respond(resp).context("respond")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn respond_json(request: Request, body: String) -> Result<()> {
|
||||
let header = Header::from_bytes(&b"Content-Type"[..], &b"application/json; charset=utf-8"[..])
|
||||
.map_err(|_| anyhow::anyhow!("header"))?;
|
||||
let resp = Response::from_string(body).with_header(header);
|
||||
request.respond(resp).context("respond")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn open_url(url: &str) -> Result<()> {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
Command::new("cmd")
|
||||
.args(["/C", "start", "", url])
|
||||
.spawn()
|
||||
.context("open browser")?;
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
Command::new("open").arg(url).spawn().context("open browser")?;
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
Command::new("xdg-open")
|
||||
.arg(url)
|
||||
.spawn()
|
||||
.context("open browser")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,424 @@
|
||||
//! Render Marqdo AST as HTML fragments for `view`.
|
||||
//!
|
||||
//! Comments are not in the AST; they are interleaved from classified source lines.
|
||||
//! Expressions are shown in surface syntax, never Rust `Debug`.
|
||||
|
||||
use crate::ast::{
|
||||
Arg, BinaryOp, CallExpr, Expr, Function, InterpPart, Literal, Module, Stmt, UnaryOp,
|
||||
};
|
||||
use crate::lex::{classify_source, ClassifiedLine, LineKind};
|
||||
use crate::view::html::escape;
|
||||
|
||||
pub struct FileViewModel {
|
||||
#[allow(dead_code)]
|
||||
pub rel_path: String,
|
||||
pub source: String,
|
||||
pub structure_html: String,
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
pub ok: bool,
|
||||
}
|
||||
|
||||
pub fn render_module_structure(module: &Module, source: &str) -> String {
|
||||
let lines = classify_source(source);
|
||||
let mut out = String::new();
|
||||
|
||||
if !module.imports.is_empty() {
|
||||
out.push_str("<div class=\"card\"><span class=\"badge\">import</span>");
|
||||
for imp in &module.imports {
|
||||
out.push_str(&format!("<span class=\"chip\">{}</span>", escape(imp)));
|
||||
}
|
||||
out.push_str("</div>");
|
||||
}
|
||||
|
||||
let body_start = skip_frontmatter_end(&lines).unwrap_or(1);
|
||||
let mut cursor = body_start;
|
||||
|
||||
if module.functions.is_empty() {
|
||||
out.push_str(&emit_comments(&lines, cursor, u32::MAX));
|
||||
if out.is_empty() {
|
||||
out.push_str("<p class=\"meta\">(empty module)</p>");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Leading comments before first function
|
||||
let first = module.functions[0].span.line;
|
||||
out.push_str(&emit_comments(&lines, cursor, first));
|
||||
cursor = first;
|
||||
|
||||
for (i, fun) in module.functions.iter().enumerate() {
|
||||
if i > 0 {
|
||||
out.push_str(&emit_comments(&lines, cursor, fun.span.line));
|
||||
}
|
||||
let (html, next) = render_fun(fun, &lines, 0);
|
||||
out.push_str(&html);
|
||||
cursor = next;
|
||||
}
|
||||
|
||||
// Trailing comments after last function tree
|
||||
out.push_str(&emit_comments(&lines, cursor, u32::MAX));
|
||||
out
|
||||
}
|
||||
|
||||
/// Line after closing frontmatter `---`, or 1 if none.
|
||||
fn skip_frontmatter_end(lines: &[ClassifiedLine]) -> Option<u32> {
|
||||
let first_code = lines.iter().find(|l| l.kind == LineKind::Code)?;
|
||||
if first_code.text.trim() != "---" {
|
||||
return Some(1);
|
||||
}
|
||||
for l in lines.iter().skip_while(|l| l.line_no <= first_code.line_no) {
|
||||
if l.kind == LineKind::Code && l.text.trim() == "---" {
|
||||
return Some(l.line_no + 1);
|
||||
}
|
||||
}
|
||||
Some(1)
|
||||
}
|
||||
|
||||
fn emit_comments(lines: &[ClassifiedLine], from_line: u32, before_line: u32) -> String {
|
||||
let mut s = String::new();
|
||||
for l in lines {
|
||||
if l.line_no < from_line {
|
||||
continue;
|
||||
}
|
||||
if l.line_no >= before_line {
|
||||
break;
|
||||
}
|
||||
if l.kind == LineKind::Comment {
|
||||
let text = l.text.trim();
|
||||
if text.is_empty() {
|
||||
continue;
|
||||
}
|
||||
s.push_str(&format!(
|
||||
"<div class=\"card comment-card\"><span class=\"badge\">comment</span><span class=\"comment-text\">{}</span></div>",
|
||||
escape(text)
|
||||
));
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn render_fun(fun: &Function, lines: &[ClassifiedLine], depth: usize) -> (String, u32) {
|
||||
let mut s = String::new();
|
||||
let nest = if depth > 0 { " nested" } else { "" };
|
||||
s.push_str(&format!("<div class=\"card fun-card{nest}\">"));
|
||||
s.push_str(&format!(
|
||||
"<div><span class=\"badge\">fn · h{}</span><strong>{}</strong></div>",
|
||||
fun.level,
|
||||
escape(&fun.name)
|
||||
));
|
||||
if !fun.params.is_empty() {
|
||||
s.push_str("<div class=\"params\">");
|
||||
for p in &fun.params {
|
||||
s.push_str(&format!("<span class=\"chip\">{}</span>", escape(p)));
|
||||
}
|
||||
s.push_str("</div>");
|
||||
}
|
||||
|
||||
let mut cursor = fun.span.line + 1;
|
||||
|
||||
// Comments / gap before first body stmt or child
|
||||
let first_body = fun.body.first().map(stmt_start);
|
||||
let first_child = fun.children.first().map(|c| c.span.line);
|
||||
let first_content = match (first_body, first_child) {
|
||||
(Some(a), Some(b)) => Some(a.min(b)),
|
||||
(Some(a), None) => Some(a),
|
||||
(None, Some(b)) => Some(b),
|
||||
(None, None) => None,
|
||||
};
|
||||
if let Some(fc) = first_content {
|
||||
s.push_str(&emit_comments(lines, cursor, fc));
|
||||
cursor = fc;
|
||||
}
|
||||
|
||||
// Interleave body stmts and nested functions by source line
|
||||
let mut bi = 0usize;
|
||||
let mut ci = 0usize;
|
||||
while bi < fun.body.len() || ci < fun.children.len() {
|
||||
let stmt_line = fun.body.get(bi).map(stmt_start);
|
||||
let child_line = fun.children.get(ci).map(|c| c.span.line);
|
||||
let take_stmt = match (stmt_line, child_line) {
|
||||
(Some(sl), Some(cl)) => sl <= cl,
|
||||
(Some(_), None) => true,
|
||||
(None, Some(_)) => false,
|
||||
(None, None) => break,
|
||||
};
|
||||
if take_stmt {
|
||||
let stmt = &fun.body[bi];
|
||||
let start = stmt_start(stmt);
|
||||
s.push_str(&emit_comments(lines, cursor, start));
|
||||
let (html, end) = render_stmt(stmt, lines);
|
||||
s.push_str(&html);
|
||||
cursor = end;
|
||||
bi += 1;
|
||||
} else {
|
||||
let child = &fun.children[ci];
|
||||
s.push_str(&emit_comments(lines, cursor, child.span.line));
|
||||
let (html, end) = render_fun(child, lines, depth + 1);
|
||||
s.push_str(&format!("<div class=\"nested\">{html}</div>"));
|
||||
cursor = end;
|
||||
ci += 1;
|
||||
}
|
||||
}
|
||||
|
||||
s.push_str("</div>");
|
||||
(s, cursor)
|
||||
}
|
||||
|
||||
fn stmt_start(stmt: &Stmt) -> u32 {
|
||||
match stmt {
|
||||
Stmt::Assign { span, .. }
|
||||
| Stmt::Return { span, .. }
|
||||
| Stmt::Call { span, .. }
|
||||
| Stmt::Branch { span, .. }
|
||||
| Stmt::While { span, .. }
|
||||
| Stmt::ForEach { span, .. } => span.line,
|
||||
}
|
||||
}
|
||||
|
||||
fn stmt_end_line(stmt: &Stmt) -> u32 {
|
||||
match stmt {
|
||||
Stmt::Assign { span, .. } | Stmt::Return { span, .. } | Stmt::Call { span, .. } => {
|
||||
span.line + 1
|
||||
}
|
||||
Stmt::Branch { arms, span, .. } => {
|
||||
let mut end = span.line + 1;
|
||||
for arm in arms {
|
||||
for st in &arm.body {
|
||||
end = end.max(stmt_end_line(st));
|
||||
}
|
||||
}
|
||||
end
|
||||
}
|
||||
Stmt::While { body, span, .. } | Stmt::ForEach { body, span, .. } => {
|
||||
let mut end = span.line + 1;
|
||||
for st in body {
|
||||
end = end.max(stmt_end_line(st));
|
||||
}
|
||||
end
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn render_stmt(stmt: &Stmt, lines: &[ClassifiedLine]) -> (String, u32) {
|
||||
let end = stmt_end_line(stmt);
|
||||
let html = match stmt {
|
||||
Stmt::Assign { name, value, .. } => format!(
|
||||
"<div class=\"card\"><span class=\"badge\">bind</span><code class=\"expr\">`{}` = {}</code></div>",
|
||||
escape(name),
|
||||
escape(&expr_display(value))
|
||||
),
|
||||
Stmt::Return { value, .. } => format!(
|
||||
"<div class=\"card ret-card\"><span class=\"badge\">return</span><code class=\"expr\">{}</code></div>",
|
||||
escape(&expr_display(value))
|
||||
),
|
||||
Stmt::Call { call, .. } => format!(
|
||||
"<div class=\"card call-card\"><span class=\"badge\">call</span><code class=\"expr\">{}</code></div>",
|
||||
escape(&call_display(call))
|
||||
),
|
||||
Stmt::Branch { arms, .. } => {
|
||||
let mut inner =
|
||||
String::from("<div class=\"card branch-card\"><span class=\"badge\">branch</span>");
|
||||
let mut arm_cursor = stmt_start(stmt) + 1;
|
||||
for arm in arms {
|
||||
let label = match &arm.condition {
|
||||
None => "else".to_string(),
|
||||
Some(c) => expr_display(c),
|
||||
};
|
||||
// comments before first stmt in arm (approx: between arms hard; use body starts)
|
||||
let arm_first = arm.body.first().map(stmt_start);
|
||||
inner.push_str(&format!(
|
||||
"<div class=\"arm\"><span class=\"badge\">arm</span><code class=\"expr\">{}</code>",
|
||||
escape(&label)
|
||||
));
|
||||
if let Some(af) = arm_first {
|
||||
inner.push_str(&emit_comments(lines, arm_cursor, af));
|
||||
arm_cursor = af;
|
||||
}
|
||||
inner.push_str("<div class=\"nested\">");
|
||||
for st in &arm.body {
|
||||
let start = stmt_start(st);
|
||||
inner.push_str(&emit_comments(lines, arm_cursor, start));
|
||||
let (h, e) = render_stmt(st, lines);
|
||||
inner.push_str(&h);
|
||||
arm_cursor = e;
|
||||
}
|
||||
inner.push_str("</div></div>");
|
||||
}
|
||||
inner.push_str("</div>");
|
||||
inner
|
||||
}
|
||||
Stmt::While {
|
||||
condition, body, ..
|
||||
} => {
|
||||
let mut inner = format!(
|
||||
"<div class=\"card loop-card\"><span class=\"badge\">while</span><code class=\"expr\">{}</code><div class=\"nested\">",
|
||||
escape(&expr_display(condition))
|
||||
);
|
||||
let mut cursor = stmt_start(stmt) + 1;
|
||||
for st in body {
|
||||
let start = stmt_start(st);
|
||||
inner.push_str(&emit_comments(lines, cursor, start));
|
||||
let (h, e) = render_stmt(st, lines);
|
||||
inner.push_str(&h);
|
||||
cursor = e;
|
||||
}
|
||||
inner.push_str("</div></div>");
|
||||
inner
|
||||
}
|
||||
Stmt::ForEach {
|
||||
item,
|
||||
collection,
|
||||
body,
|
||||
..
|
||||
} => {
|
||||
let mut inner = format!(
|
||||
"<div class=\"card loop-card\"><span class=\"badge\">foreach</span><code class=\"expr\">[{}]({})</code><div class=\"nested\">",
|
||||
escape(item),
|
||||
escape(collection)
|
||||
);
|
||||
let mut cursor = stmt_start(stmt) + 1;
|
||||
for st in body {
|
||||
let start = stmt_start(st);
|
||||
inner.push_str(&emit_comments(lines, cursor, start));
|
||||
let (h, e) = render_stmt(st, lines);
|
||||
inner.push_str(&h);
|
||||
cursor = e;
|
||||
}
|
||||
inner.push_str("</div></div>");
|
||||
inner
|
||||
}
|
||||
};
|
||||
(html, end)
|
||||
}
|
||||
|
||||
fn call_display(call: &CallExpr) -> String {
|
||||
let mut s = format!("> {}", call.callee);
|
||||
for a in &call.args {
|
||||
match a {
|
||||
Arg::Positional(e) => {
|
||||
s.push(' ');
|
||||
s.push_str(&expr_display(e));
|
||||
}
|
||||
Arg::Named { name, value } => {
|
||||
s.push(' ');
|
||||
s.push_str(name);
|
||||
s.push('=');
|
||||
s.push_str(&expr_display(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Surface-syntax preview for view (not Debug).
|
||||
pub fn expr_display(expr: &Expr) -> String {
|
||||
expr_prec(expr, 0)
|
||||
}
|
||||
|
||||
fn expr_prec(expr: &Expr, parent_prec: u8) -> String {
|
||||
match expr {
|
||||
Expr::Literal(lit) => lit_display(lit),
|
||||
Expr::Var(name) => format!("`{name}`"),
|
||||
Expr::Interp(parts) => {
|
||||
let mut s = String::new();
|
||||
for p in parts {
|
||||
match p {
|
||||
InterpPart::Lit(t) => s.push_str(t),
|
||||
InterpPart::Var(n) => {
|
||||
s.push('`');
|
||||
s.push_str(n);
|
||||
s.push('`');
|
||||
}
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
Expr::Unary { op, expr } => {
|
||||
let prec = 5;
|
||||
let inner = match op {
|
||||
UnaryOp::Not => format!("not {}", expr_prec(expr, prec)),
|
||||
UnaryOp::Neg => format!("-{}", expr_prec(expr, prec)),
|
||||
};
|
||||
wrap(inner, prec, parent_prec)
|
||||
}
|
||||
Expr::Binary { op, left, right } => {
|
||||
let (sym, prec) = bin_sym_prec(*op);
|
||||
let inner = format!(
|
||||
"{} {} {}",
|
||||
expr_prec(left, prec),
|
||||
sym,
|
||||
expr_prec(right, prec + 1) // left-assoc bias
|
||||
);
|
||||
wrap(inner, prec, parent_prec)
|
||||
}
|
||||
Expr::Call(call) => call_display(call),
|
||||
Expr::List(items) => {
|
||||
let parts: Vec<String> = items.iter().map(|e| expr_prec(e, 0)).collect();
|
||||
format!("[{}]", parts.join(", "))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn wrap(inner: String, prec: u8, parent_prec: u8) -> String {
|
||||
if prec < parent_prec {
|
||||
format!("({inner})")
|
||||
} else {
|
||||
inner
|
||||
}
|
||||
}
|
||||
|
||||
fn bin_sym_prec(op: BinaryOp) -> (&'static str, u8) {
|
||||
match op {
|
||||
BinaryOp::Or => ("or", 1),
|
||||
BinaryOp::And => ("and", 2),
|
||||
BinaryOp::Eq => ("==", 3),
|
||||
BinaryOp::Ne => ("!=", 3),
|
||||
BinaryOp::Lt => ("<", 3),
|
||||
BinaryOp::Le => ("<=", 3),
|
||||
BinaryOp::Gt => (">", 3),
|
||||
BinaryOp::Ge => (">=", 3),
|
||||
BinaryOp::Add => ("+", 4),
|
||||
BinaryOp::Sub => ("-", 4),
|
||||
BinaryOp::Mul => ("*", 5),
|
||||
BinaryOp::Div => ("/", 5),
|
||||
}
|
||||
}
|
||||
|
||||
fn lit_display(lit: &Literal) -> String {
|
||||
match lit {
|
||||
Literal::None => "None".into(),
|
||||
Literal::Bool(true) => "True".into(),
|
||||
Literal::Bool(false) => "False".into(),
|
||||
Literal::Int(n) => n.to_string(),
|
||||
Literal::Text(t) => t.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::ast::{BinaryOp, Expr, Literal};
|
||||
|
||||
#[test]
|
||||
fn expr_gt_is_surface() {
|
||||
let e = Expr::Binary {
|
||||
op: BinaryOp::Gt,
|
||||
left: Box::new(Expr::Var("x".into())),
|
||||
right: Box::new(Expr::Literal(Literal::Int(0))),
|
||||
};
|
||||
assert_eq!(expr_display(&e), "`x` > 0");
|
||||
assert!(!expr_display(&e).contains("Binary"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structure_keeps_comments_and_surface_expr() {
|
||||
let src = include_str!("../../examples/structure/nested-call.mq.md");
|
||||
let module = crate::parse::parse_source(src).unwrap();
|
||||
let html = render_module_structure(&module, src);
|
||||
assert!(html.contains("comment-card"));
|
||||
assert!(html.contains("print"));
|
||||
assert!(!html.contains("Binary {"));
|
||||
assert!(!html.contains("Literal(Int"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user