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
use syn::{Type::Path, ImplItem::{Method, Const}};
use std::fs::File;
use std::io::Read;

enum Status {Final, Empty}
use Status::*;
fn get_priority(attrs: &Vec<syn::Attribute>) -> Result<i32, Status> {
    for attr in attrs { // there's no error checking; overrider main can give richer error messages
	if attr.path.segments[0].ident.to_string() == "override_default" {
	    if let Ok(syn::Expr::Paren(expr)) = syn::parse2::<syn::Expr>(attr.tokens.clone()) {
		if let syn::Expr::Assign(assign) = *expr.expr {
		    if let syn::Expr::Path(left) = *assign.left {
			if left.path.segments.len() == 1
			    && left.path.segments[0].ident.to_string() == "priority" {
				if let syn::Expr::Lit(lit) = *assign.right {
				    if let syn::Lit::Int(i) = lit.lit {
					if let Ok(priority) = i.base10_parse::<i32>() {
					    return Ok(priority);
					}
				    }
				}
			    }
		    }
		}
	    } else { // might be default
		if attr.tokens.is_empty() {
		    return Ok(1);
		}
	    }
	} else if attr.path.segments[0].ident.to_string() == "default" {
	    if attr.tokens.is_empty() {
		return Ok(0);
	    }
	} else if attr.path.segments[0].ident.to_string() == "override_final" {
	    if attr.tokens.is_empty() {
		return Err(Final);
	    }
	}
    }
    Err(Empty)
}


#[derive(Debug)]
struct Override {
    pub flag: String,
    pub priority: i32,
}

pub fn watch_files(file_names: Vec<&str>) {

    // find all overrides in files
    let mut overrides: Vec<Override> = Vec::new();
    let mut finals:    Vec<String>   = Vec::new();
    for file_name in file_names {
	let mut file = File::open(file_name).expect(&format!("Unable to open file '{}'", file_name));
	let mut src = String::new(); 
	file.read_to_string(&mut src).expect(&format!("Unable to read file '{}'", file_name));

	let parsed = match syn::parse_file(&src) {
	    Ok(items) => items,
	    Err(_) => return, // There's a compiler error. Let rustc take care of it
	};

	for item in parsed.items {
	    match item { // step over everything in the file
		syn::Item::Fn(func) => {
		    match get_priority(&func.attrs) {
			Ok(priority) =>
			    overrides.push(Override{
				flag: format!("func_{}",func.sig.ident),
				priority,
			    }),
			Err(Final) => finals.push(format!("func_{}", func.sig.ident)),
			Err(Empty) => {},
		    }
		},
		syn::Item::Impl(impl_block) => {
		    match get_priority(&impl_block.attrs) {
			Ok(priority) => {
			    let self_type = match impl_block.self_ty.as_ref() { // The `Dummy` in `impl Dummy {}`
				Path(path) => path,
				_ => continue,
			    }.path.segments[0].ident.to_string();
			    
			    for item in impl_block.items {
				match item {
				    Method(method) =>
					overrides.push(Override{
					    flag: format!("method_{}_{}",
							  self_type,
							  &method.sig.ident),
					    priority,
					}),
				    Const(constant) =>
					overrides.push(Override{
					    flag: format!("implconst_{}_{}",
							  self_type,
							  &constant.ident),
					    priority,
					}),
				    _ => continue,
				}
			    }
			},
			Err(Final) => {
			    let self_type = match impl_block.self_ty.as_ref() { // The `Dummy` in `impl Dummy {}`
				Path(path) => path,
				_ => continue,
			    }.path.segments[0].ident.to_string();
			    
			    for item in impl_block.items {
				match item {
				    Method(method) => 
					finals.push(format!("method_{}_{}",
							    self_type,
							    &method.sig.ident)),
				    Const(constant) =>
					finals.push(format!("implconst_{}_{}",
							    self_type,
							    &constant.ident)),
				    _ => continue,
				}
			    }
			},
			Err(Empty) => {},
		    }
		},
		_ => {} // can't parse everything yet
	    }
	}
    }

    // group them into like targets
    let mut override_chains: Vec<Vec<Override>> = Vec::new();
    for overrider in overrides.into_iter() {
	if let Some(position) = override_chains.iter().position(|chain| chain[0].flag == overrider.flag) {
	    override_chains[position].push(overrider);
	} else {
	    override_chains.push(vec![overrider]);
	}
    }

    // print cfgs
    for chain in override_chains.iter() {
	let (i_of_max, _) = chain.iter().enumerate().max_by_key(|x| x.1.priority.abs()).unwrap();
	for fin in &finals {
	    if fin == &chain[i_of_max].flag {
		println!("cargo:rustc-env=__override_final_{}={}", fin, chain[i_of_max].priority+1);
	    }
	}
	for (i, overrider) in chain.iter().enumerate(){
	    if i_of_max != i {
		println!("cargo:rustc-cfg=__override_priority_{}_{}", overrider.priority, overrider.flag);
	    }
	};
    }
    
    // sometimes there's something in fin that's not in override_chains. If so, priority = 0
    for fin in finals.into_iter() {
	if !override_chains.iter().any(|chain| chain[0].flag == fin) {
	    println!("cargo:rustc-env=__override_final_{}={}", fin, 0);
	}
    }
}