Skip to content

Commit 728e9d9

Browse files
committed
feat: Add format! macro
1 parent fcd3a29 commit 728e9d9

File tree

2 files changed

+279
-0
lines changed

2 files changed

+279
-0
lines changed

src/format_macro.rs

Lines changed: 276 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,276 @@
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, Error, Macro, MacroExpander, MacroFuture, MacroResult},
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+
) -> MacroResult<'ast> {
61+
let (path_head, path_tail) = match path {
62+
[head, tail @ ..] => (head, tail),
63+
_ => return Err(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+
_ => return Err(Error::message(format!("format! expects 1 argument"))),
87+
};
88+
89+
let span = arg.span;
90+
let sp = |e: ast::Expr<'ast, Symbol>| pos::spanned(span, e);
91+
92+
let import = env
93+
.vm
94+
.get_macros()
95+
.get("import")
96+
.ok_or_else(|| Error::message(format!("format! cannot find import macro")))?;
97+
98+
let show_module =
99+
run_import(&*import, env, symbols, arena, span, &["std", "show"]).await?;
100+
let show_module = arena.alloc(show_module);
101+
let show_func = arena.alloc(sp(ast::Expr::Projection(
102+
show_module,
103+
symbols.simple_symbol("show"),
104+
Default::default(),
105+
)));
106+
107+
let semigroup_module =
108+
run_import(&*import, env, symbols, arena, span, &["std", "semigroup"]).await?;
109+
let semigroup_module = arena.alloc(semigroup_module);
110+
let append_func = arena.alloc(sp(ast::Expr::Projection(
111+
semigroup_module,
112+
symbols.simple_symbol("append"),
113+
Default::default(),
114+
)));
115+
116+
let format_string = match &arg.value {
117+
ast::Expr::Literal(ast::Literal::String(text)) => text,
118+
_ => return Err(Error::message(format!("format! expects a string argument"))),
119+
};
120+
121+
let show_expr = |e: ast::SpannedExpr<'ast, Symbol>| {
122+
let func = show_func.ast_clone(arena.borrow());
123+
124+
sp(ast::Expr::App {
125+
func,
126+
implicit_args: arena.alloc_extend(vec![]),
127+
args: arena.alloc_extend(vec![e]),
128+
})
129+
};
130+
131+
let app_exprs = |lhs, rhs| {
132+
let func = append_func.ast_clone(arena.borrow());
133+
134+
sp(ast::Expr::App {
135+
func,
136+
implicit_args: arena.alloc_extend(vec![]),
137+
args: arena.alloc_extend(vec![lhs, rhs]),
138+
})
139+
};
140+
141+
let literal_expr = |val: String| sp(ast::Expr::Literal(ast::Literal::String(val)));
142+
143+
let type_cache = TypeCache::new();
144+
145+
let mut remaining = format_string.as_str();
146+
147+
let mut result_expr = None;
148+
149+
while let Some(find_result) = find_expr(remaining)? {
150+
remaining = find_result.remaining;
151+
152+
let sub_expr = {
153+
let value = parse_expr(arena.borrow(), symbols, &type_cache, find_result.expr)
154+
.map_err(|err| {
155+
Error::message(format!(
156+
"format! could not parse subexpression: {}",
157+
err
158+
))
159+
})?
160+
.value;
161+
162+
pos::spanned(
163+
span.subspan(
164+
pos::ByteOffset(find_result.expr_start as i64),
165+
pos::ByteOffset(find_result.expr_end as i64),
166+
),
167+
value,
168+
)
169+
};
170+
171+
let part_expr = app_exprs(
172+
literal_expr(find_result.prefix.to_owned()),
173+
show_expr(sub_expr),
174+
);
175+
176+
result_expr = match result_expr.take() {
177+
None => Some(part_expr),
178+
Some(prev_expr) => Some(app_exprs(prev_expr, part_expr)),
179+
};
180+
}
181+
182+
let result_expr = match result_expr.take() {
183+
None => literal_expr(remaining.to_owned()),
184+
Some(result_expr) => {
185+
if remaining.is_empty() {
186+
result_expr
187+
} else {
188+
app_exprs(result_expr, literal_expr(remaining.to_owned()))
189+
}
190+
}
191+
};
192+
193+
Ok(result_expr.into())
194+
})
195+
}
196+
}
197+
198+
const OPEN_BRACE: &'static str = "{";
199+
const CLOSE_BRACE: &'static str = "}";
200+
201+
struct FindExprResult<'a> {
202+
prefix: &'a str,
203+
expr: &'a str,
204+
remaining: &'a str,
205+
expr_start: usize,
206+
expr_end: usize,
207+
}
208+
209+
fn find_expr<'a>(format_str: &'a str) -> Result<Option<FindExprResult<'a>>, Error> {
210+
let prefix_end_ix = match format_str.find(OPEN_BRACE) {
211+
None => return Ok(None),
212+
Some(ix) => ix,
213+
};
214+
215+
match format_str.find(CLOSE_BRACE) {
216+
Some(ix) if ix < prefix_end_ix => {
217+
return Err(Error::message(format!(
218+
"Mismatched braces in format! string"
219+
)))
220+
}
221+
_ => (),
222+
}
223+
224+
let prefix = &format_str[..prefix_end_ix];
225+
let expr_start = OPEN_BRACE.len() + prefix_end_ix;
226+
227+
let mut brace_depth = 1;
228+
229+
let mut expr_end = expr_start;
230+
let mut brace_end = expr_start;
231+
232+
while brace_depth != 0 {
233+
let next_open = format_str[brace_end..].find(OPEN_BRACE);
234+
let next_close = format_str[brace_end..].find(CLOSE_BRACE);
235+
236+
let (brace_ix, is_close) = match (next_open, next_close) {
237+
(None, None) => break,
238+
(None, Some(ix)) => (ix, true),
239+
(Some(ix), None) => (ix, false),
240+
(Some(open_ix), Some(close_ix)) => {
241+
if open_ix < close_ix {
242+
(open_ix, false)
243+
} else {
244+
(close_ix, true)
245+
}
246+
}
247+
};
248+
249+
expr_end = brace_end + brace_ix;
250+
brace_end = if is_close {
251+
brace_depth -= 1;
252+
expr_end + OPEN_BRACE.len()
253+
} else {
254+
brace_depth += 1;
255+
expr_end + CLOSE_BRACE.len()
256+
};
257+
}
258+
259+
if brace_depth != 0 {
260+
return Err(Error::message(format!(
261+
"Mismatched braces in format! string"
262+
)));
263+
}
264+
265+
let expr = &format_str[expr_start..expr_end];
266+
267+
let remaining = &format_str[brace_end..];
268+
269+
Ok(Some(FindExprResult {
270+
prefix,
271+
expr,
272+
remaining,
273+
expr_start,
274+
expr_end,
275+
}))
276+
}

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)