Added loading std from any location - #19
Conversation
| if source.is_none() { | ||
| return None; | ||
| } |
There was a problem hiding this comment.
| if source.is_none() { | |
| return None; | |
| } |
The ? operator below already returns None if source is None, so this extra check is not needed.
| let source = if file_path.starts_with("std/") { | ||
| match env::var("NOQ_STD_PATH") { | ||
| Ok(std_path) => | ||
| self.load_source(loc, | ||
| &(std_path + file_path.strip_prefix("std/").unwrap()), diag), | ||
| Err(_) => self.load_source(loc, &file_path, diag) | ||
| } | ||
| } | ||
| else { | ||
| self.load_source(loc, &file_path, diag) | ||
| }; |
There was a problem hiding this comment.
This could be rewritten in several ways. We can get rid of the unwrap by using strip_prefix in the if instead of starts_witth:
let source = if let Some(stripped_path) = file_path.strip_prefix("std/") {
match env::var("NOQ_STD_PATH") {
Ok(std_path) =>
self.load_source(loc,
&(std_path + stripped_path), diag),
Err(_) => self.load_source(loc, &file_path, diag)
}
} else {
self.load_source(loc, &file_path, diag)
};We also see the pattern of looking whether the env var is found and using it and if isn't found we fall back to the default value. We could use the unwrap_or method instead
let source = if let Some(stripped_path) = file_path.strip_prefix("std/") {
let path = env::var("NOQ_STD_PATH")
.map(|std_path| std_path + stripped_path)
.unwrap_or(file_path);
self.load_source(loc, &path, diag)
} else {
self.load_source(loc, &file_path, diag)
};Now there's one more if we can eliminate
let path = file_path.strip_prefix("std/")
.and_then(|stripped_path| env::var("NOQ_STD_PATH").map(|std_path| std_path + stripped_path))
.unwrap_or(file_path);
let source = self.load_source(loc, &path, diag).load_source(loc, &file_path, diag);Is it better? At this point I'm not fully sure whether it's better and maybe the second one is better than the third, but I did have fun writing it :D
Also there could be minor errors in my code as I just wrote it in the GitHub UI and didn't check it but the general idea should work
Now you can set NOQ_STD_PATH env variable to a path to folder with standard library you wanna use. When loading path is prefixed with
std/it will be replaced with this variable(if it's not set, the standard loading would start).