aboutsummaryrefslogtreecommitdiff
path: root/ebml_derive/src/lib.rs
blob: 18a43a92a625b217b02e953773a76a4c3154e8ed (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2023 metamuffin <metamuffin.org>
*/
use proc_macro::{token_stream, Delimiter, Span, TokenStream, TokenTree};
use quote::quote;
use syn::{Fields, FieldsUnnamed, Ident, Variant};

struct Tag {
    id: u64,
    global: bool,
    path: Vec<u64>,
    name: Ident,
    r#type: Option<String>, // None -> Master
}

#[proc_macro]
pub fn define_ebml(ts: TokenStream) -> TokenStream {
    let mut ts = ts.into_iter();
    let mut tags = vec![];
    parse_kt(&mut tags, &mut ts, vec![]);

    let enum_variants = tags
        .iter()
        .map(|e| Variant {
            ident: e.name.clone(),
            attrs: vec![],
            fields: Fields::Unnamed(
                syn::parse2::<FieldsUnnamed>(match e.r#type.clone() {
                    None => quote!((Master)),
                    Some(r#type) => match r#type.as_str() {
                        "Int" => quote!((i64)),
                        "Uint" => quote!((u64)),
                        "Float" => quote!((f64)),
                        "Utf8" => quote!((String)),
                        "Binary" => quote!((Vec<u8>)),
                        _ => panic!("unsupported type {type}"),
                    },
                })
                .expect("parse type"),
            ),
            discriminant: None,
        })
        .collect::<Vec<_>>();

    let path_match = tags
        .iter()
        .map(|e| {
            let name = &e.name;
            let path = e.path.clone();
            if e.global {
                quote! { Self::#name(_) => None }
            } else {
                quote! { Self::#name(_) => Some(&[#(#path),*]) }
            }
        })
        .collect::<Vec<_>>();
    let id_match = tags
        .iter()
        .map(|Tag { id, name, .. }| {
            quote! { Self::#name(_) => #id }
        })
        .collect::<Vec<_>>();

    let parse_match = tags
        .iter()
        .filter_map(
            |Tag {
                 id, name, r#type, ..
             }| {
                if r#type.is_some() {
                    Some(quote! { #id => Self::#name(crate::ReadValue::from_buf(data)?) })
                } else {
                    None
                }
            },
        )
        .collect::<Vec<_>>();
    let write_match = tags
        .iter()
        .map(|Tag { name, .. }| quote! { Self::#name(v) => v.write_to(w) })
        .collect::<Vec<_>>();
    let cons_master_match = tags
        .iter()
        .filter_map(
            |Tag {
                 id, name, r#type, ..
             }| {
                if r#type.is_none() {
                    Some(quote! { #id => Self::#name(kind) })
                } else {
                    None
                }
            },
        )
        .collect::<Vec<_>>();
    let is_master_match = tags
        .iter()
        .map(|Tag { id, r#type, .. }| match r#type {
            None => quote!(#id => true),
            Some(_) => quote!(#id => false),
        })
        .collect::<Vec<_>>();

    quote! {
        use crate::Master;
        use crate::WriteValue;

        #[derive(Debug, PartialEq, Clone)]
        pub enum MatroskaTag {
            #(#enum_variants),*
        }
        impl MatroskaTag {
            /// returns path in **reverse** order or None if global.
            pub fn path(&self) -> Option<&'static [u64]> {
                match self { #(#path_match),* }
            }
            pub fn id(&self) -> u64 {
                match self { #(#id_match),* }
            }
            pub fn is_master(id: u64) -> anyhow::Result<bool> {
                Ok(match id { #(#is_master_match),*, _ => anyhow::bail!("unknown id") })
            }
            pub fn construct_master(id: u64, kind: Master) -> anyhow::Result<Self> {
                Ok(match id { #(#cons_master_match),*, _ => anyhow::bail!("unknown id") })
            }
            pub fn parse(id: u64, data: &[u8]) -> anyhow::Result<Self> {
                Ok(match id { #(#parse_match),*, _ => anyhow::bail!("unknown id or master") })
            }
            pub fn write(&self, w: &mut Vec<u8>) -> anyhow::Result<()> {
                match self { #(#write_match),* }
            }
        }
    }
    .into()
}

fn parse_kt(tags: &mut Vec<Tag>, ts: &mut token_stream::IntoIter, path: Vec<u64>) {
    let mut next_glob = false;
    loop {
        let global = next_glob;
        next_glob = false;

        let name = if let Some(tt) = ts.next() {
            if let TokenTree::Ident(name) = tt {
                if &name.to_string() == "global" {
                    next_glob = true;
                    continue;
                }
                name.to_string()
            } else {
                panic!("expected ident")
            }
        } else {
            break;
        };

        let id = if let Some(TokenTree::Group(gr)) = ts.next() {
            assert_eq!(gr.delimiter(), Delimiter::Bracket);
            let mut ts = gr.stream().into_iter();
            if let TokenTree::Literal(lit) = ts.next().unwrap() {
                u64::from_str_radix(&lit.to_string()[2..], 16).unwrap()
            } else {
                panic!("literal expected")
            }
        } else {
            panic!("group expected")
        };
        if let Some(TokenTree::Punct(p)) = ts.next() {
            assert_eq!(p.as_char(), ':')
        } else {
            panic!("colon expected")
        }
        match ts.next() {
            Some(TokenTree::Group(gr)) => {
                // eprintln!("entering group");
                let mut ts = gr.stream().into_iter();
                tags.push(Tag {
                    global,
                    id,
                    name: Ident::new(&name, Span::call_site().into()),
                    path: path.clone(),
                    r#type: None,
                });
                let mut path = path.clone();
                path.push(id);
                parse_kt(tags, &mut ts, path);
                // eprintln!("leaving group");
            }
            Some(TokenTree::Ident(r#type)) => {
                let r#type = r#type.to_string();
                // eprintln!("global={global} id={id}, type={}", r#type);
                tags.push(Tag {
                    id,
                    name: Ident::new(&name, Span::call_site().into()),
                    path: path.clone(),
                    global,
                    r#type: Some(r#type),
                })
            }
            _ => panic!("group or ident expected"),
        }
        if let Some(TokenTree::Punct(p)) = ts.next() {
            assert_eq!(p.as_char(), ',')
        } else {
            panic!("colon expected")
        }
    }
}