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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
use lalrpop_util::ParseError;
use proc_macro::TokenStream;
use proc_macro2::Span;
use proc_macro_error::{abort, abort_call_site, proc_macro_error};
use quote::quote;
use std::collections::HashMap;
use std::fmt::Write;
use std::fs;
use std::path::{Path, PathBuf};
use syn::{
    parenthesized, parse, parse_macro_input, Expr, ExprLit, Ident, Lit, LitInt, LitStr, Token,
};

/// Maximum program size supported by the macro.
///
/// As the program size is limited to 32 instructions on the currently available hardware as of 2021, 1024 instructions
/// should be plenty for a while.
const MAX_PROGRAM_SIZE: usize = 1024;

struct OptionsArgs {
    ident: Ident,
    expr: Expr,
}

impl syn::parse::Parse for OptionsArgs {
    fn parse(stream: syn::parse::ParseStream) -> syn::parse::Result<Self> {
        let ident = stream.parse()?;
        let _equals: Token![=] = stream.parse()?;
        let expr = stream.parse()?;

        Ok(Self { ident, expr })
    }
}

// Options are on the form Ident = Literal
struct Options {
    options: HashMap<String, (Ident, Expr)>,
}

impl Options {
    fn validate(&self) -> Result<(), parse::Error> {
        // NOTE: Add more options here in the future
        let valid_identifiers = ["max_program_size"];

        for (name, (id, _)) in &self.options {
            if !valid_identifiers.contains(&name.as_str()) {
                abort!(
                    id,
                    "unknown identifier, expected one of {:?}",
                    valid_identifiers
                );
            }
        }

        Ok(())
    }

    fn get_max_program_size_or_default(&self) -> Result<Expr, parse::Error> {
        if let Some(mps) = self.options.get("max_program_size") {
            Ok(mps.1.clone())
        } else {
            Ok(Expr::Lit(ExprLit {
                attrs: vec![],
                lit: Lit::Int(LitInt::new("32", Span::call_site())),
            }))
        }
    }
}

impl syn::parse::Parse for Options {
    fn parse(stream: syn::parse::ParseStream) -> parse::Result<Self> {
        // Parse the optional 'options'
        let content;
        parenthesized!(content in stream);

        if !content.is_empty() {
            let mut options = HashMap::new();

            while !content.is_empty() {
                let opt: OptionsArgs = content.parse()?;
                options.insert(opt.ident.to_string(), (opt.ident, opt.expr));
                let _trailing_comma: Option<Token![,]> = content.parse().ok();
            }

            let _trailing_comma: Option<Token![,]> = stream.parse().ok();

            let s = Self { options };

            s.validate()?;

            Ok(s)
        } else {
            Ok(Self {
                options: HashMap::new(),
            })
        }
    }
}

struct SelectProgram {
    name: String,
    ident: LitStr,
}

impl syn::parse::Parse for SelectProgram {
    fn parse(stream: syn::parse::ParseStream) -> parse::Result<Self> {
        // Parse the optional 'options'
        let content;
        parenthesized!(content in stream);

        let name: LitStr = content.parse::<LitStr>()?;

        Ok(Self {
            name: name.value(),
            ident: name,
        })
    }
}

struct PioFileMacroArgs {
    max_program_size: Expr,
    program: String,
    program_name: Option<(String, LitStr)>,
}

impl syn::parse::Parse for PioFileMacroArgs {
    fn parse(stream: syn::parse::ParseStream) -> syn::parse::Result<Self> {
        let mut program = String::new();

        // Parse the list of instructions
        if let Ok(s) = stream.parse::<LitStr>() {
            let path = s.value();
            let path = Path::new(&path);

            let pathbuf = {
                let mut p = PathBuf::new();

                if path.is_relative() {
                    if let Some(crate_dir) = std::env::var_os("CARGO_MANIFEST_DIR") {
                        p.push(crate_dir);
                    } else {
                        abort!(s, "Cannot find 'CARGO_MANIFEST_DIR' environment variable");
                    }
                }

                p.push(path);

                p
            };

            if !pathbuf.exists() {
                abort!(s, "the file '{}' does not exist", pathbuf.display());
            }

            match fs::read(pathbuf) {
                Ok(content) => match std::str::from_utf8(&content) {
                    Ok(prog) => program = prog.to_string(),
                    Err(e) => {
                        abort!(s, "could parse file: '{}'", e);
                    }
                },
                Err(e) => {
                    abort!(s, "could not read file: '{}'", e);
                }
            }

            let _trailing_comma: Option<Token![,]> = stream.parse().ok();
        }

        let mut select_program = None;
        let mut options = Options {
            options: HashMap::new(),
        };

        for _ in 0..2 {
            if let Ok(ident) = stream.parse::<Ident>() {
                match ident.to_string().as_str() {
                    "select_program" => {
                        // Parse the optional 'select_program'
                        let sp: SelectProgram = stream.parse()?;
                        select_program = Some(sp);
                        let _trailing_comma: Option<Token![,]> = stream.parse().ok();
                    }
                    "options" => {
                        // Parse the optional 'options'
                        let opt: Options = stream.parse()?;
                        options = opt;
                        let _trailing_comma: Option<Token![,]> = stream.parse().ok();
                    }
                    _ => abort!(ident, "expected one of 'options' or 'select_program'"),
                }
            }
        }

        if !stream.is_empty() {
            abort!(stream.span(), "expected end of input");
        }

        // Validate options
        let max_program_size = options.get_max_program_size_or_default()?;

        Ok(Self {
            program_name: select_program.map(|v| (v.name, v.ident)),
            max_program_size,
            program,
        })
    }
}

struct PioAsmMacroArgs {
    max_program_size: Expr,
    program: String,
}

impl syn::parse::Parse for PioAsmMacroArgs {
    fn parse(stream: syn::parse::ParseStream) -> syn::parse::Result<Self> {
        let mut program = String::new();

        // Parse the list of instructions
        while let Ok(s) = stream.parse::<LitStr>() {
            writeln!(&mut program, "{}", s.value()).unwrap();

            let _trailing_comma: Option<Token![,]> = stream.parse().ok();
        }

        // Parse the optional 'options'

        let mut options = Options {
            options: HashMap::new(),
        };

        if let Ok(ident) = stream.parse::<Ident>() {
            if ident == "options" {
                let opt: Options = stream.parse()?;
                options = opt;
                let _trailing_comma: Option<Token![,]> = stream.parse().ok();
            }
        }

        if !stream.is_empty() {
            abort!(stream.span(), "expected end of input");
        }

        // Validate options
        let max_program_size = options.get_max_program_size_or_default()?;

        Ok(Self {
            max_program_size,
            program,
        })
    }
}

#[proc_macro]
#[proc_macro_error]
pub fn pio_file(item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(item as PioFileMacroArgs);
    let parsed_programs = pio_parser::Parser::<{ MAX_PROGRAM_SIZE }>::parse_file(&args.program);
    let program = match &parsed_programs {
        Ok(programs) => {
            if let Some((program_name, ident)) = args.program_name {
                if let Some(program) = programs.get(&program_name) {
                    program
                } else {
                    abort! { ident, "program name not found in the provided file" }
                }
            } else {
                // No name provided, check if there is only one in the map

                match programs.len() {
                    0 => abort_call_site! { "no programs in the provided file" },
                    1 => programs.iter().next().unwrap().1,
                    _ => {
                        abort_call_site! { "more than 1 program in the provided file, select one using `select_program(\"my_program\")`" }
                    }
                }
            }
        }
        Err(e) => return parse_error(e, &args.program).into(),
    };

    to_codegen(program, args.max_program_size).into()
}

/// A macro which invokes the PIO assembler at compile time.
#[proc_macro]
#[proc_macro_error]
pub fn pio_asm(item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(item as PioAsmMacroArgs);

    let parsed_program = pio_parser::Parser::<{ MAX_PROGRAM_SIZE }>::parse_program(&args.program);

    let program = match &parsed_program {
        Ok(program) => program,
        Err(e) => return parse_error(e, &args.program).into(),
    };

    to_codegen(program, args.max_program_size).into()
}

fn to_codegen(
    program: &pio::ProgramWithDefines<HashMap<String, i32>, { MAX_PROGRAM_SIZE }>,
    max_program_size: Expr,
) -> proc_macro2::TokenStream {
    let pio::ProgramWithDefines {
        program,
        public_defines,
    } = program;
    if let Expr::Lit(ExprLit {
        attrs: _,
        lit: Lit::Int(i),
    }) = &max_program_size
    {
        if let Ok(mps) = i.base10_parse::<usize>() {
            if program.code.len() > mps {
                abort_call_site!(
                    "the resulting program is larger than the maximum allowed: max = {}, size = {}",
                    mps,
                    program.code.len()
                );
            }
        }
    }

    let origin: proc_macro2::TokenStream = format!("{:?}", program.origin).parse().unwrap();

    let code: proc_macro2::TokenStream = format!(
        "::core::iter::IntoIterator::into_iter([{}]).collect()",
        program
            .code
            .iter()
            .map(|v| v.to_string())
            .collect::<Vec<String>>()
            .join(",")
    )
    .parse()
    .unwrap();
    let wrap: proc_macro2::TokenStream = format!(
        "::pio::Wrap {{source: {}, target: {}}}",
        program.wrap.source, program.wrap.target
    )
    .parse()
    .unwrap();
    let side_set: proc_macro2::TokenStream = format!(
        "::pio::SideSet::new_from_proc_macro({}, {}, {})",
        program.side_set.optional(),
        program.side_set.bits(),
        program.side_set.pindirs()
    )
    .parse()
    .unwrap();
    let defines_struct: proc_macro2::TokenStream = format!(
        "
            struct ExpandedDefines {{
                {}
            }}
            ",
        public_defines
            .keys()
            .map(|k| format!("{}: i32,", k))
            .collect::<Vec<String>>()
            .join("\n")
    )
    .parse()
    .unwrap();
    let defines_init: proc_macro2::TokenStream = format!(
        "
            ExpandedDefines {{
                {}
            }}
            ",
        public_defines
            .iter()
            .map(|(k, v)| format!("{}: {},", k, v))
            .collect::<Vec<String>>()
            .join("\n")
    )
    .parse()
    .unwrap();
    let program_size = max_program_size;
    quote! {
        {
            #defines_struct
            ::pio::ProgramWithDefines {
                program: ::pio::Program::<{ #program_size }> {
                    code: #code,
                    origin: #origin,
                    wrap: #wrap,
                    side_set: #side_set,
                },
                public_defines: #defines_init,
            }
        }
    }
}

fn parse_error(error: &pio_parser::ParseError, program_source: &str) -> proc_macro2::TokenStream {
    let e = error;
    let files = codespan_reporting::files::SimpleFile::new("source", program_source);

    let (loc, messages) = match e {
        ParseError::InvalidToken { location } => {
            (*location..*location, vec!["invalid token".to_string()])
        }
        ParseError::UnrecognizedEOF { location, expected } => (
            *location..*location,
            vec![
                "unrecognized eof".to_string(),
                format!("expected one of {}", expected.join(", ")),
            ],
        ),
        ParseError::UnrecognizedToken { token, expected } => (
            token.0..token.2,
            vec![
                format!("unexpected token: {:?}", format!("{}", token.1)),
                format!("expected one of {}", expected.join(", ")),
            ],
        ),
        ParseError::ExtraToken { token } => {
            (token.0..token.2, vec![format!("extra token: {}", token.1)])
        }
        ParseError::User { error } => (0..0, vec![error.to_string()]),
    };

    let diagnostic = codespan_reporting::diagnostic::Diagnostic::error()
        .with_message(messages[0].clone())
        .with_labels(
            messages
                .iter()
                .enumerate()
                .map(|(i, m)| {
                    codespan_reporting::diagnostic::Label::new(
                        if i == 0 {
                            codespan_reporting::diagnostic::LabelStyle::Primary
                        } else {
                            codespan_reporting::diagnostic::LabelStyle::Secondary
                        },
                        (),
                        loc.clone(),
                    )
                    .with_message(m)
                })
                .collect(),
        );

    let mut writer = codespan_reporting::term::termcolor::Buffer::ansi();
    let config = codespan_reporting::term::Config::default();
    codespan_reporting::term::emit(&mut writer, &config, &files, &diagnostic).unwrap();
    let data = writer.into_inner();
    let data = std::str::from_utf8(&data).unwrap();

    quote! {
        compile_error!(#data)
    }
}