Skip to content

Macros should be able to expand to methods #4621

Closed
@catamorphism

Description

@catamorphism

Requested in a FIXME (formerly XXX) in rustc::middle::lang_items

More specifically, here is (an abstraction of) the code pattern that the FIXME is noting:

pub enum E { Enil, Ergt, Elft, Eall, /* ... */ Eend, }
pub struct S { items: [int, ..5] }

pub impl S {
    pub fn name(index:uint) -> &'static str {
        match index {
            0 => "nil", 1 => "lft", 2 => "rgt", 3 => "all",
            4 => "end", _ => "???"
        }
    }

    // The cases below are where a macro that expands into a method
    // definition is of interest, since they are all very regular.
    pub fn nil_item(&self) -> int { self.items[Enil as uint] }

    pub fn lft_item(&self) -> int { self.items[Elft as uint] }

    pub fn rgt_item(&self) -> int { self.items[Ergt as uint] }

    pub fn all_item(&self) -> int { self.items[Eall as uint] }

    pub fn end_item(&self) -> int { self.items[Eend as uint] }
}

    // Presumably the macro invocation version would look something like:
    //   macro_rules! e_method( 
    //      $method $variant
    //      =>
    //      pub fn $method(&self) -> int { self.items[$variant as uint] }
    //    )
    //
    // pub impl S {
    //   pub fn name(index:uint) -> &'static str { ... }
    //   e_method!(nil_item Enil);
    //   e_method!(lft_item Elft);
    //   e_method!(rgt_item Ergt);
    //   e_method!(all_item Eall);
    //   e_method!(end_item Eend);
    // }


fn main() {
    let s = S{ items: [0, 2, 1, 3, 4]};
    io::println(fmt!("Hello World: %?", s.all_item()));
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-syntaxextArea: Syntax extensionsC-enhancementCategory: An issue proposing an enhancement or a PR with one.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions