Skip to content

Instantly share code, notes, and snippets.

@mxxo
Last active September 22, 2020 17:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mxxo/51a4d24cb9565d6c7eb2f872c9e740c4 to your computer and use it in GitHub Desktop.
Save mxxo/51a4d24cb9565d6c7eb2f872c9e740c4 to your computer and use it in GitHub Desktop.
#![allow(unknown_lints)]
#[track_caller]
pub fn f() {
// ... dreaming about IO in const fns
// * https://github.com/rust-lang/const-eval/issues/44
// * could maybe use include_bytes
let loc = std::panic::Location::caller();
let contents = std::fs::read_to_string(loc.file()).unwrap();
let mut lines: Vec<String> = Vec::new();
for line in contents.lines().take(loc.line() as usize) {
lines.push(line.to_string());
}
lines.last_mut().unwrap().truncate(loc.column() as usize);
let src: String = lines.join("\n");
let rev = src.chars().rev();
let rev = rev.skip_while(|c| c.is_alphanumeric() || c.is_whitespace());
let magic_attr = "[warn(be_careful)]";
let mut maybe_attr: String = rev.take_while(|&c| c != '#').collect();
maybe_attr.retain(|c| !c.is_whitespace());
if !maybe_attr.chars().eq(magic_attr.chars().rev()) {
// todo function name
panic!("to call this function you must specify the `#[warn(be_careful)]` \
attribute to ensure you are upholding the neccessary invariants");
}
}
#[cfg(test)]
mod tests {
#![allow(unknown_lints)]
use super::*;
#[test]
fn jammed_together() {
#[warn(be_careful)]f()
}
#[test]
fn plain_attr() {
#[warn(be_careful)] f() // hi there
}
#[test]
#[should_panic(expected = "you must specify the `#[warn(be_careful)]` attribute")]
fn bad_attribute() {
#[warn(dont_be_careful)] f()
}
#[test]
#[should_panic(expected = "you must specify the `#[warn(be_careful)]` attribute")]
fn no_attribute() { f() }
#[test]
fn whitespace_ok() {
#[warn (be_careful ) ] f()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment