|
| 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 | + * let foo = "foo" |
| 21 | + * format! "x is {x}, x + 1 is {x+1}, foo is {foo} and {foo:?}" |
| 22 | + * ``` |
| 23 | + * |
| 24 | + * ==> x is 1, x + 1 is 2, foo is foo and "foo" |
| 25 | + */ |
| 26 | +#[derive(Trace)] |
| 27 | +#[gluon(crate_name = "vm")] |
| 28 | +pub struct Format; |
| 29 | + |
| 30 | +fn expr_from_path<'ast>( |
| 31 | + arena: &mut ast::OwnedArena<'ast, Symbol>, |
| 32 | + symbols: &mut Symbols, |
| 33 | + span: pos::Span<pos::ByteIndex>, |
| 34 | + path_head: &str, |
| 35 | + path_tail: &[&str], |
| 36 | +) -> SpannedExpr<'ast, Symbol> { |
| 37 | + let mut head = pos::spanned( |
| 38 | + span, |
| 39 | + ast::Expr::Ident(ast::TypedIdent::new(symbols.simple_symbol(path_head))), |
| 40 | + ); |
| 41 | + |
| 42 | + for &item in path_tail { |
| 43 | + head = pos::spanned( |
| 44 | + span, |
| 45 | + ast::Expr::Projection( |
| 46 | + arena.alloc(head), |
| 47 | + symbols.simple_symbol(item), |
| 48 | + Default::default(), |
| 49 | + ), |
| 50 | + ); |
| 51 | + } |
| 52 | + |
| 53 | + head |
| 54 | +} |
| 55 | + |
| 56 | +async fn run_import<'a, 'ast>( |
| 57 | + importer: &dyn Macro, |
| 58 | + env: &mut MacroExpander<'a>, |
| 59 | + symbols: &mut Symbols, |
| 60 | + arena: &mut ast::OwnedArena<'ast, Symbol>, |
| 61 | + span: pos::Span<pos::ByteIndex>, |
| 62 | + path: &[&str], |
| 63 | +) -> MacroResult<'ast> { |
| 64 | + let (path_head, path_tail) = match path { |
| 65 | + [head, tail @ ..] => (head, tail), |
| 66 | + _ => return Err(Error::message("run_import for empty path")), |
| 67 | + }; |
| 68 | + |
| 69 | + let path = expr_from_path(arena, symbols, span, path_head, path_tail); |
| 70 | + let args = arena.alloc_extend(vec![path]); |
| 71 | + |
| 72 | + match importer.expand(env, symbols, arena, args).await? { |
| 73 | + macros::LazyMacroResult::Done(res) => Ok(res), |
| 74 | + macros::LazyMacroResult::Lazy(f) => f().await, |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +impl Macro for Format { |
| 79 | + fn expand<'r, 'a: 'r, 'b: 'r, 'c: 'r, 'ast: 'r>( |
| 80 | + &self, |
| 81 | + env: &'b mut MacroExpander<'a>, |
| 82 | + symbols: &'c mut Symbols, |
| 83 | + arena: &'b mut ast::OwnedArena<'ast, Symbol>, |
| 84 | + args: &'b mut [SpannedExpr<'ast, Symbol>], |
| 85 | + ) -> MacroFuture<'r, 'ast> { |
| 86 | + Box::pin(async move { |
| 87 | + let arg = match args { |
| 88 | + [arg] => (arg), |
| 89 | + _ => return Err(Error::message(format!("format! expects 1 argument"))), |
| 90 | + }; |
| 91 | + |
| 92 | + let span = arg.span; |
| 93 | + let sp = |e: ast::Expr<'ast, Symbol>| pos::spanned(span, e); |
| 94 | + |
| 95 | + let import = env |
| 96 | + .vm |
| 97 | + .get_macros() |
| 98 | + .get("import") |
| 99 | + .ok_or_else(|| Error::message(format!("format! cannot find import macro")))?; |
| 100 | + |
| 101 | + let show_module = |
| 102 | + run_import(&*import, env, symbols, arena, span, &["std", "show"]).await?; |
| 103 | + let show_module = arena.alloc(show_module); |
| 104 | + let show_func = arena.alloc(sp(ast::Expr::Projection( |
| 105 | + show_module, |
| 106 | + symbols.simple_symbol("show"), |
| 107 | + Default::default(), |
| 108 | + ))); |
| 109 | + |
| 110 | + let display_module = |
| 111 | + run_import(&*import, env, symbols, arena, span, &["std", "display"]).await?; |
| 112 | + let display_module = arena.alloc(display_module); |
| 113 | + let display_func = sp(ast::Expr::Projection( |
| 114 | + display_module, |
| 115 | + symbols.simple_symbol("display"), |
| 116 | + Default::default(), |
| 117 | + )); |
| 118 | + |
| 119 | + let semigroup_module = |
| 120 | + run_import(&*import, env, symbols, arena, span, &["std", "semigroup"]).await?; |
| 121 | + let semigroup_module = arena.alloc(semigroup_module); |
| 122 | + let append_func = sp(ast::Expr::Projection( |
| 123 | + semigroup_module, |
| 124 | + symbols.simple_symbol("append"), |
| 125 | + Default::default(), |
| 126 | + )); |
| 127 | + |
| 128 | + let format_string = match &arg.value { |
| 129 | + ast::Expr::Literal(ast::Literal::String(text)) => text, |
| 130 | + _ => return Err(Error::message(format!("format! expects a string argument"))), |
| 131 | + }; |
| 132 | + |
| 133 | + let app1 = |func: &ast::SpannedExpr<'ast, Symbol>, e: ast::SpannedExpr<'ast, Symbol>| { |
| 134 | + let func = arena.alloc(func.ast_clone(arena.borrow())); |
| 135 | + |
| 136 | + sp(ast::Expr::App { |
| 137 | + func, |
| 138 | + implicit_args: arena.alloc_extend(vec![]), |
| 139 | + args: arena.alloc_extend(vec![e]), |
| 140 | + }) |
| 141 | + }; |
| 142 | + |
| 143 | + let app_exprs = |lhs, rhs| { |
| 144 | + let func = arena.alloc(append_func.ast_clone(arena.borrow())); |
| 145 | + |
| 146 | + sp(ast::Expr::App { |
| 147 | + func, |
| 148 | + implicit_args: arena.alloc_extend(vec![]), |
| 149 | + args: arena.alloc_extend(vec![lhs, rhs]), |
| 150 | + }) |
| 151 | + }; |
| 152 | + |
| 153 | + let literal_expr = |val: String| sp(ast::Expr::Literal(ast::Literal::String(val))); |
| 154 | + |
| 155 | + let type_cache = TypeCache::new(); |
| 156 | + |
| 157 | + let mut remaining = format_string.as_str(); |
| 158 | + |
| 159 | + let mut result_expr = None; |
| 160 | + |
| 161 | + while let Some(find_result) = find_expr(remaining)? { |
| 162 | + remaining = find_result.remaining; |
| 163 | + |
| 164 | + let sub_expr = { |
| 165 | + let value = parse_expr( |
| 166 | + arena.borrow(), |
| 167 | + symbols, |
| 168 | + &type_cache, |
| 169 | + find_result.expr.expr, |
| 170 | + ) |
| 171 | + .map_err(|err| { |
| 172 | + Error::message(format!("format! could not parse subexpression: {}", err)) |
| 173 | + })? |
| 174 | + .value; |
| 175 | + |
| 176 | + pos::spanned( |
| 177 | + span.subspan( |
| 178 | + pos::ByteOffset(find_result.expr_start as i64), |
| 179 | + pos::ByteOffset(find_result.expr_end as i64), |
| 180 | + ), |
| 181 | + value, |
| 182 | + ) |
| 183 | + }; |
| 184 | + |
| 185 | + let formatted_sub_expr = match find_result.expr.modifier { |
| 186 | + FormatModifier::Display => app1(&display_func, sub_expr), |
| 187 | + FormatModifier::Debug => app1(&show_func, sub_expr), |
| 188 | + }; |
| 189 | + |
| 190 | + let part_expr = app_exprs( |
| 191 | + literal_expr(find_result.prefix.to_owned()), |
| 192 | + formatted_sub_expr, |
| 193 | + ); |
| 194 | + |
| 195 | + result_expr = match result_expr.take() { |
| 196 | + None => Some(part_expr), |
| 197 | + Some(prev_expr) => Some(app_exprs(prev_expr, part_expr)), |
| 198 | + }; |
| 199 | + } |
| 200 | + |
| 201 | + let result_expr = match result_expr.take() { |
| 202 | + None => literal_expr(remaining.to_owned()), |
| 203 | + Some(result_expr) => { |
| 204 | + if remaining.is_empty() { |
| 205 | + result_expr |
| 206 | + } else { |
| 207 | + app_exprs(result_expr, literal_expr(remaining.to_owned())) |
| 208 | + } |
| 209 | + } |
| 210 | + }; |
| 211 | + |
| 212 | + Ok(result_expr.into()) |
| 213 | + }) |
| 214 | + } |
| 215 | +} |
| 216 | + |
| 217 | +const OPEN_BRACE: &'static str = "{"; |
| 218 | +const CLOSE_BRACE: &'static str = "}"; |
| 219 | + |
| 220 | +enum FormatModifier { |
| 221 | + Display, |
| 222 | + Debug, |
| 223 | +} |
| 224 | + |
| 225 | +struct FormatExpr<'a> { |
| 226 | + expr: &'a str, |
| 227 | + modifier: FormatModifier, |
| 228 | +} |
| 229 | + |
| 230 | +struct FindExprResult<'a> { |
| 231 | + prefix: &'a str, |
| 232 | + expr: FormatExpr<'a>, |
| 233 | + remaining: &'a str, |
| 234 | + expr_start: usize, |
| 235 | + expr_end: usize, |
| 236 | +} |
| 237 | + |
| 238 | +fn parse_format_expr<'a>(contents: &'a str) -> Result<FormatExpr<'a>, Error> { |
| 239 | + let mut split_iter = contents.split(":"); |
| 240 | + |
| 241 | + match (split_iter.next(), split_iter.next(), split_iter.next()) { |
| 242 | + (Some(expr), Some(fmt), None) => { |
| 243 | + if fmt == "?" { |
| 244 | + Ok(FormatExpr { |
| 245 | + expr, |
| 246 | + modifier: FormatModifier::Debug, |
| 247 | + }) |
| 248 | + } else { |
| 249 | + Err(Error::message(format!( |
| 250 | + "Unrecognized format specifier: {}", |
| 251 | + fmt |
| 252 | + ))) |
| 253 | + } |
| 254 | + } |
| 255 | + (Some(expr), None, None) => Ok(FormatExpr { |
| 256 | + expr, |
| 257 | + modifier: FormatModifier::Display, |
| 258 | + }), |
| 259 | + _ => Err(Error::message(format!( |
| 260 | + "At most one colon allowed in format subexpression", |
| 261 | + ))), |
| 262 | + } |
| 263 | +} |
| 264 | + |
| 265 | +fn find_expr<'a>(format_str: &'a str) -> Result<Option<FindExprResult<'a>>, Error> { |
| 266 | + let open_ix = match format_str.find(OPEN_BRACE) { |
| 267 | + None => return Ok(None), |
| 268 | + Some(ix) => ix, |
| 269 | + }; |
| 270 | + |
| 271 | + let close_ix = match format_str.find(CLOSE_BRACE) { |
| 272 | + Some(ix) if ix < open_ix => { |
| 273 | + return Err(Error::message(format!( |
| 274 | + "Mismatched braces in format! string" |
| 275 | + ))) |
| 276 | + } |
| 277 | + None => |
| 278 | + return Err(Error::message(format!( |
| 279 | + "Mismatched braces in format! string" |
| 280 | + ))), |
| 281 | + Some(ix) => ix, |
| 282 | + }; |
| 283 | + |
| 284 | + let prefix = &format_str[..open_ix]; |
| 285 | + let expr_start = OPEN_BRACE.len() + open_ix; |
| 286 | + let expr_end = close_ix; |
| 287 | + let brace_end = close_ix + CLOSE_BRACE.len(); |
| 288 | + |
| 289 | + let expr = parse_format_expr(&format_str[expr_start..expr_end])?; |
| 290 | + |
| 291 | + let remaining = &format_str[brace_end..]; |
| 292 | + |
| 293 | + Ok(Some(FindExprResult { |
| 294 | + prefix, |
| 295 | + expr, |
| 296 | + remaining, |
| 297 | + expr_start, |
| 298 | + expr_end, |
| 299 | + })) |
| 300 | +} |
0 commit comments