Add English builtins, pipeline dump flags, and M1 line classification.

Document a minimal Python-inspired keyword set (print/input, True/False/None), require visible --dump-* stages, and ship working --dump-lines for .mq.md sources.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-08-04 11:28:15 +08:00
1 parent 63d7866d06
commit 69b626e919
24 files changed
+481 -86

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
//! Pipeline dump helpers (see doc/design/pipeline-debug.md).
pub use crate::lex::format_lines_dump;
+123 -4
View File
@@ -1,11 +1,130 @@
//! Line classification and tokenization (no Flex).
//! Implementation arrives in M1.
//! Line classification (M1) — no Flex.
//!
//! Unmarked lines are comments; lines whose first non-whitespace character
//! opens a Marqdo/Markdown marker are code.
#![allow(dead_code)]
use std::fmt;
/// Kind of a source line after skipping leading indentation for the test.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LineKind {
Blank,
Comment,
Code,
Blank,
}
impl fmt::Display for LineKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
LineKind::Blank => write!(f, "Blank"),
LineKind::Comment => write!(f, "Comment"),
LineKind::Code => write!(f, "Code"),
}
}
}
/// One classified source line (1-based line number).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClassifiedLine {
pub line_no: u32,
pub kind: LineKind,
pub text: String,
}
/// Characters that start a code line when they appear as the first non-ws char.
fn is_code_starter(c: char) -> bool {
matches!(
c,
'#' | '*' | '>' | '+' | '-' | '`' | '|' | '~'
) || c.is_ascii_digit()
}
/// Classify a single logical line (no trailing newline required).
pub fn classify_line(text: &str) -> LineKind {
let trimmed = text.trim_end_matches(['\r', '\n']);
if trimmed.chars().all(|c| c.is_whitespace()) {
return LineKind::Blank;
}
let first = trimmed.chars().find(|c| !c.is_whitespace());
match first {
None => LineKind::Blank,
Some(c) if is_code_starter(c) => LineKind::Code,
Some(_) => LineKind::Comment,
}
}
/// Classify every line of a source file.
pub fn classify_source(source: &str) -> Vec<ClassifiedLine> {
let source = source.strip_prefix('\u{feff}').unwrap_or(source);
let lines: Vec<&str> = if source.is_empty() {
Vec::new()
} else {
source.lines().collect()
};
lines
.into_iter()
.enumerate()
.map(|(i, text)| ClassifiedLine {
line_no: (i + 1) as u32,
kind: classify_line(text),
text: text.to_string(),
})
.collect()
}
/// Human-readable dump for `--dump-lines`.
pub fn format_lines_dump(path: &str, lines: &[ClassifiedLine]) -> String {
let mut out = String::new();
out.push_str(&format!("=== marqdo: lines ({path}) ===\n"));
for line in lines {
let preview = if line.text.len() > 80 {
format!("{}…", &line.text.chars().take(80).collect::<String>())
} else {
line.text.clone()
};
match line.kind {
LineKind::Blank => {
out.push_str(&format!("{:4} {:7}\n", line.line_no, line.kind));
}
_ => {
out.push_str(&format!(
"{:4} {:7} | {}\n",
line.line_no, line.kind, preview
));
}
}
}
out.push_str("=== marqdo: end lines ===\n");
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn blank_and_comment_and_code() {
assert_eq!(classify_line(""), LineKind::Blank);
assert_eq!(classify_line(" "), LineKind::Blank);
assert_eq!(classify_line("hello world"), LineKind::Comment);
assert_eq!(classify_line(" 中文说明"), LineKind::Comment);
assert_eq!(classify_line("> print text=hi"), LineKind::Code);
assert_eq!(classify_line("# main"), LineKind::Code);
assert_eq!(classify_line("*`x` = 1*"), LineKind::Code);
assert_eq!(classify_line("**ret**"), LineKind::Code);
assert_eq!(classify_line("+ `x` > 0"), LineKind::Code);
assert_eq!(classify_line("- item"), LineKind::Code);
assert_eq!(classify_line("1. arm"), LineKind::Code);
assert_eq!(classify_line("| a |"), LineKind::Code);
assert_eq!(classify_line("`x` = 1"), LineKind::Code);
}
#[test]
fn classify_hello_fixture() {
let src = include_str!("../../examples/hello.mq.md");
let lines = classify_source(src);
assert!(lines.iter().any(|l| l.kind == LineKind::Code && l.text.contains("print")));
assert!(lines.iter().any(|l| l.kind == LineKind::Comment));
}
}
+62 -12
View File
@@ -1,8 +1,8 @@
//! Marqdo reference interpreter (Phase I scaffolding).
//! Marqdo reference interpreter (Phase I).
//!
//! Pipeline (see `doc/roadmap/interpreter.md`):
//! load → line classify / lex → parse → sema → tree-walk eval.
//! Pipeline: load → line classify / lex → parse → sema → tree-walk eval.
pub mod debug;
pub mod diagnostics;
pub mod lex;
pub mod parse;
@@ -11,20 +11,70 @@ use std::path::Path;
use anyhow::{bail, Context, Result};
/// Run a `.mq.md` program. Phase I: not yet implemented beyond scaffolding.
pub fn run_file(path: &Path) -> Result<i32> {
use crate::lex::{classify_source, format_lines_dump};
/// Options for a single `run` / dump invocation.
#[derive(Debug, Clone, Default)]
pub struct RunOptions {
pub dump_lines: bool,
pub dump_tokens: bool,
pub dump_ast: bool,
pub dump_sema: bool,
pub trace_eval: bool,
}
impl RunOptions {
pub fn dump_all() -> Self {
Self {
dump_lines: true,
dump_tokens: true,
dump_ast: true,
dump_sema: true,
trace_eval: true,
}
}
pub fn any_dump(&self) -> bool {
self.dump_lines || self.dump_tokens || self.dump_ast || self.dump_sema || self.trace_eval
}
}
/// Run a `.mq.md` program (M1: line classify + dumps; eval still TODO).
pub fn run_file(path: &Path, opts: &RunOptions) -> Result<i32> {
let source = std::fs::read_to_string(path)
.with_context(|| format!("failed to read {}", path.display()))?;
let path_label = path.display().to_string();
let lines = classify_source(&source);
if opts.dump_lines {
print!("{}", format_lines_dump(&path_label, &lines));
}
if opts.dump_tokens {
println!("=== marqdo: tokens ({path_label}) ===");
println!("(tokens not implemented yet — M1+)");
println!("=== marqdo: end tokens ===");
}
if opts.dump_ast {
println!("=== marqdo: ast ({path_label}) ===");
println!("(ast not implemented yet — M2)");
println!("=== marqdo: end ast ===");
}
if opts.dump_sema {
println!("=== marqdo: sema ({path_label}) ===");
println!("(sema not implemented yet — M3+)");
println!("=== marqdo: end sema ===");
}
if opts.trace_eval {
println!("=== marqdo: trace-eval ({path_label}) ===");
println!("(eval not implemented yet — M2+)");
println!("=== marqdo: end trace-eval ===");
}
if source.is_empty() {
bail!("{} is empty", path.display());
}
// Placeholder: real lex/parse/eval lands in subsequent milestones.
eprintln!(
"marqdo: loaded {} ({} bytes); interpreter not implemented yet (M0 scaffold)",
path.display(),
source.len()
);
bail!("evaluation not implemented — see doc/roadmap/interpreter.md (M1+)")
// Until eval exists: dumps are useful; run still fails loudly.
bail!("evaluation not implemented — see doc/roadmap/interpreter.md (M2+)")
}
+55 -2
View File
@@ -4,6 +4,8 @@ use std::process::ExitCode;
use anyhow::Result;
use clap::{Parser, Subcommand};
use marqdo::RunOptions;
#[derive(Parser, Debug)]
#[command(name = "marqdo", version, about = "Marqdo interpreter — run .mq.md programs")]
struct Cli {
@@ -18,6 +20,30 @@ enum Commands {
/// Path to a `.mq.md` file
#[arg(value_name = "FILE")]
file: Option<PathBuf>,
/// Dump line classification
#[arg(long)]
dump_lines: bool,
/// Dump tokens (placeholder until lexer fills in)
#[arg(long)]
dump_tokens: bool,
/// Dump AST (placeholder until parser exists)
#[arg(long)]
dump_ast: bool,
/// Dump semantic info (placeholder)
#[arg(long)]
dump_sema: bool,
/// Trace evaluation (placeholder)
#[arg(long)]
trace_eval: bool,
/// Enable all dumps
#[arg(long)]
dump_all: bool,
},
}
@@ -34,9 +60,36 @@ fn main() -> ExitCode {
fn try_main() -> Result<i32> {
let cli = Cli::parse();
match cli.command {
Commands::Run { file } => {
Commands::Run {
file,
dump_lines,
dump_tokens,
dump_ast,
dump_sema,
trace_eval,
dump_all,
} => {
let path = file.unwrap_or_else(|| PathBuf::from("index.mq.md"));
marqdo::run_file(&path)?;
let mut opts = if dump_all {
RunOptions::dump_all()
} else {
RunOptions {
dump_lines,
dump_tokens,
dump_ast,
dump_sema,
trace_eval,
}
};
// dump_all already set; individual flags merge if not dump_all
if !dump_all {
opts.dump_lines = dump_lines;
opts.dump_tokens = dump_tokens;
opts.dump_ast = dump_ast;
opts.dump_sema = dump_sema;
opts.trace_eval = trace_eval;
}
marqdo::run_file(&path, &opts)?;
Ok(0)
}
}