Skip to content

Commit 5545515

Browse files
committed
feat: Add format! macro
1 parent 1a5489c commit 5545515

File tree

2 files changed

+261
-0
lines changed

2 files changed

+261
-0
lines changed

src/format_macro.rs

Lines changed: 258 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,258 @@
1+
//! Implementation of the `format!` macro
2+
use gluon_codegen::Trace;
3+
4+
use crate::{
5+
base::{
6+
ast::{self, AstClone, SpannedExpr},
7+
pos,
8+
symbol::{Symbol, Symbols},
9+
types::TypeCache,
10+
},
11+
parser::parse_expr,
12+
vm::macros::{self, Macro, MacroExpander, MacroFuture},
13+
};
14+
15+
/**
16+
* Format macro with expressions embedded in the format string
17+
*
18+
* ```ignore
19+
* let x = 1
20+
* format! "x is {x}, x + 1 is {x+1}"
21+
* ```
22+
*/
23+
#[derive(Trace)]
24+
#[gluon(crate_name = "vm")]
25+
pub struct Format;
26+
27+
fn expr_from_path<'ast>(
28+
arena: &mut ast::OwnedArena<'ast, Symbol>,
29+
symbols: &mut Symbols,
30+
span: pos::Span<pos::ByteIndex>,
31+
path_head: &str,
32+
path_tail: &[&str],
33+
) -> SpannedExpr<'ast, Symbol> {
34+
let mut head = pos::spanned(
35+
span,
36+
ast::Expr::Ident(ast::TypedIdent::new(symbols.simple_symbol(path_head))),
37+
);
38+
39+
for &item in path_tail {
40+
head = pos::spanned(
41+
span,
42+
ast::Expr::Projection(
43+
arena.alloc(head),
44+
symbols.simple_symbol(item),
45+
Default::default(),
46+
),
47+
);
48+
}
49+
50+
head
51+
}
52+
53+
async fn run_import<'a, 'ast>(
54+
importer: &dyn Macro,
55+
env: &mut MacroExpander<'a>,
56+
symbols: &mut Symbols,
57+
arena: &mut ast::OwnedArena<'ast, Symbol>,
58+
span: pos::Span<pos::ByteIndex>,
59+
path: &[&str],
60+
) -> Result<SpannedExpr<'ast, Symbol>, macros::Error> {
61+
let (path_head, path_tail) = match path {
62+
[head, tail @ ..] => (head, tail),
63+
_ => return Err(macros::Error::message("run_import for empty path")),
64+
};
65+
66+
let path = expr_from_path(arena, symbols, span, path_head, path_tail);
67+
let args = arena.alloc_extend(vec![path]);
68+
69+
match importer.expand(env, symbols, arena, args).await? {
70+
macros::LazyMacroResult::Done(res) => Ok(res),
71+
macros::LazyMacroResult::Lazy(f) => f().await,
72+
}
73+
}
74+
75+
impl Macro for Format {
76+
fn expand<'r, 'a: 'r, 'b: 'r, 'c: 'r, 'ast: 'r>(
77+
&self,
78+
env: &'b mut MacroExpander<'a>,
79+
symbols: &'c mut Symbols,
80+
arena: &'b mut ast::OwnedArena<'ast, Symbol>,
81+
args: &'b mut [SpannedExpr<'ast, Symbol>],
82+
) -> MacroFuture<'r, 'ast> {
83+
Box::pin(async move {
84+
let arg = match args {
85+
[arg] => (arg),
86+
_ => {
87+
return Err(macros::Error::message(format!(
88+
"format! expects 1 argument"
89+
)))
90+
}
91+
};
92+
93+
let span = arg.span;
94+
let sp = |e: ast::Expr<'ast, Symbol>| pos::spanned(span, e);
95+
96+
let import = env
97+
.vm
98+
.get_macros()
99+
.get("import")
100+
.ok_or_else(|| macros::Error::message(format!("Cannot find import macro")))?;
101+
102+
let show_module =
103+
run_import(&*import, env, symbols, arena, span, &["std", "show"]).await?;
104+
let show_module = arena.alloc(show_module);
105+
let show_func = arena.alloc(sp(ast::Expr::Projection(
106+
show_module,
107+
symbols.simple_symbol("show"),
108+
Default::default(),
109+
)));
110+
111+
let semigroup_module =
112+
run_import(&*import, env, symbols, arena, span, &["std", "semigroup"]).await?;
113+
let semigroup_module = arena.alloc(semigroup_module);
114+
let append_func = arena.alloc(sp(ast::Expr::Projection(
115+
semigroup_module,
116+
symbols.simple_symbol("append"),
117+
Default::default(),
118+
)));
119+
120+
let format_string = match &arg.value {
121+
ast::Expr::Literal(ast::Literal::String(text)) => text,
122+
_ => {
123+
return Err(macros::Error::message(format!(
124+
"format! expects a string argument"
125+
)))
126+
}
127+
};
128+
129+
let show_expr = |e: ast::SpannedExpr<'ast, Symbol>| {
130+
let func = show_func.ast_clone(arena.borrow());
131+
132+
sp(ast::Expr::App {
133+
func,
134+
implicit_args: arena.alloc_extend(vec![]),
135+
args: arena.alloc_extend(vec![e]),
136+
})
137+
};
138+
139+
let app_exprs = |lhs, rhs| {
140+
let func = append_func.ast_clone(arena.borrow());
141+
142+
sp(ast::Expr::App {
143+
func,
144+
implicit_args: arena.alloc_extend(vec![]),
145+
args: arena.alloc_extend(vec![lhs, rhs]),
146+
})
147+
};
148+
149+
let literal_expr = |val: String| sp(ast::Expr::Literal(ast::Literal::String(val)));
150+
151+
let type_cache = TypeCache::new();
152+
153+
let mut remaining = format_string.as_str();
154+
155+
let mut result_expr = None;
156+
157+
while let Some(find_result) = find_expr(remaining)? {
158+
remaining = find_result.remaining;
159+
160+
let sub_expr = parse_expr(arena.borrow(), symbols, &type_cache, find_result.expr)
161+
.map_err(|err| {
162+
macros::Error::message(format!(
163+
"format! could not parse subexpression: {}",
164+
err
165+
))
166+
})?;
167+
168+
let part_expr = app_exprs(
169+
literal_expr(find_result.prefix.to_owned()),
170+
show_expr(sub_expr),
171+
);
172+
173+
result_expr = match result_expr.take() {
174+
None => Some(part_expr),
175+
Some(prev_expr) => Some(app_exprs(prev_expr, part_expr)),
176+
};
177+
}
178+
179+
let result_expr = match result_expr.take() {
180+
None => literal_expr(remaining.to_owned()),
181+
Some(result_expr) => {
182+
if remaining.is_empty() {
183+
result_expr
184+
} else {
185+
app_exprs(result_expr, literal_expr(remaining.to_owned()))
186+
}
187+
}
188+
};
189+
190+
Ok(result_expr.into())
191+
})
192+
}
193+
}
194+
195+
const OPEN_BRACE: &'static str = "{";
196+
const CLOSE_BRACE: &'static str = "}";
197+
198+
struct FindExprResult<'a> {
199+
prefix: &'a str,
200+
expr: &'a str,
201+
remaining: &'a str,
202+
}
203+
204+
fn find_expr<'a>(format_str: &'a str) -> Result<Option<FindExprResult<'a>>, macros::Error> {
205+
let prefix_end_ix = match format_str.find(OPEN_BRACE) {
206+
None => return Ok(None),
207+
Some(ix) => ix,
208+
};
209+
210+
let prefix = &format_str[..prefix_end_ix];
211+
let expr_start = OPEN_BRACE.len() + prefix_end_ix;
212+
213+
let mut brace_depth = 1;
214+
215+
let mut expr_end = expr_start;
216+
let mut brace_end = expr_start;
217+
218+
while brace_depth != 0 {
219+
let next_open = format_str[brace_end..].find(OPEN_BRACE);
220+
let next_close = format_str[brace_end..].find(CLOSE_BRACE);
221+
222+
let (brace_ix, is_close) = match (next_open, next_close) {
223+
(None, None) => break,
224+
(None, Some(ix)) => (ix, true),
225+
(Some(ix), None) => (ix, false),
226+
(Some(open_ix), Some(close_ix)) => {
227+
if open_ix < close_ix {
228+
(open_ix, false)
229+
} else {
230+
(close_ix, true)
231+
}
232+
}
233+
};
234+
235+
expr_end = brace_end + brace_ix;
236+
brace_end = if is_close {
237+
brace_depth -= 1;
238+
expr_end + OPEN_BRACE.len()
239+
} else {
240+
brace_depth += 1;
241+
expr_end + CLOSE_BRACE.len()
242+
};
243+
}
244+
245+
if brace_depth != 0 {
246+
return Err(macros::Error::message(format!("mismatched braces")));
247+
}
248+
249+
let expr = &format_str[expr_start..expr_end];
250+
251+
let remaining = &format_str[brace_end..];
252+
253+
Ok(Some(FindExprResult {
254+
prefix,
255+
expr,
256+
remaining,
257+
}))
258+
}

src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ pub mod compiler_pipeline;
4949
#[macro_use]
5050
pub mod import;
5151
pub mod lift_io;
52+
pub mod format_macro;
5253
#[doc(hidden)]
5354
pub mod query;
5455
pub mod std_lib;
@@ -958,6 +959,8 @@ impl VmBuilder {
958959
}
959960

960961
macros.insert(String::from("lift_io"), lift_io::LiftIo);
962+
963+
macros.insert(String::from("format"), format_macro::Format);
961964
}
962965

963966
add_extern_module_with_deps(

0 commit comments

Comments
 (0)