rust/crates/ra_macros/src/tt.rs

101 lines
2.2 KiB
Rust
Raw Normal View History

2019-01-31 08:16:02 -06:00
use std::fmt;
2019-01-31 04:40:05 -06:00
use smol_str::SmolStr;
2019-01-31 08:16:02 -06:00
use join_to_string::join;
2019-01-30 14:02:27 -06:00
2019-01-31 08:16:02 -06:00
#[derive(Debug, Clone)]
2019-01-31 04:40:05 -06:00
pub enum TokenTree {
2019-01-30 14:02:27 -06:00
Leaf(Leaf),
Subtree(Subtree),
}
2019-01-30 14:58:52 -06:00
impl_froms!(TokenTree: Leaf, Subtree);
2019-01-30 14:02:27 -06:00
2019-01-31 08:16:02 -06:00
#[derive(Debug, Clone)]
2019-01-31 04:40:05 -06:00
pub enum Leaf {
2019-01-30 14:02:27 -06:00
Literal(Literal),
Punct(Punct),
Ident(Ident),
}
2019-01-30 14:58:52 -06:00
impl_froms!(Leaf: Literal, Punct, Ident);
2019-01-30 14:02:27 -06:00
2019-01-31 08:16:02 -06:00
#[derive(Debug, Clone)]
2019-01-31 04:40:05 -06:00
pub struct Subtree {
pub delimiter: Delimiter,
pub token_trees: Vec<TokenTree>,
2019-01-30 14:02:27 -06:00
}
2019-01-31 04:32:40 -06:00
#[derive(Clone, Copy, Debug)]
2019-01-31 04:40:05 -06:00
pub enum Delimiter {
2019-01-30 14:02:27 -06:00
Parenthesis,
Brace,
Bracket,
None,
}
2019-01-31 08:16:02 -06:00
#[derive(Debug, Clone)]
2019-01-31 04:40:05 -06:00
pub struct Literal {
pub text: SmolStr,
2019-01-30 14:02:27 -06:00
}
2019-01-31 08:16:02 -06:00
#[derive(Debug, Clone, PartialEq, Eq)]
2019-01-31 04:40:05 -06:00
pub struct Punct {
pub char: char,
2019-01-30 14:02:27 -06:00
}
2019-01-31 08:16:02 -06:00
#[derive(Debug, Clone)]
2019-01-31 04:40:05 -06:00
pub struct Ident {
pub text: SmolStr,
2019-01-30 14:02:27 -06:00
}
2019-01-31 08:16:02 -06:00
impl fmt::Display for TokenTree {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
TokenTree::Leaf(it) => fmt::Display::fmt(it, f),
TokenTree::Subtree(it) => fmt::Display::fmt(it, f),
}
}
}
impl fmt::Display for Subtree {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let (l, r) = match self.delimiter {
Delimiter::Parenthesis => ("(", ")"),
Delimiter::Brace => ("{", "}"),
Delimiter::Bracket => ("[", "]"),
Delimiter::None => ("", ""),
};
join(self.token_trees.iter())
.separator(" ")
.surround_with(l, r)
.to_fmt(f)
}
}
impl fmt::Display for Leaf {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Leaf::Ident(it) => fmt::Display::fmt(it, f),
Leaf::Literal(it) => fmt::Display::fmt(it, f),
Leaf::Punct(it) => fmt::Display::fmt(it, f),
}
}
}
impl fmt::Display for Ident {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.text, f)
}
}
impl fmt::Display for Literal {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.text, f)
}
}
impl fmt::Display for Punct {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.char, f)
}
}