Skip to content

Commit

Permalink
feat: Add format! macro
Browse files Browse the repository at this point in the history
  • Loading branch information
bch29 committed Dec 14, 2020
1 parent 1a5489c commit d89ae4e
Show file tree
Hide file tree
Showing 2 changed files with 200 additions and 0 deletions.
197 changes: 197 additions & 0 deletions src/format_macro.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
//! Implementation of the `format!` macro
use gluon_codegen::Trace;

use crate::{
base::{
ast::{self, AstClone, SpannedExpr},
pos,
symbol::{Symbol, Symbols},
types::TypeCache,
},
parser::parse_expr,
vm::macros::{self, Macro, MacroExpander, MacroFuture},
};

/**
* Format macro with expressions embedded in the format string
*
* ```
* let x = 1
* format! "x is {x}, x + 1 is {x+1}"
* ```
*/
#[derive(Trace)]
#[gluon(crate_name = "vm")]
pub struct Format;

impl Macro for Format {
fn expand<'r, 'a: 'r, 'b: 'r, 'c: 'r, 'ast: 'r>(
&self,
_env: &'b mut MacroExpander<'a>,
symbols: &'c mut Symbols,
arena: &'b mut ast::OwnedArena<'ast, Symbol>,
args: &'b mut [SpannedExpr<'ast, Symbol>],
) -> MacroFuture<'r, 'ast> {
Box::pin(async move {
let arg = match args {
[arg] => (arg),
_ => {
return Err(macros::Error::message(format!(
"format! expects 1 argument"
)))
}
};

let expr: &ast::Expr<Symbol> = &arg.value;

let format_string = match expr {
ast::Expr::Literal(ast::Literal::String(text)) => text,
_ => {
return Err(macros::Error::message(format!(
"format! expects a string argument"
)))
}
};

let span = arg.span;

let sp = |e: ast::Expr<'ast, Symbol>| pos::spanned(span, e);

let show_ident = ast::TypedIdent::new(symbols.simple_symbol("show"));
let show_func = arena.alloc(sp(ast::Expr::Ident(show_ident)));

let append_ident = ast::TypedIdent::new(symbols.simple_symbol("(++)"));
let append_func = arena.alloc(sp(ast::Expr::Ident(append_ident)));

let show_expr = |e: ast::SpannedExpr<'ast, Symbol>| {
let func = show_func.ast_clone(arena.borrow());

sp(ast::Expr::App {
func,
implicit_args: arena.alloc_extend(vec![]),
args: arena.alloc_extend(vec![e]),
})
};

let app_exprs = |lhs, rhs| {
let func = append_func.ast_clone(arena.borrow());

sp(ast::Expr::App {
func,
implicit_args: arena.alloc_extend(vec![]),
args: arena.alloc_extend(vec![lhs, rhs]),
})
};

let literal_expr = |val: String| sp(ast::Expr::Literal(ast::Literal::String(val)));

let type_cache = TypeCache::new();

let mut remaining = format_string.as_str();

let mut result_expr = None;

while let Some(find_result) = find_expr(remaining)? {
remaining = find_result.remaining;

let sub_expr =
parse_expr(arena.borrow(), symbols, &type_cache, find_result.expr)
.map_err(|err| {
macros::Error::message(format!(
"format! could not parse subexpression: {}",
err
))
})?;

let part_expr = app_exprs(
literal_expr(find_result.prefix.to_owned()),
show_expr(sub_expr),
);

result_expr = match result_expr.take() {
None => Some(part_expr),
Some(prev_expr) => Some(app_exprs(prev_expr, part_expr)),
};
}

let result_expr = match result_expr.take() {
None => literal_expr(remaining.to_owned()),
Some(result_expr) => {
if remaining.is_empty() {
result_expr
} else {
app_exprs(result_expr, literal_expr(remaining.to_owned()))
}
}
};

Ok(result_expr.into())
})
}
}

const OPEN_BRACE: &'static str = "{";
const CLOSE_BRACE: &'static str = "}";

struct FindExprResult<'a> {
prefix: &'a str,
expr: &'a str,
remaining: &'a str,
}

fn find_expr<'a>(format_str: &'a str) -> Result<Option<FindExprResult<'a>>, macros::Error> {
let prefix_end_ix = match format_str.find(OPEN_BRACE) {
None => return Ok(None),
Some(ix) => ix,
};

let prefix = &format_str[..prefix_end_ix];
let expr_start = OPEN_BRACE.len() + prefix_end_ix;

let mut brace_depth = 1;

let mut expr_end = expr_start;
let mut brace_end = expr_start;

while brace_depth != 0 {
let next_open = format_str[brace_end..].find(OPEN_BRACE);
let next_close = format_str[brace_end..].find(CLOSE_BRACE);

let (brace_ix, is_close) = match (next_open, next_close) {
(None, None) => break,
(None, Some(ix)) => (ix, true),
(Some(ix), None) => (ix, false),
(Some(open_ix), Some(close_ix)) => {
if open_ix < close_ix {
(open_ix, false)
} else {
(close_ix, true)
}
}
};

expr_end = brace_end + brace_ix;
brace_end = if is_close {
brace_depth -= 1;
expr_end + OPEN_BRACE.len()
} else {
brace_depth += 1;
expr_end + CLOSE_BRACE.len()
};
}

if brace_depth != 0 {
return Err(macros::Error::message(format!("mismatched braces")));
}

let expr = &format_str[expr_start..expr_end];

let remaining = &format_str[brace_end..];

Ok(Some(FindExprResult {
prefix,
expr,
remaining,
}))
}

3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ pub mod compiler_pipeline;
#[macro_use]
pub mod import;
pub mod lift_io;
pub mod format_macro;
#[doc(hidden)]
pub mod query;
pub mod std_lib;
Expand Down Expand Up @@ -958,6 +959,8 @@ impl VmBuilder {
}

macros.insert(String::from("lift_io"), lift_io::LiftIo);

macros.insert(String::from("format"), format_macro::Format);
}

add_extern_module_with_deps(
Expand Down

0 comments on commit d89ae4e

Please sign in to comment.