summaryrefslogtreecommitdiff
path: root/symbolmacro/src/lib.rs
blob: 636c7860b620a158d8354a91fac7c8f75112ac6b (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
extern crate proc_macro;

use proc_macro::TokenStream;
use std::{collections::HashMap, fs::File, io::BufReader};
use std::io::prelude::*;



fn fetchsymbols() -> HashMap<String, char> {
    // who needs obvious filepaths, anyways?
    let filename = "symbols";
    let file = File::open(filename).unwrap();
    let reader = BufReader::new(file);

    reader.lines()
          .filter_map(|l| l.ok())
          .filter_map(|l| {
              let segments: Vec<&str> = l
                  .split_whitespace()
                  .collect();
              match segments[..] {
                  [] => None,
                  [s,"code:",code,..] => {
                      let codepoint = u32::from_str_radix(&code[2..], 16).ok()?;
                      let unichar = std::char::from_u32(codepoint)?;
                      Some((s[2..s.len()-1].to_string(), unichar))
                  },
                  _ => None,
              }
          })
          .collect::<HashMap<String,char>>()
}


// rust macros are a strange kind of horrible, tbh
#[proc_macro]
pub fn make_symbols(_item: TokenStream) -> TokenStream {
    let symbols = fetchsymbols();

    format!(
        "fn symbol(key: &str) -> Option<char> {{
          match key {{
             {}
             _ => None
          }}
        }}",
        symbols.iter()
               .map(|(k,v)| format!("\"{}\" => Some(\'{}\'),",k,v))
               .collect::<Vec<_>>()
               .join("\n")
    ).parse().unwrap()
}