expander.rs (13633B)
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 | use super::parser::{self, ParseNode, ParseTree, Node};
use super::tokens::Site;
use std::{fmt, path::{Path, PathBuf}, ffi::OsString, error::Error};
use colored::*;
/// Error type for errors while expanding macros.
#[derive(Debug, Clone)]
pub struct ExpansionError(pub String, pub Site);
impl ExpansionError {
/// Create a new error given the ML, the message, and the site.
pub fn new(msg : &str, site : &Site) -> Self {
Self(msg.to_owned(), site.to_owned())
}
}
/// Implement fmt::Display for user-facing error output.
impl fmt::Display for ExpansionError {
fn fmt(&self, f : &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "[{}] Error Expanding Macro {}: {}",
"**".red().bold(), self.1, self.0)
}
}
/// Implements std::error::Error.
impl Error for ExpansionError { }
use std::collections::HashMap;
#[derive(Clone)]
struct Macro {
name : String,
params : Vec<String>,
body : Vec<ParseNode>
}
impl Macro {
fn new(name : &str) -> Macro {
Macro {
name: name.to_string(),
params: Vec::new(),
body: Vec::new()
}
}
}
#[derive(Clone)]
struct ExpansionContext {
definitions : HashMap<String, Macro>
}
impl ExpansionContext {
pub fn new() -> Self { Self { definitions: HashMap::new() } }
fn expand_invocation(&mut self, name : &str,
site : &Site,
params : Vec<ParseNode>)
-> Result<ParseTree, ExpansionError> { match name {
// Some macros are lazy (e.g. `ifdef`), so each macro has to
// expand the macros in its arguments individually.
"define" => {
let (head, nodes) = if let [head, nodes@..] = params.as_slice() {
(head, nodes)
} else {
return Err(ExpansionError::new(
&format!("`define` macro takes at least \
two (2) arguments ({} were given.", params.len()),
site));
};
// If head is atomic, we assign to a 'variable'.
let def_macro = if let Some(variable) = head.atomic() {
let mut definition = Macro::new(&variable.value);
for node in nodes {
definition.body.push(node.clone());
}
definition
} else { // Otherwise, we are assigning to a 'function'.
let (name, params) = if let ParseNode::List(call) = head {
let (name, params) = if let [name, params@..] = call.as_slice() {
(name, params)
} else {
return Err(ExpansionError::new(
"`define` function definition must at \
least have a name.", site));
};
let mut arguments = Vec::with_capacity(params.len());
for node in params { // Verify params are symbols.
if let ParseNode::Symbol(param) = node {
arguments.push(param.value.clone());
} else {
return Err(ExpansionError::new(
"`define` function arguments must be \
symbols/identifers.", site));
};
}
if let ParseNode::Symbol(name) = name {
(name.value.clone(), arguments)
} else {
return Err(ExpansionError::new(
"`define` function name must be \
a symbol/identifier.", site));
}
} else {
return Err(ExpansionError::new(
"First argument of `define` macro must be a list \
or variable name/identifier.", site));
};
let mut definition = Macro::new(&name);
definition.params = params;
for node in nodes {
definition.body.push(node.clone());
}
definition
};
self.definitions.insert(def_macro.name.clone(), def_macro);
Ok(vec![])
},
"ifdef" => {
if params.len() < 2 || params.len() > 3 {
eprintln!("{:?}", params);
return Err(ExpansionError::new(&format!("`ifdef` takes one (1) \
condition and one (1) consequent, a third optional \
alternative expression may also be provided, but \
`ifdef` was given {} arguments.", params.len()),
site));
}
let symbol = if let Some(node) = params[0].atomic() {
node.value
} else {
return Err(ExpansionError::new("The first argument to \
`ifdef` must be a symbol/name.", ¶ms[0].site()));
};
if self.definitions.contains_key(&symbol) {
Ok(self.expand_node(params[1].clone())?)
} else {
if let Some(alt) = params.get(2) {
Ok(self.expand_node(alt.clone())?)
} else {
Ok(vec![])
}
}
},
"include" => {
let params = self.expand_nodes(params)?;
let path_node = if let [ p ] = params.as_slice() {
p
} else {
return Err(ExpansionError::new(
&format!("Incorrect number of arguments \
to `{}' macro. Got {}, expected {}.",
name, params.len(), 1),
site));
};
let path = if let Some(node) = path_node.atomic() {
node.value
} else {
return Err(ExpansionError::new(
&format!("Bad argument to `{}' macro.\n\
Expected a path, but did not get any value
that could be interpreted as a path.", name),
site))
};
// Open file, and parse contents!
let path = Path::new(&path);
let tree = match super::parse_file_noexpand(&path) {
Ok(tree) => tree,
Err(error) => {
let err = ExpansionError::new(
&format!("{}", error), site);
// Try with `.sex` extensions appended.
let mut with_ext = PathBuf::from(path);
let filename = path.file_name().ok_or(err.clone())?;
with_ext.pop();
let mut new_filename = OsString::new();
new_filename.push(filename);
new_filename.push(".sex");
with_ext.push(new_filename);
match super::parse_file_noexpand(&with_ext) {
Ok(tree) => tree,
Err(_) => return Err(err)
}
}
};
// Build new (expanded) tree, with result of previous
// parse, while recursively expanding each branch in the
// tree too, as they are added.
let mut expanded_tree = Vec::with_capacity(tree.len());
for branch in tree {
expanded_tree.extend(self.expand_node(branch)?);
}
Ok(expanded_tree)
},
"date" => {
let params = self.expand_nodes(params)?;
let date_format = if let [ p ] = params.as_slice() {
p
} else {
return Err(ExpansionError::new(
&format!("`{}' macro only expects one formatting argument.",
name),
site))
};
let (date_format, site) = if let Some(node) = date_format.atomic() {
(node.value, node.site)
} else {
return Err(ExpansionError::new(
&format!("`{}' macro needs string (or atomic) \
formatting argument.", name),
site))
};
let now = chrono::Local::now();
let formatted = now.format(&date_format).to_string();
Ok(vec![ParseNode::String(Node::new(&formatted, &site))])
},
"log" => {
let mut words = Vec::with_capacity(params.len());
for param in self.expand_nodes(params)? {
if let Some(word) = param.atomic() {
words.push(word.value.clone());
} else {
return Err(ExpansionError::new("`log` should only take \
arguments that are either symbols, strings or numbers.",
¶m.site()));
}
}
eprintln!("{} {} {}: {}", "[#]".bold(), "log".bold().yellow(),
site, words.join(" "));
Ok(vec![])
}
name => {
let params = self.expand_nodes(params)?;
let mac = if let Some(mac) = self.definitions.get(name) {
mac
} else {
return Err(ExpansionError::new(
&format!("Macro not found (`{}').", name), site))
};
// Instance of expansion subcontext.
let mut subcontext = self.clone();
// Check enough arguments were given.
if params.len() != mac.params.len() {
return Err(ExpansionError::new(
&format!("`%{}` macro expects {} arguments, \
but {} were given.", &mac.name, mac.params.len(),
params.len()), site));
}
// Define arguments for body.
for i in 0..params.len() {
let mut arg_macro = Macro::new(&mac.params[i]);
arg_macro.body.push(params[i].clone());
subcontext.definitions.insert(mac.params[i].clone(), arg_macro);
}
// Expand body.
subcontext.expand_nodes(mac.body.clone())
}
}}
pub fn expand_node(&mut self, node : ParseNode)
-> Result<ParseTree, ExpansionError> {
match node {
ParseNode::Symbol(ref sym) => {
// Check if symbol starts with %... and replace it
// with it's defined value.
if sym.value.starts_with("%") {
let name = &sym.value[1..];
if let Some(def) = self.definitions.get(name) {
if !def.params.is_empty() { // Should not be a function.
return Err(ExpansionError::new(
&format!("`{}` is a macro that takes arguments, \
and cannot be used as a variable.", name),
&sym.site))
}
Ok(def.body.clone())
} else { // Not found.
Err(ExpansionError::new(
&format!("No such macro, `{}`.", name),
&sym.site))
}
} else {
Ok(vec![node])
}
},
ParseNode::List(list) => {
// Check for macro invocation (%_ _ _ _).
// Recurse over every element.
let len = list.len();
let mut call = list.into_iter();
let head = call.next();
if let Some(ParseNode::Symbol(ref sym)) = head {
if sym.value.starts_with("%") {
// Rebuild node...
let name = &sym.value[1..];
let Node { site, .. } = sym;
// Clean macro arguments from whitespace tokens.
let call_vec: ParseTree = call.collect();
let params = parser::strip(&call_vec, false);
return self.expand_invocation(name, site, params);
}
}
// Rebuild node...
let mut expanded_list = Vec::with_capacity(len);
expanded_list.extend(self.expand_node(head.unwrap())?);
for elem in call {
expanded_list.extend(self.expand_node(elem)?);
}
Ok(vec![ParseNode::List(expanded_list)])
},
ParseNode::Attribute(mut attr) => {
let mut expanded_nodes = self.expand_node(*attr.node)?;
attr.node = Box::new(expanded_nodes[0].clone());
expanded_nodes[0] = ParseNode::Attribute(attr);
Ok(expanded_nodes)
},
_ => Ok(vec![node])
}
}
fn expand_nodes(&mut self, tree : ParseTree) -> Result<ParseTree, ExpansionError> {
let mut expanded = Vec::with_capacity(tree.len());
for branch in tree {
expanded.extend(self.expand_node(branch)?);
}
Ok(expanded)
}
}
/// Macro-expansion phase.
/// Macros start with `%...'.
pub fn expand(tree : ParseTree) -> Result<ParseTree, ExpansionError> {
let mut context = ExpansionContext::new();
context.expand_nodes(tree)
}
|