From fc56055ecb63ef05b54aa098bde2d3b61c68e8b2 Mon Sep 17 00:00:00 2001
From: Melody Horn <melody@boringcactus.com>
Date: Fri, 2 Apr 2021 19:54:57 -0600
Subject: implement `origin`

---
 src/makefile/functions.rs | 14 ++++++++++++++
 src/makefile/macro.rs     | 13 +++++++++++++
 2 files changed, 27 insertions(+)

diff --git a/src/makefile/functions.rs b/src/makefile/functions.rs
index bc244cb..a61a0cf 100644
--- a/src/makefile/functions.rs
+++ b/src/makefile/functions.rs
@@ -56,6 +56,11 @@ pub fn expand_call(name: &str, args: &[TokenString], macros: &MacroSet) -> Resul
         // eval
         "eval" => todo!(),
 
+        "origin" => {
+            assert_eq!(args.len(), 1);
+            origin::origin(macros, &args[0])
+        }
+
         // shell
         "shell" => todo!(),
 
@@ -260,6 +265,15 @@ mod call {
     }
 }
 
+mod origin {
+    use super::*;
+
+    pub fn origin(macros: &MacroSet, variable: &TokenString) -> Result<String> {
+        let variable = macros.expand(variable)?;
+        Ok(macros.origin(&variable).to_owned())
+    }
+}
+
 #[cfg(test)]
 mod test {
     use super::*;
diff --git a/src/makefile/macro.rs b/src/makefile/macro.rs
index bb4a72d..f788edc 100644
--- a/src/makefile/macro.rs
+++ b/src/makefile/macro.rs
@@ -124,6 +124,19 @@ impl<'parent, 'lookup> Set<'parent, 'lookup> {
         Ok(result)
     }
 
+    #[cfg(feature = "full")]
+    pub fn origin(&self, name: &str) -> &'static str {
+        match self.data.get(name) {
+            None => self.parent.map_or("undefined", |p| p.origin(name)),
+            Some((Source::Builtin, _)) => "default",
+            Some((Source::Environment, _)) => "environment",
+            // TODO figure out when to return "environment override"
+            Some((Source::File, _)) => "file",
+            Some((Source::CommandLineOrMakeflags, _)) => "command line",
+            // TODO handle override and automatic
+        }
+    }
+
     pub fn with_lookup<'l, 's: 'l>(&'s self, lookup: &'l dyn LookupInternal) -> Set<'s, 'l> {
         Set {
             parent: Some(self),
-- 
cgit v1.2.3