diff options
| author | Graydon Hoare <graydon@mozilla.com> | 2012-02-29 11:46:23 -0800 |
|---|---|---|
| committer | Graydon Hoare <graydon@mozilla.com> | 2012-03-02 18:46:13 -0800 |
| commit | 87c14f1e3d85751bffffda0b1920be5e726172c4 (patch) | |
| tree | 371d86e9a7c65b06df5c8f5e6d499cf4730324fc /src/comp/syntax/ext | |
| parent | 9228947fe15af96593abf4745d91802b56c205e8 (diff) | |
Move src/comp to src/rustc
Diffstat (limited to 'src/comp/syntax/ext')
| -rw-r--r-- | src/comp/syntax/ext/base.rs | 157 | ||||
| -rw-r--r-- | src/comp/syntax/ext/build.rs | 81 | ||||
| -rw-r--r-- | src/comp/syntax/ext/concat_idents.rs | 24 | ||||
| -rw-r--r-- | src/comp/syntax/ext/env.rs | 45 | ||||
| -rw-r--r-- | src/comp/syntax/ext/expand.rs | 102 | ||||
| -rw-r--r-- | src/comp/syntax/ext/fmt.rs | 300 | ||||
| -rw-r--r-- | src/comp/syntax/ext/ident_to_str.rs | 22 | ||||
| -rw-r--r-- | src/comp/syntax/ext/log_syntax.rs | 13 | ||||
| -rw-r--r-- | src/comp/syntax/ext/qquote.rs | 338 | ||||
| -rw-r--r-- | src/comp/syntax/ext/simplext.rs | 779 |
10 files changed, 0 insertions, 1861 deletions
diff --git a/src/comp/syntax/ext/base.rs b/src/comp/syntax/ext/base.rs deleted file mode 100644 index d59591d849a..00000000000 --- a/src/comp/syntax/ext/base.rs +++ /dev/null @@ -1,157 +0,0 @@ -import std::map::hashmap; -import driver::session::session; -import codemap::{span, expn_info, expanded_from}; -import std::map::new_str_hash; - -type syntax_expander_ = - fn@(ext_ctxt, span, ast::mac_arg, ast::mac_body) -> @ast::expr; -type syntax_expander = { - expander: syntax_expander_, - span: option<span>}; -type macro_def = {ident: str, ext: syntax_extension}; -type macro_definer = - fn@(ext_ctxt, span, ast::mac_arg, ast::mac_body) -> macro_def; - -enum syntax_extension { - normal(syntax_expander), - macro_defining(macro_definer), -} - -// A temporary hard-coded map of methods for expanding syntax extension -// AST nodes into full ASTs -fn syntax_expander_table() -> hashmap<str, syntax_extension> { - fn builtin(f: syntax_expander_) -> syntax_extension - {normal({expander: f, span: none})} - let syntax_expanders = new_str_hash::<syntax_extension>(); - syntax_expanders.insert("fmt", builtin(ext::fmt::expand_syntax_ext)); - syntax_expanders.insert("env", builtin(ext::env::expand_syntax_ext)); - syntax_expanders.insert("macro", - macro_defining(ext::simplext::add_new_extension)); - syntax_expanders.insert("concat_idents", - builtin(ext::concat_idents::expand_syntax_ext)); - syntax_expanders.insert("ident_to_str", - builtin(ext::ident_to_str::expand_syntax_ext)); - syntax_expanders.insert("log_syntax", - builtin(ext::log_syntax::expand_syntax_ext)); - syntax_expanders.insert("ast", - builtin(ext::qquote::expand_ast)); - ret syntax_expanders; -} - -iface ext_ctxt { - fn session() -> session; - fn print_backtrace(); - fn backtrace() -> expn_info; - fn bt_push(ei: codemap::expn_info_); - fn bt_pop(); - fn span_fatal(sp: span, msg: str) -> !; - fn span_err(sp: span, msg: str); - fn span_unimpl(sp: span, msg: str) -> !; - fn span_bug(sp: span, msg: str) -> !; - fn bug(msg: str) -> !; - fn next_id() -> ast::node_id; -} - -fn mk_ctxt(sess: session) -> ext_ctxt { - type ctxt_repr = {sess: session, - mutable backtrace: expn_info}; - impl of ext_ctxt for ctxt_repr { - fn session() -> session { self.sess } - fn print_backtrace() { } - fn backtrace() -> expn_info { self.backtrace } - fn bt_push(ei: codemap::expn_info_) { - alt ei { - expanded_from({call_site: cs, callie: callie}) { - self.backtrace = - some(@expanded_from({ - call_site: {lo: cs.lo, hi: cs.hi, - expn_info: self.backtrace}, - callie: callie})); - } - } - } - fn bt_pop() { - alt self.backtrace { - some(@expanded_from({call_site: {expn_info: prev, _}, _})) { - self.backtrace = prev - } - _ { self.bug("tried to pop without a push"); } - } - } - fn span_fatal(sp: span, msg: str) -> ! { - self.print_backtrace(); - self.sess.span_fatal(sp, msg); - } - fn span_err(sp: span, msg: str) { - self.print_backtrace(); - self.sess.span_err(sp, msg); - } - fn span_unimpl(sp: span, msg: str) -> ! { - self.print_backtrace(); - self.sess.span_unimpl(sp, msg); - } - fn span_bug(sp: span, msg: str) -> ! { - self.print_backtrace(); - self.sess.span_bug(sp, msg); - } - fn bug(msg: str) -> ! { self.print_backtrace(); self.sess.bug(msg); } - fn next_id() -> ast::node_id { ret self.sess.next_node_id(); } - } - let imp : ctxt_repr = {sess: sess, mutable backtrace: none}; - ret imp as ext_ctxt -} - -fn expr_to_str(cx: ext_ctxt, expr: @ast::expr, error: str) -> str { - alt expr.node { - ast::expr_lit(l) { - alt l.node { - ast::lit_str(s) { ret s; } - _ { cx.span_fatal(l.span, error); } - } - } - _ { cx.span_fatal(expr.span, error); } - } -} - -fn expr_to_ident(cx: ext_ctxt, expr: @ast::expr, error: str) -> ast::ident { - alt expr.node { - ast::expr_path(p) { - if vec::len(p.node.types) > 0u || vec::len(p.node.idents) != 1u { - cx.span_fatal(expr.span, error); - } else { ret p.node.idents[0]; } - } - _ { cx.span_fatal(expr.span, error); } - } -} - -fn make_new_lit(cx: ext_ctxt, sp: codemap::span, lit: ast::lit_) -> - @ast::expr { - let sp_lit = @{node: lit, span: sp}; - ret @{id: cx.next_id(), node: ast::expr_lit(sp_lit), span: sp}; -} - -fn get_mac_arg(cx: ext_ctxt, sp: span, arg: ast::mac_arg) -> @ast::expr { - alt (arg) { - some(expr) {expr} - none {cx.span_fatal(sp, "missing macro args")} - } -} - -fn get_mac_body(cx: ext_ctxt, sp: span, args: ast::mac_body) - -> ast::mac_body_ -{ - alt (args) { - some(body) {body} - none {cx.span_fatal(sp, "missing macro body")} - } -} - -// -// Local Variables: -// mode: rust -// fill-column: 78; -// indent-tabs-mode: nil -// c-basic-offset: 4 -// buffer-file-coding-system: utf-8-unix -// End: -// diff --git a/src/comp/syntax/ext/build.rs b/src/comp/syntax/ext/build.rs deleted file mode 100644 index 5d615c4305d..00000000000 --- a/src/comp/syntax/ext/build.rs +++ /dev/null @@ -1,81 +0,0 @@ -import codemap::span; -import syntax::ext::base::ext_ctxt; - -// NOTE: Moved from fmt.rs which had this fixme: -// FIXME: Cleanup the naming of these functions - -fn mk_lit(cx: ext_ctxt, sp: span, lit: ast::lit_) -> @ast::expr { - let sp_lit = @{node: lit, span: sp}; - ret @{id: cx.next_id(), node: ast::expr_lit(sp_lit), span: sp}; -} -fn mk_str(cx: ext_ctxt, sp: span, s: str) -> @ast::expr { - let lit = ast::lit_str(s); - ret mk_lit(cx, sp, lit); -} -fn mk_int(cx: ext_ctxt, sp: span, i: int) -> @ast::expr { - let lit = ast::lit_int(i as i64, ast::ty_i); - ret mk_lit(cx, sp, lit); -} -fn mk_uint(cx: ext_ctxt, sp: span, u: uint) -> @ast::expr { - let lit = ast::lit_uint(u as u64, ast::ty_u); - ret mk_lit(cx, sp, lit); -} -fn mk_binary(cx: ext_ctxt, sp: span, op: ast::binop, - lhs: @ast::expr, rhs: @ast::expr) - -> @ast::expr { - let binexpr = ast::expr_binary(op, lhs, rhs); - ret @{id: cx.next_id(), node: binexpr, span: sp}; -} -fn mk_unary(cx: ext_ctxt, sp: span, op: ast::unop, e: @ast::expr) - -> @ast::expr { - let expr = ast::expr_unary(op, e); - ret @{id: cx.next_id(), node: expr, span: sp}; -} -fn mk_path(cx: ext_ctxt, sp: span, idents: [ast::ident]) -> - @ast::expr { - let path = {global: false, idents: idents, types: []}; - let sp_path = @{node: path, span: sp}; - let pathexpr = ast::expr_path(sp_path); - ret @{id: cx.next_id(), node: pathexpr, span: sp}; -} -fn mk_access_(cx: ext_ctxt, sp: span, p: @ast::expr, m: ast::ident) - -> @ast::expr { - let expr = ast::expr_field(p, m, []); - ret @{id: cx.next_id(), node: expr, span: sp}; -} -fn mk_access(cx: ext_ctxt, sp: span, p: [ast::ident], m: ast::ident) - -> @ast::expr { - let pathexpr = mk_path(cx, sp, p); - ret mk_access_(cx, sp, pathexpr, m); -} -fn mk_call_(cx: ext_ctxt, sp: span, fn_expr: @ast::expr, - args: [@ast::expr]) -> @ast::expr { - let callexpr = ast::expr_call(fn_expr, args, false); - ret @{id: cx.next_id(), node: callexpr, span: sp}; -} -fn mk_call(cx: ext_ctxt, sp: span, fn_path: [ast::ident], - args: [@ast::expr]) -> @ast::expr { - let pathexpr = mk_path(cx, sp, fn_path); - ret mk_call_(cx, sp, pathexpr, args); -} -// e = expr, t = type -fn mk_vec_e(cx: ext_ctxt, sp: span, exprs: [@ast::expr]) -> - @ast::expr { - let vecexpr = ast::expr_vec(exprs, ast::m_imm); - ret @{id: cx.next_id(), node: vecexpr, span: sp}; -} -fn mk_rec_e(cx: ext_ctxt, sp: span, - fields: [{ident: ast::ident, ex: @ast::expr}]) -> - @ast::expr { - let astfields: [ast::field] = []; - for field: {ident: ast::ident, ex: @ast::expr} in fields { - let ident = field.ident; - let val = field.ex; - let astfield = - {node: {mutbl: ast::m_imm, ident: ident, expr: val}, span: sp}; - astfields += [astfield]; - } - let recexpr = ast::expr_rec(astfields, option::none::<@ast::expr>); - ret @{id: cx.next_id(), node: recexpr, span: sp}; -} - diff --git a/src/comp/syntax/ext/concat_idents.rs b/src/comp/syntax/ext/concat_idents.rs deleted file mode 100644 index 4b9402f9cd9..00000000000 --- a/src/comp/syntax/ext/concat_idents.rs +++ /dev/null @@ -1,24 +0,0 @@ -import base::*; -import syntax::ast; - -fn expand_syntax_ext(cx: ext_ctxt, sp: codemap::span, arg: ast::mac_arg, - _body: ast::mac_body) -> @ast::expr { - let arg = get_mac_arg(cx,sp,arg); - let args: [@ast::expr] = - alt arg.node { - ast::expr_vec(elts, _) { elts } - _ { - cx.span_fatal(sp, "#concat_idents requires a vector argument .") - } - }; - let res: ast::ident = ""; - for e: @ast::expr in args { - res += expr_to_ident(cx, e, "expected an ident"); - } - - ret @{id: cx.next_id(), - node: ast::expr_path(@{node: {global: false, idents: [res], - types: []}, - span: sp}), - span: sp}; -} diff --git a/src/comp/syntax/ext/env.rs b/src/comp/syntax/ext/env.rs deleted file mode 100644 index cb9453ae062..00000000000 --- a/src/comp/syntax/ext/env.rs +++ /dev/null @@ -1,45 +0,0 @@ - -/* - * The compiler code necessary to support the #env extension. Eventually this - * should all get sucked into either the compiler syntax extension plugin - * interface. - */ -import std::generic_os; -import base::*; -export expand_syntax_ext; - -fn expand_syntax_ext(cx: ext_ctxt, sp: codemap::span, arg: ast::mac_arg, - _body: ast::mac_body) -> @ast::expr { - let arg = get_mac_arg(cx,sp,arg); - let args: [@ast::expr] = - alt arg.node { - ast::expr_vec(elts, _) { elts } - _ { - cx.span_fatal(sp, "#env requires arguments of the form `[...]`.") - } - }; - if vec::len::<@ast::expr>(args) != 1u { - cx.span_fatal(sp, "malformed #env call"); - } - // FIXME: if this was more thorough it would manufacture an - // option<str> rather than just an maybe-empty string. - - let var = expr_to_str(cx, args[0], "#env requires a string"); - alt generic_os::getenv(var) { - option::none { ret make_new_str(cx, sp, ""); } - option::some(s) { ret make_new_str(cx, sp, s); } - } -} - -fn make_new_str(cx: ext_ctxt, sp: codemap::span, s: str) -> @ast::expr { - ret make_new_lit(cx, sp, ast::lit_str(s)); -} -// -// Local Variables: -// mode: rust -// fill-column: 78; -// indent-tabs-mode: nil -// c-basic-offset: 4 -// buffer-file-coding-system: utf-8-unix -// End: -// diff --git a/src/comp/syntax/ext/expand.rs b/src/comp/syntax/ext/expand.rs deleted file mode 100644 index 104f49aebac..00000000000 --- a/src/comp/syntax/ext/expand.rs +++ /dev/null @@ -1,102 +0,0 @@ -import driver::session; - -import std::map::hashmap; - -import syntax::ast::{crate, expr_, expr_mac, mac_invoc}; -import syntax::fold::*; -import syntax::ext::base::*; -import syntax::ext::qquote::{qq_helper}; -import syntax::parse::parser::parse_expr_from_source_str; - -import codemap::{span, expanded_from}; - -fn expand_expr(exts: hashmap<str, syntax_extension>, cx: ext_ctxt, - e: expr_, s: span, fld: ast_fold, - orig: fn@(expr_, span, ast_fold) -> (expr_, span)) - -> (expr_, span) -{ - ret alt e { - expr_mac(mac) { - alt mac.node { - mac_invoc(pth, args, body) { - assert (vec::len(pth.node.idents) > 0u); - let extname = pth.node.idents[0]; - alt exts.find(extname) { - none { - cx.span_fatal(pth.span, - #fmt["macro undefined: '%s'", extname]) - } - some(normal({expander: exp, span: exp_sp})) { - let expanded = exp(cx, pth.span, args, body); - - let info = {call_site: s, - callie: {name: extname, span: exp_sp}}; - cx.bt_push(expanded_from(info)); - //keep going, outside-in - let fully_expanded = fld.fold_expr(expanded).node; - cx.bt_pop(); - - (fully_expanded, s) - } - some(macro_defining(ext)) { - let named_extension = ext(cx, pth.span, args, body); - exts.insert(named_extension.ident, named_extension.ext); - (ast::expr_rec([], none), s) - } - } - } - _ { cx.span_bug(mac.span, "naked syntactic bit") } - } - } - _ { orig(e, s, fld) } - }; -} - -fn new_span(cx: ext_ctxt, sp: span) -> span { - /* this discards information in the case of macro-defining macros */ - ret {lo: sp.lo, hi: sp.hi, expn_info: cx.backtrace()}; -} - -// FIXME: this is a terrible kludge to inject some macros into the default -// compilation environment. When the macro-definition system is substantially -// more mature, these should move from here, into a compiled part of libcore -// at very least. - -fn core_macros() -> str { - ret -"{ - #macro([#error[f, ...], log(core::error, #fmt[f, ...])]); - #macro([#warn[f, ...], log(core::warn, #fmt[f, ...])]); - #macro([#info[f, ...], log(core::info, #fmt[f, ...])]); - #macro([#debug[f, ...], log(core::debug, #fmt[f, ...])]); -}"; -} - -fn expand_crate(sess: session::session, c: @crate) -> @crate { - let exts = syntax_expander_table(); - let afp = default_ast_fold(); - let cx: ext_ctxt = mk_ctxt(sess); - let f_pre = - {fold_expr: bind expand_expr(exts, cx, _, _, _, afp.fold_expr), - new_span: bind new_span(cx, _) - with *afp}; - let f = make_fold(f_pre); - let cm = parse_expr_from_source_str("<core-macros>", - @core_macros(), - sess.opts.cfg, - sess.parse_sess); - - // This is run for its side-effects on the expander env, - // as it registers all the core macros as expanders. - f.fold_expr(cm); - - let res = @f.fold_crate(*c); - ret res; -} -// Local Variables: -// mode: rust -// fill-column: 78; -// indent-tabs-mode: nil -// c-basic-offset: 4 -// buffer-file-coding-system: utf-8-unix -// End: diff --git a/src/comp/syntax/ext/fmt.rs b/src/comp/syntax/ext/fmt.rs deleted file mode 100644 index 29b19a2d66c..00000000000 --- a/src/comp/syntax/ext/fmt.rs +++ /dev/null @@ -1,300 +0,0 @@ - - -/* - * The compiler code necessary to support the #fmt extension. Eventually this - * should all get sucked into either the standard library extfmt module or the - * compiler syntax extension plugin interface. - */ -import extfmt::ct::*; -import base::*; -import codemap::span; -import syntax::ext::build::*; -export expand_syntax_ext; - -fn expand_syntax_ext(cx: ext_ctxt, sp: span, arg: ast::mac_arg, - _body: ast::mac_body) -> @ast::expr { - let arg = get_mac_arg(cx,sp,arg); - let args: [@ast::expr] = - alt arg.node { - ast::expr_vec(elts, _) { elts } - _ { - cx.span_fatal(sp, "#fmt requires arguments of the form `[...]`.") - } - }; - if vec::len::<@ast::expr>(args) == 0u { - cx.span_fatal(sp, "#fmt requires a format string"); - } - let fmt = - expr_to_str(cx, args[0], - "first argument to #fmt must be a string literal."); - let fmtspan = args[0].span; - #debug("Format string:"); - log(debug, fmt); - fn parse_fmt_err_(cx: ext_ctxt, sp: span, msg: str) -> ! { - cx.span_fatal(sp, msg); - } - let parse_fmt_err = bind parse_fmt_err_(cx, fmtspan, _); - let pieces = parse_fmt_string(fmt, parse_fmt_err); - ret pieces_to_expr(cx, sp, pieces, args); -} - -// FIXME: A lot of these functions for producing expressions can probably -// be factored out in common with other code that builds expressions. -// FIXME: Cleanup the naming of these functions -// NOTE: Moved many of the common ones to build.rs --kevina -fn pieces_to_expr(cx: ext_ctxt, sp: span, pieces: [piece], args: [@ast::expr]) - -> @ast::expr { - fn make_path_vec(_cx: ext_ctxt, ident: ast::ident) -> [ast::ident] { - ret ["extfmt", "rt", ident]; - } - fn make_rt_path_expr(cx: ext_ctxt, sp: span, ident: str) -> @ast::expr { - let path = make_path_vec(cx, ident); - ret mk_path(cx, sp, path); - } - // Produces an AST expression that represents a RT::conv record, - // which tells the RT::conv* functions how to perform the conversion - - fn make_rt_conv_expr(cx: ext_ctxt, sp: span, cnv: conv) -> @ast::expr { - fn make_flags(cx: ext_ctxt, sp: span, flags: [flag]) -> @ast::expr { - let flagexprs: [@ast::expr] = []; - for f: flag in flags { - let fstr; - alt f { - flag_left_justify { fstr = "flag_left_justify"; } - flag_left_zero_pad { fstr = "flag_left_zero_pad"; } - flag_space_for_sign { fstr = "flag_space_for_sign"; } - flag_sign_always { fstr = "flag_sign_always"; } - flag_alternate { fstr = "flag_alternate"; } - } - flagexprs += [make_rt_path_expr(cx, sp, fstr)]; - } - // FIXME: 0-length vectors can't have their type inferred - // through the rec that these flags are a member of, so - // this is a hack placeholder flag - - if vec::len::<@ast::expr>(flagexprs) == 0u { - flagexprs += [make_rt_path_expr(cx, sp, "flag_none")]; - } - ret mk_vec_e(cx, sp, flagexprs); - } - fn make_count(cx: ext_ctxt, sp: span, cnt: count) -> @ast::expr { - alt cnt { - count_implied { - ret make_rt_path_expr(cx, sp, "count_implied"); - } - count_is(c) { - let count_lit = mk_int(cx, sp, c); - let count_is_path = make_path_vec(cx, "count_is"); - let count_is_args = [count_lit]; - ret mk_call(cx, sp, count_is_path, count_is_args); - } - _ { cx.span_unimpl(sp, "unimplemented #fmt conversion"); } - } - } - fn make_ty(cx: ext_ctxt, sp: span, t: ty) -> @ast::expr { - let rt_type; - alt t { - ty_hex(c) { - alt c { - case_upper { rt_type = "ty_hex_upper"; } - case_lower { rt_type = "ty_hex_lower"; } - } - } - ty_bits { rt_type = "ty_bits"; } - ty_octal { rt_type = "ty_octal"; } - _ { rt_type = "ty_default"; } - } - ret make_rt_path_expr(cx, sp, rt_type); - } - fn make_conv_rec(cx: ext_ctxt, sp: span, flags_expr: @ast::expr, - width_expr: @ast::expr, precision_expr: @ast::expr, - ty_expr: @ast::expr) -> @ast::expr { - ret mk_rec_e(cx, sp, - [{ident: "flags", ex: flags_expr}, - {ident: "width", ex: width_expr}, - {ident: "precision", ex: precision_expr}, - {ident: "ty", ex: ty_expr}]); - } - let rt_conv_flags = make_flags(cx, sp, cnv.flags); - let rt_conv_width = make_count(cx, sp, cnv.width); - let rt_conv_precision = make_count(cx, sp, cnv.precision); - let rt_conv_ty = make_ty(cx, sp, cnv.ty); - ret make_conv_rec(cx, sp, rt_conv_flags, rt_conv_width, - rt_conv_precision, rt_conv_ty); - } - fn make_conv_call(cx: ext_ctxt, sp: span, conv_type: str, cnv: conv, - arg: @ast::expr) -> @ast::expr { - let fname = "conv_" + conv_type; - let path = make_path_vec(cx, fname); - let cnv_expr = make_rt_conv_expr(cx, sp, cnv); - let args = [cnv_expr, arg]; - ret mk_call(cx, arg.span, path, args); - } - fn make_new_conv(cx: ext_ctxt, sp: span, cnv: conv, arg: @ast::expr) -> - @ast::expr { - // FIXME: Extract all this validation into extfmt::ct - - fn is_signed_type(cnv: conv) -> bool { - alt cnv.ty { - ty_int(s) { - alt s { signed { ret true; } unsigned { ret false; } } - } - ty_float { ret true; } - _ { ret false; } - } - } - let unsupported = "conversion not supported in #fmt string"; - alt cnv.param { - option::none { } - _ { cx.span_unimpl(sp, unsupported); } - } - for f: flag in cnv.flags { - alt f { - flag_left_justify { } - flag_sign_always { - if !is_signed_type(cnv) { - cx.span_fatal(sp, - "+ flag only valid in " + - "signed #fmt conversion"); - } - } - flag_space_for_sign { - if !is_signed_type(cnv) { - cx.span_fatal(sp, - "space flag only valid in " + - "signed #fmt conversions"); - } - } - flag_left_zero_pad { } - _ { cx.span_unimpl(sp, unsupported); } - } - } - alt cnv.width { - count_implied { } - count_is(_) { } - _ { cx.span_unimpl(sp, unsupported); } - } - alt cnv.precision { - count_implied { } - count_is(_) { } - _ { cx.span_unimpl(sp, unsupported); } - } - alt cnv.ty { - ty_str { ret make_conv_call(cx, arg.span, "str", cnv, arg); } - ty_int(sign) { - alt sign { - signed { ret make_conv_call(cx, arg.span, "int", cnv, arg); } - unsigned { - ret make_conv_call(cx, arg.span, "uint", cnv, arg); - } - } - } - ty_bool { ret make_conv_call(cx, arg.span, "bool", cnv, arg); } - ty_char { ret make_conv_call(cx, arg.span, "char", cnv, arg); } - ty_hex(_) { ret make_conv_call(cx, arg.span, "uint", cnv, arg); } - ty_bits { ret make_conv_call(cx, arg.span, "uint", cnv, arg); } - ty_octal { ret make_conv_call(cx, arg.span, "uint", cnv, arg); } - ty_float { ret make_conv_call(cx, arg.span, "float", cnv, arg); } - ty_poly { ret make_conv_call(cx, arg.span, "poly", cnv, arg); } - _ { cx.span_unimpl(sp, unsupported); } - } - } - fn log_conv(c: conv) { - alt c.param { - some(p) { log(debug, "param: " + int::to_str(p, 10u)); } - _ { #debug("param: none"); } - } - for f: flag in c.flags { - alt f { - flag_left_justify { #debug("flag: left justify"); } - flag_left_zero_pad { #debug("flag: left zero pad"); } - flag_space_for_sign { #debug("flag: left space pad"); } - flag_sign_always { #debug("flag: sign always"); } - flag_alternate { #debug("flag: alternate"); } - } - } - alt c.width { - count_is(i) { log(debug, - "width: count is " + int::to_str(i, 10u)); } - count_is_param(i) { - log(debug, - "width: count is param " + int::to_str(i, 10u)); - } - count_is_next_param { #debug("width: count is next param"); } - count_implied { #debug("width: count is implied"); } - } - alt c.precision { - count_is(i) { log(debug, - "prec: count is " + int::to_str(i, 10u)); } - count_is_param(i) { - log(debug, - "prec: count is param " + int::to_str(i, 10u)); - } - count_is_next_param { #debug("prec: count is next param"); } - count_implied { #debug("prec: count is implied"); } - } - alt c.ty { - ty_bool { #debug("type: bool"); } - ty_str { #debug("type: str"); } - ty_char { #debug("type: char"); } - ty_int(s) { - alt s { - signed { #debug("type: signed"); } - unsigned { #debug("type: unsigned"); } - } - } - ty_bits { #debug("type: bits"); } - ty_hex(cs) { - alt cs { - case_upper { #debug("type: uhex"); } - case_lower { #debug("type: lhex"); } - } - } - ty_octal { #debug("type: octal"); } - ty_float { #debug("type: float"); } - ty_poly { #debug("type: poly"); } - } - } - let fmt_sp = args[0].span; - let n = 0u; - let tmp_expr = mk_str(cx, sp, ""); - let nargs = vec::len::<@ast::expr>(args); - for pc: piece in pieces { - alt pc { - piece_string(s) { - let s_expr = mk_str(cx, fmt_sp, s); - tmp_expr = mk_binary(cx, fmt_sp, ast::add, tmp_expr, s_expr); - } - piece_conv(conv) { - n += 1u; - if n >= nargs { - cx.span_fatal(sp, - "not enough arguments to #fmt " + - "for the given format string"); - } - #debug("Building conversion:"); - log_conv(conv); - let arg_expr = args[n]; - let c_expr = make_new_conv(cx, fmt_sp, conv, arg_expr); - tmp_expr = mk_binary(cx, fmt_sp, ast::add, tmp_expr, c_expr); - } - } - } - let expected_nargs = n + 1u; // n conversions + the fmt string - - if expected_nargs < nargs { - cx.span_fatal - (sp, #fmt["too many arguments to #fmt. found %u, expected %u", - nargs, expected_nargs]); - } - ret tmp_expr; -} -// -// Local Variables: -// mode: rust -// fill-column: 78; -// indent-tabs-mode: nil -// c-basic-offset: 4 -// buffer-file-coding-system: utf-8-unix -// End: -// diff --git a/src/comp/syntax/ext/ident_to_str.rs b/src/comp/syntax/ext/ident_to_str.rs deleted file mode 100644 index 2bb6dac7f2a..00000000000 --- a/src/comp/syntax/ext/ident_to_str.rs +++ /dev/null @@ -1,22 +0,0 @@ -import base::*; -import syntax::ast; - -fn expand_syntax_ext(cx: ext_ctxt, sp: codemap::span, arg: ast::mac_arg, - _body: ast::mac_body) -> @ast::expr { - let arg = get_mac_arg(cx,sp,arg); - let args: [@ast::expr] = - alt arg.node { - ast::expr_vec(elts, _) { elts } - _ { - cx.span_fatal(sp, "#ident_to_str requires a vector argument .") - } - }; - if vec::len::<@ast::expr>(args) != 1u { - cx.span_fatal(sp, "malformed #ident_to_str call"); - } - - ret make_new_lit(cx, sp, - ast::lit_str(expr_to_ident(cx, args[0u], - "expected an ident"))); - -} diff --git a/src/comp/syntax/ext/log_syntax.rs b/src/comp/syntax/ext/log_syntax.rs deleted file mode 100644 index 911cf9ff2eb..00000000000 --- a/src/comp/syntax/ext/log_syntax.rs +++ /dev/null @@ -1,13 +0,0 @@ -import base::*; -import syntax::ast; -import std::io::writer_util; - -fn expand_syntax_ext(cx: ext_ctxt, sp: codemap::span, arg: ast::mac_arg, - _body: ast::mac_body) -> @ast::expr { - let arg = get_mac_arg(cx,sp,arg); - cx.print_backtrace(); - std::io::stdout().write_line(print::pprust::expr_to_str(arg)); - - //trivial expression - ret @{id: cx.next_id(), node: ast::expr_rec([], option::none), span: sp}; -} diff --git a/src/comp/syntax/ext/qquote.rs b/src/comp/syntax/ext/qquote.rs deleted file mode 100644 index 7f7d5a387f0..00000000000 --- a/src/comp/syntax/ext/qquote.rs +++ /dev/null @@ -1,338 +0,0 @@ -import driver::session; - -import syntax::ast::{crate, expr_, mac_invoc, - mac_aq, mac_var}; -import syntax::fold::*; -import syntax::visit::*; -import syntax::ext::base::*; -import syntax::ext::build::*; -import syntax::parse::parser; -import syntax::parse::parser::{parser, parse_from_source_str}; - -import syntax::print::*; -import std::io::*; - -import codemap::span; - -type aq_ctxt = @{lo: uint, - mutable gather: [{lo: uint, hi: uint, - e: @ast::expr, - constr: str}]}; -enum fragment { - from_expr(@ast::expr), - from_ty(@ast::ty) -} - -iface qq_helper { - fn span() -> span; - fn visit(aq_ctxt, vt<aq_ctxt>); - fn extract_mac() -> option<ast::mac_>; - fn mk_parse_fn(ext_ctxt,span) -> @ast::expr; - fn get_fold_fn() -> str; -} - -impl of qq_helper for @ast::crate { - fn span() -> span {self.span} - fn visit(cx: aq_ctxt, v: vt<aq_ctxt>) {visit_crate(*self, cx, v);} - fn extract_mac() -> option<ast::mac_> {fail} - fn mk_parse_fn(cx: ext_ctxt, sp: span) -> @ast::expr { - mk_path(cx, sp, ["syntax", "ext", "qquote", "parse_crate"]) - } - fn get_fold_fn() -> str {"fold_crate"} -} -impl of qq_helper for @ast::expr { - fn span() -> span {self.span} - fn visit(cx: aq_ctxt, v: vt<aq_ctxt>) {visit_expr(self, cx, v);} - fn extract_mac() -> option<ast::mac_> { - alt (self.node) { - ast::expr_mac({node: mac, _}) {some(mac)} - _ {none} - } - } - fn mk_parse_fn(cx: ext_ctxt, sp: span) -> @ast::expr { - mk_path(cx, sp, ["syntax", "parse", "parser", "parse_expr"]) - } - fn get_fold_fn() -> str {"fold_expr"} -} -impl of qq_helper for @ast::ty { - fn span() -> span {self.span} - fn visit(cx: aq_ctxt, v: vt<aq_ctxt>) {visit_ty(self, cx, v);} - fn extract_mac() -> option<ast::mac_> { - alt (self.node) { - ast::ty_mac({node: mac, _}) {some(mac)} - _ {none} - } - } - fn mk_parse_fn(cx: ext_ctxt, sp: span) -> @ast::expr { - mk_path(cx, sp, ["syntax", "ext", "qquote", "parse_ty"]) - } - fn get_fold_fn() -> str {"fold_ty"} -} -impl of qq_helper for @ast::item { - fn span() -> span {self.span} - fn visit(cx: aq_ctxt, v: vt<aq_ctxt>) {visit_item(self, cx, v);} - fn extract_mac() -> option<ast::mac_> {fail} - fn mk_parse_fn(cx: ext_ctxt, sp: span) -> @ast::expr { - mk_path(cx, sp, ["syntax", "ext", "qquote", "parse_item"]) - } - fn get_fold_fn() -> str {"fold_item"} -} -impl of qq_helper for @ast::stmt { - fn span() -> span {self.span} - fn visit(cx: aq_ctxt, v: vt<aq_ctxt>) {visit_stmt(self, cx, v);} - fn extract_mac() -> option<ast::mac_> {fail} - fn mk_parse_fn(cx: ext_ctxt, sp: span) -> @ast::expr { - mk_path(cx, sp, ["syntax", "ext", "qquote", "parse_stmt"]) - } - fn get_fold_fn() -> str {"fold_stmt"} -} -impl of qq_helper for @ast::pat { - fn span() -> span {self.span} - fn visit(cx: aq_ctxt, v: vt<aq_ctxt>) {visit_pat(self, cx, v);} - fn extract_mac() -> option<ast::mac_> {fail} - fn mk_parse_fn(cx: ext_ctxt, sp: span) -> @ast::expr { - mk_path(cx, sp, ["syntax", "parse", "parser", "parse_pat"]) - } - fn get_fold_fn() -> str {"fold_pat"} -} - -fn gather_anti_quotes<N: qq_helper>(lo: uint, node: N) -> aq_ctxt -{ - let v = @{visit_expr: visit_aq_expr, - visit_ty: visit_aq_ty - with *default_visitor()}; - let cx = @{lo:lo, mutable gather: []}; - node.visit(cx, mk_vt(v)); - ret cx; -} - -fn visit_aq<T:qq_helper>(node: T, constr: str, &&cx: aq_ctxt, v: vt<aq_ctxt>) -{ - alt (node.extract_mac()) { - some(mac_aq(sp, e)) { - cx.gather += [{lo: sp.lo - cx.lo, hi: sp.hi - cx.lo, - e: e, constr: constr}]; - } - _ {node.visit(cx, v);} - } -} -// FIXME: these are only here because I (kevina) couldn't figure out how to -// get bind to work in gather_anti_quotes -fn visit_aq_expr(node: @ast::expr, &&cx: aq_ctxt, v: vt<aq_ctxt>) { - visit_aq(node,"from_expr",cx,v); -} -fn visit_aq_ty(node: @ast::ty, &&cx: aq_ctxt, v: vt<aq_ctxt>) { - visit_aq(node,"from_ty",cx,v); -} - -fn is_space(c: char) -> bool { - syntax::parse::lexer::is_whitespace(c) -} - -fn expand_ast(ecx: ext_ctxt, _sp: span, - arg: ast::mac_arg, body: ast::mac_body) - -> @ast::expr -{ - let what = "expr"; - option::may(arg) {|arg| - let args: [@ast::expr] = - alt arg.node { - ast::expr_vec(elts, _) { elts } - _ { - ecx.span_fatal - (_sp, "#ast requires arguments of the form `[...]`.") - } - }; - if vec::len::<@ast::expr>(args) != 1u { - ecx.span_fatal(_sp, "#ast requires exactly one arg"); - } - alt (args[0].node) { - ast::expr_path(@{node: {idents: id, _},_}) if vec::len(id) == 1u - {what = id[0]} - _ {ecx.span_fatal(args[0].span, "expected an identifier");} - } - } - let body = get_mac_body(ecx,_sp,body); - - ret alt what { - "crate" {finish(ecx, body, parse_crate)} - "expr" {finish(ecx, body, parser::parse_expr)} - "ty" {finish(ecx, body, parse_ty)} - "item" {finish(ecx, body, parse_item)} - "stmt" {finish(ecx, body, parse_stmt)} - "pat" {finish(ecx, body, parser::parse_pat)} - _ {ecx.span_fatal(_sp, "unsupported ast type")} - }; -} - -fn parse_crate(p: parser) -> @ast::crate { - parser::parse_crate_mod(p, []) -} - -fn parse_ty(p: parser) -> @ast::ty { - parser::parse_ty(p, false) -} - -fn parse_stmt(p: parser) -> @ast::stmt { - parser::parse_stmt(p, []) -} - -fn parse_item(p: parser) -> @ast::item { - alt (parser::parse_item(p, [])) { - some(item) {item} - none {fail; /* FIXME: Error message, somehow */} - } -} - -fn finish<T: qq_helper> - (ecx: ext_ctxt, body: ast::mac_body_, f: fn (p: parser) -> T) - -> @ast::expr -{ - let cm = ecx.session().parse_sess.cm; - let str = @codemap::span_to_snippet(body.span, cm); - let fname = codemap::mk_substr_filename(cm, body.span); - let node = parse_from_source_str - (f, fname, codemap::fss_internal(body.span), str, - ecx.session().opts.cfg, ecx.session().parse_sess); - let loc = codemap::lookup_char_pos(cm, body.span.lo); - - let sp = node.span(); - let qcx = gather_anti_quotes(sp.lo, node); - let cx = qcx; - - // assert that the vector is sorted by position: - uint::range(1u, vec::len(cx.gather)) {|i| - assert cx.gather[i-1u].lo < cx.gather[i].lo; - } - - let str2 = ""; - enum state {active, skip(uint), blank}; - let state = active; - let i = 0u, j = 0u; - let g_len = vec::len(cx.gather); - str::chars_iter(*str) {|ch| - if (j < g_len && i == cx.gather[j].lo) { - assert ch == '$'; - let repl = #fmt("$%u ", j); - state = skip(str::char_len(repl)); - str2 += repl; - } - alt state { - active {str::push_char(str2, ch);} - skip(1u) {state = blank;} - skip(sk) {state = skip (sk-1u);} - blank if is_space(ch) {str::push_char(str2, ch);} - blank {str::push_char(str2, ' ');} - } - i += 1u; - if (j < g_len && i == cx.gather[j].hi) { - assert ch == ')'; - state = active; - j += 1u; - } - } - - let cx = ecx; - let session_call = bind mk_call_(cx,sp, - mk_access(cx,sp,["ext_cx"], "session"), - []); - let pcall = mk_call(cx,sp, - ["syntax", "parse", "parser", - "parse_from_source_str"], - [node.mk_parse_fn(cx,sp), - mk_str(cx,sp, fname), - mk_call(cx,sp, - ["syntax","ext","qquote", "mk_file_substr"], - [mk_str(cx,sp, loc.file.name), - mk_uint(cx,sp, loc.line), - mk_uint(cx,sp, loc.col)]), - mk_unary(cx,sp, ast::box(ast::m_imm), - mk_str(cx,sp, str2)), - mk_access_(cx,sp, - mk_access_(cx,sp, session_call(), "opts"), - "cfg"), - mk_access_(cx,sp, session_call(), "parse_sess")] - ); - let rcall = pcall; - if (g_len > 0u) { - rcall = mk_call(cx,sp, - ["syntax", "ext", "qquote", "replace"], - [pcall, - mk_vec_e(cx,sp, vec::map(copy qcx.gather) {|g| - mk_call(cx,sp, - ["syntax", "ext", "qquote", g.constr], - [g.e])}), - mk_path(cx,sp, - ["syntax", "ext", "qquote", - node.get_fold_fn()])]); - } - ret rcall; -} - -fn replace<T>(node: T, repls: [fragment], ff: fn (ast_fold, T) -> T) - -> T -{ - let aft = default_ast_fold(); - let f_pre = {fold_expr: bind replace_expr(repls, _, _, _, - aft.fold_expr), - fold_ty: bind replace_ty(repls, _, _, _, - aft.fold_ty) - with *aft}; - ret ff(make_fold(f_pre), node); -} -fn fold_crate(f: ast_fold, &&n: @ast::crate) -> @ast::crate { - @f.fold_crate(*n) -} -fn fold_expr(f: ast_fold, &&n: @ast::expr) -> @ast::expr {f.fold_expr(n)} -fn fold_ty(f: ast_fold, &&n: @ast::ty) -> @ast::ty {f.fold_ty(n)} -fn fold_item(f: ast_fold, &&n: @ast::item) -> @ast::item {f.fold_item(n)} -fn fold_stmt(f: ast_fold, &&n: @ast::stmt) -> @ast::stmt {f.fold_stmt(n)} -fn fold_pat(f: ast_fold, &&n: @ast::pat) -> @ast::pat {f.fold_pat(n)} - -fn replace_expr(repls: [fragment], - e: ast::expr_, s: span, fld: ast_fold, - orig: fn@(ast::expr_, span, ast_fold)->(ast::expr_, span)) - -> (ast::expr_, span) -{ - alt e { - ast::expr_mac({node: mac_var(i), _}) { - alt (repls[i]) { - from_expr(r) {(r.node, r.span)} - _ {fail /* fixme error message */}}} - _ {orig(e,s,fld)} - } -} - -fn replace_ty(repls: [fragment], - e: ast::ty_, s: span, fld: ast_fold, - orig: fn@(ast::ty_, span, ast_fold)->(ast::ty_, span)) - -> (ast::ty_, span) -{ - alt e { - ast::ty_mac({node: mac_var(i), _}) { - alt (repls[i]) { - from_ty(r) {(r.node, r.span)} - _ {fail /* fixme error message */}}} - _ {orig(e,s,fld)} - } -} - -fn print_expr(expr: @ast::expr) { - let stdout = std::io::stdout(); - let pp = pprust::rust_printer(stdout); - pprust::print_expr(pp, expr); - pp::eof(pp.s); - stdout.write_str("\n"); -} - -fn mk_file_substr(fname: str, line: uint, col: uint) -> codemap::file_substr { - codemap::fss_external({filename: fname, line: line, col: col}) -} - -// Local Variables: -// mode: rust -// fill-column: 78; -// indent-tabs-mode: nil -// c-basic-offset: 4 -// buffer-file-coding-system: utf-8-unix -// End: diff --git a/src/comp/syntax/ext/simplext.rs b/src/comp/syntax/ext/simplext.rs deleted file mode 100644 index 1baf5f97d20..00000000000 --- a/src/comp/syntax/ext/simplext.rs +++ /dev/null @@ -1,779 +0,0 @@ -use std; - -import codemap::span; -import std::map::{hashmap, new_str_hash}; -import driver::session::session; - -import base::*; - -import fold::*; -import ast_util::respan; -import ast::{ident, path, ty, blk_, expr, path_, expr_path, - expr_vec, expr_mac, mac_invoc, node_id}; - -export add_new_extension; - -fn path_to_ident(pth: @path) -> option<ident> { - if vec::len(pth.node.idents) == 1u && vec::len(pth.node.types) == 0u { - ret some(pth.node.idents[0u]); - } - ret none; -} - -//a vec of binders might be a little big. -type clause = {params: binders, body: @expr}; - -/* logically, an arb_depth should contain only one kind of matchable */ -enum arb_depth<T> { leaf(T), seq(@[arb_depth<T>], span), } - - -enum matchable { - match_expr(@expr), - match_path(@path), - match_ident(ast::spanned<ident>), - match_ty(@ty), - match_block(ast::blk), - match_exact, /* don't bind anything, just verify the AST traversal */ -} - -/* for when given an incompatible bit of AST */ -fn match_error(cx: ext_ctxt, m: matchable, expected: str) -> ! { - alt m { - match_expr(x) { - cx.span_fatal(x.span, - "this argument is an expr, expected " + expected); - } - match_path(x) { - cx.span_fatal(x.span, - "this argument is a path, expected " + expected); - } - match_ident(x) { - cx.span_fatal(x.span, - "this argument is an ident, expected " + expected); - } - match_ty(x) { - cx.span_fatal(x.span, - "this argument is a type, expected " + expected); - } - match_block(x) { - cx.span_fatal(x.span, - "this argument is a block, expected " + expected); - } - match_exact { cx.bug("what is a match_exact doing in a bindings?"); } - } -} - -// We can't make all the matchables in a match_result the same type because -// idents can be paths, which can be exprs. - -// If we want better match failure error messages (like in Fortifying Syntax), -// we'll want to return something indicating amount of progress and location -// of failure instead of `none`. -type match_result = option<arb_depth<matchable>>; -type selector = fn@(matchable) -> match_result; - -fn elts_to_ell(cx: ext_ctxt, elts: [@expr]) -> - {pre: [@expr], rep: option<@expr>, post: [@expr]} { - let idx: uint = 0u; - let res = none; - for elt: @expr in elts { - alt elt.node { - expr_mac(m) { - alt m.node { - ast::mac_ellipsis { - if res != none { - cx.span_fatal(m.span, "only one ellipsis allowed"); - } - res = - some({pre: vec::slice(elts, 0u, idx - 1u), - rep: some(elts[idx - 1u]), - post: vec::slice(elts, idx + 1u, vec::len(elts))}); - } - _ { } - } - } - _ { } - } - idx += 1u; - } - ret alt res { - some(val) { val } - none { {pre: elts, rep: none, post: []} } - } -} - -fn option_flatten_map<T: copy, U: copy>(f: fn@(T) -> option<U>, v: [T]) -> - option<[U]> { - let res = []; - for elem: T in v { - alt f(elem) { none { ret none; } some(fv) { res += [fv]; } } - } - ret some(res); -} - -fn a_d_map(ad: arb_depth<matchable>, f: selector) -> match_result { - alt ad { - leaf(x) { ret f(x); } - seq(ads, span) { - alt option_flatten_map(bind a_d_map(_, f), *ads) { - none { ret none; } - some(ts) { ret some(seq(@ts, span)); } - } - } - } -} - -fn compose_sels(s1: selector, s2: selector) -> selector { - fn scomp(s1: selector, s2: selector, m: matchable) -> match_result { - ret alt s1(m) { - none { none } - some(matches) { a_d_map(matches, s2) } - } - } - ret bind scomp(s1, s2, _); -} - - - -type binders = - {real_binders: hashmap<ident, selector>, - mutable literal_ast_matchers: [selector]}; -type bindings = hashmap<ident, arb_depth<matchable>>; - -fn acumm_bindings(_cx: ext_ctxt, _b_dest: bindings, _b_src: bindings) { } - -/* these three functions are the big moving parts */ - -/* create the selectors needed to bind and verify the pattern */ - -fn pattern_to_selectors(cx: ext_ctxt, e: @expr) -> binders { - let res: binders = - {real_binders: new_str_hash::<selector>(), - mutable literal_ast_matchers: []}; - //this oughta return binders instead, but macro args are a sequence of - //expressions, rather than a single expression - fn trivial_selector(m: matchable) -> match_result { ret some(leaf(m)); } - p_t_s_rec(cx, match_expr(e), trivial_selector, res); - ret res; -} - - - -/* use the selectors on the actual arguments to the macro to extract -bindings. Most of the work is done in p_t_s, which generates the -selectors. */ - -fn use_selectors_to_bind(b: binders, e: @expr) -> option<bindings> { - let res = new_str_hash::<arb_depth<matchable>>(); - //need to do this first, to check vec lengths. - for sel: selector in b.literal_ast_matchers { - alt sel(match_expr(e)) { none { ret none; } _ { } } - } - let never_mind: bool = false; - b.real_binders.items {|key, val| - alt val(match_expr(e)) { - none { never_mind = true; } - some(mtc) { res.insert(key, mtc); } - } - }; - //HACK: `ret` doesn't work in `for each` - if never_mind { ret none; } - ret some(res); -} - -/* use the bindings on the body to generate the expanded code */ - -fn transcribe(cx: ext_ctxt, b: bindings, body: @expr) -> @expr { - let idx_path: @mutable [uint] = @mutable []; - fn new_id(_old: node_id, cx: ext_ctxt) -> node_id { ret cx.next_id(); } - fn new_span(cx: ext_ctxt, sp: span) -> span { - /* this discards information in the case of macro-defining macros */ - ret {lo: sp.lo, hi: sp.hi, expn_info: cx.backtrace()}; - } - let afp = default_ast_fold(); - let f_pre = - {fold_ident: bind transcribe_ident(cx, b, idx_path, _, _), - fold_path: bind transcribe_path(cx, b, idx_path, _, _, _), - fold_expr: - bind transcribe_expr(cx, b, idx_path, _, _, _, afp.fold_expr), - fold_ty: bind transcribe_type(cx, b, idx_path, _, _, _, afp.fold_ty), - fold_block: - bind transcribe_block(cx, b, idx_path, _, _, _, afp.fold_block), - map_exprs: bind transcribe_exprs(cx, b, idx_path, _, _), - new_id: bind new_id(_, cx) - with *afp}; - let f = make_fold(f_pre); - let result = f.fold_expr(body); - ret result; -} - - -/* helper: descend into a matcher */ -fn follow(m: arb_depth<matchable>, idx_path: @mutable [uint]) -> - arb_depth<matchable> { - let res: arb_depth<matchable> = m; - for idx: uint in *idx_path { - alt res { - leaf(_) { ret res;/* end of the line */ } - seq(new_ms, _) { res = new_ms[idx]; } - } - } - ret res; -} - -fn follow_for_trans(cx: ext_ctxt, mmaybe: option<arb_depth<matchable>>, - idx_path: @mutable [uint]) -> option<matchable> { - alt mmaybe { - none { ret none } - some(m) { - ret alt follow(m, idx_path) { - seq(_, sp) { - cx.span_fatal(sp, - "syntax matched under ... but not " + - "used that way.") - } - leaf(m) { ret some(m) } - } - } - } - -} - -/* helper for transcribe_exprs: what vars from `b` occur in `e`? */ -fn free_vars(b: bindings, e: @expr, it: fn(ident)) { - let idents: hashmap<ident, ()> = new_str_hash::<()>(); - fn mark_ident(&&i: ident, _fld: ast_fold, b: bindings, - idents: hashmap<ident, ()>) -> ident { - if b.contains_key(i) { idents.insert(i, ()); } - ret i; - } - // using fold is a hack: we want visit, but it doesn't hit idents ) : - // solve this with macros - let f_pre = - {fold_ident: bind mark_ident(_, _, b, idents) - with *default_ast_fold()}; - let f = make_fold(f_pre); - f.fold_expr(e); // ignore result - idents.keys {|x| it(x); }; -} - - -/* handle sequences (anywhere in the AST) of exprs, either real or ...ed */ -fn transcribe_exprs(cx: ext_ctxt, b: bindings, idx_path: @mutable [uint], - recur: fn@(&&@expr) -> @expr, exprs: [@expr]) -> [@expr] { - alt elts_to_ell(cx, exprs) { - {pre: pre, rep: repeat_me_maybe, post: post} { - let res = vec::map(pre, recur); - alt repeat_me_maybe { - none { } - some(repeat_me) { - let repeat: option<{rep_count: uint, name: ident}> = none; - /* we need to walk over all the free vars in lockstep, except for - the leaves, which are just duplicated */ - free_vars(b, repeat_me) {|fv| - let cur_pos = follow(b.get(fv), idx_path); - alt cur_pos { - leaf(_) { } - seq(ms, _) { - alt repeat { - none { - repeat = some({rep_count: vec::len(*ms), name: fv}); - } - some({rep_count: old_len, name: old_name}) { - let len = vec::len(*ms); - if old_len != len { - let msg = - #fmt["'%s' occurs %u times, but ", fv, len] + - #fmt["'%s' occurs %u times", old_name, - old_len]; - cx.span_fatal(repeat_me.span, msg); - } - } - } - } - } - }; - alt repeat { - none { - cx.span_fatal(repeat_me.span, - "'...' surrounds an expression without any" + - " repeating syntax variables"); - } - some({rep_count: rc, _}) { - /* Whew, we now know how how many times to repeat */ - let idx: uint = 0u; - while idx < rc { - *idx_path += [idx]; - res += [recur(repeat_me)]; // whew! - vec::pop(*idx_path); - idx += 1u; - } - } - } - } - } - res += vec::map(post, recur); - ret res; - } - } -} - - - -// substitute, in a position that's required to be an ident -fn transcribe_ident(cx: ext_ctxt, b: bindings, idx_path: @mutable [uint], - &&i: ident, _fld: ast_fold) -> ident { - ret alt follow_for_trans(cx, b.find(i), idx_path) { - some(match_ident(a_id)) { a_id.node } - some(m) { match_error(cx, m, "an identifier") } - none { i } - } -} - - -fn transcribe_path(cx: ext_ctxt, b: bindings, idx_path: @mutable [uint], - p: path_, s:span, _fld: ast_fold) -> (path_, span) { - // Don't substitute into qualified names. - if vec::len(p.types) > 0u || vec::len(p.idents) != 1u { ret (p, s); } - ret alt follow_for_trans(cx, b.find(p.idents[0]), idx_path) { - some(match_ident(id)) { - ({global: false, idents: [id.node], types: []}, id.span) - } - some(match_path(a_pth)) { (a_pth.node, a_pth.span) } - some(m) { match_error(cx, m, "a path") } - none { (p, s) } - } -} - - -fn transcribe_expr(cx: ext_ctxt, b: bindings, idx_path: @mutable [uint], - e: ast::expr_, s: span, fld: ast_fold, - orig: fn@(ast::expr_, span, ast_fold)->(ast::expr_, span)) - -> (ast::expr_, span) -{ - ret alt e { - expr_path(p) { - // Don't substitute into qualified names. - if vec::len(p.node.types) > 0u || vec::len(p.node.idents) != 1u { - (e, s); - } - alt follow_for_trans(cx, b.find(p.node.idents[0]), idx_path) { - some(match_ident(id)) { - (expr_path(@respan(id.span, - {global: false, - idents: [id.node], - types: []})), id.span) - } - some(match_path(a_pth)) { (expr_path(a_pth), s) } - some(match_expr(a_exp)) { (a_exp.node, a_exp.span) } - some(m) { match_error(cx, m, "an expression") } - none { orig(e, s, fld) } - } - } - _ { orig(e, s, fld) } - } -} - -fn transcribe_type(cx: ext_ctxt, b: bindings, idx_path: @mutable [uint], - t: ast::ty_, s: span, fld: ast_fold, - orig: fn@(ast::ty_, span, ast_fold) -> (ast::ty_, span)) - -> (ast::ty_, span) -{ - ret alt t { - ast::ty_path(pth, _) { - alt path_to_ident(pth) { - some(id) { - alt follow_for_trans(cx, b.find(id), idx_path) { - some(match_ty(ty)) { (ty.node, ty.span) } - some(m) { match_error(cx, m, "a type") } - none { orig(t, s, fld) } - } - } - none { orig(t, s, fld) } - } - } - _ { orig(t, s, fld) } - } -} - - -/* for parsing reasons, syntax variables bound to blocks must be used like -`{v}` */ - -fn transcribe_block(cx: ext_ctxt, b: bindings, idx_path: @mutable [uint], - blk: blk_, s: span, fld: ast_fold, - orig: fn@(blk_, span, ast_fold) -> (blk_, span)) - -> (blk_, span) -{ - ret alt block_to_ident(blk) { - some(id) { - alt follow_for_trans(cx, b.find(id), idx_path) { - some(match_block(new_blk)) { (new_blk.node, new_blk.span) } - - - - - - // possibly allow promotion of ident/path/expr to blocks? - some(m) { - match_error(cx, m, "a block") - } - none { orig(blk, s, fld) } - } - } - none { orig(blk, s, fld) } - } -} - - -/* traverse the pattern, building instructions on how to bind the actual -argument. ps accumulates instructions on navigating the tree.*/ -fn p_t_s_rec(cx: ext_ctxt, m: matchable, s: selector, b: binders) { - - //it might be possible to traverse only exprs, not matchables - alt m { - match_expr(e) { - alt e.node { - expr_path(p_pth) { p_t_s_r_path(cx, p_pth, s, b); } - expr_vec(p_elts, _) { - alt elts_to_ell(cx, p_elts) { - {pre: pre, rep: some(repeat_me), post: post} { - p_t_s_r_length(cx, vec::len(pre) + vec::len(post), true, s, - b); - if vec::len(pre) > 0u { - p_t_s_r_actual_vector(cx, pre, true, s, b); - } - p_t_s_r_ellipses(cx, repeat_me, vec::len(pre), s, b); - - if vec::len(post) > 0u { - cx.span_unimpl(e.span, - "matching after `...` not yet supported"); - } - } - {pre: pre, rep: none, post: post} { - if post != [] { - cx.bug("elts_to_ell provided an invalid result"); - } - p_t_s_r_length(cx, vec::len(pre), false, s, b); - p_t_s_r_actual_vector(cx, pre, false, s, b); - } - } - } - /* FIXME: handle embedded types and blocks, at least */ - expr_mac(mac) { - p_t_s_r_mac(cx, mac, s, b); - } - _ { - fn select(cx: ext_ctxt, m: matchable, pat: @expr) -> - match_result { - ret alt m { - match_expr(e) { - if e == pat { some(leaf(match_exact)) } else { none } - } - _ { cx.bug("broken traversal in p_t_s_r") } - } - } - b.literal_ast_matchers += [bind select(cx, _, e)]; - } - } - } - _ { - cx.session().bug("undocumented invariant in p_t_s_rec"); - } - } -} - - -/* make a match more precise */ -fn specialize_match(m: matchable) -> matchable { - ret alt m { - match_expr(e) { - alt e.node { - expr_path(pth) { - alt path_to_ident(pth) { - some(id) { match_ident(respan(pth.span, id)) } - none { match_path(pth) } - } - } - _ { m } - } - } - _ { m } - } -} - -/* pattern_to_selectors helper functions */ -fn p_t_s_r_path(cx: ext_ctxt, p: @path, s: selector, b: binders) { - alt path_to_ident(p) { - some(p_id) { - fn select(cx: ext_ctxt, m: matchable) -> match_result { - ret alt m { - match_expr(e) { some(leaf(specialize_match(m))) } - _ { cx.bug("broken traversal in p_t_s_r") } - } - } - if b.real_binders.contains_key(p_id) { - cx.span_fatal(p.span, "duplicate binding identifier"); - } - b.real_binders.insert(p_id, compose_sels(s, bind select(cx, _))); - } - none { } - } -} - -fn block_to_ident(blk: blk_) -> option<ident> { - if vec::len(blk.stmts) != 0u { ret none; } - ret alt blk.expr { - some(expr) { - alt expr.node { expr_path(pth) { path_to_ident(pth) } _ { none } } - } - none { none } - } -} - -fn p_t_s_r_mac(cx: ext_ctxt, mac: ast::mac, s: selector, b: binders) { - fn select_pt_1(cx: ext_ctxt, m: matchable, - fn_m: fn(ast::mac) -> match_result) -> match_result { - ret alt m { - match_expr(e) { - alt e.node { expr_mac(mac) { fn_m(mac) } _ { none } } - } - _ { cx.bug("broken traversal in p_t_s_r") } - } - } - fn no_des(cx: ext_ctxt, sp: span, syn: str) -> ! { - cx.span_fatal(sp, "destructuring " + syn + " is not yet supported"); - } - alt mac.node { - ast::mac_ellipsis { cx.span_fatal(mac.span, "misused `...`"); } - ast::mac_invoc(_, _, _) { no_des(cx, mac.span, "macro calls"); } - ast::mac_embed_type(ty) { - alt ty.node { - ast::ty_path(pth, _) { - alt path_to_ident(pth) { - some(id) { - /* look for an embedded type */ - fn select_pt_2(m: ast::mac) -> match_result { - ret alt m.node { - ast::mac_embed_type(t) { some(leaf(match_ty(t))) } - _ { none } - } - } - let final_step = bind select_pt_1(cx, _, select_pt_2); - b.real_binders.insert(id, compose_sels(s, final_step)); - } - none { no_des(cx, pth.span, "under `#<>`"); } - } - } - _ { no_des(cx, ty.span, "under `#<>`"); } - } - } - ast::mac_embed_block(blk) { - alt block_to_ident(blk.node) { - some(id) { - fn select_pt_2(m: ast::mac) -> match_result { - ret alt m.node { - ast::mac_embed_block(blk) { - some(leaf(match_block(blk))) - } - _ { none } - } - } - let final_step = bind select_pt_1(cx, _, select_pt_2); - b.real_binders.insert(id, compose_sels(s, final_step)); - } - none { no_des(cx, blk.span, "under `#{}`"); } - } - } - ast::mac_aq(_,_) { no_des(cx, mac.span, "antiquotes"); } - ast::mac_var(_) { no_des(cx, mac.span, "antiquote variables"); } - } -} - -fn p_t_s_r_ellipses(cx: ext_ctxt, repeat_me: @expr, offset: uint, s: selector, - b: binders) { - fn select(cx: ext_ctxt, repeat_me: @expr, offset: uint, m: matchable) -> - match_result { - ret alt m { - match_expr(e) { - alt e.node { - expr_vec(arg_elts, _) { - let elts = []; - let idx = offset; - while idx < vec::len(arg_elts) { - elts += [leaf(match_expr(arg_elts[idx]))]; - idx += 1u; - } - - // using repeat_me.span is a little wacky, but the - // error we want to report is one in the macro def - some(seq(@elts, repeat_me.span)) - } - _ { none } - } - } - _ { cx.bug("broken traversal in p_t_s_r") } - } - } - p_t_s_rec(cx, match_expr(repeat_me), - compose_sels(s, bind select(cx, repeat_me, offset, _)), b); -} - - -fn p_t_s_r_length(cx: ext_ctxt, len: uint, at_least: bool, s: selector, - b: binders) { - fn len_select(_cx: ext_ctxt, m: matchable, at_least: bool, len: uint) -> - match_result { - ret alt m { - match_expr(e) { - alt e.node { - expr_vec(arg_elts, _) { - let actual_len = vec::len(arg_elts); - if at_least && actual_len >= len || actual_len == len { - some(leaf(match_exact)) - } else { none } - } - _ { none } - } - } - _ { none } - } - } - b.literal_ast_matchers += - [compose_sels(s, bind len_select(cx, _, at_least, len))]; -} - -fn p_t_s_r_actual_vector(cx: ext_ctxt, elts: [@expr], _repeat_after: bool, - s: selector, b: binders) { - let idx: uint = 0u; - while idx < vec::len(elts) { - fn select(cx: ext_ctxt, m: matchable, idx: uint) -> match_result { - ret alt m { - match_expr(e) { - alt e.node { - expr_vec(arg_elts, _) { - some(leaf(match_expr(arg_elts[idx]))) - } - _ { none } - } - } - _ { cx.bug("broken traversal in p_t_s_r") } - } - } - p_t_s_rec(cx, match_expr(elts[idx]), - compose_sels(s, bind select(cx, _, idx)), b); - idx += 1u; - } -} - -fn add_new_extension(cx: ext_ctxt, sp: span, arg: ast::mac_arg, - _body: ast::mac_body) -> base::macro_def { - let arg = get_mac_arg(cx,sp,arg); - let args: [@ast::expr] = - alt arg.node { - ast::expr_vec(elts, _) { elts } - _ { - cx.span_fatal(sp, - "#macro requires arguments of the form `[...]`.") - } - }; - - let macro_name: option<str> = none; - let clauses: [@clause] = []; - for arg: @expr in args { - alt arg.node { - expr_vec(elts, mutbl) { - if vec::len(elts) != 2u { - cx.span_fatal((*arg).span, - "extension clause must consist of [" + - "macro invocation, expansion body]"); - } - - - alt elts[0u].node { - expr_mac(mac) { - alt mac.node { - mac_invoc(pth, invoc_arg, body) { - alt path_to_ident(pth) { - some(id) { - alt macro_name { - none { macro_name = some(id); } - some(other_id) { - if id != other_id { - cx.span_fatal(pth.span, - "macro name must be " + - "consistent"); - } - } - } - } - none { - cx.span_fatal(pth.span, - "macro name must not be a path"); - } - } - clauses += - [@{params: pattern_to_selectors - (cx, get_mac_arg(cx,mac.span,invoc_arg)), - body: elts[1u]}]; - - // FIXME: check duplicates (or just simplify - // the macro arg situation) - } - _ { - cx.span_bug(mac.span, "undocumented invariant in \ - add_extension"); - } - } - } - _ { - cx.span_fatal(elts[0u].span, - "extension clause must" + - " start with a macro invocation."); - } - } - } - _ { - cx.span_fatal((*arg).span, - "extension must be [clause, " + " ...]"); - } - } - } - - let ext = bind generic_extension(_, _, _, _, clauses); - - ret {ident: - alt macro_name { - some(id) { id } - none { - cx.span_fatal(sp, - "macro definition must have " + - "at least one clause") - } - }, - ext: normal({expander: ext, span: some(arg.span)})}; - - fn generic_extension(cx: ext_ctxt, sp: span, arg: ast::mac_arg, - _body: ast::mac_body, clauses: [@clause]) -> @expr { - let arg = get_mac_arg(cx,sp,arg); - for c: @clause in clauses { - alt use_selectors_to_bind(c.params, arg) { - some(bindings) { ret transcribe(cx, bindings, c.body); } - none { cont; } - } - } - cx.span_fatal(sp, "no clauses match macro invocation"); - } -} - - - -// -// Local Variables: -// mode: rust -// fill-column: 78; -// indent-tabs-mode: nil -// c-basic-offset: 4 -// buffer-file-coding-system: utf-8-unix -// End: -// |
